livedesk 0.1.411 → 0.1.413

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,25 +0,0 @@
1
- import{r as IS,a as u,M as Pc,S as Lt,R as Ho,B as OS,P as $m,X as Ha,b as Yc,C as ri,F as tx,L as Ds,A as Uy,c as HS,d as nx,E as ax,T as BS,D as Qh,e as Hn,f as FS,g as PS,h as $S,i as US,j as Gi,k as Yt,l as Kd,m as Do,n as qy,o as Ol,p as Gy,q as gn,s as Vy,t as Wy,u as qS,v as GS,H as zl,W as Hl,w as VS,x as WS,y as Lo,K as _o,z as Yy,G as Ky,I as Qd,J as YS,N as Kc,O as Ls,Q as Ro,U as KS,V as QS,Y as XS,Z as Xh,_ as $c,$ as Zh,a0 as ZS,a1 as Jh,a2 as Qy,a3 as JS,a4 as ii,a5 as sx,a6 as ep,a7 as uf,a8 as Qc,a9 as Pd,aa as e0,ab as Xy,ac as t0,ad as Zy,ae as n0,af as a0,ag as Ah,ah as s0,ai as i0,aj as r0,ak as l0,al as o0,am as c0,an as u0,ao as ix,ap as d0,aq as f0,ar as $d,as as Ud,at as m0,au as h0,av as Um,aw as Nl,ax as p0,ay as rx,az as Jy,aA as g0,aB as v0}from"./icons-HeE5A4Vk.js";import{r as eb}from"./react-DW3yB5LY.js";import{c as x0}from"./supabase-C7qjtLN3.js";(function(){const a=document.createElement("link").relList;if(a&&a.supports&&a.supports("modulepreload"))return;for(const c of document.querySelectorAll('link[rel="modulepreload"]'))l(c);new MutationObserver(c=>{for(const d of c)if(d.type==="childList")for(const m of d.addedNodes)m.tagName==="LINK"&&m.rel==="modulepreload"&&l(m)}).observe(document,{childList:!0,subtree:!0});function r(c){const d={};return c.integrity&&(d.integrity=c.integrity),c.referrerPolicy&&(d.referrerPolicy=c.referrerPolicy),c.crossOrigin==="use-credentials"?d.credentials="include":c.crossOrigin==="anonymous"?d.credentials="omit":d.credentials="same-origin",d}function l(c){if(c.ep)return;c.ep=!0;const d=r(c);fetch(c.href,d)}})();var qm={exports:{}},Rc={};var lx;function y0(){if(lx)return Rc;lx=1;var n=Symbol.for("react.transitional.element"),a=Symbol.for("react.fragment");function r(l,c,d){var m=null;if(d!==void 0&&(m=""+d),c.key!==void 0&&(m=""+c.key),"key"in c){d={};for(var p in c)p!=="key"&&(d[p]=c[p])}else d=c;return c=d.ref,{$$typeof:n,type:l,key:m,ref:c!==void 0?c:null,props:d}}return Rc.Fragment=a,Rc.jsx=r,Rc.jsxs=r,Rc}var ox;function b0(){return ox||(ox=1,qm.exports=y0()),qm.exports}var s=b0(),Gm={exports:{}},Dc={},Vm={exports:{}},Wm={};var cx;function w0(){return cx||(cx=1,(function(n){function a(I,Q){var U=I.length;I.push(Q);e:for(;0<U;){var W=U-1>>>1,ue=I[W];if(0<c(ue,Q))I[W]=Q,I[U]=ue,U=W;else break e}}function r(I){return I.length===0?null:I[0]}function l(I){if(I.length===0)return null;var Q=I[0],U=I.pop();if(U!==Q){I[0]=U;e:for(var W=0,ue=I.length,be=ue>>>1;W<be;){var X=2*(W+1)-1,$=I[X],de=X+1,me=I[de];if(0>c($,U))de<ue&&0>c(me,$)?(I[W]=me,I[de]=U,W=de):(I[W]=$,I[X]=U,W=X);else if(de<ue&&0>c(me,U))I[W]=me,I[de]=U,W=de;else break e}}return Q}function c(I,Q){var U=I.sortIndex-Q.sortIndex;return U!==0?U:I.id-Q.id}if(n.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var d=performance;n.unstable_now=function(){return d.now()}}else{var m=Date,p=m.now();n.unstable_now=function(){return m.now()-p}}var v=[],g=[],w=1,y=null,b=3,C=!1,j=!1,A=!1,N=!1,k=typeof setTimeout=="function"?setTimeout:null,T=typeof clearTimeout=="function"?clearTimeout:null,R=typeof setImmediate<"u"?setImmediate:null;function q(I){for(var Q=r(g);Q!==null;){if(Q.callback===null)l(g);else if(Q.startTime<=I)l(g),Q.sortIndex=Q.expirationTime,a(v,Q);else break;Q=r(g)}}function O(I){if(A=!1,q(I),!j)if(r(v)!==null)j=!0,Y||(Y=!0,P());else{var Q=r(g);Q!==null&&K(O,Q.startTime-I)}}var Y=!1,_=-1,L=5,ae=-1;function G(){return N?!0:!(n.unstable_now()-ae<L)}function te(){if(N=!1,Y){var I=n.unstable_now();ae=I;var Q=!0;try{e:{j=!1,A&&(A=!1,T(_),_=-1),C=!0;var U=b;try{t:{for(q(I),y=r(v);y!==null&&!(y.expirationTime>I&&G());){var W=y.callback;if(typeof W=="function"){y.callback=null,b=y.priorityLevel;var ue=W(y.expirationTime<=I);if(I=n.unstable_now(),typeof ue=="function"){y.callback=ue,q(I),Q=!0;break t}y===r(v)&&l(v),q(I)}else l(v);y=r(v)}if(y!==null)Q=!0;else{var be=r(g);be!==null&&K(O,be.startTime-I),Q=!1}}break e}finally{y=null,b=U,C=!1}Q=void 0}}finally{Q?P():Y=!1}}}var P;if(typeof R=="function")P=function(){R(te)};else if(typeof MessageChannel<"u"){var ye=new MessageChannel,ie=ye.port2;ye.port1.onmessage=te,P=function(){ie.postMessage(null)}}else P=function(){k(te,0)};function K(I,Q){_=k(function(){I(n.unstable_now())},Q)}n.unstable_IdlePriority=5,n.unstable_ImmediatePriority=1,n.unstable_LowPriority=4,n.unstable_NormalPriority=3,n.unstable_Profiling=null,n.unstable_UserBlockingPriority=2,n.unstable_cancelCallback=function(I){I.callback=null},n.unstable_forceFrameRate=function(I){0>I||125<I?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):L=0<I?Math.floor(1e3/I):5},n.unstable_getCurrentPriorityLevel=function(){return b},n.unstable_next=function(I){switch(b){case 1:case 2:case 3:var Q=3;break;default:Q=b}var U=b;b=Q;try{return I()}finally{b=U}},n.unstable_requestPaint=function(){N=!0},n.unstable_runWithPriority=function(I,Q){switch(I){case 1:case 2:case 3:case 4:case 5:break;default:I=3}var U=b;b=I;try{return Q()}finally{b=U}},n.unstable_scheduleCallback=function(I,Q,U){var W=n.unstable_now();switch(typeof U=="object"&&U!==null?(U=U.delay,U=typeof U=="number"&&0<U?W+U:W):U=W,I){case 1:var ue=-1;break;case 2:ue=250;break;case 5:ue=1073741823;break;case 4:ue=1e4;break;default:ue=5e3}return ue=U+ue,I={id:w++,callback:Q,priorityLevel:I,startTime:U,expirationTime:ue,sortIndex:-1},U>W?(I.sortIndex=U,a(g,I),r(v)===null&&I===r(g)&&(A?(T(_),_=-1):A=!0,K(O,U-W))):(I.sortIndex=ue,a(v,I),j||C||(j=!0,Y||(Y=!0,P()))),I},n.unstable_shouldYield=G,n.unstable_wrapCallback=function(I){var Q=b;return function(){var U=b;b=Q;try{return I.apply(this,arguments)}finally{b=U}}}})(Wm)),Wm}var ux;function S0(){return ux||(ux=1,Vm.exports=w0()),Vm.exports}var dx;function C0(){if(dx)return Dc;dx=1;var n=S0(),a=IS(),r=eb();function l(e){var t="https://react.dev/errors/"+e;if(1<arguments.length){t+="?args[]="+encodeURIComponent(arguments[1]);for(var i=2;i<arguments.length;i++)t+="&args[]="+encodeURIComponent(arguments[i])}return"Minified React error #"+e+"; visit "+t+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function c(e){return!(!e||e.nodeType!==1&&e.nodeType!==9&&e.nodeType!==11)}function d(e){var t=e,i=e;if(e.alternate)for(;t.return;)t=t.return;else{e=t;do t=e,(t.flags&4098)!==0&&(i=t.return),e=t.return;while(e)}return t.tag===3?i:null}function m(e){if(e.tag===13){var t=e.memoizedState;if(t===null&&(e=e.alternate,e!==null&&(t=e.memoizedState)),t!==null)return t.dehydrated}return null}function p(e){if(e.tag===31){var t=e.memoizedState;if(t===null&&(e=e.alternate,e!==null&&(t=e.memoizedState)),t!==null)return t.dehydrated}return null}function v(e){if(d(e)!==e)throw Error(l(188))}function g(e){var t=e.alternate;if(!t){if(t=d(e),t===null)throw Error(l(188));return t!==e?null:e}for(var i=e,o=t;;){var f=i.return;if(f===null)break;var h=f.alternate;if(h===null){if(o=f.return,o!==null){i=o;continue}break}if(f.child===h.child){for(h=f.child;h;){if(h===i)return v(f),e;if(h===o)return v(f),t;h=h.sibling}throw Error(l(188))}if(i.return!==o.return)i=f,o=h;else{for(var S=!1,E=f.child;E;){if(E===i){S=!0,i=f,o=h;break}if(E===o){S=!0,o=f,i=h;break}E=E.sibling}if(!S){for(E=h.child;E;){if(E===i){S=!0,i=h,o=f;break}if(E===o){S=!0,o=h,i=f;break}E=E.sibling}if(!S)throw Error(l(189))}}if(i.alternate!==o)throw Error(l(190))}if(i.tag!==3)throw Error(l(188));return i.stateNode.current===i?e:t}function w(e){var t=e.tag;if(t===5||t===26||t===27||t===6)return e;for(e=e.child;e!==null;){if(t=w(e),t!==null)return t;e=e.sibling}return null}var y=Object.assign,b=Symbol.for("react.element"),C=Symbol.for("react.transitional.element"),j=Symbol.for("react.portal"),A=Symbol.for("react.fragment"),N=Symbol.for("react.strict_mode"),k=Symbol.for("react.profiler"),T=Symbol.for("react.consumer"),R=Symbol.for("react.context"),q=Symbol.for("react.forward_ref"),O=Symbol.for("react.suspense"),Y=Symbol.for("react.suspense_list"),_=Symbol.for("react.memo"),L=Symbol.for("react.lazy"),ae=Symbol.for("react.activity"),G=Symbol.for("react.memo_cache_sentinel"),te=Symbol.iterator;function P(e){return e===null||typeof e!="object"?null:(e=te&&e[te]||e["@@iterator"],typeof e=="function"?e:null)}var ye=Symbol.for("react.client.reference");function ie(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 A:return"Fragment";case k:return"Profiler";case N:return"StrictMode";case O:return"Suspense";case Y:return"SuspenseList";case ae:return"Activity"}if(typeof e=="object")switch(e.$$typeof){case j:return"Portal";case R:return e.displayName||"Context";case T:return(e._context.displayName||"Context")+".Consumer";case q: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:ie(e.type)||"Memo";case L:t=e._payload,e=e._init;try{return ie(e(t))}catch{}}return null}var K=Array.isArray,I=a.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,Q=r.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,U={pending:!1,data:null,method:null,action:null},W=[],ue=-1;function be(e){return{current:e}}function X(e){0>ue||(e.current=W[ue],W[ue]=null,ue--)}function $(e,t){ue++,W[ue]=e.current,e.current=t}var de=be(null),me=be(null),ve=be(null),Se=be(null);function Oe(e,t){switch($(ve,t),$(me,e),$(de,null),t.nodeType){case 9:case 11:e=(e=t.documentElement)&&(e=e.namespaceURI)?jv(e):0;break;default:if(e=t.tagName,t=t.namespaceURI)t=jv(t),e=kv(t,e);else switch(e){case"svg":e=1;break;case"math":e=2;break;default:e=0}}X(de),$(de,e)}function le(){X(de),X(me),X(ve)}function Z(e){e.memoizedState!==null&&$(Se,e);var t=de.current,i=kv(t,e.type);t!==i&&($(me,e),$(de,i))}function He(e){me.current===e&&(X(de),X(me)),Se.current===e&&(X(Se),Nc._currentValue=U)}var _e,se;function fe(e){if(_e===void 0)try{throw Error()}catch(i){var t=i.stack.trim().match(/\n( *(at )?)/);_e=t&&t[1]||"",se=-1<i.stack.indexOf(`
2
- at`)?" (<anonymous>)":-1<i.stack.indexOf("@")?"@unknown:0:0":""}return`
3
- `+_e+e+se}var Ne=!1;function Te(e,t){if(!e||Ne)return"";Ne=!0;var i=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var o={DetermineComponentFrameRoot:function(){try{if(t){var Ce=function(){throw Error()};if(Object.defineProperty(Ce.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(Ce,[])}catch(he){var ce=he}Reflect.construct(e,[],Ce)}else{try{Ce.call()}catch(he){ce=he}e.call(Ce.prototype)}}else{try{throw Error()}catch(he){ce=he}(Ce=e())&&typeof Ce.catch=="function"&&Ce.catch(function(){})}}catch(he){if(he&&ce&&typeof he.stack=="string")return[he.stack,ce.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 F=S.split(`
4
- `),oe=E.split(`
5
- `);for(f=o=0;o<F.length&&!F[o].includes("DetermineComponentFrameRoot");)o++;for(;f<oe.length&&!oe[f].includes("DetermineComponentFrameRoot");)f++;if(o===F.length||f===oe.length)for(o=F.length-1,f=oe.length-1;1<=o&&0<=f&&F[o]!==oe[f];)f--;for(;1<=o&&0<=f;o--,f--)if(F[o]!==oe[f]){if(o!==1||f!==1)do if(o--,f--,0>f||F[o]!==oe[f]){var xe=`
6
- `+F[o].replace(" at new "," at ");return e.displayName&&xe.includes("<anonymous>")&&(xe=xe.replace("<anonymous>",e.displayName)),xe}while(1<=o&&0<=f);break}}}finally{Ne=!1,Error.prepareStackTrace=i}return(i=e?e.displayName||e.name:"")?fe(i):""}function Be(e,t){switch(e.tag){case 26:case 27:case 5:return fe(e.type);case 16:return fe("Lazy");case 13:return e.child!==t&&t!==null?fe("Suspense Fallback"):fe("Suspense");case 19:return fe("SuspenseList");case 0:case 15:return Te(e.type,!1);case 11:return Te(e.type.render,!1);case 1:return Te(e.type,!0);case 31:return fe("Activity");default:return""}}function $e(e){try{var t="",i=null;do t+=Be(e,i),i=e,e=e.return;while(e);return t}catch(o){return`
7
- Error generating stack: `+o.message+`
8
- `+o.stack}}var et=Object.prototype.hasOwnProperty,Mt=n.unstable_scheduleCallback,ke=n.unstable_cancelCallback,Ye=n.unstable_shouldYield,rt=n.unstable_requestPaint,vt=n.unstable_now,vn=n.unstable_getCurrentPriorityLevel,It=n.unstable_ImmediatePriority,Zt=n.unstable_UserBlockingPriority,ht=n.unstable_NormalPriority,$n=n.unstable_LowPriority,Gt=n.unstable_IdlePriority,J=n.log,Re=n.unstable_setDisableYieldValue,ze=null,je=null;function Xe(e){if(typeof J=="function"&&Re(e),je&&typeof je.setStrictMode=="function")try{je.setStrictMode(ze,e)}catch{}}var gt=Math.clz32?Math.clz32:Un,Ee=Math.log,ua=Math.LN2;function Un(e){return e>>>=0,e===0?32:31-(Ee(e)/ua|0)|0}var tt=256,$t=262144,an=4194304;function Za(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 Ja(e,t,i){var o=e.pendingLanes;if(o===0)return 0;var f=0,h=e.suspendedLanes,S=e.pingedLanes;e=e.warmLanes;var E=o&134217727;return E!==0?(o=E&~h,o!==0?f=Za(o):(S&=E,S!==0?f=Za(S):i||(i=E&~e,i!==0&&(f=Za(i))))):(E=o&~h,E!==0?f=Za(E):S!==0?f=Za(S):i||(i=o&~e,i!==0&&(f=Za(i)))),f===0?0:t!==0&&t!==f&&(t&h)===0&&(h=f&-f,i=t&-t,h>=i||h===32&&(i&4194048)!==0)?t:f}function Xn(e,t){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&t)===0}function Wi(e,t){switch(e){case 1:case 2:case 4:case 8:case 64:return t+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function Fe(){var e=an;return an<<=1,(an&62914560)===0&&(an=4194304),e}function Is(e){for(var t=[],i=0;31>i;i++)t.push(e);return t}function ut(e,t){e.pendingLanes|=t,t!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function ui(e,t,i,o,f,h){var S=e.pendingLanes;e.pendingLanes=i,e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0,e.expiredLanes&=i,e.entangledLanes&=i,e.errorRecoveryDisabledLanes&=i,e.shellSuspendCounter=0;var E=e.entanglements,F=e.expirationTimes,oe=e.hiddenUpdates;for(i=S&~i;0<i;){var xe=31-gt(i),Ce=1<<xe;E[xe]=0,F[xe]=-1;var ce=oe[xe];if(ce!==null)for(oe[xe]=null,xe=0;xe<ce.length;xe++){var he=ce[xe];he!==null&&(he.lane&=-536870913)}i&=~Ce}o!==0&&Kt(e,o,0),h!==0&&f===0&&e.tag!==0&&(e.suspendedLanes|=h&~(S&~t))}function Kt(e,t,i){e.pendingLanes|=t,e.suspendedLanes&=~t;var o=31-gt(t);e.entangledLanes|=t,e.entanglements[o]=e.entanglements[o]|1073741824|i&261930}function H(e,t){var i=e.entangledLanes|=t;for(e=e.entanglements;i;){var o=31-gt(i),f=1<<o;f&t|e[o]&t&&(e[o]|=t),i&=~f}}function De(e,t){var i=t&-t;return i=(i&42)!==0?1:st(i),(i&(e.suspendedLanes|t))!==0?0:i}function st(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 on(e){return e&=-e,2<e?8<e?(e&134217727)!==0?32:268435456:8:2}function es(){var e=Q.p;return e!==0?e:(e=window.event,e===void 0?32:Yv(e.type))}function Tn(e,t){var i=Q.p;try{return Q.p=e,t()}finally{Q.p=i}}var da=Math.random().toString(36).slice(2),ne="__reactFiber$"+da,Ae="__reactProps$"+da,qe="__reactContainer$"+da,ot="__reactEvents$"+da,Jt="__reactListeners$"+da,Ut="__reactHandles$"+da,Ze="__reactResources$"+da,jt="__reactMarker$"+da;function Ot(e){delete e[ne],delete e[Ae],delete e[ot],delete e[Jt],delete e[Ut]}function Vt(e){var t=e[ne];if(t)return t;for(var i=e.parentNode;i;){if(t=i[qe]||i[ne]){if(i=t.alternate,t.child!==null||i!==null&&i.child!==null)for(e=Dv(e);e!==null;){if(i=e[ne])return i;e=Dv(e)}return t}e=i,i=e.parentNode}return null}function sn(e){if(e=e[ne]||e[qe]){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 cn(e){var t=e[Ze];return t||(t=e[Ze]={hoistableStyles:new Map,hoistableScripts:new Map}),t}function Tt(e){e[jt]=!0}var ts=new Set,xn={};function un(e,t){dn(e,t),dn(e+"Capture",t)}function dn(e,t){for(xn[e]=t,e=0;e<t.length;e++)ts.add(t[e])}var Os=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]*$"),ya={},Hs={};function Po(e){return et.call(Hs,e)?!0:et.call(ya,e)?!1:Os.test(e)?Hs[e]=!0:(ya[e]=!0,!1)}function Yi(e,t,i){if(Po(t))if(i===null)e.removeAttribute(t);else{switch(typeof i){case"undefined":case"function":case"symbol":e.removeAttribute(t);return;case"boolean":var o=t.toLowerCase().slice(0,5);if(o!=="data-"&&o!=="aria-"){e.removeAttribute(t);return}}e.setAttribute(t,""+i)}}function Ki(e,t,i){if(i===null)e.removeAttribute(t);else{switch(typeof i){case"undefined":case"function":case"symbol":case"boolean":e.removeAttribute(t);return}e.setAttribute(t,""+i)}}function ms(e,t,i,o){if(o===null)e.removeAttribute(i);else{switch(typeof o){case"undefined":case"function":case"symbol":case"boolean":e.removeAttribute(i);return}e.setAttributeNS(t,i,""+o)}}function Zn(e){switch(typeof e){case"bigint":case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function $l(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function bf(e,t,i){var o=Object.getOwnPropertyDescriptor(e.constructor.prototype,t);if(!e.hasOwnProperty(t)&&typeof o<"u"&&typeof o.get=="function"&&typeof o.set=="function"){var f=o.get,h=o.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return f.call(this)},set:function(S){i=""+S,h.call(this,S)}}),Object.defineProperty(e,t,{enumerable:o.enumerable}),{getValue:function(){return i},setValue:function(S){i=""+S},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function Ul(e){if(!e._valueTracker){var t=$l(e)?"checked":"value";e._valueTracker=bf(e,t,""+e[t])}}function ba(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var i=t.getValue(),o="";return e&&(o=$l(e)?e.checked?"true":"false":e.value),e=o,e!==i?(t.setValue(e),!0):!1}function Qi(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 ns=/[\n"\\]/g;function Qt(e){return e.replace(ns,function(t){return"\\"+t.charCodeAt(0).toString(16)+" "})}function hs(e,t,i,o,f,h,S,E){e.name="",S!=null&&typeof S!="function"&&typeof S!="symbol"&&typeof S!="boolean"?e.type=S:e.removeAttribute("type"),t!=null?S==="number"?(t===0&&e.value===""||e.value!=t)&&(e.value=""+Zn(t)):e.value!==""+Zn(t)&&(e.value=""+Zn(t)):S!=="submit"&&S!=="reset"||e.removeAttribute("value"),t!=null?di(e,S,Zn(t)):i!=null?di(e,S,Zn(i)):o!=null&&e.removeAttribute("value"),f==null&&h!=null&&(e.defaultChecked=!!h),f!=null&&(e.checked=f&&typeof f!="function"&&typeof f!="symbol"),E!=null&&typeof E!="function"&&typeof E!="symbol"&&typeof E!="boolean"?e.name=""+Zn(E):e.removeAttribute("name")}function Xi(e,t,i,o,f,h,S,E){if(h!=null&&typeof h!="function"&&typeof h!="symbol"&&typeof h!="boolean"&&(e.type=h),t!=null||i!=null){if(!(h!=="submit"&&h!=="reset"||t!=null)){Ul(e);return}i=i!=null?""+Zn(i):"",t=t!=null?""+Zn(t):i,E||t===e.value||(e.value=t),e.defaultValue=t}o=o??f,o=typeof o!="function"&&typeof o!="symbol"&&!!o,e.checked=E?e.checked:!!o,e.defaultChecked=!!o,S!=null&&typeof S!="function"&&typeof S!="symbol"&&typeof S!="boolean"&&(e.name=S),Ul(e)}function di(e,t,i){t==="number"&&Qi(e.ownerDocument)===e||e.defaultValue===""+i||(e.defaultValue=""+i)}function ps(e,t,i,o){if(e=e.options,t){t={};for(var f=0;f<i.length;f++)t["$"+i[f]]=!0;for(i=0;i<e.length;i++)f=t.hasOwnProperty("$"+e[i].value),e[i].selected!==f&&(e[i].selected=f),f&&o&&(e[i].defaultSelected=!0)}else{for(i=""+Zn(i),t=null,f=0;f<e.length;f++){if(e[f].value===i){e[f].selected=!0,o&&(e[f].defaultSelected=!0);return}t!==null||e[f].disabled||(t=e[f])}t!==null&&(t.selected=!0)}}function Zi(e,t,i){if(t!=null&&(t=""+Zn(t),t!==e.value&&(e.value=t),i==null)){e.defaultValue!==t&&(e.defaultValue=t);return}e.defaultValue=i!=null?""+Zn(i):""}function fi(e,t,i,o){if(t==null){if(o!=null){if(i!=null)throw Error(l(92));if(K(o)){if(1<o.length)throw Error(l(93));o=o[0]}i=o}i==null&&(i=""),t=i}i=Zn(t),e.defaultValue=i,o=e.textContent,o===i&&o!==""&&o!==null&&(e.value=o),Ul(e)}function Fa(e,t){if(t){var i=e.firstChild;if(i&&i===e.lastChild&&i.nodeType===3){i.nodeValue=t;return}}e.textContent=t}var $o=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 Ji(e,t,i){var o=t.indexOf("--")===0;i==null||typeof i=="boolean"||i===""?o?e.setProperty(t,""):t==="float"?e.cssFloat="":e[t]="":o?e.setProperty(t,i):typeof i!="number"||i===0||$o.has(t)?t==="float"?e.cssFloat=i:e[t]=(""+i).trim():e[t]=i+"px"}function Yr(e,t,i){if(t!=null&&typeof t!="object")throw Error(l(62));if(e=e.style,i!=null){for(var o in i)!i.hasOwnProperty(o)||t!=null&&t.hasOwnProperty(o)||(o.indexOf("--")===0?e.setProperty(o,""):o==="float"?e.cssFloat="":e[o]="");for(var f in t)o=t[f],t.hasOwnProperty(f)&&i[f]!==o&&Ji(e,f,o)}else for(var h in t)t.hasOwnProperty(h)&&Ji(e,h,t[h])}function er(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 ql=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"]]),Uo=/^[\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 Kr(e){return Uo.test(""+e)?"javascript:throw new Error('React has blocked a javascript: URL as a security precaution.')":e}function Ln(){}var gs=null;function as(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var tr=null,Bs=null;function wf(e){var t=sn(e);if(t&&(e=t.stateNode)){var i=e[Ae]||null;e:switch(e=t.stateNode,t.type){case"input":if(hs(e,i.value,i.defaultValue,i.defaultValue,i.checked,i.defaultChecked,i.type,i.name),t=i.name,i.type==="radio"&&t!=null){for(i=e;i.parentNode;)i=i.parentNode;for(i=i.querySelectorAll('input[name="'+Qt(""+t)+'"][type="radio"]'),t=0;t<i.length;t++){var o=i[t];if(o!==e&&o.form===e.form){var f=o[Ae]||null;if(!f)throw Error(l(90));hs(o,f.value,f.defaultValue,f.defaultValue,f.checked,f.defaultChecked,f.type,f.name)}}for(t=0;t<i.length;t++)o=i[t],o.form===e.form&&ba(o)}break e;case"textarea":Zi(e,i.value,i.defaultValue);break e;case"select":t=i.value,t!=null&&ps(e,!!i.multiple,t,!1)}}}var qo=!1;function mi(e,t,i){if(qo)return e(t,i);qo=!0;try{var o=e(t);return o}finally{if(qo=!1,(tr!==null||Bs!==null)&&(Qu(),tr&&(t=tr,e=Bs,Bs=tr=null,wf(t),e)))for(t=0;t<e.length;t++)wf(e[t])}}function Qr(e,t){var i=e.stateNode;if(i===null)return null;var o=i[Ae]||null;if(o===null)return null;i=o[t];e:switch(t){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(o=!o.disabled)||(e=e.type,o=!(e==="button"||e==="input"||e==="select"||e==="textarea")),e=!o;break e;default:e=!1}if(e)return null;if(i&&typeof i!="function")throw Error(l(231,t,typeof i));return i}var Jn=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Xr=!1;if(Jn)try{var Gl={};Object.defineProperty(Gl,"passive",{get:function(){Xr=!0}}),window.addEventListener("test",Gl,Gl),window.removeEventListener("test",Gl,Gl)}catch{Xr=!1}var hi=null,au=null,Vl=null;function Go(){if(Vl)return Vl;var e,t=au,i=t.length,o,f="value"in hi?hi.value:hi.textContent,h=f.length;for(e=0;e<i&&t[e]===f[e];e++);var S=i-e;for(o=1;o<=S&&t[i-o]===f[h-o];o++);return Vl=f.slice(e,1<o?1-o:void 0)}function Zr(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 Wl(){return!0}function su(){return!1}function ea(e){function t(i,o,f,h,S){this._reactName=i,this._targetInst=f,this.type=o,this.nativeEvent=h,this.target=S,this.currentTarget=null;for(var E in e)e.hasOwnProperty(E)&&(i=e[E],this[E]=i?i(h):h[E]);return this.isDefaultPrevented=(h.defaultPrevented!=null?h.defaultPrevented:h.returnValue===!1)?Wl:su,this.isPropagationStopped=su,this}return y(t.prototype,{preventDefault:function(){this.defaultPrevented=!0;var i=this.nativeEvent;i&&(i.preventDefault?i.preventDefault():typeof i.returnValue!="unknown"&&(i.returnValue=!1),this.isDefaultPrevented=Wl)},stopPropagation:function(){var i=this.nativeEvent;i&&(i.stopPropagation?i.stopPropagation():typeof i.cancelBubble!="unknown"&&(i.cancelBubble=!0),this.isPropagationStopped=Wl)},persist:function(){},isPersistent:Wl}),t}var vs={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},nr=ea(vs),xs=y({},vs,{view:0,detail:0}),Fs=ea(xs),ar,Yl,sr,Jr=y({},xs,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:ys,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!==sr&&(sr&&e.type==="mousemove"?(ar=e.screenX-sr.screenX,Yl=e.screenY-sr.screenY):Yl=ar=0,sr=e),ar)},movementY:function(e){return"movementY"in e?e.movementY:Yl}}),ir=ea(Jr),Vo=y({},Jr,{dataTransfer:0}),iu=ea(Vo),it=y({},xs,{relatedTarget:0}),ct=ea(it),wa=y({},vs,{animationName:0,elapsedTime:0,pseudoElement:0}),rr=ea(wa),Ps=y({},vs,{clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}}),at=ea(Ps),ru=y({},vs,{data:0}),lu=ea(ru),Kl={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},pi={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"},ou={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function Wo(e){var t=this.nativeEvent;return t.getModifierState?t.getModifierState(e):(e=ou[e])?!!t[e]:!1}function ys(){return Wo}var fa=y({},xs,{key:function(e){if(e.key){var t=Kl[e.key]||e.key;if(t!=="Unidentified")return t}return e.type==="keypress"?(e=Zr(e),e===13?"Enter":String.fromCharCode(e)):e.type==="keydown"||e.type==="keyup"?pi[e.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:ys,charCode:function(e){return e.type==="keypress"?Zr(e):0},keyCode:function(e){return e.type==="keydown"||e.type==="keyup"?e.keyCode:0},which:function(e){return e.type==="keypress"?Zr(e):e.type==="keydown"||e.type==="keyup"?e.keyCode:0}}),lr=ea(fa),qn=y({},Jr,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),bs=ea(qn),Le=y({},xs,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:ys}),cu=ea(Le),Sf=y({},vs,{propertyName:0,elapsedTime:0,pseudoElement:0}),Cf=ea(Sf),Yo=y({},Jr,{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}),el=ea(Yo),uu=y({},vs,{newState:0,oldState:0}),du=ea(uu),fu=[9,13,27,32],Ht=Jn&&"CompositionEvent"in window,or=null;Jn&&"documentMode"in document&&(or=document.documentMode);var Ql=Jn&&"TextEvent"in window&&!or,gi=Jn&&(!Ht||or&&8<or&&11>=or),mu=" ",hu=!1;function Wt(e,t){switch(e){case"keyup":return fu.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function cr(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var ur=!1;function ws(e,t){switch(e){case"compositionend":return cr(t);case"keypress":return t.which!==32?null:(hu=!0,mu);case"textInput":return e=t.data,e===mu&&hu?null:e;default:return null}}function pu(e,t){if(ur)return e==="compositionend"||!Ht&&Wt(e,t)?(e=Go(),Vl=au=hi=null,ur=!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 gi&&t.locale!=="ko"?null:t.data;default:return null}}var Xl={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 tl(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t==="input"?!!Xl[e.type]:t==="textarea"}function Sa(e,t,i,o){tr?Bs?Bs.push(o):Bs=[o]:tr=o,t=ad(t,"onChange"),0<t.length&&(i=new nr("onChange","change",null,i,o),e.push({event:i,listeners:t}))}var Ca=null,$s=null;function ss(e){xv(e,0)}function Gn(e){var t=wt(e);if(ba(t))return e}function ta(e,t){if(e==="change")return t}var gu=!1;if(Jn){var Zl;if(Jn){var Us="oninput"in document;if(!Us){var vu=document.createElement("div");vu.setAttribute("oninput","return;"),Us=typeof vu.oninput=="function"}Zl=Us}else Zl=!1;gu=Zl&&(!document.documentMode||9<document.documentMode)}function _n(){Ca&&(Ca.detachEvent("onpropertychange",vi),$s=Ca=null)}function vi(e){if(e.propertyName==="value"&&Gn($s)){var t=[];Sa(t,$s,e,as(e)),mi(ss,t)}}function Ss(e,t,i){e==="focusin"?(_n(),Ca=t,$s=i,Ca.attachEvent("onpropertychange",vi)):e==="focusout"&&_n()}function dr(e){if(e==="selectionchange"||e==="keyup"||e==="keydown")return Gn($s)}function Jl(e,t){if(e==="click")return Gn(t)}function eo(e,t){if(e==="input"||e==="change")return Gn(t)}function Cs(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var na=typeof Object.is=="function"?Object.is:Cs;function nl(e,t){if(na(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;var i=Object.keys(e),o=Object.keys(t);if(i.length!==o.length)return!1;for(o=0;o<i.length;o++){var f=i[o];if(!et.call(t,f)||!na(e[f],t[f]))return!1}return!0}function al(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function sl(e,t){var i=al(e);e=0;for(var o;i;){if(i.nodeType===3){if(o=e+i.textContent.length,e<=t&&o>=t)return{node:i,offset:t-e};e=o}e:{for(;i;){if(i.nextSibling){i=i.nextSibling;break e}i=i.parentNode}i=void 0}i=al(i)}}function Ko(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?Ko(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function xi(e){e=e!=null&&e.ownerDocument!=null&&e.ownerDocument.defaultView!=null?e.ownerDocument.defaultView:window;for(var t=Qi(e.document);t instanceof e.HTMLIFrameElement;){try{var i=typeof t.contentWindow.location.href=="string"}catch{i=!1}if(i)e=t.contentWindow;else break;t=Qi(e.document)}return t}function to(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 xu=Jn&&"documentMode"in document&&11>=document.documentMode,fr=null,qs=null,il=null,no=!1;function yu(e,t,i){var o=i.window===i?i.document:i.nodeType===9?i:i.ownerDocument;no||fr==null||fr!==Qi(o)||(o=fr,"selectionStart"in o&&to(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}),il&&nl(il,o)||(il=o,o=ad(qs,"onSelect"),0<o.length&&(t=new nr("onSelect","select",null,t,i),e.push({event:t,listeners:o}),t.target=fr)))}function yi(e,t){var i={};return i[e.toLowerCase()]=t.toLowerCase(),i["Webkit"+e]="webkit"+t,i["Moz"+e]="moz"+t,i}var bi={animationend:yi("Animation","AnimationEnd"),animationiteration:yi("Animation","AnimationIteration"),animationstart:yi("Animation","AnimationStart"),transitionrun:yi("Transition","TransitionRun"),transitionstart:yi("Transition","TransitionStart"),transitioncancel:yi("Transition","TransitionCancel"),transitionend:yi("Transition","TransitionEnd")},Qo={},Xo={};Jn&&(Xo=document.createElement("div").style,"AnimationEvent"in window||(delete bi.animationend.animation,delete bi.animationiteration.animation,delete bi.animationstart.animation),"TransitionEvent"in window||delete bi.transitionend.transition);function Pa(e){if(Qo[e])return Qo[e];if(!bi[e])return e;var t=bi[e],i;for(i in t)if(t.hasOwnProperty(i)&&i in Xo)return Qo[e]=t[i];return e}var Zo=Pa("animationend"),js=Pa("animationiteration"),rl=Pa("animationstart"),mr=Pa("transitionrun"),wi=Pa("transitionstart"),Jo=Pa("transitioncancel"),bu=Pa("transitionend"),ec=new Map,ll="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(" ");ll.push("scrollEnd");function ma(e,t){ec.set(e,t),un(t,[e])}var Gs=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)},ja=[],ks=0,ao=0;function Si(){for(var e=ks,t=ao=ks=0;t<e;){var i=ja[t];ja[t++]=null;var o=ja[t];ja[t++]=null;var f=ja[t];ja[t++]=null;var h=ja[t];if(ja[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&&cl(i,f,h)}}function hr(e,t,i,o){ja[ks++]=e,ja[ks++]=t,ja[ks++]=i,ja[ks++]=o,ao|=o,e.lanes|=o,e=e.alternate,e!==null&&(e.lanes|=o)}function ol(e,t,i,o){return hr(e,t,i,o),Vs(e)}function is(e,t){return hr(e,null,null,t),Vs(e)}function cl(e,t,i){e.lanes|=i;var o=e.alternate;o!==null&&(o.lanes|=i);for(var f=!1,h=e.return;h!==null;)h.childLanes|=i,o=h.alternate,o!==null&&(o.childLanes|=i),h.tag===22&&(e=h.stateNode,e===null||e._visibility&1||(f=!0)),e=h,h=h.return;return e.tag===3?(h=e.stateNode,f&&t!==null&&(f=31-gt(i),e=h.hiddenUpdates,o=e[f],o===null?e[f]=[t]:o.push(t),t.lane=i|536870912),h):null}function Vs(e){if(50<bc)throw bc=0,fm=null,Error(l(185));for(var t=e.return;t!==null;)e=t,t=e.return;return e.tag===3?e.stateNode:null}var As={};function pr(e,t,i,o){this.tag=e,this.key=i,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.refCleanup=this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=o,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function jn(e,t,i,o){return new pr(e,t,i,o)}function so(e){return e=e.prototype,!(!e||!e.isReactComponent)}function Vn(e,t){var i=e.alternate;return i===null?(i=jn(e.tag,t,e.key,e.mode),i.elementType=e.elementType,i.type=e.type,i.stateNode=e.stateNode,i.alternate=e,e.alternate=i):(i.pendingProps=t,i.type=e.type,i.flags=0,i.subtreeFlags=0,i.deletions=null),i.flags=e.flags&65011712,i.childLanes=e.childLanes,i.lanes=e.lanes,i.child=e.child,i.memoizedProps=e.memoizedProps,i.memoizedState=e.memoizedState,i.updateQueue=e.updateQueue,t=e.dependencies,i.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},i.sibling=e.sibling,i.index=e.index,i.ref=e.ref,i.refCleanup=e.refCleanup,i}function ul(e,t){e.flags&=65011714;var i=e.alternate;return i===null?(e.childLanes=0,e.lanes=t,e.child=null,e.subtreeFlags=0,e.memoizedProps=null,e.memoizedState=null,e.updateQueue=null,e.dependencies=null,e.stateNode=null):(e.childLanes=i.childLanes,e.lanes=i.lanes,e.child=i.child,e.subtreeFlags=0,e.deletions=null,e.memoizedProps=i.memoizedProps,e.memoizedState=i.memoizedState,e.updateQueue=i.updateQueue,e.type=i.type,t=i.dependencies,e.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext}),e}function gr(e,t,i,o,f,h){var S=0;if(o=e,typeof e=="function")so(e)&&(S=1);else if(typeof e=="string")S=jS(e,i,de.current)?26:e==="html"||e==="head"||e==="body"?27:5;else e:switch(e){case ae:return e=jn(31,i,t,f),e.elementType=ae,e.lanes=h,e;case A:return Ws(i.children,f,h,t);case N:S=8,f|=24;break;case k:return e=jn(12,i,t,f|2),e.elementType=k,e.lanes=h,e;case O:return e=jn(13,i,t,f),e.elementType=O,e.lanes=h,e;case Y:return e=jn(19,i,t,f),e.elementType=Y,e.lanes=h,e;default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case R:S=10;break e;case T:S=9;break e;case q:S=11;break e;case _:S=14;break e;case L:S=16,o=null;break e}S=29,i=Error(l(130,e===null?"null":typeof e,"")),o=null}return t=jn(S,i,t,f),t.elementType=e,t.type=o,t.lanes=h,t}function Ws(e,t,i,o){return e=jn(7,e,o,t),e.lanes=i,e}function ka(e,t,i){return e=jn(6,e,null,t),e.lanes=i,e}function tc(e){var t=jn(18,null,null,0);return t.stateNode=e,t}function Ci(e,t,i){return t=jn(4,e.children!==null?e.children:[],e.key,t),t.lanes=i,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}var vr=new WeakMap;function Aa(e,t){if(typeof e=="object"&&e!==null){var i=vr.get(e);return i!==void 0?i:(t={value:e,source:t,stack:$e(t)},vr.set(e,t),t)}return{value:e,source:t,stack:$e(t)}}var ji=[],fn=0,dl=null,Ys=0,aa=[],zn=0,Ks=null,Na=1,sa="";function Ns(e,t){ji[fn++]=Ys,ji[fn++]=dl,dl=e,Ys=t}function wu(e,t,i){aa[zn++]=Na,aa[zn++]=sa,aa[zn++]=Ks,Ks=e;var o=Na;e=sa;var f=32-gt(o)-1;o&=~(1<<f),i+=1;var h=32-gt(t)+f;if(30<h){var S=f-f%5;h=(o&(1<<S)-1).toString(32),o>>=S,f-=S,Na=1<<32-gt(t)+f|i<<f|o,sa=h+e}else Na=1<<h|i<<f|o,sa=e}function nc(e){e.return!==null&&(Ns(e,1),wu(e,1,0))}function ac(e){for(;e===dl;)dl=ji[--fn],ji[fn]=null,Ys=ji[--fn],ji[fn]=null;for(;e===Ks;)Ks=aa[--zn],aa[zn]=null,sa=aa[--zn],aa[zn]=null,Na=aa[--zn],aa[zn]=null}function io(e,t){aa[zn++]=Na,aa[zn++]=sa,aa[zn++]=Ks,Na=t.id,sa=t.overflow,Ks=e}var yn=null,Et=null,xt=!1,rs=null,Ma=!1,ki=Error(l(519));function Qs(e){var t=Error(l(418,1<arguments.length&&arguments[1]!==void 0&&arguments[1]?"text":"HTML",""));throw yr(Aa(t,e)),ki}function Su(e){var t=e.stateNode,i=e.type,o=e.memoizedProps;switch(t[ne]=e,t[Ae]=o,i){case"dialog":bt("cancel",t),bt("close",t);break;case"iframe":case"object":case"embed":bt("load",t);break;case"video":case"audio":for(i=0;i<Sc.length;i++)bt(Sc[i],t);break;case"source":bt("error",t);break;case"img":case"image":case"link":bt("error",t),bt("load",t);break;case"details":bt("toggle",t);break;case"input":bt("invalid",t),Xi(t,o.value,o.defaultValue,o.checked,o.defaultChecked,o.type,o.name,!0);break;case"select":bt("invalid",t);break;case"textarea":bt("invalid",t),fi(t,o.value,o.defaultValue,o.children)}i=o.children,typeof i!="string"&&typeof i!="number"&&typeof i!="bigint"||t.textContent===""+i||o.suppressHydrationWarning===!0||Sv(t.textContent,i)?(o.popover!=null&&(bt("beforetoggle",t),bt("toggle",t)),o.onScroll!=null&&bt("scroll",t),o.onScrollEnd!=null&&bt("scrollend",t),o.onClick!=null&&(t.onclick=Ln),t=!0):t=!1,t||Qs(e,!0)}function fl(e){for(yn=e.return;yn;)switch(yn.tag){case 5:case 31:case 13:Ma=!1;return;case 27:case 3:Ma=!0;return;default:yn=yn.return}}function xr(e){if(e!==yn)return!1;if(!xt)return fl(e),xt=!0,!1;var t=e.tag,i;if((i=t!==3&&t!==27)&&((i=t===5)&&(i=e.type,i=!(i!=="form"&&i!=="button")||Nm(e.type,e.memoizedProps)),i=!i),i&&Et&&Qs(e),fl(e),t===13){if(e=e.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(l(317));Et=Rv(e)}else if(t===31){if(e=e.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(l(317));Et=Rv(e)}else t===27?(t=Et,_r(e.type)?(e=Dm,Dm=null,Et=e):Et=t):Et=yn?cs(e.stateNode.nextSibling):null;return!0}function Xs(){Et=yn=null,xt=!1}function ro(){var e=rs;return e!==null&&(Da===null?Da=e:Da.push.apply(Da,e),rs=null),e}function yr(e){rs===null?rs=[e]:rs.push(e)}var sc=be(null),ls=null,In=null;function $a(e,t,i){$(sc,t._currentValue),t._currentValue=i}function Ms(e){e._currentValue=sc.current,X(sc)}function ml(e,t,i){for(;e!==null;){var o=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,o!==null&&(o.childLanes|=t)):o!==null&&(o.childLanes&t)!==t&&(o.childLanes|=t),e===i)break;e=e.return}}function hl(e,t,i,o){var f=e.child;for(f!==null&&(f.return=e);f!==null;){var h=f.dependencies;if(h!==null){var S=f.child;h=h.firstContext;e:for(;h!==null;){var E=h;h=f;for(var F=0;F<t.length;F++)if(E.context===t[F]){h.lanes|=i,E=h.alternate,E!==null&&(E.lanes|=i),ml(h.return,i,e),o||(S=null);break e}h=E.next}}else if(f.tag===18){if(S=f.return,S===null)throw Error(l(341));S.lanes|=i,h=S.alternate,h!==null&&(h.lanes|=i),ml(S,i,e),S=null}else S=f.child;if(S!==null)S.return=f;else for(S=f;S!==null;){if(S===e){S=null;break}if(f=S.sibling,f!==null){f.return=S.return,S=f;break}S=S.return}f=S}}function Me(e,t,i,o){e=null;for(var f=t,h=!1;f!==null;){if(!h){if((f.flags&524288)!==0)h=!0;else if((f.flags&262144)!==0)break}if(f.tag===10){var S=f.alternate;if(S===null)throw Error(l(387));if(S=S.memoizedProps,S!==null){var E=f.type;na(f.pendingProps.value,S.value)||(e!==null?e.push(E):e=[E])}}else if(f===Se.current){if(S=f.alternate,S===null)throw Error(l(387));S.memoizedState.memoizedState!==f.memoizedState.memoizedState&&(e!==null?e.push(Nc):e=[Nc])}f=f.return}e!==null&&hl(t,e,i,o),t.flags|=262144}function Ai(e){for(e=e.firstContext;e!==null;){if(!na(e.context._currentValue,e.memoizedValue))return!0;e=e.next}return!1}function Zs(e){ls=e,In=null,e=e.dependencies,e!==null&&(e.firstContext=null)}function En(e){return lo(ls,e)}function ic(e,t){return ls===null&&Zs(e),lo(e,t)}function lo(e,t){var i=t._currentValue;if(t={context:t,memoizedValue:i,next:null},In===null){if(e===null)throw Error(l(308));In=t,e.dependencies={lanes:0,firstContext:t},e.flags|=524288}else In=In.next=t;return i}var oo=typeof AbortController<"u"?AbortController:function(){var e=[],t=this.signal={aborted:!1,addEventListener:function(i,o){e.push(o)}};this.abort=function(){t.aborted=!0,e.forEach(function(i){return i()})}},Rn=n.unstable_scheduleCallback,ha=n.unstable_NormalPriority,Qe={$$typeof:R,Consumer:null,Provider:null,_currentValue:null,_currentValue2:null,_threadCount:0};function rc(){return{controller:new oo,data:new Map,refCount:0}}function os(e){e.refCount--,e.refCount===0&&Rn(ha,function(){e.controller.abort()})}var br=null,pl=0,wr=0,Sr=null;function Cu(e,t){if(br===null){var i=br=[];pl=0,wr=xm(),Sr={status:"pending",value:void 0,then:function(o){i.push(o)}}}return pl++,t.then(co,co),t}function co(){if(--pl===0&&br!==null){Sr!==null&&(Sr.status="fulfilled");var e=br;br=null,wr=0,Sr=null;for(var t=0;t<e.length;t++)(0,e[t])()}}function jf(e,t){var i=[],o={status:"pending",value:null,reason:null,then:function(f){i.push(f)}};return e.then(function(){o.status="fulfilled",o.value=t;for(var f=0;f<i.length;f++)(0,i[f])(t)},function(f){for(o.status="rejected",o.reason=f,f=0;f<i.length;f++)(0,i[f])(void 0)}),o}var ju=I.S;I.S=function(e,t){Vg=vt(),typeof t=="object"&&t!==null&&typeof t.then=="function"&&Cu(e,t),ju!==null&&ju(e,t)};var rn=be(null);function Cr(){var e=rn.current;return e!==null?e:qt.pooledCache}function gl(e,t){t===null?$(rn,rn.current):$(rn,t.pool)}function ku(){var e=Cr();return e===null?null:{parent:Qe._currentValue,pool:e}}var vl=Error(l(460)),lc=Error(l(474)),uo=Error(l(542)),xl={then:function(){}};function yl(e){return e=e.status,e==="fulfilled"||e==="rejected"}function jr(e,t,i){switch(i=e[i],i===void 0?e.push(t):i!==t&&(t.then(Ln,Ln),t=i),t.status){case"fulfilled":return t.value;case"rejected":throw e=t.reason,Nu(e),e;default:if(typeof t.status=="string")t.then(Ln,Ln);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,Nu(e),e}throw Ni=t,vl}}function Js(e){try{var t=e._init;return t(e._payload)}catch(i){throw i!==null&&typeof i=="object"&&typeof i.then=="function"?(Ni=i,vl):i}}var Ni=null;function Au(){if(Ni===null)throw Error(l(459));var e=Ni;return Ni=null,e}function Nu(e){if(e===vl||e===uo)throw Error(l(483))}var kr=null,bl=0;function fo(e){var t=bl;return bl+=1,kr===null&&(kr=[]),jr(kr,e,t)}function wl(e,t){t=t.props.ref,e.ref=t!==void 0?t:null}function Wn(e,t){throw t.$$typeof===b?Error(l(525)):(e=Object.prototype.toString.call(t),Error(l(31,e==="[object Object]"?"object with keys {"+Object.keys(t).join(", ")+"}":e)))}function Mu(e){function t(ee,V){if(e){var re=ee.deletions;re===null?(ee.deletions=[V],ee.flags|=16):re.push(V)}}function i(ee,V){if(!e)return null;for(;V!==null;)t(ee,V),V=V.sibling;return null}function o(ee){for(var V=new Map;ee!==null;)ee.key!==null?V.set(ee.key,ee):V.set(ee.index,ee),ee=ee.sibling;return V}function f(ee,V){return ee=Vn(ee,V),ee.index=0,ee.sibling=null,ee}function h(ee,V,re){return ee.index=re,e?(re=ee.alternate,re!==null?(re=re.index,re<V?(ee.flags|=67108866,V):re):(ee.flags|=67108866,V)):(ee.flags|=1048576,V)}function S(ee){return e&&ee.alternate===null&&(ee.flags|=67108866),ee}function E(ee,V,re,we){return V===null||V.tag!==6?(V=ka(re,ee.mode,we),V.return=ee,V):(V=f(V,re),V.return=ee,V)}function F(ee,V,re,we){var Je=re.type;return Je===A?xe(ee,V,re.props.children,we,re.key):V!==null&&(V.elementType===Je||typeof Je=="object"&&Je!==null&&Je.$$typeof===L&&Js(Je)===V.type)?(V=f(V,re.props),wl(V,re),V.return=ee,V):(V=gr(re.type,re.key,re.props,null,ee.mode,we),wl(V,re),V.return=ee,V)}function oe(ee,V,re,we){return V===null||V.tag!==4||V.stateNode.containerInfo!==re.containerInfo||V.stateNode.implementation!==re.implementation?(V=Ci(re,ee.mode,we),V.return=ee,V):(V=f(V,re.children||[]),V.return=ee,V)}function xe(ee,V,re,we,Je){return V===null||V.tag!==7?(V=Ws(re,ee.mode,we,Je),V.return=ee,V):(V=f(V,re),V.return=ee,V)}function Ce(ee,V,re){if(typeof V=="string"&&V!==""||typeof V=="number"||typeof V=="bigint")return V=ka(""+V,ee.mode,re),V.return=ee,V;if(typeof V=="object"&&V!==null){switch(V.$$typeof){case C:return re=gr(V.type,V.key,V.props,null,ee.mode,re),wl(re,V),re.return=ee,re;case j:return V=Ci(V,ee.mode,re),V.return=ee,V;case L:return V=Js(V),Ce(ee,V,re)}if(K(V)||P(V))return V=Ws(V,ee.mode,re,null),V.return=ee,V;if(typeof V.then=="function")return Ce(ee,fo(V),re);if(V.$$typeof===R)return Ce(ee,ic(ee,V),re);Wn(ee,V)}return null}function ce(ee,V,re,we){var Je=V!==null?V.key:null;if(typeof re=="string"&&re!==""||typeof re=="number"||typeof re=="bigint")return Je!==null?null:E(ee,V,""+re,we);if(typeof re=="object"&&re!==null){switch(re.$$typeof){case C:return re.key===Je?F(ee,V,re,we):null;case j:return re.key===Je?oe(ee,V,re,we):null;case L:return re=Js(re),ce(ee,V,re,we)}if(K(re)||P(re))return Je!==null?null:xe(ee,V,re,we,null);if(typeof re.then=="function")return ce(ee,V,fo(re),we);if(re.$$typeof===R)return ce(ee,V,ic(ee,re),we);Wn(ee,re)}return null}function he(ee,V,re,we,Je){if(typeof we=="string"&&we!==""||typeof we=="number"||typeof we=="bigint")return ee=ee.get(re)||null,E(V,ee,""+we,Je);if(typeof we=="object"&&we!==null){switch(we.$$typeof){case C:return ee=ee.get(we.key===null?re:we.key)||null,F(V,ee,we,Je);case j:return ee=ee.get(we.key===null?re:we.key)||null,oe(V,ee,we,Je);case L:return we=Js(we),he(ee,V,re,we,Je)}if(K(we)||P(we))return ee=ee.get(re)||null,xe(V,ee,we,Je,null);if(typeof we.then=="function")return he(ee,V,re,fo(we),Je);if(we.$$typeof===R)return he(ee,V,re,ic(V,we),Je);Wn(V,we)}return null}function Ve(ee,V,re,we){for(var Je=null,At=null,We=V,pt=V=0,Ct=null;We!==null&&pt<re.length;pt++){We.index>pt?(Ct=We,We=null):Ct=We.sibling;var Nt=ce(ee,We,re[pt],we);if(Nt===null){We===null&&(We=Ct);break}e&&We&&Nt.alternate===null&&t(ee,We),V=h(Nt,V,pt),At===null?Je=Nt:At.sibling=Nt,At=Nt,We=Ct}if(pt===re.length)return i(ee,We),xt&&Ns(ee,pt),Je;if(We===null){for(;pt<re.length;pt++)We=Ce(ee,re[pt],we),We!==null&&(V=h(We,V,pt),At===null?Je=We:At.sibling=We,At=We);return xt&&Ns(ee,pt),Je}for(We=o(We);pt<re.length;pt++)Ct=he(We,ee,pt,re[pt],we),Ct!==null&&(e&&Ct.alternate!==null&&We.delete(Ct.key===null?pt:Ct.key),V=h(Ct,V,pt),At===null?Je=Ct:At.sibling=Ct,At=Ct);return e&&We.forEach(function(Br){return t(ee,Br)}),xt&&Ns(ee,pt),Je}function nt(ee,V,re,we){if(re==null)throw Error(l(151));for(var Je=null,At=null,We=V,pt=V=0,Ct=null,Nt=re.next();We!==null&&!Nt.done;pt++,Nt=re.next()){We.index>pt?(Ct=We,We=null):Ct=We.sibling;var Br=ce(ee,We,Nt.value,we);if(Br===null){We===null&&(We=Ct);break}e&&We&&Br.alternate===null&&t(ee,We),V=h(Br,V,pt),At===null?Je=Br:At.sibling=Br,At=Br,We=Ct}if(Nt.done)return i(ee,We),xt&&Ns(ee,pt),Je;if(We===null){for(;!Nt.done;pt++,Nt=re.next())Nt=Ce(ee,Nt.value,we),Nt!==null&&(V=h(Nt,V,pt),At===null?Je=Nt:At.sibling=Nt,At=Nt);return xt&&Ns(ee,pt),Je}for(We=o(We);!Nt.done;pt++,Nt=re.next())Nt=he(We,ee,pt,Nt.value,we),Nt!==null&&(e&&Nt.alternate!==null&&We.delete(Nt.key===null?pt:Nt.key),V=h(Nt,V,pt),At===null?Je=Nt:At.sibling=Nt,At=Nt);return e&&We.forEach(function(zS){return t(ee,zS)}),xt&&Ns(ee,pt),Je}function Pt(ee,V,re,we){if(typeof re=="object"&&re!==null&&re.type===A&&re.key===null&&(re=re.props.children),typeof re=="object"&&re!==null){switch(re.$$typeof){case C:e:{for(var Je=re.key;V!==null;){if(V.key===Je){if(Je=re.type,Je===A){if(V.tag===7){i(ee,V.sibling),we=f(V,re.props.children),we.return=ee,ee=we;break e}}else if(V.elementType===Je||typeof Je=="object"&&Je!==null&&Je.$$typeof===L&&Js(Je)===V.type){i(ee,V.sibling),we=f(V,re.props),wl(we,re),we.return=ee,ee=we;break e}i(ee,V);break}else t(ee,V);V=V.sibling}re.type===A?(we=Ws(re.props.children,ee.mode,we,re.key),we.return=ee,ee=we):(we=gr(re.type,re.key,re.props,null,ee.mode,we),wl(we,re),we.return=ee,ee=we)}return S(ee);case j:e:{for(Je=re.key;V!==null;){if(V.key===Je)if(V.tag===4&&V.stateNode.containerInfo===re.containerInfo&&V.stateNode.implementation===re.implementation){i(ee,V.sibling),we=f(V,re.children||[]),we.return=ee,ee=we;break e}else{i(ee,V);break}else t(ee,V);V=V.sibling}we=Ci(re,ee.mode,we),we.return=ee,ee=we}return S(ee);case L:return re=Js(re),Pt(ee,V,re,we)}if(K(re))return Ve(ee,V,re,we);if(P(re)){if(Je=P(re),typeof Je!="function")throw Error(l(150));return re=Je.call(re),nt(ee,V,re,we)}if(typeof re.then=="function")return Pt(ee,V,fo(re),we);if(re.$$typeof===R)return Pt(ee,V,ic(ee,re),we);Wn(ee,re)}return typeof re=="string"&&re!==""||typeof re=="number"||typeof re=="bigint"?(re=""+re,V!==null&&V.tag===6?(i(ee,V.sibling),we=f(V,re),we.return=ee,ee=we):(i(ee,V),we=ka(re,ee.mode,we),we.return=ee,ee=we),S(ee)):i(ee,V)}return function(ee,V,re,we){try{bl=0;var Je=Pt(ee,V,re,we);return kr=null,Je}catch(We){if(We===vl||We===uo)throw We;var At=jn(29,We,null,ee.mode);return At.lanes=we,At.return=ee,At}}}var Mi=Mu(!0),Ti=Mu(!1),ei=!1;function Sl(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function ti(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 ni(e){return{lane:e,tag:0,payload:null,callback:null,next:null}}function ia(e,t,i){var o=e.updateQueue;if(o===null)return null;if(o=o.shared,(Rt&2)!==0){var f=o.pending;return f===null?t.next=t:(t.next=f.next,f.next=t),o.pending=t,t=Vs(e),cl(e,null,i),t}return hr(e,o,t,i),Vs(e)}function Ei(e,t,i){if(t=t.updateQueue,t!==null&&(t=t.shared,(i&4194048)!==0)){var o=t.lanes;o&=e.pendingLanes,i|=o,t.lanes=i,H(e,i)}}function x(e,t){var i=e.updateQueue,o=e.alternate;if(o!==null&&(o=o.updateQueue,i===o)){var f=null,h=null;if(i=i.firstBaseUpdate,i!==null){do{var S={lane:i.lane,tag:i.tag,payload:i.payload,callback:null,next:null};h===null?f=h=S:h=h.next=S,i=i.next}while(i!==null);h===null?f=h=t:h=h.next=t}else f=h=t;i={baseState:o.baseState,firstBaseUpdate:f,lastBaseUpdate:h,shared:o.shared,callbacks:o.callbacks},e.updateQueue=i;return}e=i.lastBaseUpdate,e===null?i.firstBaseUpdate=t:e.next=t,i.lastBaseUpdate=t}var M=!1;function D(){if(M){var e=Sr;if(e!==null)throw e}}function B(e,t,i,o){M=!1;var f=e.updateQueue;ei=!1;var h=f.firstBaseUpdate,S=f.lastBaseUpdate,E=f.shared.pending;if(E!==null){f.shared.pending=null;var F=E,oe=F.next;F.next=null,S===null?h=oe:S.next=oe,S=F;var xe=e.alternate;xe!==null&&(xe=xe.updateQueue,E=xe.lastBaseUpdate,E!==S&&(E===null?xe.firstBaseUpdate=oe:E.next=oe,xe.lastBaseUpdate=F))}if(h!==null){var Ce=f.baseState;S=0,xe=oe=F=null,E=h;do{var ce=E.lane&-536870913,he=ce!==E.lane;if(he?(St&ce)===ce:(o&ce)===ce){ce!==0&&ce===wr&&(M=!0),xe!==null&&(xe=xe.next={lane:0,tag:E.tag,payload:E.payload,callback:null,next:null});e:{var Ve=e,nt=E;ce=t;var Pt=i;switch(nt.tag){case 1:if(Ve=nt.payload,typeof Ve=="function"){Ce=Ve.call(Pt,Ce,ce);break e}Ce=Ve;break e;case 3:Ve.flags=Ve.flags&-65537|128;case 0:if(Ve=nt.payload,ce=typeof Ve=="function"?Ve.call(Pt,Ce,ce):Ve,ce==null)break e;Ce=y({},Ce,ce);break e;case 2:ei=!0}}ce=E.callback,ce!==null&&(e.flags|=64,he&&(e.flags|=8192),he=f.callbacks,he===null?f.callbacks=[ce]:he.push(ce))}else he={lane:ce,tag:E.tag,payload:E.payload,callback:E.callback,next:null},xe===null?(oe=xe=he,F=Ce):xe=xe.next=he,S|=ce;if(E=E.next,E===null){if(E=f.shared.pending,E===null)break;he=E,E=he.next,he.next=null,f.lastBaseUpdate=he,f.shared.pending=null}}while(!0);xe===null&&(F=Ce),f.baseState=F,f.firstBaseUpdate=oe,f.lastBaseUpdate=xe,h===null&&(f.shared.lanes=0),Tr|=S,e.lanes=S,e.memoizedState=Ce}}function z(e,t){if(typeof e!="function")throw Error(l(191,e));e.call(t)}function ge(e,t){var i=e.callbacks;if(i!==null)for(e.callbacks=null,e=0;e<i.length;e++)z(i[e],t)}var pe=be(null),Ie=be(0);function Ue(e,t){e=Bi,$(Ie,e),$(pe,t),Bi=e|t.baseLanes}function Ke(){$(Ie,Bi),$(pe,pe.current)}function en(){Bi=Ie.current,X(pe),X(Ie)}var Dt=be(null),tn=null;function Ua(e){var t=e.alternate;$(bn,bn.current&1),$(Dt,e),tn===null&&(t===null||pe.current!==null||t.memoizedState!==null)&&(tn=e)}function Ar(e){$(bn,bn.current),$(Dt,e),tn===null&&(tn=e)}function Tu(e){e.tag===22?($(bn,bn.current),$(Dt,e),tn===null&&(tn=e)):qa()}function qa(){$(bn,bn.current),$(Dt,Dt.current)}function pa(e){X(Dt),tn===e&&(tn=null),X(bn)}var bn=be(0);function Eu(e){for(var t=e;t!==null;){if(t.tag===13){var i=t.memoizedState;if(i!==null&&(i=i.dehydrated,i===null||Em(i)||Rm(i)))return t}else if(t.tag===19&&(t.memoizedProps.revealOrder==="forwards"||t.memoizedProps.revealOrder==="backwards"||t.memoizedProps.revealOrder==="unstable_legacy-backwards"||t.memoizedProps.revealOrder==="together")){if((t.flags&128)!==0)return t}else if(t.child!==null){t.child.return=t,t=t.child;continue}if(t===e)break;for(;t.sibling===null;){if(t.return===null||t.return===e)return null;t=t.return}t.sibling.return=t.return,t=t.sibling}return null}var Ri=0,dt=null,Bt=null,kn=null,Ru=!1,mo=!1,Cl=!1,Du=0,oc=0,ho=null,kw=0;function mn(){throw Error(l(321))}function kf(e,t){if(t===null)return!1;for(var i=0;i<t.length&&i<e.length;i++)if(!na(e[i],t[i]))return!1;return!0}function Af(e,t,i,o,f,h){return Ri=h,dt=t,t.memoizedState=null,t.updateQueue=null,t.lanes=0,I.H=e===null||e.memoizedState===null?ag:Pf,Cl=!1,h=i(o,f),Cl=!1,mo&&(h=Sp(t,i,o,f)),wp(e),h}function wp(e){I.H=dc;var t=Bt!==null&&Bt.next!==null;if(Ri=0,kn=Bt=dt=null,Ru=!1,oc=0,ho=null,t)throw Error(l(300));e===null||An||(e=e.dependencies,e!==null&&Ai(e)&&(An=!0))}function Sp(e,t,i,o){dt=e;var f=0;do{if(mo&&(ho=null),oc=0,mo=!1,25<=f)throw Error(l(301));if(f+=1,kn=Bt=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=sg,h=t(i,o)}while(mo);return h}function Aw(){var e=I.H,t=e.useState()[0];return t=typeof t.then=="function"?cc(t):t,e=e.useState()[0],(Bt!==null?Bt.memoizedState:null)!==e&&(dt.flags|=1024),t}function Nf(){var e=Du!==0;return Du=0,e}function Mf(e,t,i){t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~i}function Tf(e){if(Ru){for(e=e.memoizedState;e!==null;){var t=e.queue;t!==null&&(t.pending=null),e=e.next}Ru=!1}Ri=0,kn=Bt=dt=null,mo=!1,oc=Du=0,ho=null}function ga(){var e={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return kn===null?dt.memoizedState=kn=e:kn=kn.next=e,kn}function wn(){if(Bt===null){var e=dt.alternate;e=e!==null?e.memoizedState:null}else e=Bt.next;var t=kn===null?dt.memoizedState:kn.next;if(t!==null)kn=t,Bt=e;else{if(e===null)throw dt.alternate===null?Error(l(467)):Error(l(310));Bt=e,e={memoizedState:Bt.memoizedState,baseState:Bt.baseState,baseQueue:Bt.baseQueue,queue:Bt.queue,next:null},kn===null?dt.memoizedState=kn=e:kn=kn.next=e}return kn}function Lu(){return{lastEffect:null,events:null,stores:null,memoCache:null}}function cc(e){var t=oc;return oc+=1,ho===null&&(ho=[]),e=jr(ho,e,t),t=dt,(kn===null?t.memoizedState:kn.next)===null&&(t=t.alternate,I.H=t===null||t.memoizedState===null?ag:Pf),e}function _u(e){if(e!==null&&typeof e=="object"){if(typeof e.then=="function")return cc(e);if(e.$$typeof===R)return En(e)}throw Error(l(438,String(e)))}function Ef(e){var t=null,i=dt.updateQueue;if(i!==null&&(t=i.memoCache),t==null){var o=dt.alternate;o!==null&&(o=o.updateQueue,o!==null&&(o=o.memoCache,o!=null&&(t={data:o.data.map(function(f){return f.slice()}),index:0})))}if(t==null&&(t={data:[],index:0}),i===null&&(i=Lu(),dt.updateQueue=i),i.memoCache=t,i=t.data[t.index],i===void 0)for(i=t.data[t.index]=Array(e),o=0;o<e;o++)i[o]=G;return t.index++,i}function Di(e,t){return typeof t=="function"?t(e):t}function zu(e){var t=wn();return Rf(t,Bt,e)}function Rf(e,t,i){var o=e.queue;if(o===null)throw Error(l(311));o.lastRenderedReducer=i;var f=e.baseQueue,h=o.pending;if(h!==null){if(f!==null){var S=f.next;f.next=h.next,h.next=S}t.baseQueue=f=h,o.pending=null}if(h=e.baseState,f===null)e.memoizedState=h;else{t=f.next;var E=S=null,F=null,oe=t,xe=!1;do{var Ce=oe.lane&-536870913;if(Ce!==oe.lane?(St&Ce)===Ce:(Ri&Ce)===Ce){var ce=oe.revertLane;if(ce===0)F!==null&&(F=F.next={lane:0,revertLane:0,gesture:null,action:oe.action,hasEagerState:oe.hasEagerState,eagerState:oe.eagerState,next:null}),Ce===wr&&(xe=!0);else if((Ri&ce)===ce){oe=oe.next,ce===wr&&(xe=!0);continue}else Ce={lane:0,revertLane:oe.revertLane,gesture:null,action:oe.action,hasEagerState:oe.hasEagerState,eagerState:oe.eagerState,next:null},F===null?(E=F=Ce,S=h):F=F.next=Ce,dt.lanes|=ce,Tr|=ce;Ce=oe.action,Cl&&i(h,Ce),h=oe.hasEagerState?oe.eagerState:i(h,Ce)}else ce={lane:Ce,revertLane:oe.revertLane,gesture:oe.gesture,action:oe.action,hasEagerState:oe.hasEagerState,eagerState:oe.eagerState,next:null},F===null?(E=F=ce,S=h):F=F.next=ce,dt.lanes|=Ce,Tr|=Ce;oe=oe.next}while(oe!==null&&oe!==t);if(F===null?S=h:F.next=E,!na(h,e.memoizedState)&&(An=!0,xe&&(i=Sr,i!==null)))throw i;e.memoizedState=h,e.baseState=S,e.baseQueue=F,o.lastRenderedState=h}return f===null&&(o.lanes=0),[e.memoizedState,o.dispatch]}function Df(e){var t=wn(),i=t.queue;if(i===null)throw Error(l(311));i.lastRenderedReducer=e;var o=i.dispatch,f=i.pending,h=t.memoizedState;if(f!==null){i.pending=null;var S=f=f.next;do h=e(h,S.action),S=S.next;while(S!==f);na(h,t.memoizedState)||(An=!0),t.memoizedState=h,t.baseQueue===null&&(t.baseState=h),i.lastRenderedState=h}return[h,o]}function Cp(e,t,i){var o=dt,f=wn(),h=xt;if(h){if(i===void 0)throw Error(l(407));i=i()}else i=t();var S=!na((Bt||f).memoizedState,i);if(S&&(f.memoizedState=i,An=!0),f=f.queue,zf(Ap.bind(null,o,f,e),[e]),f.getSnapshot!==t||S||kn!==null&&kn.memoizedState.tag&1){if(o.flags|=2048,po(9,{destroy:void 0},kp.bind(null,o,f,i,t),null),qt===null)throw Error(l(349));h||(Ri&127)!==0||jp(o,t,i)}return i}function jp(e,t,i){e.flags|=16384,e={getSnapshot:t,value:i},t=dt.updateQueue,t===null?(t=Lu(),dt.updateQueue=t,t.stores=[e]):(i=t.stores,i===null?t.stores=[e]:i.push(e))}function kp(e,t,i,o){t.value=i,t.getSnapshot=o,Np(t)&&Mp(e)}function Ap(e,t,i){return i(function(){Np(t)&&Mp(e)})}function Np(e){var t=e.getSnapshot;e=e.value;try{var i=t();return!na(e,i)}catch{return!0}}function Mp(e){var t=is(e,2);t!==null&&La(t,e,2)}function Lf(e){var t=ga();if(typeof e=="function"){var i=e;if(e=i(),Cl){Xe(!0);try{i()}finally{Xe(!1)}}}return t.memoizedState=t.baseState=e,t.queue={pending:null,lanes:0,dispatch:null,lastRenderedReducer:Di,lastRenderedState:e},t}function Tp(e,t,i,o){return e.baseState=i,Rf(e,Bt,typeof o=="function"?o:Di)}function Nw(e,t,i,o,f){if(Hu(e))throw Error(l(485));if(e=t.action,e!==null){var h={payload:f,action:e,next:null,isTransition:!0,status:"pending",value:null,reason:null,listeners:[],then:function(S){h.listeners.push(S)}};I.T!==null?i(!0):h.isTransition=!1,o(h),i=t.pending,i===null?(h.next=t.pending=h,Ep(t,h)):(h.next=i.next,t.pending=i.next=h)}}function Ep(e,t){var i=t.action,o=t.payload,f=e.state;if(t.isTransition){var h=I.T,S={};I.T=S;try{var E=i(f,o),F=I.S;F!==null&&F(S,E),Rp(e,t,E)}catch(oe){_f(e,t,oe)}finally{h!==null&&S.types!==null&&(h.types=S.types),I.T=h}}else try{h=i(f,o),Rp(e,t,h)}catch(oe){_f(e,t,oe)}}function Rp(e,t,i){i!==null&&typeof i=="object"&&typeof i.then=="function"?i.then(function(o){Dp(e,t,o)},function(o){return _f(e,t,o)}):Dp(e,t,i)}function Dp(e,t,i){t.status="fulfilled",t.value=i,Lp(t),e.state=i,t=e.pending,t!==null&&(i=t.next,i===t?e.pending=null:(i=i.next,t.next=i,Ep(e,i)))}function _f(e,t,i){var o=e.pending;if(e.pending=null,o!==null){o=o.next;do t.status="rejected",t.reason=i,Lp(t),t=t.next;while(t!==o)}e.action=null}function Lp(e){e=e.listeners;for(var t=0;t<e.length;t++)(0,e[t])()}function _p(e,t){return t}function zp(e,t){if(xt){var i=qt.formState;if(i!==null){e:{var o=dt;if(xt){if(Et){t:{for(var f=Et,h=Ma;f.nodeType!==8;){if(!h){f=null;break t}if(f=cs(f.nextSibling),f===null){f=null;break t}}h=f.data,f=h==="F!"||h==="F"?f:null}if(f){Et=cs(f.nextSibling),o=f.data==="F!";break e}}Qs(o)}o=!1}o&&(t=i[0])}}return i=ga(),i.memoizedState=i.baseState=t,o={pending:null,lanes:0,dispatch:null,lastRenderedReducer:_p,lastRenderedState:t},i.queue=o,i=eg.bind(null,dt,o),o.dispatch=i,o=Lf(!1),h=Ff.bind(null,dt,!1,o.queue),o=ga(),f={state:t,dispatch:null,action:e,pending:null},o.queue=f,i=Nw.bind(null,dt,f,h,i),f.dispatch=i,o.memoizedState=e,[t,i,!1]}function Ip(e){var t=wn();return Op(t,Bt,e)}function Op(e,t,i){if(t=Rf(e,t,_p)[0],e=zu(Di)[0],typeof t=="object"&&t!==null&&typeof t.then=="function")try{var o=cc(t)}catch(S){throw S===vl?uo:S}else o=t;t=wn();var f=t.queue,h=f.dispatch;return i!==t.memoizedState&&(dt.flags|=2048,po(9,{destroy:void 0},Mw.bind(null,f,i),null)),[o,h,e]}function Mw(e,t){e.action=t}function Hp(e){var t=wn(),i=Bt;if(i!==null)return Op(t,i,e);wn(),t=t.memoizedState,i=wn();var o=i.queue.dispatch;return i.memoizedState=e,[t,o,!1]}function po(e,t,i,o){return e={tag:e,create:i,deps:o,inst:t,next:null},t=dt.updateQueue,t===null&&(t=Lu(),dt.updateQueue=t),i=t.lastEffect,i===null?t.lastEffect=e.next=e:(o=i.next,i.next=e,e.next=o,t.lastEffect=e),e}function Bp(){return wn().memoizedState}function Iu(e,t,i,o){var f=ga();dt.flags|=e,f.memoizedState=po(1|t,{destroy:void 0},i,o===void 0?null:o)}function Ou(e,t,i,o){var f=wn();o=o===void 0?null:o;var h=f.memoizedState.inst;Bt!==null&&o!==null&&kf(o,Bt.memoizedState.deps)?f.memoizedState=po(t,h,i,o):(dt.flags|=e,f.memoizedState=po(1|t,h,i,o))}function Fp(e,t){Iu(8390656,8,e,t)}function zf(e,t){Ou(2048,8,e,t)}function Tw(e){dt.flags|=4;var t=dt.updateQueue;if(t===null)t=Lu(),dt.updateQueue=t,t.events=[e];else{var i=t.events;i===null?t.events=[e]:i.push(e)}}function Pp(e){var t=wn().memoizedState;return Tw({ref:t,nextImpl:e}),function(){if((Rt&2)!==0)throw Error(l(440));return t.impl.apply(void 0,arguments)}}function $p(e,t){return Ou(4,2,e,t)}function Up(e,t){return Ou(4,4,e,t)}function qp(e,t){if(typeof t=="function"){e=e();var i=t(e);return function(){typeof i=="function"?i():t(null)}}if(t!=null)return e=e(),t.current=e,function(){t.current=null}}function Gp(e,t,i){i=i!=null?i.concat([e]):null,Ou(4,4,qp.bind(null,t,e),i)}function If(){}function Vp(e,t){var i=wn();t=t===void 0?null:t;var o=i.memoizedState;return t!==null&&kf(t,o[1])?o[0]:(i.memoizedState=[e,t],e)}function Wp(e,t){var i=wn();t=t===void 0?null:t;var o=i.memoizedState;if(t!==null&&kf(t,o[1]))return o[0];if(o=e(),Cl){Xe(!0);try{e()}finally{Xe(!1)}}return i.memoizedState=[o,t],o}function Of(e,t,i){return i===void 0||(Ri&1073741824)!==0&&(St&261930)===0?e.memoizedState=t:(e.memoizedState=i,e=Yg(),dt.lanes|=e,Tr|=e,i)}function Yp(e,t,i,o){return na(i,t)?i:pe.current!==null?(e=Of(e,i,o),na(e,t)||(An=!0),e):(Ri&42)===0||(Ri&1073741824)!==0&&(St&261930)===0?(An=!0,e.memoizedState=i):(e=Yg(),dt.lanes|=e,Tr|=e,t)}function Kp(e,t,i,o,f){var h=Q.p;Q.p=h!==0&&8>h?h:8;var S=I.T,E={};I.T=E,Ff(e,!1,t,i);try{var F=f(),oe=I.S;if(oe!==null&&oe(E,F),F!==null&&typeof F=="object"&&typeof F.then=="function"){var xe=jf(F,o);uc(e,t,xe,Wa(e))}else uc(e,t,o,Wa(e))}catch(Ce){uc(e,t,{then:function(){},status:"rejected",reason:Ce},Wa())}finally{Q.p=h,S!==null&&E.types!==null&&(S.types=E.types),I.T=S}}function Ew(){}function Hf(e,t,i,o){if(e.tag!==5)throw Error(l(476));var f=Qp(e).queue;Kp(e,f,t,U,i===null?Ew:function(){return Xp(e),i(o)})}function Qp(e){var t=e.memoizedState;if(t!==null)return t;t={memoizedState:U,baseState:U,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Di,lastRenderedState:U},next:null};var i={};return t.next={memoizedState:i,baseState:i,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Di,lastRenderedState:i},next:null},e.memoizedState=t,e=e.alternate,e!==null&&(e.memoizedState=t),t}function Xp(e){var t=Qp(e);t.next===null&&(t=e.alternate.memoizedState),uc(e,t.next.queue,{},Wa())}function Bf(){return En(Nc)}function Zp(){return wn().memoizedState}function Jp(){return wn().memoizedState}function Rw(e){for(var t=e.return;t!==null;){switch(t.tag){case 24:case 3:var i=Wa();e=ni(i);var o=ia(t,e,i);o!==null&&(La(o,t,i),Ei(o,t,i)),t={cache:rc()},e.payload=t;return}t=t.return}}function Dw(e,t,i){var o=Wa();i={lane:o,revertLane:0,gesture:null,action:i,hasEagerState:!1,eagerState:null,next:null},Hu(e)?tg(t,i):(i=ol(e,t,i,o),i!==null&&(La(i,e,o),ng(i,t,o)))}function eg(e,t,i){var o=Wa();uc(e,t,i,o)}function uc(e,t,i,o){var f={lane:o,revertLane:0,gesture:null,action:i,hasEagerState:!1,eagerState:null,next:null};if(Hu(e))tg(t,f);else{var h=e.alternate;if(e.lanes===0&&(h===null||h.lanes===0)&&(h=t.lastRenderedReducer,h!==null))try{var S=t.lastRenderedState,E=h(S,i);if(f.hasEagerState=!0,f.eagerState=E,na(E,S))return hr(e,t,f,0),qt===null&&Si(),!1}catch{}if(i=ol(e,t,f,o),i!==null)return La(i,e,o),ng(i,t,o),!0}return!1}function Ff(e,t,i,o){if(o={lane:2,revertLane:xm(),gesture:null,action:o,hasEagerState:!1,eagerState:null,next:null},Hu(e)){if(t)throw Error(l(479))}else t=ol(e,i,o,2),t!==null&&La(t,e,2)}function Hu(e){var t=e.alternate;return e===dt||t!==null&&t===dt}function tg(e,t){mo=Ru=!0;var i=e.pending;i===null?t.next=t:(t.next=i.next,i.next=t),e.pending=t}function ng(e,t,i){if((i&4194048)!==0){var o=t.lanes;o&=e.pendingLanes,i|=o,t.lanes=i,H(e,i)}}var dc={readContext:En,use:_u,useCallback:mn,useContext:mn,useEffect:mn,useImperativeHandle:mn,useLayoutEffect:mn,useInsertionEffect:mn,useMemo:mn,useReducer:mn,useRef:mn,useState:mn,useDebugValue:mn,useDeferredValue:mn,useTransition:mn,useSyncExternalStore:mn,useId:mn,useHostTransitionStatus:mn,useFormState:mn,useActionState:mn,useOptimistic:mn,useMemoCache:mn,useCacheRefresh:mn};dc.useEffectEvent=mn;var ag={readContext:En,use:_u,useCallback:function(e,t){return ga().memoizedState=[e,t===void 0?null:t],e},useContext:En,useEffect:Fp,useImperativeHandle:function(e,t,i){i=i!=null?i.concat([e]):null,Iu(4194308,4,qp.bind(null,t,e),i)},useLayoutEffect:function(e,t){return Iu(4194308,4,e,t)},useInsertionEffect:function(e,t){Iu(4,2,e,t)},useMemo:function(e,t){var i=ga();t=t===void 0?null:t;var o=e();if(Cl){Xe(!0);try{e()}finally{Xe(!1)}}return i.memoizedState=[o,t],o},useReducer:function(e,t,i){var o=ga();if(i!==void 0){var f=i(t);if(Cl){Xe(!0);try{i(t)}finally{Xe(!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,dt,e),[o.memoizedState,e]},useRef:function(e){var t=ga();return e={current:e},t.memoizedState=e},useState:function(e){e=Lf(e);var t=e.queue,i=eg.bind(null,dt,t);return t.dispatch=i,[e.memoizedState,i]},useDebugValue:If,useDeferredValue:function(e,t){var i=ga();return Of(i,e,t)},useTransition:function(){var e=Lf(!1);return e=Kp.bind(null,dt,e.queue,!0,!1),ga().memoizedState=e,[!1,e]},useSyncExternalStore:function(e,t,i){var o=dt,f=ga();if(xt){if(i===void 0)throw Error(l(407));i=i()}else{if(i=t(),qt===null)throw Error(l(349));(St&127)!==0||jp(o,t,i)}f.memoizedState=i;var h={value:i,getSnapshot:t};return f.queue=h,Fp(Ap.bind(null,o,h,e),[e]),o.flags|=2048,po(9,{destroy:void 0},kp.bind(null,o,h,i,t),null),i},useId:function(){var e=ga(),t=qt.identifierPrefix;if(xt){var i=sa,o=Na;i=(o&~(1<<32-gt(o)-1)).toString(32)+i,t="_"+t+"R_"+i,i=Du++,0<i&&(t+="H"+i.toString(32)),t+="_"}else i=kw++,t="_"+t+"r_"+i.toString(32)+"_";return e.memoizedState=t},useHostTransitionStatus:Bf,useFormState:zp,useActionState:zp,useOptimistic:function(e){var t=ga();t.memoizedState=t.baseState=e;var i={pending:null,lanes:0,dispatch:null,lastRenderedReducer:null,lastRenderedState:null};return t.queue=i,t=Ff.bind(null,dt,!0,i),i.dispatch=t,[e,t]},useMemoCache:Ef,useCacheRefresh:function(){return ga().memoizedState=Rw.bind(null,dt)},useEffectEvent:function(e){var t=ga(),i={impl:e};return t.memoizedState=i,function(){if((Rt&2)!==0)throw Error(l(440));return i.impl.apply(void 0,arguments)}}},Pf={readContext:En,use:_u,useCallback:Vp,useContext:En,useEffect:zf,useImperativeHandle:Gp,useInsertionEffect:$p,useLayoutEffect:Up,useMemo:Wp,useReducer:zu,useRef:Bp,useState:function(){return zu(Di)},useDebugValue:If,useDeferredValue:function(e,t){var i=wn();return Yp(i,Bt.memoizedState,e,t)},useTransition:function(){var e=zu(Di)[0],t=wn().memoizedState;return[typeof e=="boolean"?e:cc(e),t]},useSyncExternalStore:Cp,useId:Zp,useHostTransitionStatus:Bf,useFormState:Ip,useActionState:Ip,useOptimistic:function(e,t){var i=wn();return Tp(i,Bt,e,t)},useMemoCache:Ef,useCacheRefresh:Jp};Pf.useEffectEvent=Pp;var sg={readContext:En,use:_u,useCallback:Vp,useContext:En,useEffect:zf,useImperativeHandle:Gp,useInsertionEffect:$p,useLayoutEffect:Up,useMemo:Wp,useReducer:Df,useRef:Bp,useState:function(){return Df(Di)},useDebugValue:If,useDeferredValue:function(e,t){var i=wn();return Bt===null?Of(i,e,t):Yp(i,Bt.memoizedState,e,t)},useTransition:function(){var e=Df(Di)[0],t=wn().memoizedState;return[typeof e=="boolean"?e:cc(e),t]},useSyncExternalStore:Cp,useId:Zp,useHostTransitionStatus:Bf,useFormState:Hp,useActionState:Hp,useOptimistic:function(e,t){var i=wn();return Bt!==null?Tp(i,Bt,e,t):(i.baseState=e,[e,i.queue.dispatch])},useMemoCache:Ef,useCacheRefresh:Jp};sg.useEffectEvent=Pp;function $f(e,t,i,o){t=e.memoizedState,i=i(o,t),i=i==null?t:y({},t,i),e.memoizedState=i,e.lanes===0&&(e.updateQueue.baseState=i)}var Uf={enqueueSetState:function(e,t,i){e=e._reactInternals;var o=Wa(),f=ni(o);f.payload=t,i!=null&&(f.callback=i),t=ia(e,f,o),t!==null&&(La(t,e,o),Ei(t,e,o))},enqueueReplaceState:function(e,t,i){e=e._reactInternals;var o=Wa(),f=ni(o);f.tag=1,f.payload=t,i!=null&&(f.callback=i),t=ia(e,f,o),t!==null&&(La(t,e,o),Ei(t,e,o))},enqueueForceUpdate:function(e,t){e=e._reactInternals;var i=Wa(),o=ni(i);o.tag=2,t!=null&&(o.callback=t),t=ia(e,o,i),t!==null&&(La(t,e,i),Ei(t,e,i))}};function ig(e,t,i,o,f,h,S){return e=e.stateNode,typeof e.shouldComponentUpdate=="function"?e.shouldComponentUpdate(o,h,S):t.prototype&&t.prototype.isPureReactComponent?!nl(i,o)||!nl(f,h):!0}function rg(e,t,i,o){e=t.state,typeof t.componentWillReceiveProps=="function"&&t.componentWillReceiveProps(i,o),typeof t.UNSAFE_componentWillReceiveProps=="function"&&t.UNSAFE_componentWillReceiveProps(i,o),t.state!==e&&Uf.enqueueReplaceState(t,t.state,null)}function jl(e,t){var i=t;if("ref"in t){i={};for(var o in t)o!=="ref"&&(i[o]=t[o])}if(e=e.defaultProps){i===t&&(i=y({},i));for(var f in e)i[f]===void 0&&(i[f]=e[f])}return i}function lg(e){Gs(e)}function og(e){console.error(e)}function cg(e){Gs(e)}function Bu(e,t){try{var i=e.onUncaughtError;i(t.value,{componentStack:t.stack})}catch(o){setTimeout(function(){throw o})}}function ug(e,t,i){try{var o=e.onCaughtError;o(i.value,{componentStack:i.stack,errorBoundary:t.tag===1?t.stateNode:null})}catch(f){setTimeout(function(){throw f})}}function qf(e,t,i){return i=ni(i),i.tag=3,i.payload={element:null},i.callback=function(){Bu(e,t)},i}function dg(e){return e=ni(e),e.tag=3,e}function fg(e,t,i,o){var f=i.type.getDerivedStateFromError;if(typeof f=="function"){var h=o.value;e.payload=function(){return f(h)},e.callback=function(){ug(t,i,o)}}var S=i.stateNode;S!==null&&typeof S.componentDidCatch=="function"&&(e.callback=function(){ug(t,i,o),typeof f!="function"&&(Er===null?Er=new Set([this]):Er.add(this));var E=o.stack;this.componentDidCatch(o.value,{componentStack:E!==null?E:""})})}function Lw(e,t,i,o,f){if(i.flags|=32768,o!==null&&typeof o=="object"&&typeof o.then=="function"){if(t=i.alternate,t!==null&&Me(t,i,f,!0),i=Dt.current,i!==null){switch(i.tag){case 31:case 13:return tn===null?Xu():i.alternate===null&&hn===0&&(hn=3),i.flags&=-257,i.flags|=65536,i.lanes=f,o===xl?i.flags|=16384:(t=i.updateQueue,t===null?i.updateQueue=new Set([o]):t.add(o),pm(e,o,f)),!1;case 22:return i.flags|=65536,o===xl?i.flags|=16384:(t=i.updateQueue,t===null?(t={transitions:null,markerInstances:null,retryQueue:new Set([o])},i.updateQueue=t):(i=t.retryQueue,i===null?t.retryQueue=new Set([o]):i.add(o)),pm(e,o,f)),!1}throw Error(l(435,i.tag))}return pm(e,o,f),Xu(),!1}if(xt)return t=Dt.current,t!==null?((t.flags&65536)===0&&(t.flags|=256),t.flags|=65536,t.lanes=f,o!==ki&&(e=Error(l(422),{cause:o}),yr(Aa(e,i)))):(o!==ki&&(t=Error(l(423),{cause:o}),yr(Aa(t,i))),e=e.current.alternate,e.flags|=65536,f&=-f,e.lanes|=f,o=Aa(o,i),f=qf(e.stateNode,o,f),x(e,f),hn!==4&&(hn=2)),!1;var h=Error(l(520),{cause:o});if(h=Aa(h,i),yc===null?yc=[h]:yc.push(h),hn!==4&&(hn=2),t===null)return!0;o=Aa(o,i),i=t;do{switch(i.tag){case 3:return i.flags|=65536,e=f&-f,i.lanes|=e,e=qf(i.stateNode,o,e),x(i,e),!1;case 1:if(t=i.type,h=i.stateNode,(i.flags&128)===0&&(typeof t.getDerivedStateFromError=="function"||h!==null&&typeof h.componentDidCatch=="function"&&(Er===null||!Er.has(h))))return i.flags|=65536,f&=-f,i.lanes|=f,f=dg(f),fg(f,e,i,o),x(i,f),!1}i=i.return}while(i!==null);return!1}var Gf=Error(l(461)),An=!1;function Yn(e,t,i,o){t.child=e===null?Ti(t,null,i,o):Mi(t,e.child,i,o)}function mg(e,t,i,o,f){i=i.render;var h=t.ref;if("ref"in o){var S={};for(var E in o)E!=="ref"&&(S[E]=o[E])}else S=o;return Zs(t),o=Af(e,t,i,S,h,f),E=Nf(),e!==null&&!An?(Mf(e,t,f),Li(e,t,f)):(xt&&E&&nc(t),t.flags|=1,Yn(e,t,o,f),t.child)}function hg(e,t,i,o,f){if(e===null){var h=i.type;return typeof h=="function"&&!so(h)&&h.defaultProps===void 0&&i.compare===null?(t.tag=15,t.type=h,pg(e,t,h,o,f)):(e=gr(i.type,null,o,t,t.mode,f),e.ref=t.ref,e.return=t,t.child=e)}if(h=e.child,!Jf(e,f)){var S=h.memoizedProps;if(i=i.compare,i=i!==null?i:nl,i(S,o)&&e.ref===t.ref)return Li(e,t,f)}return t.flags|=1,e=Vn(h,o),e.ref=t.ref,e.return=t,t.child=e}function pg(e,t,i,o,f){if(e!==null){var h=e.memoizedProps;if(nl(h,o)&&e.ref===t.ref)if(An=!1,t.pendingProps=o=h,Jf(e,f))(e.flags&131072)!==0&&(An=!0);else return t.lanes=e.lanes,Li(e,t,f)}return Vf(e,t,i,o,f)}function gg(e,t,i,o){var f=o.children,h=e!==null?e.memoizedState:null;if(e===null&&t.stateNode===null&&(t.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),o.mode==="hidden"){if((t.flags&128)!==0){if(h=h!==null?h.baseLanes|i:i,e!==null){for(o=t.child=e.child,f=0;o!==null;)f=f|o.lanes|o.childLanes,o=o.sibling;o=f&~h}else o=0,t.child=null;return vg(e,t,h,i,o)}if((i&536870912)!==0)t.memoizedState={baseLanes:0,cachePool:null},e!==null&&gl(t,h!==null?h.cachePool:null),h!==null?Ue(t,h):Ke(),Tu(t);else return o=t.lanes=536870912,vg(e,t,h!==null?h.baseLanes|i:i,i,o)}else h!==null?(gl(t,h.cachePool),Ue(t,h),qa(),t.memoizedState=null):(e!==null&&gl(t,null),Ke(),qa());return Yn(e,t,f,i),t.child}function fc(e,t){return e!==null&&e.tag===22||t.stateNode!==null||(t.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),t.sibling}function vg(e,t,i,o,f){var h=Cr();return h=h===null?null:{parent:Qe._currentValue,pool:h},t.memoizedState={baseLanes:i,cachePool:h},e!==null&&gl(t,null),Ke(),Tu(t),e!==null&&Me(e,t,o,!0),t.childLanes=f,null}function Fu(e,t){return t=$u({mode:t.mode,children:t.children},e.mode),t.ref=e.ref,e.child=t,t.return=e,t}function xg(e,t,i){return Mi(t,e.child,null,i),e=Fu(t,t.pendingProps),e.flags|=2,pa(t),t.memoizedState=null,e}function _w(e,t,i){var o=t.pendingProps,f=(t.flags&128)!==0;if(t.flags&=-129,e===null){if(xt){if(o.mode==="hidden")return e=Fu(t,o),t.lanes=536870912,fc(null,e);if(Ar(t),(e=Et)?(e=Ev(e,Ma),e=e!==null&&e.data==="&"?e:null,e!==null&&(t.memoizedState={dehydrated:e,treeContext:Ks!==null?{id:Na,overflow:sa}:null,retryLane:536870912,hydrationErrors:null},i=tc(e),i.return=t,t.child=i,yn=t,Et=null)):e=null,e===null)throw Qs(t);return t.lanes=536870912,null}return Fu(t,o)}var h=e.memoizedState;if(h!==null){var S=h.dehydrated;if(Ar(t),f)if(t.flags&256)t.flags&=-257,t=xg(e,t,i);else if(t.memoizedState!==null)t.child=e.child,t.flags|=128,t=null;else throw Error(l(558));else if(An||Me(e,t,i,!1),f=(i&e.childLanes)!==0,An||f){if(o=qt,o!==null&&(S=De(o,i),S!==0&&S!==h.retryLane))throw h.retryLane=S,is(e,S),La(o,e,S),Gf;Xu(),t=xg(e,t,i)}else e=h.treeContext,Et=cs(S.nextSibling),yn=t,xt=!0,rs=null,Ma=!1,e!==null&&io(t,e),t=Fu(t,o),t.flags|=4096;return t}return e=Vn(e.child,{mode:o.mode,children:o.children}),e.ref=t.ref,t.child=e,e.return=t,e}function Pu(e,t){var i=t.ref;if(i===null)e!==null&&e.ref!==null&&(t.flags|=4194816);else{if(typeof i!="function"&&typeof i!="object")throw Error(l(284));(e===null||e.ref!==i)&&(t.flags|=4194816)}}function Vf(e,t,i,o,f){return Zs(t),i=Af(e,t,i,o,void 0,f),o=Nf(),e!==null&&!An?(Mf(e,t,f),Li(e,t,f)):(xt&&o&&nc(t),t.flags|=1,Yn(e,t,i,f),t.child)}function yg(e,t,i,o,f,h){return Zs(t),t.updateQueue=null,i=Sp(t,o,i,f),wp(e),o=Nf(),e!==null&&!An?(Mf(e,t,h),Li(e,t,h)):(xt&&o&&nc(t),t.flags|=1,Yn(e,t,i,h),t.child)}function bg(e,t,i,o,f){if(Zs(t),t.stateNode===null){var h=As,S=i.contextType;typeof S=="object"&&S!==null&&(h=En(S)),h=new i(o,h),t.memoizedState=h.state!==null&&h.state!==void 0?h.state:null,h.updater=Uf,t.stateNode=h,h._reactInternals=t,h=t.stateNode,h.props=o,h.state=t.memoizedState,h.refs={},Sl(t),S=i.contextType,h.context=typeof S=="object"&&S!==null?En(S):As,h.state=t.memoizedState,S=i.getDerivedStateFromProps,typeof S=="function"&&($f(t,i,S,o),h.state=t.memoizedState),typeof i.getDerivedStateFromProps=="function"||typeof h.getSnapshotBeforeUpdate=="function"||typeof h.UNSAFE_componentWillMount!="function"&&typeof h.componentWillMount!="function"||(S=h.state,typeof h.componentWillMount=="function"&&h.componentWillMount(),typeof h.UNSAFE_componentWillMount=="function"&&h.UNSAFE_componentWillMount(),S!==h.state&&Uf.enqueueReplaceState(h,h.state,null),B(t,o,h,f),D(),h.state=t.memoizedState),typeof h.componentDidMount=="function"&&(t.flags|=4194308),o=!0}else if(e===null){h=t.stateNode;var E=t.memoizedProps,F=jl(i,E);h.props=F;var oe=h.context,xe=i.contextType;S=As,typeof xe=="object"&&xe!==null&&(S=En(xe));var Ce=i.getDerivedStateFromProps;xe=typeof Ce=="function"||typeof h.getSnapshotBeforeUpdate=="function",E=t.pendingProps!==E,xe||typeof h.UNSAFE_componentWillReceiveProps!="function"&&typeof h.componentWillReceiveProps!="function"||(E||oe!==S)&&rg(t,h,o,S),ei=!1;var ce=t.memoizedState;h.state=ce,B(t,o,h,f),D(),oe=t.memoizedState,E||ce!==oe||ei?(typeof Ce=="function"&&($f(t,i,Ce,o),oe=t.memoizedState),(F=ei||ig(t,i,F,o,ce,oe,S))?(xe||typeof h.UNSAFE_componentWillMount!="function"&&typeof h.componentWillMount!="function"||(typeof h.componentWillMount=="function"&&h.componentWillMount(),typeof h.UNSAFE_componentWillMount=="function"&&h.UNSAFE_componentWillMount()),typeof h.componentDidMount=="function"&&(t.flags|=4194308)):(typeof h.componentDidMount=="function"&&(t.flags|=4194308),t.memoizedProps=o,t.memoizedState=oe),h.props=o,h.state=oe,h.context=S,o=F):(typeof h.componentDidMount=="function"&&(t.flags|=4194308),o=!1)}else{h=t.stateNode,ti(e,t),S=t.memoizedProps,xe=jl(i,S),h.props=xe,Ce=t.pendingProps,ce=h.context,oe=i.contextType,F=As,typeof oe=="object"&&oe!==null&&(F=En(oe)),E=i.getDerivedStateFromProps,(oe=typeof E=="function"||typeof h.getSnapshotBeforeUpdate=="function")||typeof h.UNSAFE_componentWillReceiveProps!="function"&&typeof h.componentWillReceiveProps!="function"||(S!==Ce||ce!==F)&&rg(t,h,o,F),ei=!1,ce=t.memoizedState,h.state=ce,B(t,o,h,f),D();var he=t.memoizedState;S!==Ce||ce!==he||ei||e!==null&&e.dependencies!==null&&Ai(e.dependencies)?(typeof E=="function"&&($f(t,i,E,o),he=t.memoizedState),(xe=ei||ig(t,i,xe,o,ce,he,F)||e!==null&&e.dependencies!==null&&Ai(e.dependencies))?(oe||typeof h.UNSAFE_componentWillUpdate!="function"&&typeof h.componentWillUpdate!="function"||(typeof h.componentWillUpdate=="function"&&h.componentWillUpdate(o,he,F),typeof h.UNSAFE_componentWillUpdate=="function"&&h.UNSAFE_componentWillUpdate(o,he,F)),typeof h.componentDidUpdate=="function"&&(t.flags|=4),typeof h.getSnapshotBeforeUpdate=="function"&&(t.flags|=1024)):(typeof h.componentDidUpdate!="function"||S===e.memoizedProps&&ce===e.memoizedState||(t.flags|=4),typeof h.getSnapshotBeforeUpdate!="function"||S===e.memoizedProps&&ce===e.memoizedState||(t.flags|=1024),t.memoizedProps=o,t.memoizedState=he),h.props=o,h.state=he,h.context=F,o=xe):(typeof h.componentDidUpdate!="function"||S===e.memoizedProps&&ce===e.memoizedState||(t.flags|=4),typeof h.getSnapshotBeforeUpdate!="function"||S===e.memoizedProps&&ce===e.memoizedState||(t.flags|=1024),o=!1)}return h=o,Pu(e,t),o=(t.flags&128)!==0,h||o?(h=t.stateNode,i=o&&typeof i.getDerivedStateFromError!="function"?null:h.render(),t.flags|=1,e!==null&&o?(t.child=Mi(t,e.child,null,f),t.child=Mi(t,null,i,f)):Yn(e,t,i,f),t.memoizedState=h.state,e=t.child):e=Li(e,t,f),e}function wg(e,t,i,o){return Xs(),t.flags|=256,Yn(e,t,i,o),t.child}var Wf={dehydrated:null,treeContext:null,retryLane:0,hydrationErrors:null};function Yf(e){return{baseLanes:e,cachePool:ku()}}function Kf(e,t,i){return e=e!==null?e.childLanes&~i:0,t&&(e|=Va),e}function Sg(e,t,i){var o=t.pendingProps,f=!1,h=(t.flags&128)!==0,S;if((S=h)||(S=e!==null&&e.memoizedState===null?!1:(bn.current&2)!==0),S&&(f=!0,t.flags&=-129),S=(t.flags&32)!==0,t.flags&=-33,e===null){if(xt){if(f?Ua(t):qa(),(e=Et)?(e=Ev(e,Ma),e=e!==null&&e.data!=="&"?e:null,e!==null&&(t.memoizedState={dehydrated:e,treeContext:Ks!==null?{id:Na,overflow:sa}:null,retryLane:536870912,hydrationErrors:null},i=tc(e),i.return=t,t.child=i,yn=t,Et=null)):e=null,e===null)throw Qs(t);return Rm(e)?t.lanes=32:t.lanes=536870912,null}var E=o.children;return o=o.fallback,f?(qa(),f=t.mode,E=$u({mode:"hidden",children:E},f),o=Ws(o,f,i,null),E.return=t,o.return=t,E.sibling=o,t.child=E,o=t.child,o.memoizedState=Yf(i),o.childLanes=Kf(e,S,i),t.memoizedState=Wf,fc(null,o)):(Ua(t),Qf(t,E))}var F=e.memoizedState;if(F!==null&&(E=F.dehydrated,E!==null)){if(h)t.flags&256?(Ua(t),t.flags&=-257,t=Xf(e,t,i)):t.memoizedState!==null?(qa(),t.child=e.child,t.flags|=128,t=null):(qa(),E=o.fallback,f=t.mode,o=$u({mode:"visible",children:o.children},f),E=Ws(E,f,i,null),E.flags|=2,o.return=t,E.return=t,o.sibling=E,t.child=o,Mi(t,e.child,null,i),o=t.child,o.memoizedState=Yf(i),o.childLanes=Kf(e,S,i),t.memoizedState=Wf,t=fc(null,o));else if(Ua(t),Rm(E)){if(S=E.nextSibling&&E.nextSibling.dataset,S)var oe=S.dgst;S=oe,o=Error(l(419)),o.stack="",o.digest=S,yr({value:o,source:null,stack:null}),t=Xf(e,t,i)}else if(An||Me(e,t,i,!1),S=(i&e.childLanes)!==0,An||S){if(S=qt,S!==null&&(o=De(S,i),o!==0&&o!==F.retryLane))throw F.retryLane=o,is(e,o),La(S,e,o),Gf;Em(E)||Xu(),t=Xf(e,t,i)}else Em(E)?(t.flags|=192,t.child=e.child,t=null):(e=F.treeContext,Et=cs(E.nextSibling),yn=t,xt=!0,rs=null,Ma=!1,e!==null&&io(t,e),t=Qf(t,o.children),t.flags|=4096);return t}return f?(qa(),E=o.fallback,f=t.mode,F=e.child,oe=F.sibling,o=Vn(F,{mode:"hidden",children:o.children}),o.subtreeFlags=F.subtreeFlags&65011712,oe!==null?E=Vn(oe,E):(E=Ws(E,f,i,null),E.flags|=2),E.return=t,o.return=t,o.sibling=E,t.child=o,fc(null,o),o=t.child,E=e.child.memoizedState,E===null?E=Yf(i):(f=E.cachePool,f!==null?(F=Qe._currentValue,f=f.parent!==F?{parent:F,pool:F}:f):f=ku(),E={baseLanes:E.baseLanes|i,cachePool:f}),o.memoizedState=E,o.childLanes=Kf(e,S,i),t.memoizedState=Wf,fc(e.child,o)):(Ua(t),i=e.child,e=i.sibling,i=Vn(i,{mode:"visible",children:o.children}),i.return=t,i.sibling=null,e!==null&&(S=t.deletions,S===null?(t.deletions=[e],t.flags|=16):S.push(e)),t.child=i,t.memoizedState=null,i)}function Qf(e,t){return t=$u({mode:"visible",children:t},e.mode),t.return=e,e.child=t}function $u(e,t){return e=jn(22,e,null,t),e.lanes=0,e}function Xf(e,t,i){return Mi(t,e.child,null,i),e=Qf(t,t.pendingProps.children),e.flags|=2,t.memoizedState=null,e}function Cg(e,t,i){e.lanes|=t;var o=e.alternate;o!==null&&(o.lanes|=t),ml(e.return,t,i)}function Zf(e,t,i,o,f,h){var S=e.memoizedState;S===null?e.memoizedState={isBackwards:t,rendering:null,renderingStartTime:0,last:o,tail:i,tailMode:f,treeForkCount:h}:(S.isBackwards=t,S.rendering=null,S.renderingStartTime=0,S.last=o,S.tail=i,S.tailMode=f,S.treeForkCount=h)}function jg(e,t,i){var o=t.pendingProps,f=o.revealOrder,h=o.tail;o=o.children;var S=bn.current,E=(S&2)!==0;if(E?(S=S&1|2,t.flags|=128):S&=1,$(bn,S),Yn(e,t,o,i),o=xt?Ys:0,!E&&e!==null&&(e.flags&128)!==0)e:for(e=t.child;e!==null;){if(e.tag===13)e.memoizedState!==null&&Cg(e,i,t);else if(e.tag===19)Cg(e,i,t);else if(e.child!==null){e.child.return=e,e=e.child;continue}if(e===t)break e;for(;e.sibling===null;){if(e.return===null||e.return===t)break e;e=e.return}e.sibling.return=e.return,e=e.sibling}switch(f){case"forwards":for(i=t.child,f=null;i!==null;)e=i.alternate,e!==null&&Eu(e)===null&&(f=i),i=i.sibling;i=f,i===null?(f=t.child,t.child=null):(f=i.sibling,i.sibling=null),Zf(t,!1,f,i,h,o);break;case"backwards":case"unstable_legacy-backwards":for(i=null,f=t.child,t.child=null;f!==null;){if(e=f.alternate,e!==null&&Eu(e)===null){t.child=f;break}e=f.sibling,f.sibling=i,i=f,f=e}Zf(t,!0,i,null,h,o);break;case"together":Zf(t,!1,null,null,void 0,o);break;default:t.memoizedState=null}return t.child}function Li(e,t,i){if(e!==null&&(t.dependencies=e.dependencies),Tr|=t.lanes,(i&t.childLanes)===0)if(e!==null){if(Me(e,t,i,!1),(i&t.childLanes)===0)return null}else return null;if(e!==null&&t.child!==e.child)throw Error(l(153));if(t.child!==null){for(e=t.child,i=Vn(e,e.pendingProps),t.child=i,i.return=t;e.sibling!==null;)e=e.sibling,i=i.sibling=Vn(e,e.pendingProps),i.return=t;i.sibling=null}return t.child}function Jf(e,t){return(e.lanes&t)!==0?!0:(e=e.dependencies,!!(e!==null&&Ai(e)))}function zw(e,t,i){switch(t.tag){case 3:Oe(t,t.stateNode.containerInfo),$a(t,Qe,e.memoizedState.cache),Xs();break;case 27:case 5:Z(t);break;case 4:Oe(t,t.stateNode.containerInfo);break;case 10:$a(t,t.type,t.memoizedProps.value);break;case 31:if(t.memoizedState!==null)return t.flags|=128,Ar(t),null;break;case 13:var o=t.memoizedState;if(o!==null)return o.dehydrated!==null?(Ua(t),t.flags|=128,null):(i&t.child.childLanes)!==0?Sg(e,t,i):(Ua(t),e=Li(e,t,i),e!==null?e.sibling:null);Ua(t);break;case 19:var f=(e.flags&128)!==0;if(o=(i&t.childLanes)!==0,o||(Me(e,t,i,!1),o=(i&t.childLanes)!==0),f){if(o)return jg(e,t,i);t.flags|=128}if(f=t.memoizedState,f!==null&&(f.rendering=null,f.tail=null,f.lastEffect=null),$(bn,bn.current),o)break;return null;case 22:return t.lanes=0,gg(e,t,i,t.pendingProps);case 24:$a(t,Qe,e.memoizedState.cache)}return Li(e,t,i)}function kg(e,t,i){if(e!==null)if(e.memoizedProps!==t.pendingProps)An=!0;else{if(!Jf(e,i)&&(t.flags&128)===0)return An=!1,zw(e,t,i);An=(e.flags&131072)!==0}else An=!1,xt&&(t.flags&1048576)!==0&&wu(t,Ys,t.index);switch(t.lanes=0,t.tag){case 16:e:{var o=t.pendingProps;if(e=Js(t.elementType),t.type=e,typeof e=="function")so(e)?(o=jl(e,o),t.tag=1,t=bg(null,t,e,o,i)):(t.tag=0,t=Vf(null,t,e,o,i));else{if(e!=null){var f=e.$$typeof;if(f===q){t.tag=11,t=mg(null,t,e,o,i);break e}else if(f===_){t.tag=14,t=hg(null,t,e,o,i);break e}}throw t=ie(e)||e,Error(l(306,t,""))}}return t;case 0:return Vf(e,t,t.type,t.pendingProps,i);case 1:return o=t.type,f=jl(o,t.pendingProps),bg(e,t,o,f,i);case 3:e:{if(Oe(t,t.stateNode.containerInfo),e===null)throw Error(l(387));o=t.pendingProps;var h=t.memoizedState;f=h.element,ti(e,t),B(t,o,null,i);var S=t.memoizedState;if(o=S.cache,$a(t,Qe,o),o!==h.cache&&hl(t,[Qe],i,!0),D(),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=wg(e,t,o,i);break e}else if(o!==f){f=Aa(Error(l(424)),t),yr(f),t=wg(e,t,o,i);break e}else for(e=t.stateNode.containerInfo,e.nodeType===9?e=e.body:e=e.nodeName==="HTML"?e.ownerDocument.body:e,Et=cs(e.firstChild),yn=t,xt=!0,rs=null,Ma=!0,i=Ti(t,null,o,i),t.child=i;i;)i.flags=i.flags&-3|4096,i=i.sibling;else{if(Xs(),o===f){t=Li(e,t,i);break e}Yn(e,t,o,i)}t=t.child}return t;case 26:return Pu(e,t),e===null?(i=Iv(t.type,null,t.pendingProps,null))?t.memoizedState=i:xt||(i=t.type,e=t.pendingProps,o=sd(ve.current).createElement(i),o[ne]=t,o[Ae]=e,Kn(o,i,e),Tt(o),t.stateNode=o):t.memoizedState=Iv(t.type,e.memoizedProps,t.pendingProps,e.memoizedState),null;case 27:return Z(t),e===null&&xt&&(o=t.stateNode=Lv(t.type,t.pendingProps,ve.current),yn=t,Ma=!0,f=Et,_r(t.type)?(Dm=f,Et=cs(o.firstChild)):Et=f),Yn(e,t,t.pendingProps.children,i),Pu(e,t),e===null&&(t.flags|=4194304),t.child;case 5:return e===null&&xt&&((f=o=Et)&&(o=dS(o,t.type,t.pendingProps,Ma),o!==null?(t.stateNode=o,yn=t,Et=cs(o.firstChild),Ma=!1,f=!0):f=!1),f||Qs(t)),Z(t),f=t.type,h=t.pendingProps,S=e!==null?e.memoizedProps:null,o=h.children,Nm(f,h)?o=null:S!==null&&Nm(f,S)&&(t.flags|=32),t.memoizedState!==null&&(f=Af(e,t,Aw,null,null,i),Nc._currentValue=f),Pu(e,t),Yn(e,t,o,i),t.child;case 6:return e===null&&xt&&((e=i=Et)&&(i=fS(i,t.pendingProps,Ma),i!==null?(t.stateNode=i,yn=t,Et=null,e=!0):e=!1),e||Qs(t)),null;case 13:return Sg(e,t,i);case 4:return Oe(t,t.stateNode.containerInfo),o=t.pendingProps,e===null?t.child=Mi(t,null,o,i):Yn(e,t,o,i),t.child;case 11:return mg(e,t,t.type,t.pendingProps,i);case 7:return Yn(e,t,t.pendingProps,i),t.child;case 8:return Yn(e,t,t.pendingProps.children,i),t.child;case 12:return Yn(e,t,t.pendingProps.children,i),t.child;case 10:return o=t.pendingProps,$a(t,t.type,o.value),Yn(e,t,o.children,i),t.child;case 9:return f=t.type._context,o=t.pendingProps.children,Zs(t),f=En(f),o=o(f),t.flags|=1,Yn(e,t,o,i),t.child;case 14:return hg(e,t,t.type,t.pendingProps,i);case 15:return pg(e,t,t.type,t.pendingProps,i);case 19:return jg(e,t,i);case 31:return _w(e,t,i);case 22:return gg(e,t,i,t.pendingProps);case 24:return Zs(t),o=En(Qe),e===null?(f=Cr(),f===null&&(f=qt,h=rc(),f.pooledCache=h,h.refCount++,h!==null&&(f.pooledCacheLanes|=i),f=h),t.memoizedState={parent:o,cache:f},Sl(t),$a(t,Qe,f)):((e.lanes&i)!==0&&(ti(e,t),B(t,null,null,i),D()),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),$a(t,Qe,o)):(o=h.cache,$a(t,Qe,o),o!==f.cache&&hl(t,[Qe],i,!0))),Yn(e,t,t.pendingProps.children,i),t.child;case 29:throw t.pendingProps}throw Error(l(156,t.tag))}function _i(e){e.flags|=4}function em(e,t,i,o,f){if((t=(e.mode&32)!==0)&&(t=!1),t){if(e.flags|=16777216,(f&335544128)===f)if(e.stateNode.complete)e.flags|=8192;else if(Zg())e.flags|=8192;else throw Ni=xl,lc}else e.flags&=-16777217}function Ag(e,t){if(t.type!=="stylesheet"||(t.state.loading&4)!==0)e.flags&=-16777217;else if(e.flags|=16777216,!Pv(t))if(Zg())e.flags|=8192;else throw Ni=xl,lc}function Uu(e,t){t!==null&&(e.flags|=4),e.flags&16384&&(t=e.tag!==22?Fe():536870912,e.lanes|=t,yo|=t)}function mc(e,t){if(!xt)switch(e.tailMode){case"hidden":t=e.tail;for(var i=null;t!==null;)t.alternate!==null&&(i=t),t=t.sibling;i===null?e.tail=null:i.sibling=null;break;case"collapsed":i=e.tail;for(var o=null;i!==null;)i.alternate!==null&&(o=i),i=i.sibling;o===null?t||e.tail===null?e.tail=null:e.tail.sibling=null:o.sibling=null}}function Xt(e){var t=e.alternate!==null&&e.alternate.child===e.child,i=0,o=0;if(t)for(var f=e.child;f!==null;)i|=f.lanes|f.childLanes,o|=f.subtreeFlags&65011712,o|=f.flags&65011712,f.return=e,f=f.sibling;else for(f=e.child;f!==null;)i|=f.lanes|f.childLanes,o|=f.subtreeFlags,o|=f.flags,f.return=e,f=f.sibling;return e.subtreeFlags|=o,e.childLanes=i,t}function Iw(e,t,i){var o=t.pendingProps;switch(ac(t),t.tag){case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return Xt(t),null;case 1:return Xt(t),null;case 3:return i=t.stateNode,o=null,e!==null&&(o=e.memoizedState.cache),t.memoizedState.cache!==o&&(t.flags|=2048),Ms(Qe),le(),i.pendingContext&&(i.context=i.pendingContext,i.pendingContext=null),(e===null||e.child===null)&&(xr(t)?_i(t):e===null||e.memoizedState.isDehydrated&&(t.flags&256)===0||(t.flags|=1024,ro())),Xt(t),null;case 26:var f=t.type,h=t.memoizedState;return e===null?(_i(t),h!==null?(Xt(t),Ag(t,h)):(Xt(t),em(t,f,null,o,i))):h?h!==e.memoizedState?(_i(t),Xt(t),Ag(t,h)):(Xt(t),t.flags&=-16777217):(e=e.memoizedProps,e!==o&&_i(t),Xt(t),em(t,f,e,o,i)),null;case 27:if(He(t),i=ve.current,f=t.type,e!==null&&t.stateNode!=null)e.memoizedProps!==o&&_i(t);else{if(!o){if(t.stateNode===null)throw Error(l(166));return Xt(t),null}e=de.current,xr(t)?Su(t):(e=Lv(f,o,i),t.stateNode=e,_i(t))}return Xt(t),null;case 5:if(He(t),f=t.type,e!==null&&t.stateNode!=null)e.memoizedProps!==o&&_i(t);else{if(!o){if(t.stateNode===null)throw Error(l(166));return Xt(t),null}if(h=de.current,xr(t))Su(t);else{var S=sd(ve.current);switch(h){case 1:h=S.createElementNS("http://www.w3.org/2000/svg",f);break;case 2:h=S.createElementNS("http://www.w3.org/1998/Math/MathML",f);break;default:switch(f){case"svg":h=S.createElementNS("http://www.w3.org/2000/svg",f);break;case"math":h=S.createElementNS("http://www.w3.org/1998/Math/MathML",f);break;case"script":h=S.createElement("div"),h.innerHTML="<script><\/script>",h=h.removeChild(h.firstChild);break;case"select":h=typeof o.is=="string"?S.createElement("select",{is:o.is}):S.createElement("select"),o.multiple?h.multiple=!0:o.size&&(h.size=o.size);break;default:h=typeof o.is=="string"?S.createElement(f,{is:o.is}):S.createElement(f)}}h[ne]=t,h[Ae]=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&&_i(t)}}return Xt(t),em(t,t.type,e===null?null:e.memoizedProps,t.pendingProps,i),null;case 6:if(e&&t.stateNode!=null)e.memoizedProps!==o&&_i(t);else{if(typeof o!="string"&&t.stateNode===null)throw Error(l(166));if(e=ve.current,xr(t)){if(e=t.stateNode,i=t.memoizedProps,o=null,f=yn,f!==null)switch(f.tag){case 27:case 5:o=f.memoizedProps}e[ne]=t,e=!!(e.nodeValue===i||o!==null&&o.suppressHydrationWarning===!0||Sv(e.nodeValue,i)),e||Qs(t,!0)}else e=sd(e).createTextNode(o),e[ne]=t,t.stateNode=e}return Xt(t),null;case 31:if(i=t.memoizedState,e===null||e.memoizedState!==null){if(o=xr(t),i!==null){if(e===null){if(!o)throw Error(l(318));if(e=t.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(l(557));e[ne]=t}else Xs(),(t.flags&128)===0&&(t.memoizedState=null),t.flags|=4;Xt(t),e=!1}else i=ro(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=i),e=!0;if(!e)return t.flags&256?(pa(t),t):(pa(t),null);if((t.flags&128)!==0)throw Error(l(558))}return Xt(t),null;case 13:if(o=t.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(f=xr(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 Xs(),(t.flags&128)===0&&(t.memoizedState=null),t.flags|=4;Xt(t),f=!1}else f=ro(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=f),f=!0;if(!f)return t.flags&256?(pa(t),t):(pa(t),null)}return pa(t),(t.flags&128)!==0?(t.lanes=i,t):(i=o!==null,e=e!==null&&e.memoizedState!==null,i&&(o=t.child,f=null,o.alternate!==null&&o.alternate.memoizedState!==null&&o.alternate.memoizedState.cachePool!==null&&(f=o.alternate.memoizedState.cachePool.pool),h=null,o.memoizedState!==null&&o.memoizedState.cachePool!==null&&(h=o.memoizedState.cachePool.pool),h!==f&&(o.flags|=2048)),i!==e&&i&&(t.child.flags|=8192),Uu(t,t.updateQueue),Xt(t),null);case 4:return le(),e===null&&Sm(t.stateNode.containerInfo),Xt(t),null;case 10:return Ms(t.type),Xt(t),null;case 19:if(X(bn),o=t.memoizedState,o===null)return Xt(t),null;if(f=(t.flags&128)!==0,h=o.rendering,h===null)if(f)mc(o,!1);else{if(hn!==0||e!==null&&(e.flags&128)!==0)for(e=t.child;e!==null;){if(h=Eu(e),h!==null){for(t.flags|=128,mc(o,!1),e=h.updateQueue,t.updateQueue=e,Uu(t,e),t.subtreeFlags=0,e=i,i=t.child;i!==null;)ul(i,e),i=i.sibling;return $(bn,bn.current&1|2),xt&&Ns(t,o.treeForkCount),t.child}e=e.sibling}o.tail!==null&&vt()>Yu&&(t.flags|=128,f=!0,mc(o,!1),t.lanes=4194304)}else{if(!f)if(e=Eu(h),e!==null){if(t.flags|=128,f=!0,e=e.updateQueue,t.updateQueue=e,Uu(t,e),mc(o,!0),o.tail===null&&o.tailMode==="hidden"&&!h.alternate&&!xt)return Xt(t),null}else 2*vt()-o.renderingStartTime>Yu&&i!==536870912&&(t.flags|=128,f=!0,mc(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=vt(),e.sibling=null,i=bn.current,$(bn,f?i&1|2:i&1),xt&&Ns(t,o.treeForkCount),e):(Xt(t),null);case 22:case 23:return pa(t),en(),o=t.memoizedState!==null,e!==null?e.memoizedState!==null!==o&&(t.flags|=8192):o&&(t.flags|=8192),o?(i&536870912)!==0&&(t.flags&128)===0&&(Xt(t),t.subtreeFlags&6&&(t.flags|=8192)):Xt(t),i=t.updateQueue,i!==null&&Uu(t,i.retryQueue),i=null,e!==null&&e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(i=e.memoizedState.cachePool.pool),o=null,t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(o=t.memoizedState.cachePool.pool),o!==i&&(t.flags|=2048),e!==null&&X(rn),null;case 24:return i=null,e!==null&&(i=e.memoizedState.cache),t.memoizedState.cache!==i&&(t.flags|=2048),Ms(Qe),Xt(t),null;case 25:return null;case 30:return null}throw Error(l(156,t.tag))}function Ow(e,t){switch(ac(t),t.tag){case 1:return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Ms(Qe),le(),e=t.flags,(e&65536)!==0&&(e&128)===0?(t.flags=e&-65537|128,t):null;case 26:case 27:case 5:return He(t),null;case 31:if(t.memoizedState!==null){if(pa(t),t.alternate===null)throw Error(l(340));Xs()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 13:if(pa(t),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(l(340));Xs()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return X(bn),null;case 4:return le(),null;case 10:return Ms(t.type),null;case 22:case 23:return pa(t),en(),e!==null&&X(rn),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 24:return Ms(Qe),null;case 25:return null;default:return null}}function Ng(e,t){switch(ac(t),t.tag){case 3:Ms(Qe),le();break;case 26:case 27:case 5:He(t);break;case 4:le();break;case 31:t.memoizedState!==null&&pa(t);break;case 13:pa(t);break;case 19:X(bn);break;case 10:Ms(t.type);break;case 22:case 23:pa(t),en(),e!==null&&X(rn);break;case 24:Ms(Qe)}}function hc(e,t){try{var i=t.updateQueue,o=i!==null?i.lastEffect:null;if(o!==null){var f=o.next;i=f;do{if((i.tag&e)===e){o=void 0;var h=i.create,S=i.inst;o=h(),S.destroy=o}i=i.next}while(i!==f)}}catch(E){zt(t,t.return,E)}}function Nr(e,t,i){try{var o=t.updateQueue,f=o!==null?o.lastEffect:null;if(f!==null){var h=f.next;o=h;do{if((o.tag&e)===e){var S=o.inst,E=S.destroy;if(E!==void 0){S.destroy=void 0,f=t;var F=i,oe=E;try{oe()}catch(xe){zt(f,F,xe)}}}o=o.next}while(o!==h)}}catch(xe){zt(t,t.return,xe)}}function Mg(e){var t=e.updateQueue;if(t!==null){var i=e.stateNode;try{ge(t,i)}catch(o){zt(e,e.return,o)}}}function Tg(e,t,i){i.props=jl(e.type,e.memoizedProps),i.state=e.memoizedState;try{i.componentWillUnmount()}catch(o){zt(e,t,o)}}function pc(e,t){try{var i=e.ref;if(i!==null){switch(e.tag){case 26:case 27:case 5:var o=e.stateNode;break;case 30:o=e.stateNode;break;default:o=e.stateNode}typeof i=="function"?e.refCleanup=i(o):i.current=o}}catch(f){zt(e,t,f)}}function ai(e,t){var i=e.ref,o=e.refCleanup;if(i!==null)if(typeof o=="function")try{o()}catch(f){zt(e,t,f)}finally{e.refCleanup=null,e=e.alternate,e!=null&&(e.refCleanup=null)}else if(typeof i=="function")try{i(null)}catch(f){zt(e,t,f)}else i.current=null}function Eg(e){var t=e.type,i=e.memoizedProps,o=e.stateNode;try{e:switch(t){case"button":case"input":case"select":case"textarea":i.autoFocus&&o.focus();break e;case"img":i.src?o.src=i.src:i.srcSet&&(o.srcset=i.srcSet)}}catch(f){zt(e,e.return,f)}}function tm(e,t,i){try{var o=e.stateNode;iS(o,e.type,i,t),o[Ae]=t}catch(f){zt(e,e.return,f)}}function Rg(e){return e.tag===5||e.tag===3||e.tag===26||e.tag===27&&_r(e.type)||e.tag===4}function nm(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||Rg(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&&_r(e.type)||e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function am(e,t,i){var o=e.tag;if(o===5||o===6)e=e.stateNode,t?(i.nodeType===9?i.body:i.nodeName==="HTML"?i.ownerDocument.body:i).insertBefore(e,t):(t=i.nodeType===9?i.body:i.nodeName==="HTML"?i.ownerDocument.body:i,t.appendChild(e),i=i._reactRootContainer,i!=null||t.onclick!==null||(t.onclick=Ln));else if(o!==4&&(o===27&&_r(e.type)&&(i=e.stateNode,t=null),e=e.child,e!==null))for(am(e,t,i),e=e.sibling;e!==null;)am(e,t,i),e=e.sibling}function qu(e,t,i){var o=e.tag;if(o===5||o===6)e=e.stateNode,t?i.insertBefore(e,t):i.appendChild(e);else if(o!==4&&(o===27&&_r(e.type)&&(i=e.stateNode),e=e.child,e!==null))for(qu(e,t,i),e=e.sibling;e!==null;)qu(e,t,i),e=e.sibling}function Dg(e){var t=e.stateNode,i=e.memoizedProps;try{for(var o=e.type,f=t.attributes;f.length;)t.removeAttributeNode(f[0]);Kn(t,o,i),t[ne]=e,t[Ae]=i}catch(h){zt(e,e.return,h)}}var zi=!1,Nn=!1,sm=!1,Lg=typeof WeakSet=="function"?WeakSet:Set,On=null;function Hw(e,t){if(e=e.containerInfo,km=dd,e=xi(e),to(e)){if("selectionStart"in e)var i={start:e.selectionStart,end:e.selectionEnd};else e:{i=(i=e.ownerDocument)&&i.defaultView||window;var o=i.getSelection&&i.getSelection();if(o&&o.rangeCount!==0){i=o.anchorNode;var f=o.anchorOffset,h=o.focusNode;o=o.focusOffset;try{i.nodeType,h.nodeType}catch{i=null;break e}var S=0,E=-1,F=-1,oe=0,xe=0,Ce=e,ce=null;t:for(;;){for(var he;Ce!==i||f!==0&&Ce.nodeType!==3||(E=S+f),Ce!==h||o!==0&&Ce.nodeType!==3||(F=S+o),Ce.nodeType===3&&(S+=Ce.nodeValue.length),(he=Ce.firstChild)!==null;)ce=Ce,Ce=he;for(;;){if(Ce===e)break t;if(ce===i&&++oe===f&&(E=S),ce===h&&++xe===o&&(F=S),(he=Ce.nextSibling)!==null)break;Ce=ce,ce=Ce.parentNode}Ce=he}i=E===-1||F===-1?null:{start:E,end:F}}else i=null}i=i||{start:0,end:0}}else i=null;for(Am={focusedElem:e,selectionRange:i},dd=!1,On=t;On!==null;)if(t=On,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,On=e;else for(;On!==null;){switch(t=On,h=t.alternate,e=t.flags,t.tag){case 0:if((e&4)!==0&&(e=t.updateQueue,e=e!==null?e.events:null,e!==null))for(i=0;i<e.length;i++)f=e[i],f.ref.impl=f.nextImpl;break;case 11:case 15:break;case 1:if((e&1024)!==0&&h!==null){e=void 0,i=t,f=h.memoizedProps,h=h.memoizedState,o=i.stateNode;try{var Ve=jl(i.type,f);e=o.getSnapshotBeforeUpdate(Ve,h),o.__reactInternalSnapshotBeforeUpdate=e}catch(nt){zt(i,i.return,nt)}}break;case 3:if((e&1024)!==0){if(e=t.stateNode.containerInfo,i=e.nodeType,i===9)Tm(e);else if(i===1)switch(e.nodeName){case"HEAD":case"HTML":case"BODY":Tm(e);break;default:e.textContent=""}}break;case 5:case 26:case 27:case 6:case 4:case 17:break;default:if((e&1024)!==0)throw Error(l(163))}if(e=t.sibling,e!==null){e.return=t.return,On=e;break}On=t.return}}function _g(e,t,i){var o=i.flags;switch(i.tag){case 0:case 11:case 15:Oi(e,i),o&4&&hc(5,i);break;case 1:if(Oi(e,i),o&4)if(e=i.stateNode,t===null)try{e.componentDidMount()}catch(S){zt(i,i.return,S)}else{var f=jl(i.type,t.memoizedProps);t=t.memoizedState;try{e.componentDidUpdate(f,t,e.__reactInternalSnapshotBeforeUpdate)}catch(S){zt(i,i.return,S)}}o&64&&Mg(i),o&512&&pc(i,i.return);break;case 3:if(Oi(e,i),o&64&&(e=i.updateQueue,e!==null)){if(t=null,i.child!==null)switch(i.child.tag){case 27:case 5:t=i.child.stateNode;break;case 1:t=i.child.stateNode}try{ge(e,t)}catch(S){zt(i,i.return,S)}}break;case 27:t===null&&o&4&&Dg(i);case 26:case 5:Oi(e,i),t===null&&o&4&&Eg(i),o&512&&pc(i,i.return);break;case 12:Oi(e,i);break;case 31:Oi(e,i),o&4&&Og(e,i);break;case 13:Oi(e,i),o&4&&Hg(e,i),o&64&&(e=i.memoizedState,e!==null&&(e=e.dehydrated,e!==null&&(i=Ww.bind(null,i),mS(e,i))));break;case 22:if(o=i.memoizedState!==null||zi,!o){t=t!==null&&t.memoizedState!==null||Nn,f=zi;var h=Nn;zi=o,(Nn=t)&&!h?Hi(e,i,(i.subtreeFlags&8772)!==0):Oi(e,i),zi=f,Nn=h}break;case 30:break;default:Oi(e,i)}}function zg(e){var t=e.alternate;t!==null&&(e.alternate=null,zg(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&Ot(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 nn=null,Ta=!1;function Ii(e,t,i){for(i=i.child;i!==null;)Ig(e,t,i),i=i.sibling}function Ig(e,t,i){if(je&&typeof je.onCommitFiberUnmount=="function")try{je.onCommitFiberUnmount(ze,i)}catch{}switch(i.tag){case 26:Nn||ai(i,t),Ii(e,t,i),i.memoizedState?i.memoizedState.count--:i.stateNode&&(i=i.stateNode,i.parentNode.removeChild(i));break;case 27:Nn||ai(i,t);var o=nn,f=Ta;_r(i.type)&&(nn=i.stateNode,Ta=!1),Ii(e,t,i),jc(i.stateNode),nn=o,Ta=f;break;case 5:Nn||ai(i,t);case 6:if(o=nn,f=Ta,nn=null,Ii(e,t,i),nn=o,Ta=f,nn!==null)if(Ta)try{(nn.nodeType===9?nn.body:nn.nodeName==="HTML"?nn.ownerDocument.body:nn).removeChild(i.stateNode)}catch(h){zt(i,t,h)}else try{nn.removeChild(i.stateNode)}catch(h){zt(i,t,h)}break;case 18:nn!==null&&(Ta?(e=nn,Mv(e.nodeType===9?e.body:e.nodeName==="HTML"?e.ownerDocument.body:e,i.stateNode),No(e)):Mv(nn,i.stateNode));break;case 4:o=nn,f=Ta,nn=i.stateNode.containerInfo,Ta=!0,Ii(e,t,i),nn=o,Ta=f;break;case 0:case 11:case 14:case 15:Nr(2,i,t),Nn||Nr(4,i,t),Ii(e,t,i);break;case 1:Nn||(ai(i,t),o=i.stateNode,typeof o.componentWillUnmount=="function"&&Tg(i,t,o)),Ii(e,t,i);break;case 21:Ii(e,t,i);break;case 22:Nn=(o=Nn)||i.memoizedState!==null,Ii(e,t,i),Nn=o;break;default:Ii(e,t,i)}}function Og(e,t){if(t.memoizedState===null&&(e=t.alternate,e!==null&&(e=e.memoizedState,e!==null))){e=e.dehydrated;try{No(e)}catch(i){zt(t,t.return,i)}}}function Hg(e,t){if(t.memoizedState===null&&(e=t.alternate,e!==null&&(e=e.memoizedState,e!==null&&(e=e.dehydrated,e!==null))))try{No(e)}catch(i){zt(t,t.return,i)}}function Bw(e){switch(e.tag){case 31:case 13:case 19:var t=e.stateNode;return t===null&&(t=e.stateNode=new Lg),t;case 22:return e=e.stateNode,t=e._retryCache,t===null&&(t=e._retryCache=new Lg),t;default:throw Error(l(435,e.tag))}}function Gu(e,t){var i=Bw(e);t.forEach(function(o){if(!i.has(o)){i.add(o);var f=Yw.bind(null,e,o);o.then(f,f)}})}function Ea(e,t){var i=t.deletions;if(i!==null)for(var o=0;o<i.length;o++){var f=i[o],h=e,S=t,E=S;e:for(;E!==null;){switch(E.tag){case 27:if(_r(E.type)){nn=E.stateNode,Ta=!1;break e}break;case 5:nn=E.stateNode,Ta=!1;break e;case 3:case 4:nn=E.stateNode.containerInfo,Ta=!0;break e}E=E.return}if(nn===null)throw Error(l(160));Ig(h,S,f),nn=null,Ta=!1,h=f.alternate,h!==null&&(h.return=null),f.return=null}if(t.subtreeFlags&13886)for(t=t.child;t!==null;)Bg(t,e),t=t.sibling}var Ts=null;function Bg(e,t){var i=e.alternate,o=e.flags;switch(e.tag){case 0:case 11:case 14:case 15:Ea(t,e),Ra(e),o&4&&(Nr(3,e,e.return),hc(3,e),Nr(5,e,e.return));break;case 1:Ea(t,e),Ra(e),o&512&&(Nn||i===null||ai(i,i.return)),o&64&&zi&&(e=e.updateQueue,e!==null&&(o=e.callbacks,o!==null&&(i=e.shared.hiddenCallbacks,e.shared.hiddenCallbacks=i===null?o:i.concat(o))));break;case 26:var f=Ts;if(Ea(t,e),Ra(e),o&512&&(Nn||i===null||ai(i,i.return)),o&4){var h=i!==null?i.memoizedState:null;if(o=e.memoizedState,i===null)if(o===null)if(e.stateNode===null){e:{o=e.type,i=e.memoizedProps,f=f.ownerDocument||f;t:switch(o){case"title":h=f.getElementsByTagName("title")[0],(!h||h[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,i),h[ne]=e,Tt(h),o=h;break e;case"link":var S=Bv("link","href",f).get(o+(i.href||""));if(S){for(var E=0;E<S.length;E++)if(h=S[E],h.getAttribute("href")===(i.href==null||i.href===""?null:i.href)&&h.getAttribute("rel")===(i.rel==null?null:i.rel)&&h.getAttribute("title")===(i.title==null?null:i.title)&&h.getAttribute("crossorigin")===(i.crossOrigin==null?null:i.crossOrigin)){S.splice(E,1);break t}}h=f.createElement(o),Kn(h,o,i),f.head.appendChild(h);break;case"meta":if(S=Bv("meta","content",f).get(o+(i.content||""))){for(E=0;E<S.length;E++)if(h=S[E],h.getAttribute("content")===(i.content==null?null:""+i.content)&&h.getAttribute("name")===(i.name==null?null:i.name)&&h.getAttribute("property")===(i.property==null?null:i.property)&&h.getAttribute("http-equiv")===(i.httpEquiv==null?null:i.httpEquiv)&&h.getAttribute("charset")===(i.charSet==null?null:i.charSet)){S.splice(E,1);break t}}h=f.createElement(o),Kn(h,o,i),f.head.appendChild(h);break;default:throw Error(l(468,o))}h[ne]=e,Tt(h),o=h}e.stateNode=o}else Fv(f,e.type,e.stateNode);else e.stateNode=Hv(f,o,e.memoizedProps);else h!==o?(h===null?i.stateNode!==null&&(i=i.stateNode,i.parentNode.removeChild(i)):h.count--,o===null?Fv(f,e.type,e.stateNode):Hv(f,o,e.memoizedProps)):o===null&&e.stateNode!==null&&tm(e,e.memoizedProps,i.memoizedProps)}break;case 27:Ea(t,e),Ra(e),o&512&&(Nn||i===null||ai(i,i.return)),i!==null&&o&4&&tm(e,e.memoizedProps,i.memoizedProps);break;case 5:if(Ea(t,e),Ra(e),o&512&&(Nn||i===null||ai(i,i.return)),e.flags&32){f=e.stateNode;try{Fa(f,"")}catch(Ve){zt(e,e.return,Ve)}}o&4&&e.stateNode!=null&&(f=e.memoizedProps,tm(e,f,i!==null?i.memoizedProps:f)),o&1024&&(sm=!0);break;case 6:if(Ea(t,e),Ra(e),o&4){if(e.stateNode===null)throw Error(l(162));o=e.memoizedProps,i=e.stateNode;try{i.nodeValue=o}catch(Ve){zt(e,e.return,Ve)}}break;case 3:if(ld=null,f=Ts,Ts=id(t.containerInfo),Ea(t,e),Ts=f,Ra(e),o&4&&i!==null&&i.memoizedState.isDehydrated)try{No(t.containerInfo)}catch(Ve){zt(e,e.return,Ve)}sm&&(sm=!1,Fg(e));break;case 4:o=Ts,Ts=id(e.stateNode.containerInfo),Ea(t,e),Ra(e),Ts=o;break;case 12:Ea(t,e),Ra(e);break;case 31:Ea(t,e),Ra(e),o&4&&(o=e.updateQueue,o!==null&&(e.updateQueue=null,Gu(e,o)));break;case 13:Ea(t,e),Ra(e),e.child.flags&8192&&e.memoizedState!==null!=(i!==null&&i.memoizedState!==null)&&(Wu=vt()),o&4&&(o=e.updateQueue,o!==null&&(e.updateQueue=null,Gu(e,o)));break;case 22:f=e.memoizedState!==null;var F=i!==null&&i.memoizedState!==null,oe=zi,xe=Nn;if(zi=oe||f,Nn=xe||F,Ea(t,e),Nn=xe,zi=oe,Ra(e),o&8192)e:for(t=e.stateNode,t._visibility=f?t._visibility&-2:t._visibility|1,f&&(i===null||F||zi||Nn||kl(e)),i=null,t=e;;){if(t.tag===5||t.tag===26){if(i===null){F=i=t;try{if(h=F.stateNode,f)S=h.style,typeof S.setProperty=="function"?S.setProperty("display","none","important"):S.display="none";else{E=F.stateNode;var Ce=F.memoizedProps.style,ce=Ce!=null&&Ce.hasOwnProperty("display")?Ce.display:null;E.style.display=ce==null||typeof ce=="boolean"?"":(""+ce).trim()}}catch(Ve){zt(F,F.return,Ve)}}}else if(t.tag===6){if(i===null){F=t;try{F.stateNode.nodeValue=f?"":F.memoizedProps}catch(Ve){zt(F,F.return,Ve)}}}else if(t.tag===18){if(i===null){F=t;try{var he=F.stateNode;f?Tv(he,!0):Tv(F.stateNode,!1)}catch(Ve){zt(F,F.return,Ve)}}}else if((t.tag!==22&&t.tag!==23||t.memoizedState===null||t===e)&&t.child!==null){t.child.return=t,t=t.child;continue}if(t===e)break e;for(;t.sibling===null;){if(t.return===null||t.return===e)break e;i===t&&(i=null),t=t.return}i===t&&(i=null),t.sibling.return=t.return,t=t.sibling}o&4&&(o=e.updateQueue,o!==null&&(i=o.retryQueue,i!==null&&(o.retryQueue=null,Gu(e,i))));break;case 19:Ea(t,e),Ra(e),o&4&&(o=e.updateQueue,o!==null&&(e.updateQueue=null,Gu(e,o)));break;case 30:break;case 21:break;default:Ea(t,e),Ra(e)}}function Ra(e){var t=e.flags;if(t&2){try{for(var i,o=e.return;o!==null;){if(Rg(o)){i=o;break}o=o.return}if(i==null)throw Error(l(160));switch(i.tag){case 27:var f=i.stateNode,h=nm(e);qu(e,h,f);break;case 5:var S=i.stateNode;i.flags&32&&(Fa(S,""),i.flags&=-33);var E=nm(e);qu(e,E,S);break;case 3:case 4:var F=i.stateNode.containerInfo,oe=nm(e);am(e,oe,F);break;default:throw Error(l(161))}}catch(xe){zt(e,e.return,xe)}e.flags&=-3}t&4096&&(e.flags&=-4097)}function Fg(e){if(e.subtreeFlags&1024)for(e=e.child;e!==null;){var t=e;Fg(t),t.tag===5&&t.flags&1024&&t.stateNode.reset(),e=e.sibling}}function Oi(e,t){if(t.subtreeFlags&8772)for(t=t.child;t!==null;)_g(e,t.alternate,t),t=t.sibling}function kl(e){for(e=e.child;e!==null;){var t=e;switch(t.tag){case 0:case 11:case 14:case 15:Nr(4,t,t.return),kl(t);break;case 1:ai(t,t.return);var i=t.stateNode;typeof i.componentWillUnmount=="function"&&Tg(t,t.return,i),kl(t);break;case 27:jc(t.stateNode);case 26:case 5:ai(t,t.return),kl(t);break;case 22:t.memoizedState===null&&kl(t);break;case 30:kl(t);break;default:kl(t)}e=e.sibling}}function Hi(e,t,i){for(i=i&&(t.subtreeFlags&8772)!==0,t=t.child;t!==null;){var o=t.alternate,f=e,h=t,S=h.flags;switch(h.tag){case 0:case 11:case 15:Hi(f,h,i),hc(4,h);break;case 1:if(Hi(f,h,i),o=h,f=o.stateNode,typeof f.componentDidMount=="function")try{f.componentDidMount()}catch(oe){zt(o,o.return,oe)}if(o=h,f=o.updateQueue,f!==null){var E=o.stateNode;try{var F=f.shared.hiddenCallbacks;if(F!==null)for(f.shared.hiddenCallbacks=null,f=0;f<F.length;f++)z(F[f],E)}catch(oe){zt(o,o.return,oe)}}i&&S&64&&Mg(h),pc(h,h.return);break;case 27:Dg(h);case 26:case 5:Hi(f,h,i),i&&o===null&&S&4&&Eg(h),pc(h,h.return);break;case 12:Hi(f,h,i);break;case 31:Hi(f,h,i),i&&S&4&&Og(f,h);break;case 13:Hi(f,h,i),i&&S&4&&Hg(f,h);break;case 22:h.memoizedState===null&&Hi(f,h,i),pc(h,h.return);break;case 30:break;default:Hi(f,h,i)}t=t.sibling}}function im(e,t){var i=null;e!==null&&e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(i=e.memoizedState.cachePool.pool),e=null,t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(e=t.memoizedState.cachePool.pool),e!==i&&(e!=null&&e.refCount++,i!=null&&os(i))}function rm(e,t){e=null,t.alternate!==null&&(e=t.alternate.memoizedState.cache),t=t.memoizedState.cache,t!==e&&(t.refCount++,e!=null&&os(e))}function Es(e,t,i,o){if(t.subtreeFlags&10256)for(t=t.child;t!==null;)Pg(e,t,i,o),t=t.sibling}function Pg(e,t,i,o){var f=t.flags;switch(t.tag){case 0:case 11:case 15:Es(e,t,i,o),f&2048&&hc(9,t);break;case 1:Es(e,t,i,o);break;case 3:Es(e,t,i,o),f&2048&&(e=null,t.alternate!==null&&(e=t.alternate.memoizedState.cache),t=t.memoizedState.cache,t!==e&&(t.refCount++,e!=null&&os(e)));break;case 12:if(f&2048){Es(e,t,i,o),e=t.stateNode;try{var h=t.memoizedProps,S=h.id,E=h.onPostCommit;typeof E=="function"&&E(S,t.alternate===null?"mount":"update",e.passiveEffectDuration,-0)}catch(F){zt(t,t.return,F)}}else Es(e,t,i,o);break;case 31:Es(e,t,i,o);break;case 13:Es(e,t,i,o);break;case 23:break;case 22:h=t.stateNode,S=t.alternate,t.memoizedState!==null?h._visibility&2?Es(e,t,i,o):gc(e,t):h._visibility&2?Es(e,t,i,o):(h._visibility|=2,go(e,t,i,o,(t.subtreeFlags&10256)!==0||!1)),f&2048&&im(S,t);break;case 24:Es(e,t,i,o),f&2048&&rm(t.alternate,t);break;default:Es(e,t,i,o)}}function go(e,t,i,o,f){for(f=f&&((t.subtreeFlags&10256)!==0||!1),t=t.child;t!==null;){var h=e,S=t,E=i,F=o,oe=S.flags;switch(S.tag){case 0:case 11:case 15:go(h,S,E,F,f),hc(8,S);break;case 23:break;case 22:var xe=S.stateNode;S.memoizedState!==null?xe._visibility&2?go(h,S,E,F,f):gc(h,S):(xe._visibility|=2,go(h,S,E,F,f)),f&&oe&2048&&im(S.alternate,S);break;case 24:go(h,S,E,F,f),f&&oe&2048&&rm(S.alternate,S);break;default:go(h,S,E,F,f)}t=t.sibling}}function gc(e,t){if(t.subtreeFlags&10256)for(t=t.child;t!==null;){var i=e,o=t,f=o.flags;switch(o.tag){case 22:gc(i,o),f&2048&&im(o.alternate,o);break;case 24:gc(i,o),f&2048&&rm(o.alternate,o);break;default:gc(i,o)}t=t.sibling}}var vc=8192;function vo(e,t,i){if(e.subtreeFlags&vc)for(e=e.child;e!==null;)$g(e,t,i),e=e.sibling}function $g(e,t,i){switch(e.tag){case 26:vo(e,t,i),e.flags&vc&&e.memoizedState!==null&&kS(i,Ts,e.memoizedState,e.memoizedProps);break;case 5:vo(e,t,i);break;case 3:case 4:var o=Ts;Ts=id(e.stateNode.containerInfo),vo(e,t,i),Ts=o;break;case 22:e.memoizedState===null&&(o=e.alternate,o!==null&&o.memoizedState!==null?(o=vc,vc=16777216,vo(e,t,i),vc=o):vo(e,t,i));break;default:vo(e,t,i)}}function Ug(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 xc(e){var t=e.deletions;if((e.flags&16)!==0){if(t!==null)for(var i=0;i<t.length;i++){var o=t[i];On=o,Gg(o,e)}Ug(e)}if(e.subtreeFlags&10256)for(e=e.child;e!==null;)qg(e),e=e.sibling}function qg(e){switch(e.tag){case 0:case 11:case 15:xc(e),e.flags&2048&&Nr(9,e,e.return);break;case 3:xc(e);break;case 12:xc(e);break;case 22:var t=e.stateNode;e.memoizedState!==null&&t._visibility&2&&(e.return===null||e.return.tag!==13)?(t._visibility&=-3,Vu(e)):xc(e);break;default:xc(e)}}function Vu(e){var t=e.deletions;if((e.flags&16)!==0){if(t!==null)for(var i=0;i<t.length;i++){var o=t[i];On=o,Gg(o,e)}Ug(e)}for(e=e.child;e!==null;){switch(t=e,t.tag){case 0:case 11:case 15:Nr(8,t,t.return),Vu(t);break;case 22:i=t.stateNode,i._visibility&2&&(i._visibility&=-3,Vu(t));break;default:Vu(t)}e=e.sibling}}function Gg(e,t){for(;On!==null;){var i=On;switch(i.tag){case 0:case 11:case 15:Nr(8,i,t);break;case 23:case 22:if(i.memoizedState!==null&&i.memoizedState.cachePool!==null){var o=i.memoizedState.cachePool.pool;o!=null&&o.refCount++}break;case 24:os(i.memoizedState.cache)}if(o=i.child,o!==null)o.return=i,On=o;else e:for(i=e;On!==null;){o=On;var f=o.sibling,h=o.return;if(zg(o),o===i){On=null;break e}if(f!==null){f.return=h,On=f;break e}On=h}}}var Fw={getCacheForType:function(e){var t=En(Qe),i=t.data.get(e);return i===void 0&&(i=e(),t.data.set(e,i)),i},cacheSignal:function(){return En(Qe).controller.signal}},Pw=typeof WeakMap=="function"?WeakMap:Map,Rt=0,qt=null,yt=null,St=0,_t=0,Ga=null,Mr=!1,xo=!1,lm=!1,Bi=0,hn=0,Tr=0,Al=0,om=0,Va=0,yo=0,yc=null,Da=null,cm=!1,Wu=0,Vg=0,Yu=1/0,Ku=null,Er=null,Dn=0,Rr=null,bo=null,Fi=0,um=0,dm=null,Wg=null,bc=0,fm=null;function Wa(){return(Rt&2)!==0&&St!==0?St&-St:I.T!==null?xm():es()}function Yg(){if(Va===0)if((St&536870912)===0||xt){var e=$t;$t<<=1,($t&3932160)===0&&($t=262144),Va=e}else Va=536870912;return e=Dt.current,e!==null&&(e.flags|=32),Va}function La(e,t,i){(e===qt&&(_t===2||_t===9)||e.cancelPendingCommit!==null)&&(wo(e,0),Dr(e,St,Va,!1)),ut(e,i),((Rt&2)===0||e!==qt)&&(e===qt&&((Rt&2)===0&&(Al|=i),hn===4&&Dr(e,St,Va,!1)),si(e))}function Kg(e,t,i){if((Rt&6)!==0)throw Error(l(327));var o=!i&&(t&127)===0&&(t&e.expiredLanes)===0||Xn(e,t),f=o?qw(e,t):hm(e,t,!0),h=o;do{if(f===0){xo&&!o&&Dr(e,t,0,!1);break}else{if(i=e.current.alternate,h&&!$w(i)){f=hm(e,t,!1),h=!1;continue}if(f===2){if(h=t,e.errorRecoveryDisabledLanes&h)var S=0;else S=e.pendingLanes&-536870913,S=S!==0?S:S&536870912?536870912:0;if(S!==0){t=S;e:{var E=e;f=yc;var F=E.current.memoizedState.isDehydrated;if(F&&(wo(E,S).flags|=256),S=hm(E,S,!1),S!==2){if(lm&&!F){E.errorRecoveryDisabledLanes|=h,Al|=h,f=4;break e}h=Da,Da=f,h!==null&&(Da===null?Da=h:Da.push.apply(Da,h))}f=S}if(h=!1,f!==2)continue}}if(f===1){wo(e,0),Dr(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:Dr(o,t,Va,!Mr);break e;case 2:Da=null;break;case 3:case 5:break;default:throw Error(l(329))}if((t&62914560)===t&&(f=Wu+300-vt(),10<f)){if(Dr(o,t,Va,!Mr),Ja(o,0,!0)!==0)break e;Fi=t,o.timeoutHandle=Av(Qg.bind(null,o,i,Da,Ku,cm,t,Va,Al,yo,Mr,h,"Throttled",-0,0),f);break e}Qg(o,i,Da,Ku,cm,t,Va,Al,yo,Mr,h,null,-0,0)}}break}while(!0);si(e)}function Qg(e,t,i,o,f,h,S,E,F,oe,xe,Ce,ce,he){if(e.timeoutHandle=-1,Ce=t.subtreeFlags,Ce&8192||(Ce&16785408)===16785408){Ce={stylesheets:null,count:0,imgCount:0,imgBytes:0,suspenseyImages:[],waitingForImages:!0,waitingForViewTransition:!1,unsuspend:Ln},$g(t,h,Ce);var Ve=(h&62914560)===h?Wu-vt():(h&4194048)===h?Vg-vt():0;if(Ve=AS(Ce,Ve),Ve!==null){Fi=h,e.cancelPendingCommit=Ve(sv.bind(null,e,t,h,i,o,f,S,E,F,xe,Ce,null,ce,he)),Dr(e,h,S,!oe);return}}sv(e,t,h,i,o,f,S,E,F)}function $w(e){for(var t=e;;){var i=t.tag;if((i===0||i===11||i===15)&&t.flags&16384&&(i=t.updateQueue,i!==null&&(i=i.stores,i!==null)))for(var o=0;o<i.length;o++){var f=i[o],h=f.getSnapshot;f=f.value;try{if(!na(h(),f))return!1}catch{return!1}}if(i=t.child,t.subtreeFlags&16384&&i!==null)i.return=t,t=i;else{if(t===e)break;for(;t.sibling===null;){if(t.return===null||t.return===e)return!0;t=t.return}t.sibling.return=t.return,t=t.sibling}}return!0}function Dr(e,t,i,o){t&=~om,t&=~Al,e.suspendedLanes|=t,e.pingedLanes&=~t,o&&(e.warmLanes|=t),o=e.expirationTimes;for(var f=t;0<f;){var h=31-gt(f),S=1<<h;o[h]=-1,f&=~S}i!==0&&Kt(e,i,t)}function Qu(){return(Rt&6)===0?(wc(0),!1):!0}function mm(){if(yt!==null){if(_t===0)var e=yt.return;else e=yt,In=ls=null,Tf(e),kr=null,bl=0,e=yt;for(;e!==null;)Ng(e.alternate,e),e=e.return;yt=null}}function wo(e,t){var i=e.timeoutHandle;i!==-1&&(e.timeoutHandle=-1,oS(i)),i=e.cancelPendingCommit,i!==null&&(e.cancelPendingCommit=null,i()),Fi=0,mm(),qt=e,yt=i=Vn(e.current,null),St=t,_t=0,Ga=null,Mr=!1,xo=Xn(e,t),lm=!1,yo=Va=om=Al=Tr=hn=0,Da=yc=null,cm=!1,(t&8)!==0&&(t|=t&32);var o=e.entangledLanes;if(o!==0)for(e=e.entanglements,o&=t;0<o;){var f=31-gt(o),h=1<<f;t|=e[f],o&=~h}return Bi=t,Si(),i}function Xg(e,t){dt=null,I.H=dc,t===vl||t===uo?(t=Au(),_t=3):t===lc?(t=Au(),_t=4):_t=t===Gf?8:t!==null&&typeof t=="object"&&typeof t.then=="function"?6:1,Ga=t,yt===null&&(hn=1,Bu(e,Aa(t,e.current)))}function Zg(){var e=Dt.current;return e===null?!0:(St&4194048)===St?tn===null:(St&62914560)===St||(St&536870912)!==0?e===tn:!1}function Jg(){var e=I.H;return I.H=dc,e===null?dc:e}function ev(){var e=I.A;return I.A=Fw,e}function Xu(){hn=4,Mr||(St&4194048)!==St&&Dt.current!==null||(xo=!0),(Tr&134217727)===0&&(Al&134217727)===0||qt===null||Dr(qt,St,Va,!1)}function hm(e,t,i){var o=Rt;Rt|=2;var f=Jg(),h=ev();(qt!==e||St!==t)&&(Ku=null,wo(e,t)),t=!1;var S=hn;e:do try{if(_t!==0&&yt!==null){var E=yt,F=Ga;switch(_t){case 8:mm(),S=6;break e;case 3:case 2:case 9:case 6:Dt.current===null&&(t=!0);var oe=_t;if(_t=0,Ga=null,So(e,E,F,oe),i&&xo){S=0;break e}break;default:oe=_t,_t=0,Ga=null,So(e,E,F,oe)}}Uw(),S=hn;break}catch(xe){Xg(e,xe)}while(!0);return t&&e.shellSuspendCounter++,In=ls=null,Rt=o,I.H=f,I.A=h,yt===null&&(qt=null,St=0,Si()),S}function Uw(){for(;yt!==null;)tv(yt)}function qw(e,t){var i=Rt;Rt|=2;var o=Jg(),f=ev();qt!==e||St!==t?(Ku=null,Yu=vt()+500,wo(e,t)):xo=Xn(e,t);e:do try{if(_t!==0&&yt!==null){t=yt;var h=Ga;t:switch(_t){case 1:_t=0,Ga=null,So(e,t,h,1);break;case 2:case 9:if(yl(h)){_t=0,Ga=null,nv(t);break}t=function(){_t!==2&&_t!==9||qt!==e||(_t=7),si(e)},h.then(t,t);break e;case 3:_t=7;break e;case 4:_t=5;break e;case 7:yl(h)?(_t=0,Ga=null,nv(t)):(_t=0,Ga=null,So(e,t,h,7));break;case 5:var S=null;switch(yt.tag){case 26:S=yt.memoizedState;case 5:case 27:var E=yt;if(S?Pv(S):E.stateNode.complete){_t=0,Ga=null;var F=E.sibling;if(F!==null)yt=F;else{var oe=E.return;oe!==null?(yt=oe,Zu(oe)):yt=null}break t}}_t=0,Ga=null,So(e,t,h,5);break;case 6:_t=0,Ga=null,So(e,t,h,6);break;case 8:mm(),hn=6;break e;default:throw Error(l(462))}}Gw();break}catch(xe){Xg(e,xe)}while(!0);return In=ls=null,I.H=o,I.A=f,Rt=i,yt!==null?0:(qt=null,St=0,Si(),hn)}function Gw(){for(;yt!==null&&!Ye();)tv(yt)}function tv(e){var t=kg(e.alternate,e,Bi);e.memoizedProps=e.pendingProps,t===null?Zu(e):yt=t}function nv(e){var t=e,i=t.alternate;switch(t.tag){case 15:case 0:t=yg(i,t,t.pendingProps,t.type,void 0,St);break;case 11:t=yg(i,t,t.pendingProps,t.type.render,t.ref,St);break;case 5:Tf(t);default:Ng(i,t),t=yt=ul(t,Bi),t=kg(i,t,Bi)}e.memoizedProps=e.pendingProps,t===null?Zu(e):yt=t}function So(e,t,i,o){In=ls=null,Tf(t),kr=null,bl=0;var f=t.return;try{if(Lw(e,f,t,i,St)){hn=1,Bu(e,Aa(i,e.current)),yt=null;return}}catch(h){if(f!==null)throw yt=f,h;hn=1,Bu(e,Aa(i,e.current)),yt=null;return}t.flags&32768?(xt||o===1?e=!0:xo||(St&536870912)!==0?e=!1:(Mr=e=!0,(o===2||o===9||o===3||o===6)&&(o=Dt.current,o!==null&&o.tag===13&&(o.flags|=16384))),av(t,e)):Zu(t)}function Zu(e){var t=e;do{if((t.flags&32768)!==0){av(t,Mr);return}e=t.return;var i=Iw(t.alternate,t,Bi);if(i!==null){yt=i;return}if(t=t.sibling,t!==null){yt=t;return}yt=t=e}while(t!==null);hn===0&&(hn=5)}function av(e,t){do{var i=Ow(e.alternate,e);if(i!==null){i.flags&=32767,yt=i;return}if(i=e.return,i!==null&&(i.flags|=32768,i.subtreeFlags=0,i.deletions=null),!t&&(e=e.sibling,e!==null)){yt=e;return}yt=e=i}while(e!==null);hn=6,yt=null}function sv(e,t,i,o,f,h,S,E,F){e.cancelPendingCommit=null;do Ju();while(Dn!==0);if((Rt&6)!==0)throw Error(l(327));if(t!==null){if(t===e.current)throw Error(l(177));if(h=t.lanes|t.childLanes,h|=ao,ui(e,i,h,S,E,F),e===qt&&(yt=qt=null,St=0),bo=t,Rr=e,Fi=i,um=h,dm=f,Wg=o,(t.subtreeFlags&10256)!==0||(t.flags&10256)!==0?(e.callbackNode=null,e.callbackPriority=0,Kw(ht,function(){return cv(),null})):(e.callbackNode=null,e.callbackPriority=0),o=(t.flags&13878)!==0,(t.subtreeFlags&13878)!==0||o){o=I.T,I.T=null,f=Q.p,Q.p=2,S=Rt,Rt|=4;try{Hw(e,t,i)}finally{Rt=S,Q.p=f,I.T=o}}Dn=1,iv(),rv(),lv()}}function iv(){if(Dn===1){Dn=0;var e=Rr,t=bo,i=(t.flags&13878)!==0;if((t.subtreeFlags&13878)!==0||i){i=I.T,I.T=null;var o=Q.p;Q.p=2;var f=Rt;Rt|=4;try{Bg(t,e);var h=Am,S=xi(e.containerInfo),E=h.focusedElem,F=h.selectionRange;if(S!==E&&E&&E.ownerDocument&&Ko(E.ownerDocument.documentElement,E)){if(F!==null&&to(E)){var oe=F.start,xe=F.end;if(xe===void 0&&(xe=oe),"selectionStart"in E)E.selectionStart=oe,E.selectionEnd=Math.min(xe,E.value.length);else{var Ce=E.ownerDocument||document,ce=Ce&&Ce.defaultView||window;if(ce.getSelection){var he=ce.getSelection(),Ve=E.textContent.length,nt=Math.min(F.start,Ve),Pt=F.end===void 0?nt:Math.min(F.end,Ve);!he.extend&&nt>Pt&&(S=Pt,Pt=nt,nt=S);var ee=sl(E,nt),V=sl(E,Pt);if(ee&&V&&(he.rangeCount!==1||he.anchorNode!==ee.node||he.anchorOffset!==ee.offset||he.focusNode!==V.node||he.focusOffset!==V.offset)){var re=Ce.createRange();re.setStart(ee.node,ee.offset),he.removeAllRanges(),nt>Pt?(he.addRange(re),he.extend(V.node,V.offset)):(re.setEnd(V.node,V.offset),he.addRange(re))}}}}for(Ce=[],he=E;he=he.parentNode;)he.nodeType===1&&Ce.push({element:he,left:he.scrollLeft,top:he.scrollTop});for(typeof E.focus=="function"&&E.focus(),E=0;E<Ce.length;E++){var we=Ce[E];we.element.scrollLeft=we.left,we.element.scrollTop=we.top}}dd=!!km,Am=km=null}finally{Rt=f,Q.p=o,I.T=i}}e.current=t,Dn=2}}function rv(){if(Dn===2){Dn=0;var e=Rr,t=bo,i=(t.flags&8772)!==0;if((t.subtreeFlags&8772)!==0||i){i=I.T,I.T=null;var o=Q.p;Q.p=2;var f=Rt;Rt|=4;try{_g(e,t.alternate,t)}finally{Rt=f,Q.p=o,I.T=i}}Dn=3}}function lv(){if(Dn===4||Dn===3){Dn=0,rt();var e=Rr,t=bo,i=Fi,o=Wg;(t.subtreeFlags&10256)!==0||(t.flags&10256)!==0?Dn=5:(Dn=0,bo=Rr=null,ov(e,e.pendingLanes));var f=e.pendingLanes;if(f===0&&(Er=null),on(i),t=t.stateNode,je&&typeof je.onCommitFiberRoot=="function")try{je.onCommitFiberRoot(ze,t,void 0,(t.current.flags&128)===128)}catch{}if(o!==null){t=I.T,f=Q.p,Q.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,Q.p=f}}(Fi&3)!==0&&Ju(),si(e),f=e.pendingLanes,(i&261930)!==0&&(f&42)!==0?e===fm?bc++:(bc=0,fm=e):bc=0,wc(0)}}function ov(e,t){(e.pooledCacheLanes&=t)===0&&(t=e.pooledCache,t!=null&&(e.pooledCache=null,os(t)))}function Ju(){return iv(),rv(),lv(),cv()}function cv(){if(Dn!==5)return!1;var e=Rr,t=um;um=0;var i=on(Fi),o=I.T,f=Q.p;try{Q.p=32>i?32:i,I.T=null,i=dm,dm=null;var h=Rr,S=Fi;if(Dn=0,bo=Rr=null,Fi=0,(Rt&6)!==0)throw Error(l(331));var E=Rt;if(Rt|=4,qg(h.current),Pg(h,h.current,S,i),Rt=E,wc(0,!1),je&&typeof je.onPostCommitFiberRoot=="function")try{je.onPostCommitFiberRoot(ze,h)}catch{}return!0}finally{Q.p=f,I.T=o,ov(e,t)}}function uv(e,t,i){t=Aa(i,t),t=qf(e.stateNode,t,2),e=ia(e,t,2),e!==null&&(ut(e,2),si(e))}function zt(e,t,i){if(e.tag===3)uv(e,e,i);else for(;t!==null;){if(t.tag===3){uv(t,e,i);break}else if(t.tag===1){var o=t.stateNode;if(typeof t.type.getDerivedStateFromError=="function"||typeof o.componentDidCatch=="function"&&(Er===null||!Er.has(o))){e=Aa(i,e),i=dg(2),o=ia(t,i,2),o!==null&&(fg(i,o,t,e),ut(o,2),si(o));break}}t=t.return}}function pm(e,t,i){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(i)||(lm=!0,f.add(i),e=Vw.bind(null,e,t,i),t.then(e,e))}function Vw(e,t,i){var o=e.pingCache;o!==null&&o.delete(t),e.pingedLanes|=e.suspendedLanes&i,e.warmLanes&=~i,qt===e&&(St&i)===i&&(hn===4||hn===3&&(St&62914560)===St&&300>vt()-Wu?(Rt&2)===0&&wo(e,0):om|=i,yo===St&&(yo=0)),si(e)}function dv(e,t){t===0&&(t=Fe()),e=is(e,t),e!==null&&(ut(e,t),si(e))}function Ww(e){var t=e.memoizedState,i=0;t!==null&&(i=t.retryLane),dv(e,i)}function Yw(e,t){var i=0;switch(e.tag){case 31:case 13:var o=e.stateNode,f=e.memoizedState;f!==null&&(i=f.retryLane);break;case 19:o=e.stateNode;break;case 22:o=e.stateNode._retryCache;break;default:throw Error(l(314))}o!==null&&o.delete(t),dv(e,i)}function Kw(e,t){return Mt(e,t)}var ed=null,Co=null,gm=!1,td=!1,vm=!1,Lr=0;function si(e){e!==Co&&e.next===null&&(Co===null?ed=Co=e:Co=Co.next=e),td=!0,gm||(gm=!0,Xw())}function wc(e,t){if(!vm&&td){vm=!0;do for(var i=!1,o=ed;o!==null;){if(e!==0){var f=o.pendingLanes;if(f===0)var h=0;else{var S=o.suspendedLanes,E=o.pingedLanes;h=(1<<31-gt(42|e)+1)-1,h&=f&~(S&~E),h=h&201326741?h&201326741|1:h?h|2:0}h!==0&&(i=!0,pv(o,h))}else h=St,h=Ja(o,o===qt?h:0,o.cancelPendingCommit!==null||o.timeoutHandle!==-1),(h&3)===0||Xn(o,h)||(i=!0,pv(o,h));o=o.next}while(i);vm=!1}}function Qw(){fv()}function fv(){td=gm=!1;var e=0;Lr!==0&&lS()&&(e=Lr);for(var t=vt(),i=null,o=ed;o!==null;){var f=o.next,h=mv(o,t);h===0?(o.next=null,i===null?ed=f:i.next=f,f===null&&(Co=i)):(i=o,(e!==0||(h&3)!==0)&&(td=!0)),o=f}Dn!==0&&Dn!==5||wc(e),Lr!==0&&(Lr=0)}function mv(e,t){for(var i=e.suspendedLanes,o=e.pingedLanes,f=e.expirationTimes,h=e.pendingLanes&-62914561;0<h;){var S=31-gt(h),E=1<<S,F=f[S];F===-1?((E&i)===0||(E&o)!==0)&&(f[S]=Wi(E,t)):F<=t&&(e.expiredLanes|=E),h&=~E}if(t=qt,i=St,i=Ja(e,e===t?i:0,e.cancelPendingCommit!==null||e.timeoutHandle!==-1),o=e.callbackNode,i===0||e===t&&(_t===2||_t===9)||e.cancelPendingCommit!==null)return o!==null&&o!==null&&ke(o),e.callbackNode=null,e.callbackPriority=0;if((i&3)===0||Xn(e,i)){if(t=i&-i,t===e.callbackPriority)return t;switch(o!==null&&ke(o),on(i)){case 2:case 8:i=Zt;break;case 32:i=ht;break;case 268435456:i=Gt;break;default:i=ht}return o=hv.bind(null,e),i=Mt(i,o),e.callbackPriority=t,e.callbackNode=i,t}return o!==null&&o!==null&&ke(o),e.callbackPriority=2,e.callbackNode=null,2}function hv(e,t){if(Dn!==0&&Dn!==5)return e.callbackNode=null,e.callbackPriority=0,null;var i=e.callbackNode;if(Ju()&&e.callbackNode!==i)return null;var o=St;return o=Ja(e,e===qt?o:0,e.cancelPendingCommit!==null||e.timeoutHandle!==-1),o===0?null:(Kg(e,o,t),mv(e,vt()),e.callbackNode!=null&&e.callbackNode===i?hv.bind(null,e):null)}function pv(e,t){if(Ju())return null;Kg(e,t,!0)}function Xw(){cS(function(){(Rt&6)!==0?Mt(It,Qw):fv()})}function xm(){if(Lr===0){var e=wr;e===0&&(e=tt,tt<<=1,(tt&261888)===0&&(tt=256)),Lr=e}return Lr}function gv(e){return e==null||typeof e=="symbol"||typeof e=="boolean"?null:typeof e=="function"?e:Kr(""+e)}function vv(e,t){var i=t.ownerDocument.createElement("input");return i.name=t.name,i.value=t.value,e.id&&i.setAttribute("form",e.id),t.parentNode.insertBefore(i,t),e=new FormData(e),i.parentNode.removeChild(i),e}function Zw(e,t,i,o,f){if(t==="submit"&&i&&i.stateNode===f){var h=gv((f[Ae]||null).action),S=o.submitter;S&&(t=(t=S[Ae]||null)?gv(t.formAction):S.getAttribute("formAction"),t!==null&&(h=t,S=null));var E=new nr("action","action",null,o,f);e.push({event:E,listeners:[{instance:null,listener:function(){if(o.defaultPrevented){if(Lr!==0){var F=S?vv(f,S):new FormData(f);Hf(i,{pending:!0,data:F,method:f.method,action:h},null,F)}}else typeof h=="function"&&(E.preventDefault(),F=S?vv(f,S):new FormData(f),Hf(i,{pending:!0,data:F,method:f.method,action:h},h,F))},currentTarget:f}]})}}for(var ym=0;ym<ll.length;ym++){var bm=ll[ym],Jw=bm.toLowerCase(),eS=bm[0].toUpperCase()+bm.slice(1);ma(Jw,"on"+eS)}ma(Zo,"onAnimationEnd"),ma(js,"onAnimationIteration"),ma(rl,"onAnimationStart"),ma("dblclick","onDoubleClick"),ma("focusin","onFocus"),ma("focusout","onBlur"),ma(mr,"onTransitionRun"),ma(wi,"onTransitionStart"),ma(Jo,"onTransitionCancel"),ma(bu,"onTransitionEnd"),dn("onMouseEnter",["mouseout","mouseover"]),dn("onMouseLeave",["mouseout","mouseover"]),dn("onPointerEnter",["pointerout","pointerover"]),dn("onPointerLeave",["pointerout","pointerover"]),un("onChange","change click focusin focusout input keydown keyup selectionchange".split(" ")),un("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" ")),un("onBeforeInput",["compositionend","keypress","textInput","paste"]),un("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" ")),un("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" ")),un("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var Sc="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(Sc));function xv(e,t){t=(t&4)!==0;for(var i=0;i<e.length;i++){var o=e[i],f=o.event;o=o.listeners;e:{var h=void 0;if(t)for(var S=o.length-1;0<=S;S--){var E=o[S],F=E.instance,oe=E.currentTarget;if(E=E.listener,F!==h&&f.isPropagationStopped())break e;h=E,f.currentTarget=oe;try{h(f)}catch(xe){Gs(xe)}f.currentTarget=null,h=F}else for(S=0;S<o.length;S++){if(E=o[S],F=E.instance,oe=E.currentTarget,E=E.listener,F!==h&&f.isPropagationStopped())break e;h=E,f.currentTarget=oe;try{h(f)}catch(xe){Gs(xe)}f.currentTarget=null,h=F}}}}function bt(e,t){var i=t[ot];i===void 0&&(i=t[ot]=new Set);var o=e+"__bubble";i.has(o)||(yv(t,e,2,!1),i.add(o))}function wm(e,t,i){var o=0;t&&(o|=4),yv(i,e,o,t)}var nd="_reactListening"+Math.random().toString(36).slice(2);function Sm(e){if(!e[nd]){e[nd]=!0,ts.forEach(function(i){i!=="selectionchange"&&(tS.has(i)||wm(i,!1,e),wm(i,!0,e))});var t=e.nodeType===9?e:e.ownerDocument;t===null||t[nd]||(t[nd]=!0,wm("selectionchange",!1,t))}}function yv(e,t,i,o){switch(Yv(t)){case 2:var f=TS;break;case 8:f=ES;break;default:f=Om}i=f.bind(null,t,i,e),f=void 0,!Xr||t!=="touchstart"&&t!=="touchmove"&&t!=="wheel"||(f=!0),o?f!==void 0?e.addEventListener(t,i,{capture:!0,passive:f}):e.addEventListener(t,i,!0):f!==void 0?e.addEventListener(t,i,{passive:f}):e.addEventListener(t,i,!1)}function Cm(e,t,i,o,f){var h=o;if((t&1)===0&&(t&2)===0&&o!==null)e:for(;;){if(o===null)return;var S=o.tag;if(S===3||S===4){var E=o.stateNode.containerInfo;if(E===f)break;if(S===4)for(S=o.return;S!==null;){var F=S.tag;if((F===3||F===4)&&S.stateNode.containerInfo===f)return;S=S.return}for(;E!==null;){if(S=Vt(E),S===null)return;if(F=S.tag,F===5||F===6||F===26||F===27){o=h=S;continue e}E=E.parentNode}}o=o.return}mi(function(){var oe=h,xe=as(i),Ce=[];e:{var ce=ec.get(e);if(ce!==void 0){var he=nr,Ve=e;switch(e){case"keypress":if(Zr(i)===0)break e;case"keydown":case"keyup":he=lr;break;case"focusin":Ve="focus",he=ct;break;case"focusout":Ve="blur",he=ct;break;case"beforeblur":case"afterblur":he=ct;break;case"click":if(i.button===2)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":he=ir;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":he=iu;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":he=cu;break;case Zo:case js:case rl:he=rr;break;case bu:he=Cf;break;case"scroll":case"scrollend":he=Fs;break;case"wheel":he=el;break;case"copy":case"cut":case"paste":he=at;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":he=bs;break;case"toggle":case"beforetoggle":he=du}var nt=(t&4)!==0,Pt=!nt&&(e==="scroll"||e==="scrollend"),ee=nt?ce!==null?ce+"Capture":null:ce;nt=[];for(var V=oe,re;V!==null;){var we=V;if(re=we.stateNode,we=we.tag,we!==5&&we!==26&&we!==27||re===null||ee===null||(we=Qr(V,ee),we!=null&&nt.push(Cc(V,we,re))),Pt)break;V=V.return}0<nt.length&&(ce=new he(ce,Ve,null,i,xe),Ce.push({event:ce,listeners:nt}))}}if((t&7)===0){e:{if(ce=e==="mouseover"||e==="pointerover",he=e==="mouseout"||e==="pointerout",ce&&i!==gs&&(Ve=i.relatedTarget||i.fromElement)&&(Vt(Ve)||Ve[qe]))break e;if((he||ce)&&(ce=xe.window===xe?xe:(ce=xe.ownerDocument)?ce.defaultView||ce.parentWindow:window,he?(Ve=i.relatedTarget||i.toElement,he=oe,Ve=Ve?Vt(Ve):null,Ve!==null&&(Pt=d(Ve),nt=Ve.tag,Ve!==Pt||nt!==5&&nt!==27&&nt!==6)&&(Ve=null)):(he=null,Ve=oe),he!==Ve)){if(nt=ir,we="onMouseLeave",ee="onMouseEnter",V="mouse",(e==="pointerout"||e==="pointerover")&&(nt=bs,we="onPointerLeave",ee="onPointerEnter",V="pointer"),Pt=he==null?ce:wt(he),re=Ve==null?ce:wt(Ve),ce=new nt(we,V+"leave",he,i,xe),ce.target=Pt,ce.relatedTarget=re,we=null,Vt(xe)===oe&&(nt=new nt(ee,V+"enter",Ve,i,xe),nt.target=re,nt.relatedTarget=Pt,we=nt),Pt=we,he&&Ve)t:{for(nt=nS,ee=he,V=Ve,re=0,we=ee;we;we=nt(we))re++;we=0;for(var Je=V;Je;Je=nt(Je))we++;for(;0<re-we;)ee=nt(ee),re--;for(;0<we-re;)V=nt(V),we--;for(;re--;){if(ee===V||V!==null&&ee===V.alternate){nt=ee;break t}ee=nt(ee),V=nt(V)}nt=null}else nt=null;he!==null&&bv(Ce,ce,he,nt,!1),Ve!==null&&Pt!==null&&bv(Ce,Pt,Ve,nt,!0)}}e:{if(ce=oe?wt(oe):window,he=ce.nodeName&&ce.nodeName.toLowerCase(),he==="select"||he==="input"&&ce.type==="file")var At=ta;else if(tl(ce))if(gu)At=eo;else{At=dr;var We=Ss}else he=ce.nodeName,!he||he.toLowerCase()!=="input"||ce.type!=="checkbox"&&ce.type!=="radio"?oe&&er(oe.elementType)&&(At=ta):At=Jl;if(At&&(At=At(e,oe))){Sa(Ce,At,i,xe);break e}We&&We(e,ce,oe),e==="focusout"&&oe&&ce.type==="number"&&oe.memoizedProps.value!=null&&di(ce,"number",ce.value)}switch(We=oe?wt(oe):window,e){case"focusin":(tl(We)||We.contentEditable==="true")&&(fr=We,qs=oe,il=null);break;case"focusout":il=qs=fr=null;break;case"mousedown":no=!0;break;case"contextmenu":case"mouseup":case"dragend":no=!1,yu(Ce,i,xe);break;case"selectionchange":if(xu)break;case"keydown":case"keyup":yu(Ce,i,xe)}var pt;if(Ht)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 ur?Wt(e,i)&&(Ct="onCompositionEnd"):e==="keydown"&&i.keyCode===229&&(Ct="onCompositionStart");Ct&&(gi&&i.locale!=="ko"&&(ur||Ct!=="onCompositionStart"?Ct==="onCompositionEnd"&&ur&&(pt=Go()):(hi=xe,au="value"in hi?hi.value:hi.textContent,ur=!0)),We=ad(oe,Ct),0<We.length&&(Ct=new lu(Ct,e,null,i,xe),Ce.push({event:Ct,listeners:We}),pt?Ct.data=pt:(pt=cr(i),pt!==null&&(Ct.data=pt)))),(pt=Ql?ws(e,i):pu(e,i))&&(Ct=ad(oe,"onBeforeInput"),0<Ct.length&&(We=new lu("onBeforeInput","beforeinput",null,i,xe),Ce.push({event:We,listeners:Ct}),We.data=pt)),Zw(Ce,e,oe,i,xe)}xv(Ce,t)})}function Cc(e,t,i){return{instance:e,listener:t,currentTarget:i}}function ad(e,t){for(var i=t+"Capture",o=[];e!==null;){var f=e,h=f.stateNode;if(f=f.tag,f!==5&&f!==26&&f!==27||h===null||(f=Qr(e,i),f!=null&&o.unshift(Cc(e,f,h)),f=Qr(e,t),f!=null&&o.push(Cc(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 bv(e,t,i,o,f){for(var h=t._reactName,S=[];i!==null&&i!==o;){var E=i,F=E.alternate,oe=E.stateNode;if(E=E.tag,F!==null&&F===o)break;E!==5&&E!==26&&E!==27||oe===null||(F=oe,f?(oe=Qr(i,h),oe!=null&&S.unshift(Cc(i,oe,F))):f||(oe=Qr(i,h),oe!=null&&S.push(Cc(i,oe,F)))),i=i.return}S.length!==0&&e.push({event:t,listeners:S})}var aS=/\r\n?/g,sS=/\u0000|\uFFFD/g;function wv(e){return(typeof e=="string"?e:""+e).replace(aS,`
9
- `).replace(sS,"")}function Sv(e,t){return t=wv(t),wv(e)===t}function Ft(e,t,i,o,f,h){switch(i){case"children":typeof o=="string"?t==="body"||t==="textarea"&&o===""||Fa(e,o):(typeof o=="number"||typeof o=="bigint")&&t!=="body"&&Fa(e,""+o);break;case"className":Ki(e,"class",o);break;case"tabIndex":Ki(e,"tabindex",o);break;case"dir":case"role":case"viewBox":case"width":case"height":Ki(e,i,o);break;case"style":Yr(e,o,h);break;case"data":if(t!=="object"){Ki(e,"data",o);break}case"src":case"href":if(o===""&&(t!=="a"||i!=="href")){e.removeAttribute(i);break}if(o==null||typeof o=="function"||typeof o=="symbol"||typeof o=="boolean"){e.removeAttribute(i);break}o=Kr(""+o),e.setAttribute(i,o);break;case"action":case"formAction":if(typeof o=="function"){e.setAttribute(i,"javascript:throw new Error('A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you\\'re trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().')");break}else typeof h=="function"&&(i==="formAction"?(t!=="input"&&Ft(e,t,"name",f.name,f,null),Ft(e,t,"formEncType",f.formEncType,f,null),Ft(e,t,"formMethod",f.formMethod,f,null),Ft(e,t,"formTarget",f.formTarget,f,null)):(Ft(e,t,"encType",f.encType,f,null),Ft(e,t,"method",f.method,f,null),Ft(e,t,"target",f.target,f,null)));if(o==null||typeof o=="symbol"||typeof o=="boolean"){e.removeAttribute(i);break}o=Kr(""+o),e.setAttribute(i,o);break;case"onClick":o!=null&&(e.onclick=Ln);break;case"onScroll":o!=null&&bt("scroll",e);break;case"onScrollEnd":o!=null&&bt("scrollend",e);break;case"dangerouslySetInnerHTML":if(o!=null){if(typeof o!="object"||!("__html"in o))throw Error(l(61));if(i=o.__html,i!=null){if(f.children!=null)throw Error(l(60));e.innerHTML=i}}break;case"multiple":e.multiple=o&&typeof o!="function"&&typeof o!="symbol";break;case"muted":e.muted=o&&typeof o!="function"&&typeof o!="symbol";break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"defaultValue":case"defaultChecked":case"innerHTML":case"ref":break;case"autoFocus":break;case"xlinkHref":if(o==null||typeof o=="function"||typeof o=="boolean"||typeof o=="symbol"){e.removeAttribute("xlink:href");break}i=Kr(""+o),e.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",i);break;case"contentEditable":case"spellCheck":case"draggable":case"value":case"autoReverse":case"externalResourcesRequired":case"focusable":case"preserveAlpha":o!=null&&typeof o!="function"&&typeof o!="symbol"?e.setAttribute(i,""+o):e.removeAttribute(i);break;case"inert":case"allowFullScreen":case"async":case"autoPlay":case"controls":case"default":case"defer":case"disabled":case"disablePictureInPicture":case"disableRemotePlayback":case"formNoValidate":case"hidden":case"loop":case"noModule":case"noValidate":case"open":case"playsInline":case"readOnly":case"required":case"reversed":case"scoped":case"seamless":case"itemScope":o&&typeof o!="function"&&typeof o!="symbol"?e.setAttribute(i,""):e.removeAttribute(i);break;case"capture":case"download":o===!0?e.setAttribute(i,""):o!==!1&&o!=null&&typeof o!="function"&&typeof o!="symbol"?e.setAttribute(i,o):e.removeAttribute(i);break;case"cols":case"rows":case"size":case"span":o!=null&&typeof o!="function"&&typeof o!="symbol"&&!isNaN(o)&&1<=o?e.setAttribute(i,o):e.removeAttribute(i);break;case"rowSpan":case"start":o==null||typeof o=="function"||typeof o=="symbol"||isNaN(o)?e.removeAttribute(i):e.setAttribute(i,o);break;case"popover":bt("beforetoggle",e),bt("toggle",e),Yi(e,"popover",o);break;case"xlinkActuate":ms(e,"http://www.w3.org/1999/xlink","xlink:actuate",o);break;case"xlinkArcrole":ms(e,"http://www.w3.org/1999/xlink","xlink:arcrole",o);break;case"xlinkRole":ms(e,"http://www.w3.org/1999/xlink","xlink:role",o);break;case"xlinkShow":ms(e,"http://www.w3.org/1999/xlink","xlink:show",o);break;case"xlinkTitle":ms(e,"http://www.w3.org/1999/xlink","xlink:title",o);break;case"xlinkType":ms(e,"http://www.w3.org/1999/xlink","xlink:type",o);break;case"xmlBase":ms(e,"http://www.w3.org/XML/1998/namespace","xml:base",o);break;case"xmlLang":ms(e,"http://www.w3.org/XML/1998/namespace","xml:lang",o);break;case"xmlSpace":ms(e,"http://www.w3.org/XML/1998/namespace","xml:space",o);break;case"is":Yi(e,"is",o);break;case"innerText":case"textContent":break;default:(!(2<i.length)||i[0]!=="o"&&i[0]!=="O"||i[1]!=="n"&&i[1]!=="N")&&(i=ql.get(i)||i,Yi(e,i,o))}}function jm(e,t,i,o,f,h){switch(i){case"style":Yr(e,o,h);break;case"dangerouslySetInnerHTML":if(o!=null){if(typeof o!="object"||!("__html"in o))throw Error(l(61));if(i=o.__html,i!=null){if(f.children!=null)throw Error(l(60));e.innerHTML=i}}break;case"children":typeof o=="string"?Fa(e,o):(typeof o=="number"||typeof o=="bigint")&&Fa(e,""+o);break;case"onScroll":o!=null&&bt("scroll",e);break;case"onScrollEnd":o!=null&&bt("scrollend",e);break;case"onClick":o!=null&&(e.onclick=Ln);break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"innerHTML":case"ref":break;case"innerText":case"textContent":break;default:if(!xn.hasOwnProperty(i))e:{if(i[0]==="o"&&i[1]==="n"&&(f=i.endsWith("Capture"),t=i.slice(2,f?i.length-7:void 0),h=e[Ae]||null,h=h!=null?h[i]:null,typeof h=="function"&&e.removeEventListener(t,h,f),typeof o=="function")){typeof h!="function"&&h!==null&&(i in e?e[i]=null:e.hasAttribute(i)&&e.removeAttribute(i)),e.addEventListener(t,o,f);break e}i in e?e[i]=o:o===!0?e.setAttribute(i,""):Yi(e,i,o)}}}function Kn(e,t,i){switch(t){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"img":bt("error",e),bt("load",e);var o=!1,f=!1,h;for(h in i)if(i.hasOwnProperty(h)){var S=i[h];if(S!=null)switch(h){case"src":o=!0;break;case"srcSet":f=!0;break;case"children":case"dangerouslySetInnerHTML":throw Error(l(137,t));default:Ft(e,t,h,S,i,null)}}f&&Ft(e,t,"srcSet",i.srcSet,i,null),o&&Ft(e,t,"src",i.src,i,null);return;case"input":bt("invalid",e);var E=h=S=f=null,F=null,oe=null;for(o in i)if(i.hasOwnProperty(o)){var xe=i[o];if(xe!=null)switch(o){case"name":f=xe;break;case"type":S=xe;break;case"checked":F=xe;break;case"defaultChecked":oe=xe;break;case"value":h=xe;break;case"defaultValue":E=xe;break;case"children":case"dangerouslySetInnerHTML":if(xe!=null)throw Error(l(137,t));break;default:Ft(e,t,o,xe,i,null)}}Xi(e,h,E,F,oe,S,f,!1);return;case"select":bt("invalid",e),o=S=h=null;for(f in i)if(i.hasOwnProperty(f)&&(E=i[f],E!=null))switch(f){case"value":h=E;break;case"defaultValue":S=E;break;case"multiple":o=E;default:Ft(e,t,f,E,i,null)}t=h,i=S,e.multiple=!!o,t!=null?ps(e,!!o,t,!1):i!=null&&ps(e,!!o,i,!0);return;case"textarea":bt("invalid",e),h=f=o=null;for(S in i)if(i.hasOwnProperty(S)&&(E=i[S],E!=null))switch(S){case"value":o=E;break;case"defaultValue":f=E;break;case"children":h=E;break;case"dangerouslySetInnerHTML":if(E!=null)throw Error(l(91));break;default:Ft(e,t,S,E,i,null)}fi(e,o,f,h);return;case"option":for(F in i)i.hasOwnProperty(F)&&(o=i[F],o!=null)&&(F==="selected"?e.selected=o&&typeof o!="function"&&typeof o!="symbol":Ft(e,t,F,o,i,null));return;case"dialog":bt("beforetoggle",e),bt("toggle",e),bt("cancel",e),bt("close",e);break;case"iframe":case"object":bt("load",e);break;case"video":case"audio":for(o=0;o<Sc.length;o++)bt(Sc[o],e);break;case"image":bt("error",e),bt("load",e);break;case"details":bt("toggle",e);break;case"embed":case"source":case"link":bt("error",e),bt("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(oe in i)if(i.hasOwnProperty(oe)&&(o=i[oe],o!=null))switch(oe){case"children":case"dangerouslySetInnerHTML":throw Error(l(137,t));default:Ft(e,t,oe,o,i,null)}return;default:if(er(t)){for(xe in i)i.hasOwnProperty(xe)&&(o=i[xe],o!==void 0&&jm(e,t,xe,o,i,void 0));return}}for(E in i)i.hasOwnProperty(E)&&(o=i[E],o!=null&&Ft(e,t,E,o,i,null))}function iS(e,t,i,o){switch(t){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"input":var f=null,h=null,S=null,E=null,F=null,oe=null,xe=null;for(he in i){var Ce=i[he];if(i.hasOwnProperty(he)&&Ce!=null)switch(he){case"checked":break;case"value":break;case"defaultValue":F=Ce;default:o.hasOwnProperty(he)||Ft(e,t,he,null,o,Ce)}}for(var ce in o){var he=o[ce];if(Ce=i[ce],o.hasOwnProperty(ce)&&(he!=null||Ce!=null))switch(ce){case"type":h=he;break;case"name":f=he;break;case"checked":oe=he;break;case"defaultChecked":xe=he;break;case"value":S=he;break;case"defaultValue":E=he;break;case"children":case"dangerouslySetInnerHTML":if(he!=null)throw Error(l(137,t));break;default:he!==Ce&&Ft(e,t,ce,he,o,Ce)}}hs(e,S,E,F,oe,xe,h,f);return;case"select":he=S=E=ce=null;for(h in i)if(F=i[h],i.hasOwnProperty(h)&&F!=null)switch(h){case"value":break;case"multiple":he=F;default:o.hasOwnProperty(h)||Ft(e,t,h,null,o,F)}for(f in o)if(h=o[f],F=i[f],o.hasOwnProperty(f)&&(h!=null||F!=null))switch(f){case"value":ce=h;break;case"defaultValue":E=h;break;case"multiple":S=h;default:h!==F&&Ft(e,t,f,h,o,F)}t=E,i=S,o=he,ce!=null?ps(e,!!i,ce,!1):!!o!=!!i&&(t!=null?ps(e,!!i,t,!0):ps(e,!!i,i?[]:"",!1));return;case"textarea":he=ce=null;for(E in i)if(f=i[E],i.hasOwnProperty(E)&&f!=null&&!o.hasOwnProperty(E))switch(E){case"value":break;case"children":break;default:Ft(e,t,E,null,o,f)}for(S in o)if(f=o[S],h=i[S],o.hasOwnProperty(S)&&(f!=null||h!=null))switch(S){case"value":ce=f;break;case"defaultValue":he=f;break;case"children":break;case"dangerouslySetInnerHTML":if(f!=null)throw Error(l(91));break;default:f!==h&&Ft(e,t,S,f,o,h)}Zi(e,ce,he);return;case"option":for(var Ve in i)ce=i[Ve],i.hasOwnProperty(Ve)&&ce!=null&&!o.hasOwnProperty(Ve)&&(Ve==="selected"?e.selected=!1:Ft(e,t,Ve,null,o,ce));for(F in o)ce=o[F],he=i[F],o.hasOwnProperty(F)&&ce!==he&&(ce!=null||he!=null)&&(F==="selected"?e.selected=ce&&typeof ce!="function"&&typeof ce!="symbol":Ft(e,t,F,ce,o,he));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 nt in i)ce=i[nt],i.hasOwnProperty(nt)&&ce!=null&&!o.hasOwnProperty(nt)&&Ft(e,t,nt,null,o,ce);for(oe in o)if(ce=o[oe],he=i[oe],o.hasOwnProperty(oe)&&ce!==he&&(ce!=null||he!=null))switch(oe){case"children":case"dangerouslySetInnerHTML":if(ce!=null)throw Error(l(137,t));break;default:Ft(e,t,oe,ce,o,he)}return;default:if(er(t)){for(var Pt in i)ce=i[Pt],i.hasOwnProperty(Pt)&&ce!==void 0&&!o.hasOwnProperty(Pt)&&jm(e,t,Pt,void 0,o,ce);for(xe in o)ce=o[xe],he=i[xe],!o.hasOwnProperty(xe)||ce===he||ce===void 0&&he===void 0||jm(e,t,xe,ce,o,he);return}}for(var ee in i)ce=i[ee],i.hasOwnProperty(ee)&&ce!=null&&!o.hasOwnProperty(ee)&&Ft(e,t,ee,null,o,ce);for(Ce in o)ce=o[Ce],he=i[Ce],!o.hasOwnProperty(Ce)||ce===he||ce==null&&he==null||Ft(e,t,Ce,ce,o,he)}function Cv(e){switch(e){case"css":case"script":case"font":case"img":case"image":case"input":case"link":return!0;default:return!1}}function rS(){if(typeof performance.getEntriesByType=="function"){for(var e=0,t=0,i=performance.getEntriesByType("resource"),o=0;o<i.length;o++){var f=i[o],h=f.transferSize,S=f.initiatorType,E=f.duration;if(h&&E&&Cv(S)){for(S=0,E=f.responseEnd,o+=1;o<i.length;o++){var F=i[o],oe=F.startTime;if(oe>E)break;var xe=F.transferSize,Ce=F.initiatorType;xe&&Cv(Ce)&&(F=F.responseEnd,S+=xe*(F<E?1:(E-oe)/(F-oe)))}if(--o,t+=8*(h+S)/(f.duration/1e3),e++,10<e)break}}if(0<e)return t/e/1e6}return navigator.connection&&(e=navigator.connection.downlink,typeof e=="number")?e:5}var km=null,Am=null;function sd(e){return e.nodeType===9?e:e.ownerDocument}function jv(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 kv(e,t){if(e===0)switch(t){case"svg":return 1;case"math":return 2;default:return 0}return e===1&&t==="foreignObject"?0:e}function Nm(e,t){return e==="textarea"||e==="noscript"||typeof t.children=="string"||typeof t.children=="number"||typeof t.children=="bigint"||typeof t.dangerouslySetInnerHTML=="object"&&t.dangerouslySetInnerHTML!==null&&t.dangerouslySetInnerHTML.__html!=null}var Mm=null;function lS(){var e=window.event;return e&&e.type==="popstate"?e===Mm?!1:(Mm=e,!0):(Mm=null,!1)}var Av=typeof setTimeout=="function"?setTimeout:void 0,oS=typeof clearTimeout=="function"?clearTimeout:void 0,Nv=typeof Promise=="function"?Promise:void 0,cS=typeof queueMicrotask=="function"?queueMicrotask:typeof Nv<"u"?function(e){return Nv.resolve(null).then(e).catch(uS)}:Av;function uS(e){setTimeout(function(){throw e})}function _r(e){return e==="head"}function Mv(e,t){var i=t,o=0;do{var f=i.nextSibling;if(e.removeChild(i),f&&f.nodeType===8)if(i=f.data,i==="/$"||i==="/&"){if(o===0){e.removeChild(f),No(t);return}o--}else if(i==="$"||i==="$?"||i==="$~"||i==="$!"||i==="&")o++;else if(i==="html")jc(e.ownerDocument.documentElement);else if(i==="head"){i=e.ownerDocument.head,jc(i);for(var h=i.firstChild;h;){var S=h.nextSibling,E=h.nodeName;h[jt]||E==="SCRIPT"||E==="STYLE"||E==="LINK"&&h.rel.toLowerCase()==="stylesheet"||i.removeChild(h),h=S}}else i==="body"&&jc(e.ownerDocument.body);i=f}while(i);No(t)}function Tv(e,t){var i=e;e=0;do{var o=i.nextSibling;if(i.nodeType===1?t?(i._stashedDisplay=i.style.display,i.style.display="none"):(i.style.display=i._stashedDisplay||"",i.getAttribute("style")===""&&i.removeAttribute("style")):i.nodeType===3&&(t?(i._stashedText=i.nodeValue,i.nodeValue=""):i.nodeValue=i._stashedText||""),o&&o.nodeType===8)if(i=o.data,i==="/$"){if(e===0)break;e--}else i!=="$"&&i!=="$?"&&i!=="$~"&&i!=="$!"||e++;i=o}while(i)}function Tm(e){var t=e.firstChild;for(t&&t.nodeType===10&&(t=t.nextSibling);t;){var i=t;switch(t=t.nextSibling,i.nodeName){case"HTML":case"HEAD":case"BODY":Tm(i),Ot(i);continue;case"SCRIPT":case"STYLE":continue;case"LINK":if(i.rel.toLowerCase()==="stylesheet")continue}e.removeChild(i)}}function dS(e,t,i,o){for(;e.nodeType===1;){var f=i;if(e.nodeName.toLowerCase()!==t.toLowerCase()){if(!o&&(e.nodeName!=="INPUT"||e.type!=="hidden"))break}else if(o){if(!e[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=cs(e.nextSibling),e===null)break}return null}function fS(e,t,i){if(t==="")return null;for(;e.nodeType!==3;)if((e.nodeType!==1||e.nodeName!=="INPUT"||e.type!=="hidden")&&!i||(e=cs(e.nextSibling),e===null))return null;return e}function Ev(e,t){for(;e.nodeType!==8;)if((e.nodeType!==1||e.nodeName!=="INPUT"||e.type!=="hidden")&&!t||(e=cs(e.nextSibling),e===null))return null;return e}function Em(e){return e.data==="$?"||e.data==="$~"}function Rm(e){return e.data==="$!"||e.data==="$?"&&e.ownerDocument.readyState!=="loading"}function mS(e,t){var i=e.ownerDocument;if(e.data==="$~")e._reactRetry=t;else if(e.data!=="$?"||i.readyState!=="loading")t();else{var o=function(){t(),i.removeEventListener("DOMContentLoaded",o)};i.addEventListener("DOMContentLoaded",o),e._reactRetry=o}}function cs(e){for(;e!=null;e=e.nextSibling){var t=e.nodeType;if(t===1||t===3)break;if(t===8){if(t=e.data,t==="$"||t==="$!"||t==="$?"||t==="$~"||t==="&"||t==="F!"||t==="F")break;if(t==="/$"||t==="/&")return null}}return e}var Dm=null;function Rv(e){e=e.nextSibling;for(var t=0;e;){if(e.nodeType===8){var i=e.data;if(i==="/$"||i==="/&"){if(t===0)return cs(e.nextSibling);t--}else i!=="$"&&i!=="$!"&&i!=="$?"&&i!=="$~"&&i!=="&"||t++}e=e.nextSibling}return null}function Dv(e){e=e.previousSibling;for(var t=0;e;){if(e.nodeType===8){var i=e.data;if(i==="$"||i==="$!"||i==="$?"||i==="$~"||i==="&"){if(t===0)return e;t--}else i!=="/$"&&i!=="/&"||t++}e=e.previousSibling}return null}function Lv(e,t,i){switch(t=sd(i),e){case"html":if(e=t.documentElement,!e)throw Error(l(452));return e;case"head":if(e=t.head,!e)throw Error(l(453));return e;case"body":if(e=t.body,!e)throw Error(l(454));return e;default:throw Error(l(451))}}function jc(e){for(var t=e.attributes;t.length;)e.removeAttributeNode(t[0]);Ot(e)}var us=new Map,_v=new Set;function id(e){return typeof e.getRootNode=="function"?e.getRootNode():e.nodeType===9?e:e.ownerDocument}var Pi=Q.d;Q.d={f:hS,r:pS,D:gS,C:vS,L:xS,m:yS,X:wS,S:bS,M:SS};function hS(){var e=Pi.f(),t=Qu();return e||t}function pS(e){var t=sn(e);t!==null&&t.tag===5&&t.type==="form"?Xp(t):Pi.r(e)}var jo=typeof document>"u"?null:document;function zv(e,t,i){var o=jo;if(o&&typeof t=="string"&&t){var f=Qt(t);f='link[rel="'+e+'"][href="'+f+'"]',typeof i=="string"&&(f+='[crossorigin="'+i+'"]'),_v.has(f)||(_v.add(f),e={rel:e,crossOrigin:i,href:t},o.querySelector(f)===null&&(t=o.createElement("link"),Kn(t,"link",e),Tt(t),o.head.appendChild(t)))}}function gS(e){Pi.D(e),zv("dns-prefetch",e,null)}function vS(e,t){Pi.C(e,t),zv("preconnect",e,t)}function xS(e,t,i){Pi.L(e,t,i);var o=jo;if(o&&e&&t){var f='link[rel="preload"][as="'+Qt(t)+'"]';t==="image"&&i&&i.imageSrcSet?(f+='[imagesrcset="'+Qt(i.imageSrcSet)+'"]',typeof i.imageSizes=="string"&&(f+='[imagesizes="'+Qt(i.imageSizes)+'"]')):f+='[href="'+Qt(e)+'"]';var h=f;switch(t){case"style":h=ko(e);break;case"script":h=Ao(e)}us.has(h)||(e=y({rel:"preload",href:t==="image"&&i&&i.imageSrcSet?void 0:e,as:t},i),us.set(h,e),o.querySelector(f)!==null||t==="style"&&o.querySelector(kc(h))||t==="script"&&o.querySelector(Ac(h))||(t=o.createElement("link"),Kn(t,"link",e),Tt(t),o.head.appendChild(t)))}}function yS(e,t){Pi.m(e,t);var i=jo;if(i&&e){var o=t&&typeof t.as=="string"?t.as:"script",f='link[rel="modulepreload"][as="'+Qt(o)+'"][href="'+Qt(e)+'"]',h=f;switch(o){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":h=Ao(e)}if(!us.has(h)&&(e=y({rel:"modulepreload",href:e},t),us.set(h,e),i.querySelector(f)===null)){switch(o){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(i.querySelector(Ac(h)))return}o=i.createElement("link"),Kn(o,"link",e),Tt(o),i.head.appendChild(o)}}}function bS(e,t,i){Pi.S(e,t,i);var o=jo;if(o&&e){var f=cn(o).hoistableStyles,h=ko(e);t=t||"default";var S=f.get(h);if(!S){var E={loading:0,preload:null};if(S=o.querySelector(kc(h)))E.loading=5;else{e=y({rel:"stylesheet",href:e,"data-precedence":t},i),(i=us.get(h))&&Lm(e,i);var F=S=o.createElement("link");Tt(F),Kn(F,"link",e),F._p=new Promise(function(oe,xe){F.onload=oe,F.onerror=xe}),F.addEventListener("load",function(){E.loading|=1}),F.addEventListener("error",function(){E.loading|=2}),E.loading|=4,rd(S,t,o)}S={type:"stylesheet",instance:S,count:1,state:E},f.set(h,S)}}}function wS(e,t){Pi.X(e,t);var i=jo;if(i&&e){var o=cn(i).hoistableScripts,f=Ao(e),h=o.get(f);h||(h=i.querySelector(Ac(f)),h||(e=y({src:e,async:!0},t),(t=us.get(f))&&_m(e,t),h=i.createElement("script"),Tt(h),Kn(h,"link",e),i.head.appendChild(h)),h={type:"script",instance:h,count:1,state:null},o.set(f,h))}}function SS(e,t){Pi.M(e,t);var i=jo;if(i&&e){var o=cn(i).hoistableScripts,f=Ao(e),h=o.get(f);h||(h=i.querySelector(Ac(f)),h||(e=y({src:e,async:!0,type:"module"},t),(t=us.get(f))&&_m(e,t),h=i.createElement("script"),Tt(h),Kn(h,"link",e),i.head.appendChild(h)),h={type:"script",instance:h,count:1,state:null},o.set(f,h))}}function Iv(e,t,i,o){var f=(f=ve.current)?id(f):null;if(!f)throw Error(l(446));switch(e){case"meta":case"title":return null;case"style":return typeof i.precedence=="string"&&typeof i.href=="string"?(t=ko(i.href),i=cn(f).hoistableStyles,o=i.get(t),o||(o={type:"style",instance:null,count:0,state:null},i.set(t,o)),o):{type:"void",instance:null,count:0,state:null};case"link":if(i.rel==="stylesheet"&&typeof i.href=="string"&&typeof i.precedence=="string"){e=ko(i.href);var h=cn(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(kc(e)))&&!h._p&&(S.instance=h,S.state.loading=5),us.has(e)||(i={rel:"preload",as:"style",href:i.href,crossOrigin:i.crossOrigin,integrity:i.integrity,media:i.media,hrefLang:i.hrefLang,referrerPolicy:i.referrerPolicy},us.set(e,i),h||CS(f,e,i,S.state))),t&&o===null)throw Error(l(528,""));return S}if(t&&o!==null)throw Error(l(529,""));return null;case"script":return t=i.async,i=i.src,typeof i=="string"&&t&&typeof t!="function"&&typeof t!="symbol"?(t=Ao(i),i=cn(f).hoistableScripts,o=i.get(t),o||(o={type:"script",instance:null,count:0,state:null},i.set(t,o)),o):{type:"void",instance:null,count:0,state:null};default:throw Error(l(444,e))}}function ko(e){return'href="'+Qt(e)+'"'}function kc(e){return'link[rel="stylesheet"]['+e+"]"}function Ov(e){return y({},e,{"data-precedence":e.precedence,precedence:null})}function CS(e,t,i,o){e.querySelector('link[rel="preload"][as="style"]['+t+"]")?o.loading=1:(t=e.createElement("link"),o.preload=t,t.addEventListener("load",function(){return o.loading|=1}),t.addEventListener("error",function(){return o.loading|=2}),Kn(t,"link",i),Tt(t),e.head.appendChild(t))}function Ao(e){return'[src="'+Qt(e)+'"]'}function Ac(e){return"script[async]"+e}function Hv(e,t,i){if(t.count++,t.instance===null)switch(t.type){case"style":var o=e.querySelector('style[data-href~="'+Qt(i.href)+'"]');if(o)return t.instance=o,Tt(o),o;var f=y({},i,{"data-href":i.href,"data-precedence":i.precedence,href:null,precedence:null});return o=(e.ownerDocument||e).createElement("style"),Tt(o),Kn(o,"style",f),rd(o,i.precedence,e),t.instance=o;case"stylesheet":f=ko(i.href);var h=e.querySelector(kc(f));if(h)return t.state.loading|=4,t.instance=h,Tt(h),h;o=Ov(i),(f=us.get(f))&&Lm(o,f),h=(e.ownerDocument||e).createElement("link"),Tt(h);var S=h;return S._p=new Promise(function(E,F){S.onload=E,S.onerror=F}),Kn(h,"link",o),t.state.loading|=4,rd(h,i.precedence,e),t.instance=h;case"script":return h=Ao(i.src),(f=e.querySelector(Ac(h)))?(t.instance=f,Tt(f),f):(o=i,(f=us.get(h))&&(o=y({},i),_m(o,f)),e=e.ownerDocument||e,f=e.createElement("script"),Tt(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,rd(o,i.precedence,e));return t.instance}function rd(e,t,i){for(var o=i.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),f=o.length?o[o.length-1]:null,h=f,S=0;S<o.length;S++){var E=o[S];if(E.dataset.precedence===t)h=E;else if(h!==f)break}h?h.parentNode.insertBefore(e,h.nextSibling):(t=i.nodeType===9?i.head:i,t.insertBefore(e,t.firstChild))}function Lm(e,t){e.crossOrigin==null&&(e.crossOrigin=t.crossOrigin),e.referrerPolicy==null&&(e.referrerPolicy=t.referrerPolicy),e.title==null&&(e.title=t.title)}function _m(e,t){e.crossOrigin==null&&(e.crossOrigin=t.crossOrigin),e.referrerPolicy==null&&(e.referrerPolicy=t.referrerPolicy),e.integrity==null&&(e.integrity=t.integrity)}var ld=null;function Bv(e,t,i){if(ld===null){var o=new Map,f=ld=new Map;f.set(i,o)}else f=ld,o=f.get(i),o||(o=new Map,f.set(i,o));if(o.has(e))return o;for(o.set(e,null),i=i.getElementsByTagName(e),f=0;f<i.length;f++){var h=i[f];if(!(h[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 Fv(e,t,i){e=e.ownerDocument||e,e.head.insertBefore(i,t==="title"?e.querySelector("head > title"):null)}function jS(e,t,i){if(i===1||t.itemProp!=null)return!1;switch(e){case"meta":case"title":return!0;case"style":if(typeof t.precedence!="string"||typeof t.href!="string"||t.href==="")break;return!0;case"link":if(typeof t.rel!="string"||typeof t.href!="string"||t.href===""||t.onLoad||t.onError)break;return t.rel==="stylesheet"?(e=t.disabled,typeof t.precedence=="string"&&e==null):!0;case"script":if(t.async&&typeof t.async!="function"&&typeof t.async!="symbol"&&!t.onLoad&&!t.onError&&t.src&&typeof t.src=="string")return!0}return!1}function Pv(e){return!(e.type==="stylesheet"&&(e.state.loading&3)===0)}function kS(e,t,i,o){if(i.type==="stylesheet"&&(typeof o.media!="string"||matchMedia(o.media).matches!==!1)&&(i.state.loading&4)===0){if(i.instance===null){var f=ko(o.href),h=t.querySelector(kc(f));if(h){t=h._p,t!==null&&typeof t=="object"&&typeof t.then=="function"&&(e.count++,e=od.bind(e),t.then(e,e)),i.state.loading|=4,i.instance=h,Tt(h);return}h=t.ownerDocument||t,o=Ov(o),(f=us.get(f))&&Lm(o,f),h=h.createElement("link"),Tt(h);var S=h;S._p=new Promise(function(E,F){S.onload=E,S.onerror=F}),Kn(h,"link",o),i.instance=h}e.stylesheets===null&&(e.stylesheets=new Map),e.stylesheets.set(i,t),(t=i.state.preload)&&(i.state.loading&3)===0&&(e.count++,i=od.bind(e),t.addEventListener("load",i),t.addEventListener("error",i))}}var zm=0;function AS(e,t){return e.stylesheets&&e.count===0&&ud(e,e.stylesheets),0<e.count||0<e.imgCount?function(i){var o=setTimeout(function(){if(e.stylesheets&&ud(e,e.stylesheets),e.unsuspend){var h=e.unsuspend;e.unsuspend=null,h()}},6e4+t);0<e.imgBytes&&zm===0&&(zm=62500*rS());var f=setTimeout(function(){if(e.waitingForImages=!1,e.count===0&&(e.stylesheets&&ud(e,e.stylesheets),e.unsuspend)){var h=e.unsuspend;e.unsuspend=null,h()}},(e.imgBytes>zm?50:800)+t);return e.unsuspend=i,function(){e.unsuspend=null,clearTimeout(o),clearTimeout(f)}}:null}function od(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)ud(this,this.stylesheets);else if(this.unsuspend){var e=this.unsuspend;this.unsuspend=null,e()}}}var cd=null;function ud(e,t){e.stylesheets=null,e.unsuspend!==null&&(e.count++,cd=new Map,t.forEach(NS,e),cd=null,od.call(e))}function NS(e,t){if(!(t.state.loading&4)){var i=cd.get(e);if(i)var o=i.get(null);else{i=new Map,cd.set(e,i);for(var f=e.querySelectorAll("link[data-precedence],style[data-precedence]"),h=0;h<f.length;h++){var S=f[h];(S.nodeName==="LINK"||S.getAttribute("media")!=="not all")&&(i.set(S.dataset.precedence,S),o=S)}o&&i.set(null,o)}f=t.instance,S=f.getAttribute("data-precedence"),h=i.get(S)||o,h===o&&i.set(null,f),i.set(S,f),this.count++,o=od.bind(this),f.addEventListener("load",o),f.addEventListener("error",o),h?h.parentNode.insertBefore(f,h.nextSibling):(e=e.nodeType===9?e.head:e,e.insertBefore(f,e.firstChild)),t.state.loading|=4}}var Nc={$$typeof:R,Provider:null,Consumer:null,_currentValue:U,_currentValue2:U,_threadCount:0};function MS(e,t,i,o,f,h,S,E,F){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=Is(-1),this.entangledLanes=this.shellSuspendCounter=this.errorRecoveryDisabledLanes=this.expiredLanes=this.warmLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Is(0),this.hiddenUpdates=Is(null),this.identifierPrefix=o,this.onUncaughtError=f,this.onCaughtError=h,this.onRecoverableError=S,this.pooledCache=null,this.pooledCacheLanes=0,this.formState=F,this.incompleteTransitions=new Map}function $v(e,t,i,o,f,h,S,E,F,oe,xe,Ce){return e=new MS(e,t,i,S,F,oe,xe,Ce,E),t=1,h===!0&&(t|=24),h=jn(3,null,null,t),e.current=h,h.stateNode=e,t=rc(),t.refCount++,e.pooledCache=t,t.refCount++,h.memoizedState={element:o,isDehydrated:i,cache:t},Sl(h),e}function Uv(e){return e?(e=As,e):As}function qv(e,t,i,o,f,h){f=Uv(f),o.context===null?o.context=f:o.pendingContext=f,o=ni(t),o.payload={element:i},h=h===void 0?null:h,h!==null&&(o.callback=h),i=ia(e,o,t),i!==null&&(La(i,e,t),Ei(i,e,t))}function Gv(e,t){if(e=e.memoizedState,e!==null&&e.dehydrated!==null){var i=e.retryLane;e.retryLane=i!==0&&i<t?i:t}}function Im(e,t){Gv(e,t),(e=e.alternate)&&Gv(e,t)}function Vv(e){if(e.tag===13||e.tag===31){var t=is(e,67108864);t!==null&&La(t,e,67108864),Im(e,67108864)}}function Wv(e){if(e.tag===13||e.tag===31){var t=Wa();t=st(t);var i=is(e,t);i!==null&&La(i,e,t),Im(e,t)}}var dd=!0;function TS(e,t,i,o){var f=I.T;I.T=null;var h=Q.p;try{Q.p=2,Om(e,t,i,o)}finally{Q.p=h,I.T=f}}function ES(e,t,i,o){var f=I.T;I.T=null;var h=Q.p;try{Q.p=8,Om(e,t,i,o)}finally{Q.p=h,I.T=f}}function Om(e,t,i,o){if(dd){var f=Hm(o);if(f===null)Cm(e,t,o,fd,i),Kv(e,o);else if(DS(f,e,t,i,o))o.stopPropagation();else if(Kv(e,o),t&4&&-1<RS.indexOf(e)){for(;f!==null;){var h=sn(f);if(h!==null)switch(h.tag){case 3:if(h=h.stateNode,h.current.memoizedState.isDehydrated){var S=Za(h.pendingLanes);if(S!==0){var E=h;for(E.pendingLanes|=2,E.entangledLanes|=2;S;){var F=1<<31-gt(S);E.entanglements[1]|=F,S&=~F}si(h),(Rt&6)===0&&(Yu=vt()+500,wc(0))}}break;case 31:case 13:E=is(h,2),E!==null&&La(E,h,2),Qu(),Im(h,2)}if(h=Hm(o),h===null&&Cm(e,t,o,fd,i),h===f)break;f=h}f!==null&&o.stopPropagation()}else Cm(e,t,o,null,i)}}function Hm(e){return e=as(e),Bm(e)}var fd=null;function Bm(e){if(fd=null,e=Vt(e),e!==null){var t=d(e);if(t===null)e=null;else{var i=t.tag;if(i===13){if(e=m(t),e!==null)return e;e=null}else if(i===31){if(e=p(t),e!==null)return e;e=null}else if(i===3){if(t.stateNode.current.memoizedState.isDehydrated)return t.tag===3?t.stateNode.containerInfo:null;e=null}else t!==e&&(e=null)}}return fd=e,null}function Yv(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(vn()){case It:return 2;case Zt:return 8;case ht:case $n:return 32;case Gt:return 268435456;default:return 32}default:return 32}}var Fm=!1,zr=null,Ir=null,Or=null,Mc=new Map,Tc=new Map,Hr=[],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 Kv(e,t){switch(e){case"focusin":case"focusout":zr=null;break;case"dragenter":case"dragleave":Ir=null;break;case"mouseover":case"mouseout":Or=null;break;case"pointerover":case"pointerout":Mc.delete(t.pointerId);break;case"gotpointercapture":case"lostpointercapture":Tc.delete(t.pointerId)}}function Ec(e,t,i,o,f,h){return e===null||e.nativeEvent!==h?(e={blockedOn:t,domEventName:i,eventSystemFlags:o,nativeEvent:h,targetContainers:[f]},t!==null&&(t=sn(t),t!==null&&Vv(t)),e):(e.eventSystemFlags|=o,t=e.targetContainers,f!==null&&t.indexOf(f)===-1&&t.push(f),e)}function DS(e,t,i,o,f){switch(t){case"focusin":return zr=Ec(zr,e,t,i,o,f),!0;case"dragenter":return Ir=Ec(Ir,e,t,i,o,f),!0;case"mouseover":return Or=Ec(Or,e,t,i,o,f),!0;case"pointerover":var h=f.pointerId;return Mc.set(h,Ec(Mc.get(h)||null,e,t,i,o,f)),!0;case"gotpointercapture":return h=f.pointerId,Tc.set(h,Ec(Tc.get(h)||null,e,t,i,o,f)),!0}return!1}function Qv(e){var t=Vt(e.target);if(t!==null){var i=d(t);if(i!==null){if(t=i.tag,t===13){if(t=m(i),t!==null){e.blockedOn=t,Tn(e.priority,function(){Wv(i)});return}}else if(t===31){if(t=p(i),t!==null){e.blockedOn=t,Tn(e.priority,function(){Wv(i)});return}}else if(t===3&&i.stateNode.current.memoizedState.isDehydrated){e.blockedOn=i.tag===3?i.stateNode.containerInfo:null;return}}}e.blockedOn=null}function md(e){if(e.blockedOn!==null)return!1;for(var t=e.targetContainers;0<t.length;){var i=Hm(e.nativeEvent);if(i===null){i=e.nativeEvent;var o=new i.constructor(i.type,i);gs=o,i.target.dispatchEvent(o),gs=null}else return t=sn(i),t!==null&&Vv(t),e.blockedOn=i,!1;t.shift()}return!0}function Xv(e,t,i){md(e)&&i.delete(t)}function LS(){Fm=!1,zr!==null&&md(zr)&&(zr=null),Ir!==null&&md(Ir)&&(Ir=null),Or!==null&&md(Or)&&(Or=null),Mc.forEach(Xv),Tc.forEach(Xv)}function hd(e,t){e.blockedOn===t&&(e.blockedOn=null,Fm||(Fm=!0,n.unstable_scheduleCallback(n.unstable_NormalPriority,LS)))}var pd=null;function Zv(e){pd!==e&&(pd=e,n.unstable_scheduleCallback(n.unstable_NormalPriority,function(){pd===e&&(pd=null);for(var t=0;t<e.length;t+=3){var i=e[t],o=e[t+1],f=e[t+2];if(typeof o!="function"){if(Bm(o||i)===null)continue;break}var h=sn(i);h!==null&&(e.splice(t,3),t-=3,Hf(h,{pending:!0,data:f,method:i.method,action:o},o,f))}}))}function No(e){function t(F){return hd(F,e)}zr!==null&&hd(zr,e),Ir!==null&&hd(Ir,e),Or!==null&&hd(Or,e),Mc.forEach(t),Tc.forEach(t);for(var i=0;i<Hr.length;i++){var o=Hr[i];o.blockedOn===e&&(o.blockedOn=null)}for(;0<Hr.length&&(i=Hr[0],i.blockedOn===null);)Qv(i),i.blockedOn===null&&Hr.shift();if(i=(e.ownerDocument||e).$$reactFormReplay,i!=null)for(o=0;o<i.length;o+=3){var f=i[o],h=i[o+1],S=f[Ae]||null;if(typeof h=="function")S||Zv(i);else if(S){var E=null;if(h&&h.hasAttribute("formAction")){if(f=h,S=h[Ae]||null)E=S.formAction;else if(Bm(f)!==null)continue}else E=S.action;typeof E=="function"?i[o+1]=E:(i.splice(o,3),o-=3),Zv(i)}}}function Jv(){function e(h){h.canIntercept&&h.info==="react-transition"&&h.intercept({handler:function(){return new Promise(function(S){return f=S})},focusReset:"manual",scroll:"manual"})}function t(){f!==null&&(f(),f=null),o||setTimeout(i,20)}function i(){if(!o&&!navigation.transition){var h=navigation.currentEntry;h&&h.url!=null&&navigation.navigate(h.url,{state:h.getState(),info:"react-transition",history:"replace"})}}if(typeof navigation=="object"){var o=!1,f=null;return navigation.addEventListener("navigate",e),navigation.addEventListener("navigatesuccess",t),navigation.addEventListener("navigateerror",t),setTimeout(i,100),function(){o=!0,navigation.removeEventListener("navigate",e),navigation.removeEventListener("navigatesuccess",t),navigation.removeEventListener("navigateerror",t),f!==null&&(f(),f=null)}}}function Pm(e){this._internalRoot=e}gd.prototype.render=Pm.prototype.render=function(e){var t=this._internalRoot;if(t===null)throw Error(l(409));var i=t.current,o=Wa();qv(i,o,e,t,null,null)},gd.prototype.unmount=Pm.prototype.unmount=function(){var e=this._internalRoot;if(e!==null){this._internalRoot=null;var t=e.containerInfo;qv(e.current,2,null,e,null,null),Qu(),t[qe]=null}};function gd(e){this._internalRoot=e}gd.prototype.unstable_scheduleHydration=function(e){if(e){var t=es();e={blockedOn:null,target:e,priority:t};for(var i=0;i<Hr.length&&t!==0&&t<Hr[i].priority;i++);Hr.splice(i,0,e),i===0&&Qv(e)}};var ex=a.version;if(ex!=="19.2.7")throw Error(l(527,ex,"19.2.7"));Q.findDOMNode=function(e){var t=e._reactInternals;if(t===void 0)throw typeof e.render=="function"?Error(l(188)):(e=Object.keys(e).join(","),Error(l(268,e)));return e=g(t),e=e!==null?w(e):null,e=e===null?null:e.stateNode,e};var _S={bundleType:0,version:"19.2.7",rendererPackageName:"react-dom",currentDispatcherRef:I,reconcilerVersion:"19.2.7"};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"){var vd=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!vd.isDisabled&&vd.supportsFiber)try{ze=vd.inject(_S),je=vd}catch{}}return Dc.createRoot=function(e,t){if(!c(e))throw Error(l(299));var i=!1,o="",f=lg,h=og,S=cg;return t!=null&&(t.unstable_strictMode===!0&&(i=!0),t.identifierPrefix!==void 0&&(o=t.identifierPrefix),t.onUncaughtError!==void 0&&(f=t.onUncaughtError),t.onCaughtError!==void 0&&(h=t.onCaughtError),t.onRecoverableError!==void 0&&(S=t.onRecoverableError)),t=$v(e,1,!1,null,null,i,o,null,f,h,S,Jv),e[qe]=t.current,Sm(e),new Pm(t)},Dc.hydrateRoot=function(e,t,i){if(!c(e))throw Error(l(299));var o=!1,f="",h=lg,S=og,E=cg,F=null;return i!=null&&(i.unstable_strictMode===!0&&(o=!0),i.identifierPrefix!==void 0&&(f=i.identifierPrefix),i.onUncaughtError!==void 0&&(h=i.onUncaughtError),i.onCaughtError!==void 0&&(S=i.onCaughtError),i.onRecoverableError!==void 0&&(E=i.onRecoverableError),i.formState!==void 0&&(F=i.formState)),t=$v(e,1,!0,t,i??null,o,f,F,h,S,E,Jv),t.context=Uv(null),i=t.current,o=Wa(),o=st(o),f=ni(o),f.callback=null,ia(i,f,o),i=o,t.current.lanes=i,ut(t,i),si(t),e[qe]=t.current,Sm(e),new gd(t)},Dc.version="19.2.7",Dc}var fx;function j0(){if(fx)return Gm.exports;fx=1;function n(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(a){console.error(a)}}return n(),Gm.exports=C0(),Gm.exports}var k0=j0();const A0="https://otbyfkjxrkngvjziawki.supabase.co",N0="sb_publishable_NpUs0RDJH2YnllsqTKO6TQ_1jTdSsNQ",M0={getItem:()=>null,setItem:()=>{},removeItem:()=>{}},mx=typeof window<"u"&&!!window.liveDesk,mt=x0(A0,N0,{auth:{autoRefreshToken:!0,persistSession:!mx,storage:mx?M0:void 0,detectSessionInUrl:!0,flowType:"pkce",storageKey:"livedesk.mindexec.supabase.auth"}}),T0=new Set(["browserLanguage","platform","online","viewport","timezone","screen"]),E0={id:"browser-safe-v1",collect(){if(typeof navigator>"u")return{};const n={browserLanguage:navigator.language||"",platform:navigator.platform||"",online:navigator.onLine,timezone:typeof Intl>"u"?"":Intl.DateTimeFormat().resolvedOptions().timeZone||"",viewport:typeof window>"u"?void 0:{width:window.innerWidth,height:window.innerHeight},screen:typeof window>"u"?void 0:{width:window.screen.width,height:window.screen.height}};return Object.fromEntries(Object.entries(n).filter(([a,r])=>T0.has(a)&&r!==void 0))}};function R0(n,a="Support request failed."){if(n&&typeof n=="object"&&"message"in n){const r=String(n.message||"").trim();if(r)return r.replace(/^.*Support request failed:\s*/i,"")}return n instanceof Error?n.message:a}function D0(n=E0){return n.collect()}async function L0(n,a="livedesk"){const{data:r,error:l}=await mt.from("app_admins").select("role").eq("user_id",n).limit(1);if(l)throw l;const c=r?.[0]?.role||"user";if(c!=="owner"){const{error:C}=await mt.rpc("register_product_access",{p_product_key:a,p_access_type:"free"});if(C)throw C}const[d,m,p]=await Promise.all([mt.from("products").select("id, product_key, name, description, sort_order").order("sort_order"),mt.from("product_admins").select("product_id, role").eq("user_id",n),mt.from("user_products").select("product_id").eq("user_id",n).eq("is_active",!0)]);if(d.error)throw d.error;if(m.error)throw m.error;if(p.error)throw p.error;const v=d.data||[],g=(m.data||[]).map(C=>String(C.product_id)),w=(p.data||[]).map(C=>String(C.product_id)),y=c==="owner",b=y?v.map(C=>C.id):[...new Set([...g,...w])];return{products:v,access:{userId:n,globalRole:c,accessibleProductIds:b,managedProductIds:y?v.map(C=>C.id):g,canViewAllProducts:y,canViewAllPrivatePosts:y,canManageAllProducts:y,canCreateAnnouncements:y||g.length>0}}}async function _0(n=""){const{data:a,error:r}=await mt.rpc("search_support_posts",{p_query:n.trim()||null,p_limit:250});if(r)throw r;return a||[]}async function z0(n){const{data:a,error:r}=await mt.from("support_attachments").select("*").eq("post_id",n).order("created_at");if(r)throw r;const l=a||[];return Promise.all(l.map(async c=>{const d=await mt.storage.from("support-attachments").createSignedUrl(c.storage_path,3600);return{...c,signed_url:d.data?.signedUrl||void 0}}))}async function I0(){const{data:n,error:a}=await mt.from("support_notifications").select("*").order("created_at",{ascending:!1}).limit(30);if(a)throw a;return n||[]}async function O0(n){const{error:a}=await mt.rpc("mark_support_notification_read",{p_notification_id:n});if(a)throw a}async function hx(n){const{data:a,error:r}=await mt.from("support_comments").select("*").eq("post_id",n).order("created_at");if(r)throw r;return a||[]}async function H0(n){const{data:a,error:r}=await mt.from("support_votes").select("post_id").eq("user_id",n);if(r)throw r;return new Set((a||[]).map(l=>String(l.post_id)))}async function B0(n){const{data:a,error:r}=await mt.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?D0():{}});if(r)throw r;const l=Array.isArray(a)?a[0]?.post_id:a?.post_id;if(!l)throw new Error("Support post was not created.");return String(l)}const F0=new Set(["image/png","image/jpeg","image/webp","text/plain","text/markdown","application/json","application/pdf"]);async function P0(n,a){if(!F0.has(a.type))throw new Error("This file type is not allowed.");if(a.size<=0||a.size>10*1024*1024)throw new Error("Attachments must be smaller than 10 MB.");const r=a.name.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"attachment",l=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`,c=`${n}/${l}-${r}`,d=await mt.storage.from("support-attachments").upload(c,a,{contentType:a.type,upsert:!1});if(d.error)throw d.error;const{data:m,error:p}=await mt.rpc("add_support_attachment",{p_post_id:n,p_storage_path:c,p_file_name:r,p_mime_type:a.type,p_size_bytes:a.size});if(p)throw await mt.storage.from("support-attachments").remove([c]),p;const v=Array.isArray(m)?m[0]?.attachment_id:m?.attachment_id;if(!v)throw new Error("Attachment metadata was not created.");return String(v)}async function $0(n,a,r,l){const{error:c}=await mt.rpc("update_support_post",{p_post_id:n,p_title:a,p_body:r,p_visibility:l});if(c)throw c}async function U0(n,a){const{error:r}=await mt.rpc("add_support_comment",{p_post_id:n,p_body:a});if(r)throw r}async function q0(n){const{data:a,error:r}=await mt.rpc("toggle_support_vote",{p_post_id:n});if(r)throw r;const l=Array.isArray(a)?a[0]:a;return{voted:!!l?.voted,totalVotes:Number(l?.total_votes||0)}}async function G0(n,a){const{error:r}=await mt.rpc("change_support_post_status",{p_post_id:n,p_target_status:a});if(r)throw r}async function V0(n){const{error:a}=await mt.rpc("set_support_post_hidden",{p_post_id:n,p_hidden:!0});if(a)throw a}async function W0(n,a){const{error:r}=await mt.rpc("set_support_post_locked",{p_post_id:n,p_locked:a});if(r)throw r}async function Y0(n,a){const{error:r}=await mt.rpc("set_support_post_pinned",{p_post_id:n,p_pinned:a});if(r)throw r}async function K0(n,a){const{error:r}=await mt.rpc("mark_support_duplicate",{p_post_id:n,p_duplicate_of_post_id:a});if(r)throw r}async function Q0(n,a){const{error:r}=await mt.rpc("accept_support_answer",{p_post_id:n,p_comment_id:a});if(r)throw r}async function X0(n,a=!0){const{error:r}=await mt.rpc("hide_support_comment",{p_comment_id:n,p_hidden:a});if(r)throw r}const Nh=[{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"}],Z0=[{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"}],J0={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"]},eC={type:"all",product:"",status:"all",visibility:"all",sort:"recent",query:""};function Ym(){if(typeof window>"u")return eC;const n=new URLSearchParams(window.location.search),a=window.location.pathname.match(/^\/support\/(questions|issues|features|announcements)$/)?.[1],r=n.get("type")||a||"",l=r==="questions"||r==="question"?"question":r==="issues"||r==="issue"?"issue":r==="features"||r==="feature"?"feature":r==="announcements"||r==="announcement"?"announcement":"all",c=n.get("visibility"),d=n.get("sort");return{type:l,product:n.get("product")||"",status:n.get("status")||"all",visibility:c==="public"||c==="private"?c:"all",sort:d==="votes"||d==="newest"?d:"recent",query:n.get("q")||""}}function tC(n){return n==="all"?"":n==="question"?"questions":n==="issue"?"issues":n==="feature"?"features":"announcements"}function nC(n,a){const r={...n,...a},l=new URLSearchParams;r.product&&l.set("product",r.product),r.status!=="all"&&l.set("status",r.status),r.visibility!=="all"&&l.set("visibility",r.visibility),r.sort!=="recent"&&l.set("sort",r.sort),r.query&&l.set("q",r.query);const c=tC(r.type),d=l.toString();return`/support${c?`/${c}`:""}${d?`?${d}`:""}`}function xd(n){const a=new Date(n);return Number.isFinite(a.getTime())?a.toLocaleString(void 0,{dateStyle:"medium",timeStyle:"short"}):n}function Km(n){return n.replaceAll("-"," ").replace(/\b\w/g,a=>a.toUpperCase())}function px(n){return n==="question"?FS:n==="issue"?PS:n==="feature"?$S:US}function gx(n){return Nh.find(a=>a.id===n)?.shortLabel||n}function Qm(n,a){return n.find(r=>r.id===a)?.name||"Product"}function _a(n){const a=R0(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 tb({session:n,currentProductKey:a="livedesk",appVersion:r="",onSignIn:l}){const[c,d]=u.useState(()=>Ym()),[m,p]=u.useState(null),[v,g]=u.useState([]),[w,y]=u.useState([]),[b,C]=u.useState(""),[j,A]=u.useState([]),[N,k]=u.useState([]),[T,R]=u.useState([]),[q,O]=u.useState(()=>new Set),[Y,_]=u.useState(!0),[L,ae]=u.useState(""),[G,te]=u.useState(""),[P,ye]=u.useState(!1),[ie,K]=u.useState(!1),[I,Q]=u.useState(""),[U,W]=u.useState(()=>Ym().query),[ue,be]=u.useState(!1),[X,$]=u.useState(!1),[de,me]=u.useState(""),[ve,Se]=u.useState(""),[Oe,le]=u.useState("free"),[Z,He]=u.useState(""),[_e,se]=u.useState(""),[fe,Ne]=u.useState("admin"),[Te,Be]=u.useState(""),[$e,et]=u.useState(""),[Mt,ke]=u.useState(""),[Ye,rt]=u.useState(""),[vt,vn]=u.useState(""),[It,Zt]=u.useState([]),[ht,$n]=u.useState({productId:"",postType:"question",title:"",body:"",visibility:"public",includeEnvironment:!0,files:[]}),Gt=u.useCallback(H=>{const De={...c,...H};d(De),typeof window<"u"&&window.history.pushState({},"",nC(c,H))},[c]);u.useEffect(()=>{const H=()=>d(Ym());return window.addEventListener("popstate",H),()=>window.removeEventListener("popstate",H)},[]);const J=u.useCallback(async()=>{const H=await _0(c.query);return y(H),n?.user.id&&O(await H0(n.user.id)),H},[c.query,n?.user.id]),Re=u.useCallback(async()=>{if(!n?.user.id){p(null),g([]),y([]),C(""),R([]),_(!1);return}_(!0),te("");try{const H=await L0(n.user.id,a);p(H.access),g(H.products),await J(),R(await I0())}catch(H){te(_a(H))}finally{_(!1)}},[a,J,n?.user.id]);u.useEffect(()=>{Re()},[Re]);const ze=u.useMemo(()=>m?m.canViewAllProducts?v:v.filter(H=>m.accessibleProductIds.includes(H.id)):[],[m,v]),je=u.useMemo(()=>{const H=ze.find(De=>De.product_key===c.product);return m?.canViewAllProducts&&!c.product||c.product==="all"&&m?.canViewAllProducts?"all":H?H.product_key:ze.some(De=>De.product_key===a)?a:ze[0]?.product_key||""},[m?.canViewAllProducts,ze,a,c.product]),Xe=je==="all"?"":ze.find(H=>H.product_key===je)?.id||"",gt=u.useMemo(()=>{const H=new Map(v.map(st=>[st.id,st.product_key]));return[...w.filter(st=>c.type!=="all"&&st.post_type!==c.type||je!=="all"&&Xe&&st.product_id!==Xe||c.status==="needs-response"&&!["open","needs-info"].includes(st.status)||c.status!=="all"&&c.status!=="needs-response"&&st.status!==c.status||c.visibility!=="all"&&st.visibility!==c.visibility?!1:H.has(st.product_id))].sort((st,on)=>c.sort==="votes"?on.vote_count-st.vote_count||on.updated_at.localeCompare(st.updated_at):c.sort==="newest"?on.created_at.localeCompare(st.created_at):Number(on.is_pinned)-Number(st.is_pinned)||on.updated_at.localeCompare(st.updated_at))},[w,v,c.sort,c.status,c.type,c.visibility,Xe,je]),Ee=gt.find(H=>H.id===b)||gt[0]||null,ua=!!(Ee&&m&&(m.canViewAllProducts||m.managedProductIds.includes(Ee.product_id))),Un=!!(Ee&&n?.user.id===Ee.author_id)||ua;u.useEffect(()=>{if(!Ee){C(""),A([]),K(!1);return}Ee.id!==b&&C(Ee.id)},[Ee,b]),u.useEffect(()=>{let H=!0;return b?(hx(b).then(De=>{H&&A(De)}).catch(De=>{H&&te(_a(De))}),z0(b).then(De=>{H&&k(De)}).catch(De=>{H&&te(_a(De))}),()=>{H=!1}):(A([]),k([]),()=>{H=!1})},[b]),u.useEffect(()=>{!ht.productId&&ze[0]&&$n(H=>({...H,productId:Xe||ze[0].id}))},[ze,ht.productId,Xe]),u.useEffect(()=>{W(c.query)},[c.query]),u.useEffect(()=>{!ve&&ze[0]&&Se(ze[0].id),!_e&&ze[0]&&se(ze[0].id)},[ze,ve,_e]);const tt=H=>{Ee&&y(De=>De.map(st=>st.id===Ee.id?{...st,...H}:st))},$t=async H=>{if(H.preventDefault(),!(!n||!ht.productId)){ae("create"),te("");try{const De=await B0({productId:ht.productId,postType:ht.postType,title:ht.title,body:ht.body,visibility:ht.postType==="announcement"?"public":ht.visibility,appVersion:r,includeEnvironment:ht.postType==="issue"&&ht.includeEnvironment});for(const on of It)await P0(De,on);const st=await J();ye(!1),Zt([]),$n(on=>({...on,title:"",body:"",files:[]})),C(De),st.some(on=>on.id===De)||await Re()}catch(De){te(_a(De))}finally{ae("")}}},an=async H=>{if(H.preventDefault(),!!Ee){ae("edit"),te("");try{await $0(Ee.id,Ee.title,Ee.body,Ee.visibility),K(!1),await J()}catch(De){te(_a(De))}finally{ae("")}}},Za=async H=>{if(H.preventDefault(),!(!Ee||!I.trim())){ae("comment"),te("");try{await U0(Ee.id,I),Q(""),A(await hx(Ee.id)),await J()}catch(De){te(_a(De))}finally{ae("")}}},Ja=async()=>{if(!(!Ee||Ee.post_type!=="feature")){ae("vote"),te("");try{const H=await q0(Ee.id);O(De=>{const st=new Set(De);return H.voted?st.add(Ee.id):st.delete(Ee.id),st}),tt({vote_count:H.totalVotes})}catch(H){te(_a(H))}finally{ae("")}}},Xn=async H=>{if(Ee){ae("status"),te("");try{await G0(Ee.id,H),tt({status:H}),await J()}catch(De){te(_a(De))}finally{ae("")}}},Wi=async()=>{if(!(!Ee||!window.confirm("Hide this Support post from the board?"))){ae("hide"),te("");try{await V0(Ee.id),C(""),await J()}catch(H){te(_a(H))}finally{ae("")}}},Fe=async()=>{if(Ee){ae("lock"),te("");try{await W0(Ee.id,!Ee.is_locked),tt({is_locked:!Ee.is_locked}),await J()}catch(H){te(_a(H))}finally{ae("")}}},Is=async()=>{if(Ee){ae("pin"),te("");try{await Y0(Ee.id,!Ee.is_pinned),tt({is_pinned:!Ee.is_pinned}),await J()}catch(H){te(_a(H))}finally{ae("")}}},ut=async H=>{if(Ee){ae(`accept-${H}`),te("");try{await Q0(Ee.id,H),tt({accepted_comment_id:H,status:Ee.post_type==="question"?"answered":Ee.status}),await J()}catch(De){te(_a(De))}finally{ae("")}}},ui=async()=>{if(!(!Ee||!Ye||Ye===Ee.id)){ae("duplicate"),te("");try{await K0(Ee.id,Ye),C(""),rt(""),await J()}catch(H){te(_a(H))}finally{ae("")}}},Kt=async H=>{if(!H.read_at)try{await O0(H.id),R(De=>De.map(st=>st.id===H.id?{...st,read_at:new Date().toISOString()}:st))}catch(De){te(_a(De))}H.post_id&&C(H.post_id),be(!1)};return n?Y&&!m?s.jsxs("section",{className:"support-page support-loading",children:[s.jsx(Ho,{className:"support-spin",size:23})," Loading Support Board..."]}):s.jsxs("section",{className:"support-page",children:[s.jsx("header",{className:"support-page-header support-page-actions-only",children:s.jsxs("div",{className:"support-header-actions",children:[s.jsxs("div",{className:"support-notification-wrap",children:[s.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>be(H=>!H),title:"Notifications",children:[s.jsx(OS,{size:16})," ",T.filter(H=>!H.read_at).length>0&&s.jsx("b",{children:T.filter(H=>!H.read_at).length})]}),ue&&s.jsxs("div",{className:"support-notification-popover",children:[s.jsx("strong",{children:"Notifications"}),T.length===0?s.jsx("span",{className:"support-muted",children:"No notifications yet."}):T.map(H=>s.jsxs("button",{type:"button",className:H.read_at?"":"unread",onClick:()=>{Kt(H)},children:[s.jsx("b",{children:H.title}),s.jsx("span",{children:H.body}),s.jsx("small",{children:xd(H.created_at)})]},H.id))]})]}),m?.canViewAllProducts&&s.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>$(H=>!H),children:[s.jsx(Lt,{size:16})," Admin"]}),s.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>{Re()},disabled:Y,children:[s.jsx(Ho,{size:16,className:Y?"support-spin":""})," Refresh"]}),s.jsxs("button",{className:"support-primary-button",type:"button",onClick:()=>ye(!0),disabled:ze.length===0,children:[s.jsx($m,{size:17})," New request"]})]})}),G&&s.jsxs("div",{className:"support-error",role:"alert",children:[s.jsx(Ha,{size:17})," ",s.jsx("span",{children:G}),s.jsx("button",{type:"button",onClick:()=>te(""),"aria-label":"Dismiss error",children:s.jsx(Ha,{size:15})})]}),P&&s.jsxs("form",{className:"support-composer",onSubmit:H=>{$t(H)},children:[s.jsxs("div",{className:"support-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"New Support request"}),s.jsx("strong",{children:"Describe one actionable problem or idea."})]}),s.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>ye(!1),"aria-label":"Close composer",children:s.jsx(Ha,{size:18})})]}),s.jsxs("div",{className:"support-form-grid",children:[s.jsxs("label",{children:[s.jsx("span",{children:"Product"}),s.jsx("select",{value:ht.productId,onChange:H=>$n(De=>({...De,productId:H.target.value})),children:ze.map(H=>s.jsx("option",{value:H.id,children:H.name},H.id))})]}),s.jsxs("label",{children:[s.jsx("span",{children:"Type"}),s.jsx("select",{value:ht.postType,onChange:H=>$n(De=>({...De,postType:H.target.value})),children:Nh.filter(H=>H.id!=="announcement"||m?.canCreateAnnouncements).map(H=>s.jsx("option",{value:H.id,children:H.label},H.id))})]}),s.jsxs("label",{className:"support-form-wide",children:[s.jsx("span",{children:"Title"}),s.jsx("input",{required:!0,minLength:3,maxLength:180,value:ht.title,onChange:H=>$n(De=>({...De,title:H.target.value})),placeholder:"A short, searchable summary"})]}),s.jsxs("label",{className:"support-form-wide",children:[s.jsx("span",{children:ht.postType==="issue"?"What happened?":ht.postType==="feature"?"Describe the desired behavior":ht.postType==="announcement"?"Announcement":"Question"}),s.jsx("textarea",{required:!0,value:ht.body,onChange:H=>$n(De=>({...De,body:H.target.value})),placeholder:"Include the context another person needs to respond.",rows:6})]}),s.jsxs("label",{children:[s.jsx("span",{children:"Visibility"}),s.jsxs("select",{value:ht.visibility,disabled:ht.postType==="announcement",onChange:H=>$n(De=>({...De,visibility:H.target.value})),children:[s.jsx("option",{value:"public",children:"Public"}),s.jsx("option",{value:"private",children:"Private"})]})]}),ht.postType==="issue"&&s.jsxs("label",{className:"support-checkbox",children:[s.jsx("input",{type:"checkbox",checked:ht.includeEnvironment,onChange:H=>$n(De=>({...De,includeEnvironment:H.target.checked}))}),s.jsx("span",{children:"Attach safe browser/runtime details"})]}),s.jsxs("label",{className:"support-form-wide",children:[s.jsx("span",{children:"Attachments"}),s.jsx("input",{type:"file",multiple:!0,accept:"image/png,image/jpeg,image/webp,text/plain,text/markdown,application/json,application/pdf",onChange:H=>Zt(Array.from(H.target.files||[]).slice(0,5))}),s.jsx("small",{className:"support-muted",children:"Up to 5 files, 10 MB each. Images, text, JSON, Markdown, and PDF."})]})]}),s.jsxs("div",{className:"support-composer-footer",children:[s.jsx("span",{children:It.length>0?`${It.length} attachment${It.length===1?"":"s"} selected.`:"Private posts are visible only to you and the product support staff."}),s.jsxs("button",{className:"support-primary-button",type:"submit",disabled:L==="create",children:[s.jsx(Yc,{size:16})," ",L==="create"?"Submitting...":"Submit request"]})]})]}),s.jsxs("div",{className:"support-tabs",role:"tablist","aria-label":"Support post type",children:[s.jsx("button",{className:c.type==="all"?"active":"",type:"button",onClick:()=>Gt({type:"all"}),children:"All"}),Nh.map(H=>{const De=px(H.id);return s.jsxs("button",{className:c.type===H.id?"active":"",type:"button",onClick:()=>Gt({type:H.id}),children:[s.jsx(De,{size:15})," ",H.label]},H.id)})]}),X&&m?.canViewAllProducts&&s.jsxs("section",{className:"support-admin-panel",children:[s.jsxs("div",{className:"support-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Owner controls"}),s.jsx("strong",{children:"Products and access are managed by immutable user IDs behind these email lookup forms."})]}),s.jsx(Lt,{size:19})]}),s.jsxs("div",{className:"support-admin-grid",children:[s.jsxs("form",{onSubmit:H=>{},children:[s.jsx("strong",{children:"Grant product access"}),s.jsx("input",{type:"email",required:!0,placeholder:"User email",value:de,onChange:H=>me(H.target.value)}),s.jsx("select",{value:ve,onChange:H=>Se(H.target.value),children:ze.map(H=>s.jsx("option",{value:H.id,children:H.name},H.id))}),s.jsxs("select",{value:Oe,onChange:H=>le(H.target.value),children:[s.jsx("option",{value:"free",children:"Free"}),s.jsx("option",{value:"user",children:"User"}),s.jsx("option",{value:"paid",children:"Paid"}),s.jsx("option",{value:"beta",children:"Beta"}),s.jsx("option",{value:"staff",children:"Staff"})]}),s.jsxs("button",{className:"support-secondary-button",type:"submit",disabled:vt==="access",children:[s.jsx(ri,{size:15})," Grant access"]})]}),s.jsxs("form",{onSubmit:H=>{},children:[s.jsx("strong",{children:"Assign product admin"}),s.jsx("input",{type:"email",required:!0,placeholder:"Admin email",value:Z,onChange:H=>He(H.target.value)}),s.jsx("select",{value:_e,onChange:H=>se(H.target.value),children:ze.map(H=>s.jsx("option",{value:H.id,children:H.name},H.id))}),s.jsxs("select",{value:fe,onChange:H=>Ne(H.target.value),children:[s.jsx("option",{value:"admin",children:"Admin"}),s.jsx("option",{value:"support",children:"Support"}),s.jsx("option",{value:"moderator",children:"Moderator"})]}),s.jsxs("button",{className:"support-secondary-button",type:"submit",disabled:vt==="product-admin",children:[s.jsx(Lt,{size:15})," Assign admin"]})]}),s.jsxs("form",{onSubmit:H=>{},children:[s.jsx("strong",{children:"Add a product"}),s.jsx("input",{required:!0,pattern:"[a-z0-9][a-z0-9_-]{1,48}",placeholder:"product-key",value:Te,onChange:H=>Be(H.target.value)}),s.jsx("input",{required:!0,placeholder:"Product name",value:$e,onChange:H=>et(H.target.value)}),s.jsx("input",{placeholder:"Description",value:Mt,onChange:H=>ke(H.target.value)}),s.jsxs("button",{className:"support-secondary-button",type:"submit",disabled:vt==="product",children:[s.jsx($m,{size:15})," Add product"]})]})]})]}),s.jsxs("form",{className:"support-search-bar",onSubmit:H=>{H.preventDefault(),Gt({query:U.trim()})},children:[s.jsxs("label",{children:[s.jsx("span",{children:"Search Support"}),s.jsx("input",{value:U,onChange:H=>W(H.target.value),placeholder:"Search titles and request details"})]}),s.jsxs("button",{className:"support-secondary-button",type:"submit",children:[s.jsx(tx,{size:15})," Search"]}),c.query&&s.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>{W(""),Gt({query:""})},"aria-label":"Clear search",children:s.jsx(Ha,{size:16})})]}),s.jsxs("div",{className:"support-filter-bar",children:[s.jsxs("div",{className:"support-filter-title",children:[s.jsx(tx,{size:16}),s.jsx("span",{children:"Filter"})]}),s.jsxs("label",{children:[s.jsx("span",{children:"Product"}),s.jsxs("select",{value:je,onChange:H=>Gt({product:H.target.value}),disabled:!m?.canViewAllProducts&&ze.length<=1,children:[s.jsx("option",{value:"all",children:"All products"}),ze.map(H=>s.jsx("option",{value:H.product_key,children:H.name},H.id))]})]}),s.jsxs("label",{children:[s.jsx("span",{children:"Status"}),s.jsx("select",{value:c.status,onChange:H=>Gt({status:H.target.value}),children:Z0.map(H=>s.jsx("option",{value:H.id,children:H.label},H.id))})]}),s.jsxs("label",{children:[s.jsx("span",{children:"Visibility"}),s.jsxs("select",{value:c.visibility,onChange:H=>Gt({visibility:H.target.value}),children:[s.jsx("option",{value:"all",children:"All visibility"}),s.jsx("option",{value:"public",children:"Public"}),s.jsx("option",{value:"private",children:"Private"})]})]}),s.jsxs("label",{children:[s.jsx("span",{children:"Sort"}),s.jsxs("select",{value:c.sort,onChange:H=>Gt({sort:H.target.value}),children:[s.jsx("option",{value:"recent",children:"Recently updated"}),s.jsx("option",{value:"newest",children:"Newest"}),s.jsx("option",{value:"votes",children:"Most votes"})]})]})]}),m?.canViewAllProducts&&s.jsxs("div",{className:"support-admin-shortcuts",children:[s.jsxs("span",{children:[s.jsx(Lt,{size:15})," Owner view"]}),s.jsx("button",{type:"button",onClick:()=>Gt({status:"needs-response"}),children:"Needs response"}),s.jsx("button",{type:"button",onClick:()=>Gt({visibility:"private"}),children:"Private requests"}),s.jsx("button",{type:"button",onClick:()=>Gt({type:"feature",status:"all",sort:"votes"}),children:"High-vote features"})]}),s.jsxs("div",{className:"support-board-layout",children:[s.jsxs("section",{className:"support-post-list","aria-label":"Support posts",children:[s.jsxs("div",{className:"support-list-heading",children:[s.jsxs("span",{children:[gt.length," request",gt.length===1?"":"s"]}),s.jsx("small",{children:je==="all"?"All products":Qm(ze,Xe)})]}),gt.length===0?s.jsxs("div",{className:"support-list-empty",children:[s.jsx(Pc,{size:25}),s.jsx("strong",{children:"No posts match these filters."}),s.jsx("span",{children:"Start with a focused question, issue report, or feature request."}),ze.length>0&&s.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>ye(!0),children:[s.jsx($m,{size:16})," Create the first request"]})]}):gt.map(H=>{const De=px(H.post_type);return s.jsxs("button",{type:"button",className:`support-post-row ${H.id===Ee?.id?"active":""}`,onClick:()=>{C(H.id),K(!1)},children:[s.jsx("span",{className:"support-post-row-icon",children:s.jsx(De,{size:17})}),s.jsxs("span",{className:"support-post-row-copy",children:[s.jsxs("span",{className:"support-post-row-meta",children:[s.jsx("b",{children:Qm(v,H.product_id)}),s.jsx("em",{children:gx(H.post_type)}),H.visibility==="private"&&s.jsx(Ds,{size:13})]}),s.jsx("strong",{children:H.title}),s.jsxs("small",{children:[Km(H.status)," · ",xd(H.updated_at)," · ",H.comment_count," comments"]})]}),H.post_type==="feature"&&s.jsxs("span",{className:"support-vote-count",children:[s.jsx(Uy,{size:14})," ",H.vote_count]})]},H.id)})]}),s.jsx("section",{className:"support-post-detail","aria-label":"Support post detail",children:Ee?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"support-detail-head",children:[s.jsxs("div",{className:"support-detail-badges",children:[s.jsx("span",{className:"support-product-badge",children:Qm(v,Ee.product_id)}),s.jsx("span",{className:"support-type-badge",children:gx(Ee.post_type)}),s.jsx("span",{className:`support-status-badge status-${Ee.status}`,children:Km(Ee.status)}),Ee.visibility==="private"&&s.jsxs("span",{className:"support-private-badge",children:[s.jsx(Ds,{size:13})," Private"]})]}),s.jsxs("div",{className:"support-detail-actions",children:[Un&&s.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>K(H=>!H),title:"Edit post",children:s.jsx(HS,{size:16})}),ua&&s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>{Is()},disabled:L==="pin",title:Ee.is_pinned?"Unpin post":"Pin post",children:s.jsx(nx,{size:16})}),s.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>{Fe()},disabled:L==="lock",title:Ee.is_locked?"Unlock post":"Lock post",children:s.jsx(Ds,{size:16})}),s.jsx("button",{className:"support-icon-button danger",type:"button",onClick:()=>{Wi()},disabled:L==="hide",title:"Hide post",children:s.jsx(ax,{size:16})})]})]})]}),ie?s.jsxs("form",{className:"support-edit-form",onSubmit:H=>{an(H)},children:[s.jsx("input",{value:Ee.title,onChange:H=>tt({title:H.target.value}),minLength:3,maxLength:180,required:!0}),s.jsx("textarea",{value:Ee.body,onChange:H=>tt({body:H.target.value}),rows:9,required:!0}),s.jsxs("div",{className:"support-edit-actions",children:[s.jsxs("select",{value:Ee.visibility,onChange:H=>tt({visibility:H.target.value}),children:[s.jsx("option",{value:"public",children:"Public"}),s.jsx("option",{value:"private",children:"Private"})]}),s.jsxs("button",{className:"support-primary-button",type:"submit",disabled:L==="edit",children:[s.jsx(ri,{size:16})," Save changes"]})]})]}):s.jsxs(s.Fragment,{children:[s.jsx("h3",{children:Ee.title}),s.jsx("div",{className:"support-detail-body",children:Ee.body.split(`
10
- `).map((H,De)=>s.jsx("p",{children:H||" "},`${Ee.id}-body-${De}`))})]}),s.jsxs("div",{className:"support-detail-meta",children:[s.jsxs("span",{children:["Opened ",xd(Ee.created_at)]}),Ee.app_version&&s.jsxs("span",{children:["Version ",Ee.app_version]}),Ee.platform&&s.jsx("span",{children:Ee.platform}),Ee.is_locked&&s.jsxs("span",{children:[s.jsx(Ds,{size:13})," Locked"]}),Ee.is_pinned&&s.jsxs("span",{children:[s.jsx(nx,{size:13})," Pinned"]})]}),s.jsxs("div",{className:"support-detail-controls",children:[Ee.post_type==="feature"&&s.jsxs("button",{className:`support-vote-button ${q.has(Ee.id)?"voted":""}`,type:"button",onClick:()=>{Ja()},disabled:L==="vote",children:[s.jsx(BS,{size:16})," ",q.has(Ee.id)?"Voted":"Vote"," ",s.jsx("b",{children:Ee.vote_count})]}),ua&&s.jsxs("label",{className:"support-status-control",children:[s.jsx("span",{children:"Change status"}),s.jsx("select",{value:Ee.status,onChange:H=>{Xn(H.target.value)},disabled:L==="status",children:(J0[Ee.post_type]||[]).map(H=>s.jsx("option",{value:H,children:Km(H)},H))})]}),ua&&s.jsxs(s.Fragment,{children:[s.jsxs("select",{className:"support-status-control",value:Ye,onChange:H=>rt(H.target.value),children:[s.jsx("option",{value:"",children:"Duplicate of..."}),gt.filter(H=>H.id!==Ee.id&&H.product_id===Ee.product_id).map(H=>s.jsx("option",{value:H.id,children:H.title.slice(0,55)},H.id))]}),s.jsx("button",{className:"support-secondary-button",type:"button",onClick:()=>{ui()},disabled:!Ye||L==="duplicate",children:"Merge duplicate"})]})]}),N.length>0&&s.jsxs("div",{className:"support-attachments",children:[s.jsx("div",{className:"support-section-heading",children:s.jsxs("div",{children:[s.jsx("span",{children:"Attachments"}),s.jsxs("strong",{children:[N.length," file",N.length===1?"":"s"]})]})}),N.map(H=>s.jsxs("a",{href:H.signed_url,target:"_blank",rel:"noreferrer",children:[s.jsx(Qh,{size:14})," ",H.file_name,s.jsxs("small",{children:[Math.ceil(H.size_bytes/1024)," KB"]})]},H.id))]}),s.jsxs("div",{className:"support-comments",children:[s.jsxs("div",{className:"support-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Discussion"}),s.jsxs("strong",{children:[j.length," comment",j.length===1?"":"s"]})]}),Ee.is_locked&&s.jsxs("span",{className:"support-locked-label",children:[s.jsx(Ds,{size:14})," Locked"]})]}),j.length===0?s.jsx("p",{className:"support-muted",children:"No response yet. Keep the conversation focused on this request."}):s.jsx("div",{className:"support-comment-list",children:j.map(H=>s.jsxs("article",{className:`support-comment ${H.is_staff_answer?"staff":""} ${Ee.accepted_comment_id===H.id?"accepted":""}`,children:[s.jsxs("div",{className:"support-comment-head",children:[s.jsx("strong",{children:H.is_staff_answer?"LiveDesk Support":H.author_id===n.user.id?"You":"Support user"}),H.is_staff_answer&&s.jsxs("span",{children:[s.jsx(Lt,{size:13})," Staff answer"]}),Ee.accepted_comment_id===H.id&&s.jsxs("span",{children:[s.jsx(Hn,{size:13})," Accepted"]}),s.jsx("time",{children:xd(H.created_at)})]}),s.jsx("p",{children:H.body}),s.jsxs("div",{className:"support-comment-actions",children:[(n.user.id===Ee.author_id||ua)&&Ee.post_type==="question"&&Ee.accepted_comment_id!==H.id&&s.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>{ut(H.id)},disabled:L===`accept-${H.id}`,children:[s.jsx(ri,{size:14})," Accept answer"]}),ua&&s.jsx("button",{className:"support-icon-button danger",type:"button",onClick:()=>{X0(H.id)},title:"Hide comment",children:s.jsx(ax,{size:14})})]})]},H.id))}),!Ee.is_locked&&s.jsxs("form",{className:"support-comment-form",onSubmit:H=>{Za(H)},children:[s.jsx("textarea",{value:I,onChange:H=>Q(H.target.value),placeholder:"Add a focused reply...",rows:3}),s.jsxs("button",{className:"support-primary-button",type:"submit",disabled:L==="comment"||!I.trim(),children:[s.jsx(Yc,{size:15})," Reply"]})]})]})]}):s.jsxs("div",{className:"support-detail-empty",children:[s.jsx(Pc,{size:28}),s.jsx("strong",{children:"Select a Support request"}),s.jsx("span",{children:"Its discussion and staff actions will appear here."})]})})]})]}):s.jsx("section",{className:"support-page support-auth-page",children:s.jsxs("div",{className:"support-empty-hero",children:[s.jsx("span",{className:"support-hero-icon",children:s.jsx(Pc,{size:28})}),s.jsx("p",{className:"support-eyebrow",children:"LiveDesk Support"}),s.jsx("h2",{children:"Get help, report issues, and shape the product."}),s.jsx("p",{children:"Sign in to see the products attached to your account and submit a private or public request."}),s.jsxs("button",{className:"support-primary-button",type:"button",onClick:l,children:[s.jsx(Lt,{size:17})," Sign in with Google"]})]})})}function yd(n){return!!n&&typeof n=="object"}function nb(n){let a=n;return yd(a)&&"data"in a&&(a=a.data),yd(a)&&"session"in a&&(a=a.session),!yd(a)||typeof a.access_token!="string"||!a.access_token||!yd(a.user)||typeof a.user.id!="string"||!a.user.id?null:a}function vx(n){return n?.access_token?n.refresh_token?"":"refresh-token-required":"access-token-required"}const Uc=5179,Cn=Wr(`http://127.0.0.1:${Uc}`);function aC(n){const a=n.split(".").map(r=>Number(r));return a.length===4&&a.every(r=>Number.isInteger(r)&&r>=0&&r<=255)?a:[]}function sC(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 rC(n){const a=aC(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 lC(n){return n.includes(":")&&!n.startsWith("[")?`[${n}]`:n}function oC(n){const a=String(n||"").trim();if(!a)return null;const r=/^[a-z][a-z\d+.-]*:\/\//i.test(a)?a:`tcp://${a}`;try{const l=new URL(r),c=l.hostname.replace(/^\[|\]$/g,""),d=Number(l.port);return!c||!Number.isInteger(d)||d<1||d>65535||iC(c)?null:{host:c,port:d}}catch{return null}}function Wr(n){const a=String(n||"").trim()||`http://127.0.0.1:${Uc}`,r=/^[a-z][a-z\d+.-]*:\/\//i.test(a)?a:`http://${a}`;try{const l=new URL(r);return l.port||(l.port=String(Uc)),l.hash="",l.search="",l.toString().replace(/\/+$/,"")}catch{return`http://127.0.0.1:${Uc}`}}function cC(n){const a=oC(n);return a?Wr(`http://${lC(a.host)}:${Uc}`):""}function xx(n){const r=[n?.endpoint,...Array.isArray(n?.endpoint_candidates)?n.endpoint_candidates:[]].map(l=>cC(String(l||""))).filter(Boolean);return[...new Set(r)]}function qc(n=Cn){if(!(typeof window>"u"||window.location.protocol!=="https:"))try{const a=new URL(n);if(a.protocol!=="http:")return;if(sC(a.hostname))return"loopback";if(rC(a.hostname))return"local"}catch{return}}function df(n,a=Cn){const r=new URL(n,Wr(a));return r.protocol=r.protocol==="https:"?"wss:":"ws:",r.toString()}async function Ge(n,a,r=Cn){const l=Wr(r),c={...a,headers:{"Content-Type":"application/json",...a?.headers||{}},cache:"no-store"},d=qc(l);d&&(c.targetAddressSpace=d);let m;try{m=await fetch(`${l}${n}`,c)}catch(v){throw d?new Error("LiveDesk Hub is not reachable at this local network address. If Chrome shows a local network prompt, allow it; otherwise restart the Hub so port 5179 is open on the network."):v}let p=null;try{p=await m.json()}catch{p=null}if(!m.ok){const v=p&&typeof p=="object"&&"error"in p?String(p.error||""):"";throw new Error(`${m.status} ${v||m.statusText}`)}return p}async function ab({baseUrl:n=Cn,targetRole:a,previousRuntimePid:r=0,allowedStates:l=["running","waiting-auth"],timeoutMs:c=3e4}){const d=Date.now()+c;let m=null;for(;Date.now()<d;){try{const v=await Ge("/api/runtime/status",void 0,n),g=String(v.role||"").toLowerCase(),w=String(v.state||"").toLowerCase(),y=Number(v.runtimePid||0),b=r>1?y>1&&y!==r:y>1;if(g===a&&l.map(C=>C.toLowerCase()).includes(w)&&b)return v}catch(v){m=v}await new Promise(v=>setTimeout(v,300))}const p=m instanceof Error?` ${m.message}`:"";throw new Error(`LiveDesk runtime did not become ${a} with a new process.${p}`)}function uC(n,a=120){if(typeof window>"u")return;const r=new URL(window.location.href);r.port=String(n),r.pathname="/",r.search="",r.hash="";const l=r.toString();let c=0;const d=()=>{fetch(l,{cache:"no-store",mode:"no-cors"}).then(()=>window.location.replace(l)).catch(()=>{if(c+=1,c>=a){window.location.replace(l);return}window.setTimeout(d,250)})};d()}function sb(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 Ll(n){await navigator.clipboard.writeText(n)}function ib({size:n=22}){return s.jsxs("svg",{width:n,height:n,viewBox:"0 0 28 28",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",children:[s.jsx("rect",{x:"2.5",y:"4",width:"14",height:"9",rx:"1.5",stroke:"currentColor",strokeWidth:"1.7",opacity:"0.42"}),s.jsx("path",{d:"M7 16v1.5h5",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",opacity:"0.42"}),s.jsx("rect",{x:"10.5",y:"2.5",width:"14",height:"9",rx:"1.5",stroke:"currentColor",strokeWidth:"1.7",opacity:"0.62"}),s.jsx("path",{d:"M15 14.5V16h5",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",opacity:"0.62"}),s.jsx("rect",{x:"6.5",y:"8.5",width:"15",height:"10",rx:"1.7",fill:"currentColor",fillOpacity:"0.12",stroke:"currentColor",strokeWidth:"1.9"}),s.jsx("path",{d:"M12 21v1.5H9.5M16 21v1.5h2.5M9.5 22.5h9",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round"})]})}const rb={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."},Mh={en:rb,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 ff(n){const a=n?[n]:typeof navigator>"u"?["en"]:navigator.languages?.length?navigator.languages:[navigator.language];for(const r of a){const l=String(r||"").trim(),c=l.toLowerCase();if(!c)continue;if(c.startsWith("zh-tw")||c.startsWith("zh-hk"))return"zh-TW";if(c.startsWith("zh"))return"zh";if(c.startsWith("pt"))return"pt-BR";const d=c.split("-")[0];if(Mh[l])return l;if(Mh[d])return d}return"en"}function Xd(n,a){const r=ff(a);return Mh[r]?.[n]||rb[n]}function Th(n,a,r){return`${n}
11
- ${Xd(a,r)}`}const lb={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"},dC={en:lb,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"}},ob={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"},fC={en:ob,ko:{eyebrow:"컴퓨터 역할",title:"이 컴퓨터를 Hub로 사용할까요?",description:"Hub는 Client 컴퓨터를 연결하고 관리합니다.",restartNotice:"다른 컴퓨터가 Hub라면 이 컴퓨터가 새 Hub가 됩니다.",cancel:"취소",confirm:"Hub로 설정",closeLabel:"Hub 설정 확인 닫기"}};function mC(n){const a=ff(n);return dC[a]||lb}function hC(n){const a=ff(n);return fC[a]||ob}const pC=[{id:"docs",label:"Doc",icon:Kd},{id:"support",label:"Support",icon:Pc},{id:"pricing",label:"Pricing",icon:Do},{id:"settings",label:"Settings",icon:qy}],yx=[0,1e3,2e3,5e3,1e4,2e4,3e4];function gC(){return typeof window>"u"?"":window.location.port==="5179"?window.location.origin:"http://127.0.0.1:5179"}async function Lc(n,a=!1){const r=a?"":sessionStorage.getItem("livedesk.client.csrf");if(r)return r;const l=await fetch(`${n}/api/runtime/status`,{cache:"no-store"}),c=await l.json().catch(()=>({}));if(!l.ok)throw new Error(c.error||`Client runtime returned HTTP ${l.status}.`);const d=String(c.csrfToken||"");return d&&sessionStorage.setItem("livedesk.client.csrf",d),d}function Eh(n){return`${Math.max(0,Math.min(100,Number(n||0))).toFixed(0)}%`}function Xm(n){return Number.isFinite(n)?`${Math.max(0,Math.min(100,Number(n))).toFixed(0)}%`:"—"}function cb(n){return Number.isFinite(n)?Eh(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 bx(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 vC(n,a){const r=Number(n||0)/1073741824,l=Number(a||0)/1024**3;return l>0?`${r.toFixed(1)} / ${l.toFixed(1)} GB`:"Checking..."}function xC(n,a){return!Number.isFinite(a)||Number(a)<=0?"Dedicated memory unavailable":Number.isFinite(n)?`${Il(n)} / ${Il(a)}`:`${Il(a)} available`}function yC(n){const a=Math.max(0,Math.floor(Number(n||0)/60)),r=Math.floor(a/1440),l=Math.floor(a%1440/60),c=a%60;return r>0?`${r}d ${l}h`:l>0?`${l}h ${c}m`:`${c}m`}function bd({icon:n,label:a,value:r,detail:l,percent:c}){return s.jsxs("article",{className:"client-resource-metric",children:[s.jsxs("div",{className:"client-resource-metric-head",children:[s.jsx(n,{size:17}),s.jsx("span",{children:a}),s.jsx("strong",{children:r})]}),s.jsx("small",{title:l,children:l}),s.jsx("i",{"aria-hidden":"true",children:s.jsx("b",{style:{width:cb(c)}})})]})}function bC(n){const a=n?.user.user_metadata||{},r=a.full_name||a.name||a.preferred_username||n?.user.email||n?.user.id||"Account";return String(r).trim()||"Account"}function wC(n){const a=n?.user.user_metadata||{},r=a.avatar_url||a.picture;return typeof r=="string"?r.trim():""}function SC({page:n,status:a}){const l={docs:{label:"DOC",title:"Using this computer",body:"This computer connects to its assigned Hub automatically. Keep LiveDesk running and manage screens, files, and remote control from the Hub."},pricing:{label:"PRICING",title:"LiveDesk plans",body:"Plans are based on how many computers the Hub manages. This Client computer does not need a separate subscription or setup."},settings:{label:"SETTINGS",title:"Computer preferences",body:"LiveDesk keeps the verified sign-in on this computer and reconnects to the assigned Hub automatically."}}[n];return s.jsxs("section",{className:"client-service-page",children:[s.jsx("span",{className:"client-unified-section-label",children:l.label}),s.jsx("h2",{children:l.title}),s.jsx("p",{children:l.body}),s.jsxs("div",{className:"client-service-page-card",children:[n==="docs"&&s.jsxs(s.Fragment,{children:[s.jsx("strong",{children:"Automatic connection"}),s.jsx("span",{children:"Start LiveDesk. This computer signs in, finds the Hub, and becomes available without another action."})]}),n==="pricing"&&s.jsxs(s.Fragment,{children:[s.jsx("strong",{children:"One plan, managed at the Hub"}),s.jsx("span",{children:"Computer access follows the account and plan used by the Hub."})]}),n==="settings"&&s.jsxs(s.Fragment,{children:[s.jsx("strong",{children:"Saved sign-in"}),s.jsx("span",{children:a?.auth?.persisted?"Enabled on this computer":"Sign in once to enable automatic reconnection"})]})]})]})}function CC({session:n,status:a,pin:r,error:l,roleChangeMessage:c,roleChangeBusy:d,onSignIn:m,onPinChange:p,onSubmitPin:v,onSwitchToHub:g}){const w=a?.connectionState==="connected",y=a?.system?.memoryTotalBytes?Number(a.system.memoryUsedBytes||0)/a.system.memoryTotalBytes*100:0,b=a?.system?.gpus||[],C=b.find(O=>Number.isFinite(O.usagePercent)||Number.isFinite(O.memoryTotalBytes))||b[0],j=Number.isFinite(C?.usagePercent)?Number(C?.usagePercent):null,A=Number.isFinite(C?.memoryTotalBytes)&&Number(C?.memoryTotalBytes)>0&&Number.isFinite(C?.memoryUsedBytes)?Number(C?.memoryUsedBytes)/Number(C?.memoryTotalBytes)*100:null,N=a?.system?.disks||[],k=a?.system?.network,T=k?.interfaces||[],R=[...new Set(T.map(O=>O.name).filter(Boolean))],q=T.map(O=>O.address).filter(Boolean);return s.jsxs("section",{className:"client-home-page",children:[s.jsxs("header",{className:"client-home-heading",children:[s.jsxs("div",{children:[s.jsx("p",{className:"client-unified-eyebrow",children:"THIS COMPUTER"}),s.jsx("h2",{children:a?.deviceName||"This Computer"})]}),s.jsxs("span",{className:`client-unified-role-chip ${w?"connected":""}`,children:[s.jsx(Yt,{size:15})," ",w?"Online":"Connecting"]})]}),s.jsxs("div",{className:"client-home-layout",children:[s.jsxs("section",{className:"client-main-surface","aria-label":"Client computer",children:[s.jsxs("div",{className:"client-main-surface-head",children:[s.jsxs("div",{children:[s.jsx("span",{className:"client-unified-section-label",children:"SYSTEM STATUS"}),s.jsx("strong",{children:"Hardware at a glance"})]}),s.jsxs("small",{children:[s.jsx(Vy,{size:14})," Uptime ",yC(a?.system?.uptimeSeconds)]})]}),s.jsxs("div",{className:"client-system-dashboard",children:[s.jsxs("section",{className:"client-performance-panel","aria-label":"Performance",children:[s.jsxs("div",{className:"client-system-subhead",children:[s.jsxs("div",{children:[s.jsx("span",{className:"client-unified-section-label",children:"PERFORMANCE"}),s.jsx("strong",{children:"Live resources"})]}),s.jsx("small",{children:"Live updates"})]}),s.jsxs("div",{className:"client-live-metrics",children:[s.jsx(bd,{icon:Wy,label:"CPU",value:Eh(a?.system?.cpuUsagePercent),detail:a?.system?.cpuLogicalCores?`${a.system.cpuLogicalCores} logical cores · Current processor usage`:"Current processor usage",percent:a?.system?.cpuUsagePercent}),s.jsx(bd,{icon:qS,label:"Memory",value:Eh(y),detail:vC(a?.system?.memoryUsedBytes,a?.system?.memoryTotalBytes),percent:y}),s.jsx(bd,{icon:GS,label:"GPU",value:Xm(j),detail:C?.name||(a?.system?.hardwareCollecting?"Detecting graphics hardware…":"Graphics usage unavailable"),percent:j}),s.jsx(bd,{icon:Gi,label:"VRAM",value:Xm(A),detail:xC(C?.memoryUsedBytes,C?.memoryTotalBytes),percent:A})]})]}),s.jsxs("section",{className:"client-storage-panel","aria-label":"Local storage",children:[s.jsxs("div",{className:"client-system-subhead",children:[s.jsxs("div",{children:[s.jsx("span",{className:"client-unified-section-label",children:"STORAGE"}),s.jsx("strong",{children:"Local drives"})]}),s.jsx("small",{children:N.length>0?`${N.length} ${N.length===1?"drive":"drives"}`:a?.system?.hardwareCollecting?"Detecting…":"Unavailable"})]}),s.jsxs("div",{className:"client-disk-list",children:[N.map(O=>s.jsxs("article",{className:"client-disk-row",children:[s.jsxs("div",{className:"client-disk-row-head",children:[s.jsxs("span",{children:[s.jsx(zl,{size:16}),s.jsx("strong",{children:O.mount||"Disk"}),s.jsx("small",{children:O.name||"Local disk"})]}),s.jsx("strong",{children:Xm(O.usedPercent)})]}),s.jsxs("small",{children:[Il(O.freeBytes)," free · ",Il(O.totalBytes)," total"]}),s.jsx("i",{"aria-hidden":"true",children:s.jsx("b",{style:{width:cb(O.usedPercent)}})})]},`${O.mount}-${O.name||""}`)),N.length===0&&s.jsxs("div",{className:"client-disk-empty",children:[s.jsx(zl,{size:18}),s.jsx("span",{children:a?.system?.hardwareCollecting?"Detecting local drives…":"Storage information is not available."})]})]})]}),s.jsxs("section",{className:"client-network-panel","aria-label":"Network activity",children:[s.jsxs("div",{className:"client-system-subhead",children:[s.jsxs("div",{children:[s.jsx("span",{className:"client-unified-section-label",children:"NETWORK"}),s.jsx("strong",{children:"Live traffic"})]}),s.jsx("small",{children:R.length>0?R.join(", "):"Detecting adapter"})]}),s.jsxs("div",{className:"client-network-live",children:[s.jsxs("div",{className:"client-network-adapter",children:[s.jsx(Hl,{size:18}),s.jsxs("span",{children:[s.jsx("strong",{children:R.join(", ")||"Network"}),s.jsx("small",{children:q.join(" / ")||"Checking active connection"})]})]}),s.jsxs("div",{className:"client-network-rate download",children:[s.jsx(VS,{size:17}),s.jsxs("span",{children:[s.jsx("small",{children:"Receive"}),s.jsx("strong",{children:bx(k?.receiveBytesPerSecond)})]})]}),s.jsxs("div",{className:"client-network-rate upload",children:[s.jsx(WS,{size:17}),s.jsxs("span",{children:[s.jsx("small",{children:"Send"}),s.jsx("strong",{children:bx(k?.sendBytesPerSecond)})]})]}),s.jsxs("small",{className:"client-network-total",children:["Total ",Il(k?.receivedBytes)," received / ",Il(k?.sentBytes)," sent"]})]})]})]})]}),s.jsxs("aside",{className:"client-connection-panel",children:[s.jsx("span",{className:"client-unified-section-label",children:"LIVEDESK SERVICES"}),s.jsx("h3",{children:w?"Connected to the Hub":a?.authenticated?"Finding the Hub":"Connect this computer"}),w?s.jsxs(s.Fragment,{children:[s.jsx("p",{className:"client-unified-copy",children:"This computer is available from the LiveDesk Hub."}),s.jsxs("div",{className:"client-service-status-list",children:[s.jsxs("div",{children:[s.jsx(Yt,{size:17}),s.jsxs("span",{children:[s.jsx("strong",{children:"Screen sharing"}),s.jsx("small",{children:a?.permissions?.screenCapture?"Active":"Waiting"})]})]}),s.jsxs("div",{children:[s.jsx(Lt,{size:17}),s.jsxs("span",{children:[s.jsx("strong",{children:"Remote control"}),s.jsx("small",{children:a?.permissions?.remoteInput?"Available":"Unavailable"})]})]}),s.jsxs("div",{children:[s.jsx(Lo,{size:17}),s.jsxs("span",{children:[s.jsx("strong",{children:"File delivery"}),s.jsx("small",{children:a?.permissions?.files?"Ready to receive":"Unavailable"})]})]}),s.jsxs("div",{children:[s.jsx(gn,{size:17}),s.jsxs("span",{children:[s.jsx("strong",{children:"Computer audio"}),s.jsx("small",{children:a?.permissions?.audio?"Available":"Unavailable"})]})]})]})]}):s.jsxs(s.Fragment,{children:[s.jsx("p",{className:"client-unified-copy",children:a?.authenticated?"LiveDesk is checking the registered Hub endpoints. A temporary Hub PIN can be used as a fallback.":"Sign in once on this computer. LiveDesk saves the verified session, finds the Hub, and starts screen sharing automatically."}),!n&&!a?.authenticated?s.jsxs("button",{className:"client-unified-primary",type:"button",onClick:m,children:[s.jsx(Ol,{size:16})," Sign in with Google"]}):s.jsxs("p",{className:"client-unified-success",children:[s.jsx(Hn,{size:16})," Signed in as ",n?.user.email||n?.user.id||a?.userEmail||a?.userId||"saved account"]}),s.jsxs("div",{className:"client-unified-pin-row",children:[s.jsx(_o,{size:16}),s.jsx("input",{value:r,onChange:O=>p(O.target.value),placeholder:"6-digit Hub PIN",inputMode:"numeric","aria-label":"6-digit Hub PIN"}),s.jsx("button",{className:"client-unified-secondary",type:"button",onClick:v,disabled:r.length!==6,children:"Connect"})]})]}),(l||a?.lastError)&&s.jsxs("p",{className:"client-unified-error",role:"alert",children:[s.jsx(Yy,{size:15})," ",l||a?.lastError]}),c&&s.jsx("p",{className:"client-unified-success",children:c}),s.jsxs("button",{className:"client-unified-secondary full client-hub-switch-trigger",type:"button",onClick:g,disabled:d||!a?.authenticated,children:[s.jsx(Gi,{size:16})," ",d?"Switching to Hub…":"Switch this computer to Hub"]})]})]})]})}function jC(){const[n,a]=u.useState(null),[r,l]=u.useState(null),[c,d]=u.useState(!1),[m,p]=u.useState(""),[v,g]=u.useState(""),[w,y]=u.useState(""),[b,C]=u.useState(!1),[j,A]=u.useState(!1),[N,k]=u.useState("computer"),[T,R]=u.useState(!1),q=u.useRef(null),O=u.useRef(null),Y=u.useRef(!1),_=u.useRef(!1),L=u.useRef(!1),ae=u.useRef(0),G=u.useMemo(gC,[]),te=u.useMemo(()=>bC(r),[r]),P=u.useMemo(()=>wC(r),[r]),ye=te.slice(0,1).toUpperCase()||"L",ie=u.useCallback(async()=>{if(g(""),window.liveDesk?.auth?.signInWithGoogle){const le=await window.liveDesk.auth.signInWithGoogle();return le?.ok===!1?(g(le.error||"LiveDesk could not open the system browser for Google sign-in."),!1):!0}return window.location.assign(`${G}/auth/google`),!0},[G]),K=u.useCallback(async()=>{L.current||(L.current=!0,g("Your saved Google sign-in is incomplete. LiveDesk is reopening sign-in once to repair it."),await mt.auth.signOut({scope:"local"}).catch(()=>{}),l(null),await ie()||(L.current=!1))},[ie]),I=u.useCallback(async le=>{const Z=vx(le);if(Z)throw new Error(Z);if(Y.current)return!1;Y.current=!0;try{const He=await window.liveDesk?.auth?.persistSession?.(le);if(He?.ok===!1)throw new Error(He.error||"LiveDesk could not validate the desktop session.");for(let _e=0;_e<2;_e+=1){const se=await Lc(G,_e>0),fe=await fetch(`${G}/api/auth/session`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":se},signal:AbortSignal.timeout(1e4),body:JSON.stringify({accessToken:le.access_token,refreshToken:le.refresh_token,expiresAt:le.expires_at,user:{id:le.user.id,email:le.user.email}})}),Ne=await fe.json().catch(()=>({}));if(fe.status===403&&_e===0){sessionStorage.removeItem("livedesk.client.csrf");continue}if(!fe.ok)throw new Error(Ne.error||`Client runtime returned HTTP ${fe.status}.`);return g(""),!0}throw new Error("Client runtime rejected the session transfer.")}finally{Y.current=!1}},[G]),Q=u.useCallback(async()=>{try{const le=await fetch(`${G}/api/client/status`,{cache:"no-store"}),Z=await le.json().catch(()=>({}));if(!le.ok)throw new Error(Z.error||`Client runtime returned HTTP ${le.status}.`);if(Z.csrfToken&&sessionStorage.setItem("livedesk.client.csrf",Z.csrfToken),String(Z.role||"").toLowerCase()==="hub")throw new Error("This computer is assigned to the Hub role.");a(Z)}catch(le){g(le instanceof Error?le.message:String(le))}},[G]);u.useEffect(()=>{Q();const le=window.setInterval(()=>{Q()},2e3);return()=>window.clearInterval(le)},[Q]);const U=u.useCallback(async()=>{const le=Date.now();if(!(!n?.authenticated||n.connectionState==="connected"||!["waiting","reconnecting"].includes(String(n.agent?.state||""))||le-ae.current<4e3)){ae.current=le;try{const Z=await fetch(`${G}/api/client/reconnect`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await Lc(G)},body:JSON.stringify({onlyIfWaiting:!0,reason:"app-active"})});if(!Z.ok)throw new Error(`Client reconnect returned HTTP ${Z.status}.`);await Q()}catch(Z){g(Z instanceof Error?Z.message:String(Z))}}},[G,Q,n]);u.useEffect(()=>{const le=()=>{U()},Z=()=>{U()},He=()=>{document.visibilityState==="visible"&&U()};return window.addEventListener("online",le),window.addEventListener("focus",Z),document.addEventListener("visibilitychange",He),()=>{window.removeEventListener("online",le),window.removeEventListener("focus",Z),document.removeEventListener("visibilitychange",He)}},[U]),u.useEffect(()=>{if(!c||!n||!r?.access_token||n.authenticated)return;if(vx(r)==="refresh-token-required"){K().catch(se=>{L.current=!1,g(se instanceof Error?se.message:String(se))});return}let le=!1,Z,He=0;const _e=async()=>{if(le)return;try{const fe=await I(r);if(await Q(),fe)return}catch(fe){g(fe instanceof Error?fe.message:String(fe))}if(le)return;const se=yx[Math.min(He,yx.length-1)];He+=1,Z=window.setTimeout(()=>{_e()},se)};return _e(),()=>{le=!0,Z!==void 0&&window.clearTimeout(Z)}},[c,Q,K,r,n,I]),u.useEffect(()=>{const le=new URLSearchParams(window.location.search),Z=le.get("auth_error");if(!Z)return;g(Z),le.delete("auth_error");const He=le.toString();window.history.replaceState(window.history.state,"",`${window.location.pathname}${He?`?${He}`:""}${window.location.hash}`)},[]),u.useEffect(()=>{let le=!0;if(!window.liveDesk?.auth)return l(null),d(!0),Q(),()=>{le=!1};const Z=window.liveDesk?.auth?.onComplete?.(_e=>{_e.ok&&_e.session?mt.auth.setSession(_e.session).catch(se=>g(se instanceof Error?se.message:String(se))):_e.error&&g(_e.error)});(async()=>{try{const _e=window.liveDesk?.auth?.getSession?await window.liveDesk.auth.getSession():await mt.auth.getSession();if(!le)return;const se=nb(_e);l(se),Q()}catch(_e){le&&g(_e instanceof Error?_e.message:String(_e))}finally{le&&d(!0)}})();const{data:He}=mt.auth.onAuthStateChange((_e,se)=>{le&&(l(se),d(!0),Q())});return()=>{le=!1,Z?.(),He.subscription.unsubscribe()}},[Q]),u.useEffect(()=>{if(!c||!n||_.current||L.current||r||n.authenticated)return;const le=new URLSearchParams(window.location.search);if(!le.has("livedesk_launch"))return;_.current=!0,le.delete("livedesk_launch");const Z=le.toString();window.history.replaceState(window.history.state,"",`${window.location.pathname}${Z?`?${Z}`:""}${window.location.hash}`),ie().catch(He=>g(He instanceof Error?He.message:String(He)))},[c,r,ie,n]);const W=async()=>{R(!1),window.liveDesk?.auth?.persistSession?(await mt.auth.signOut(),(await window.liveDesk.auth.persistSession(null))?.runtimeCleared===!1&&g("Signed out locally. The LiveDesk runtime could not be reached to clear its session.")):await fetch(`${G}/api/auth/session`,{method:"DELETE",headers:{"X-LiveDesk-CSRF":await Lc(G)}}).catch(()=>{}),l(null),await Q()};u.useEffect(()=>{if(!T)return;const le=He=>{He.target instanceof Element&&He.target.closest(".account-popover, .rail-account")||R(!1)},Z=He=>{He.key==="Escape"&&R(!1)};return window.addEventListener("pointerdown",le),window.addEventListener("keydown",Z),()=>{window.removeEventListener("pointerdown",le),window.removeEventListener("keydown",Z)}},[T]);const ue=u.useCallback((le=!0)=>{b||(A(!1),le&&window.requestAnimationFrame(()=>O.current?.focus()))},[b]),be=u.useCallback(()=>{b||!n?.authenticated||(O.current=document.activeElement instanceof HTMLElement?document.activeElement:null,y(""),A(!0))},[b,n?.authenticated]);u.useEffect(()=>{if(!j)return;const le=window.requestAnimationFrame(()=>q.current?.focus()),Z=_e=>{_e.target instanceof Element&&_e.target.closest(".client-hub-switch-popover, .client-hub-switch-trigger")||ue(!1)},He=_e=>{_e.key==="Escape"&&ue()};return window.addEventListener("pointerdown",Z),window.addEventListener("keydown",He),()=>{window.cancelAnimationFrame(le),window.removeEventListener("pointerdown",Z),window.removeEventListener("keydown",He)}},[ue,j]);const X=async()=>{g("");try{const le=await fetch(`${G}/api/client/pin`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await Lc(G)},body:JSON.stringify({pin:m})}),Z=await le.json().catch(()=>({}));if(!le.ok||Z?.ok===!1)throw new Error(Z?.error||"PIN could not be accepted.");p(""),await Q()}catch(le){g(le instanceof Error?le.message:String(le))}},$=async()=>{A(!1),C(!0),y(""),g("");try{const le=await fetch(`${G}/api/runtime/switch-role`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await Lc(G)},body:JSON.stringify({role:"hub"})}),Z=await le.json().catch(()=>({}));if(!le.ok||Z?.ok===!1)throw new Error(Z?.error||`Role change failed with HTTP ${le.status}.`);y("Hub role accepted. LiveDesk is restarting this computer with the Hub Wall.");const He=Number(n?.runtimePid||0);await ab({baseUrl:G,targetRole:"hub",previousRuntimePid:He,allowedStates:["running"]}),window.location.reload()}catch(le){g(le instanceof Error?le.message:String(le)),C(!1)}},de=!!(n?.authenticated||r),me=u.useMemo(()=>ff(),[]),ve=Xd("switch-to-hub",me),Se=Xd("client",me),Oe=mC(me);return s.jsxs("main",{className:"app-shell client-unified-shell",children:[s.jsxs("aside",{className:"tool-rail","aria-label":"LiveDesk Client tools",children:[s.jsx("div",{className:"rail-brand",title:"LiveDesk",children:s.jsx(ib,{size:25})}),s.jsx("nav",{className:"rail-tools","aria-label":"Client navigation",children:s.jsxs("div",{className:"client-main-tool-slot",children:[s.jsxs("button",{className:"rail-tool client-main-tool client-hub-tool client-hub-switch-trigger accent-blue",type:"button",onClick:be,disabled:b||!n?.authenticated,"aria-busy":b,"aria-expanded":j,"aria-haspopup":"dialog","aria-controls":j?"client-hub-switch-popover":void 0,"aria-label":`Hub. ${ve}`,"data-tooltip":j?void 0:Th("Hub","switch-to-hub",me),children:[s.jsx(Gi,{size:19}),s.jsx("span",{children:b?"Switching…":"Hub"})]}),s.jsxs("button",{className:`rail-tool client-main-tool accent-blue ${N==="computer"?"active":""}`,type:"button",onClick:()=>k("computer"),"aria-current":N==="computer"?"page":void 0,"aria-label":`Client. ${Se}`,"data-tooltip":Th("Client","client",me),children:[s.jsx(Yt,{size:19}),s.jsx("span",{children:"Client"})]})]})}),s.jsxs("div",{className:"rail-footer",children:[pC.map(le=>{const Z=le.icon;return s.jsxs("button",{className:`rail-tool compact ${N===le.id?"active":""}`,type:"button",onClick:()=>k(le.id),title:le.label,children:[s.jsx(Z,{size:18}),s.jsx("span",{children:le.label})]},le.id)}),s.jsxs("button",{className:`rail-account ${de?"signed-in":""}`,type:"button",onClick:()=>R(le=>!le),"aria-expanded":T,"aria-haspopup":"dialog",title:de?"Account":"Sign in",children:[r&&P?s.jsx("img",{src:P,alt:te,referrerPolicy:"no-referrer"}):r?s.jsx("span",{className:"avatar-fallback",children:ye}):de?s.jsx(Lt,{size:18}):s.jsx(Ol,{size:18}),s.jsx("span",{children:de?"Account":"Sign in"})]})]})]}),j&&s.jsxs("section",{id:"client-hub-switch-popover",className:"client-hub-switch-popover",role:"dialog","aria-modal":"false","aria-labelledby":"client-hub-switch-title","aria-describedby":"client-hub-switch-description client-hub-switch-restart",children:[s.jsxs("header",{className:"client-hub-switch-head",children:[s.jsx("span",{className:"client-hub-switch-mark","aria-hidden":"true",children:s.jsx(Gi,{size:19})}),s.jsx("span",{className:"client-hub-switch-eyebrow",children:Oe.eyebrow}),s.jsx("button",{className:"client-hub-switch-close",type:"button",onClick:()=>ue(),"aria-label":Oe.closeLabel,children:s.jsx(Ha,{size:17})})]}),s.jsx("h2",{id:"client-hub-switch-title",children:Oe.title}),s.jsx("p",{id:"client-hub-switch-description",children:Oe.description}),s.jsxs("p",{id:"client-hub-switch-restart",className:"client-hub-switch-notice",children:[s.jsx(Lt,{size:16,"aria-hidden":"true"}),s.jsx("span",{children:Oe.restartNotice})]}),s.jsxs("div",{className:"client-hub-switch-actions",children:[s.jsx("button",{type:"button",onClick:()=>ue(),children:Oe.cancel}),s.jsxs("button",{ref:q,className:"primary",type:"button",onClick:()=>{$()},disabled:b||!n?.authenticated,children:[s.jsx(Gi,{size:16}),Oe.confirm]})]})]}),T&&s.jsxs("section",{className:"account-popover",role:"dialog","aria-label":"LiveDesk account",children:[s.jsxs("div",{className:"account-popover-head",children:[s.jsx("div",{className:"account-popover-avatar",children:r&&P?s.jsx("img",{src:P,alt:te,referrerPolicy:"no-referrer"}):r?s.jsx("span",{children:ye}):s.jsx(Ol,{size:18})}),s.jsxs("div",{children:[s.jsx("strong",{children:r?te:de?"Saved account":"Account"}),s.jsx("p",{children:r?.user.email||n?.userEmail||n?.userId||"Not signed in"})]})]}),s.jsxs("dl",{className:"account-popover-facts",children:[s.jsx("dt",{children:"User"}),s.jsx("dd",{children:r?.user.email||n?.userEmail||n?.userId||"Not signed in"}),s.jsx("dt",{children:"Runtime"}),s.jsx("dd",{children:n?"Local app ready":"Checking local app"}),s.jsx("dt",{children:"Session"}),s.jsx("dd",{children:n?.auth?.persisted?"Saved on this computer":de?"Active for this run":"Not saved"}),s.jsx("dt",{children:"Role"}),s.jsx("dd",{children:"Client"})]}),de?s.jsxs("button",{className:"account-popover-action",onClick:()=>{W()},type:"button",children:[s.jsx(Gy,{size:16}),"Logout"]}):s.jsxs("button",{className:"account-popover-action primary",onClick:()=>{R(!1),ie()},type:"button",children:[s.jsx(Ol,{size:16}),"Sign in with Google"]})]}),s.jsxs("section",{className:"desk-stage client-unified-stage",children:[s.jsx("header",{className:"topbar",children:s.jsxs("div",{className:"brand",children:[s.jsx("span",{className:"brand-mark",children:s.jsx(gn,{size:18})}),s.jsxs("div",{children:[s.jsx("h1",{children:"LiveDesk"}),s.jsx("p",{children:"Client workspace"})]})]})}),N==="support"?s.jsx("section",{className:"client-unified-page",children:s.jsx(tb,{session:r,currentProductKey:"livedesk",appVersion:n?.appVersion||"",onSignIn:()=>{ie()}})}):N!=="computer"?s.jsx("section",{className:"client-unified-page",children:s.jsx(SC,{page:N,status:n})}):s.jsx(CC,{session:r,status:n,pin:m,error:v,roleChangeMessage:w,roleChangeBusy:b,onSignIn:()=>{ie()},onPinChange:le=>p(le.replace(/\D/g,"").slice(0,6)),onSubmitPin:()=>{X()},onSwitchToHub:be})]})]})}function $r(n,a,r){if(r<0||a<0||a+r>n.length)throw new Error("Invalid LZO1X block: input overrun.")}function Zm(n,a,r){let l=0;for(;$r(n,a.inputIndex,1),n[a.inputIndex]===0;)l+=1,a.inputIndex+=1;const c=l*255+r+n[a.inputIndex];return a.inputIndex+=1,c}function wd(n,a,r,l){if($r(n,a.inputIndex,l),a.outputIndex+l>r.length)throw new Error("Invalid LZO1X block: output overrun.");r.set(n.subarray(a.inputIndex,a.inputIndex+l),a.outputIndex),a.inputIndex+=l,a.outputIndex+=l}function kC(n,a,r,l){const c=a-r;if(c<=0||l<=0)throw new Error("Invalid LZO1X block: invalid match distance.");let d=Math.min(c,l);for(n.set(n.subarray(r,r+d),a);d<l;){const m=Math.min(d,l-d);n.copyWithin(a+d,a,a+m),d+=m}return a+l}function ub(n,a){if(!(n instanceof Uint8Array)||n.length<3||a<0)throw new Error("Invalid LZO1X block.");const r=new Uint8Array(a),l={inputIndex:0,outputIndex:0};let c=0,d=0;if(n[l.inputIndex]>=22){const m=n[l.inputIndex]-17;l.inputIndex+=1,wd(n,l,r,m),c=4}else n[l.inputIndex]>=18&&(c=n[l.inputIndex]-17,l.inputIndex+=1,wd(n,l,r,c));for(;;){$r(n,l.inputIndex,1);const m=n[l.inputIndex];l.inputIndex+=1;let p,v;if((m&192)!==0)$r(n,l.inputIndex,1),v=l.outputIndex-((n[l.inputIndex]<<3)+(m>>2&7)+1),l.inputIndex+=1,d=(m>>5)+1,p=m&3;else if((m&32)!==0){d=(m&31)+2,d===2&&(d+=Zm(n,l,31)),$r(n,l.inputIndex,2);const g=n[l.inputIndex]|n[l.inputIndex+1]<<8;l.inputIndex+=2,v=l.outputIndex-((g>>2)+1),p=g&3}else if((m&16)!==0){d=(m&7)+2,d===2&&(d+=Zm(n,l,7)),$r(n,l.inputIndex,2);const g=n[l.inputIndex]|n[l.inputIndex+1]<<8;if(l.inputIndex+=2,v=l.outputIndex-(((m&8)<<11)+(g>>2)),p=g&3,v===l.outputIndex)break;v-=16384}else if(c===0){let g=m+3;g===3&&(g+=Zm(n,l,15)),wd(n,l,r,g),c=4;continue}else c!==4?($r(n,l.inputIndex,1),p=m&3,v=l.outputIndex-((m>>2)+(n[l.inputIndex]<<2)+1),l.inputIndex+=1,d=2):($r(n,l.inputIndex,1),p=m&3,v=l.outputIndex-((m>>2)+(n[l.inputIndex]<<2)+2049),l.inputIndex+=1,d=3);if(v<0||l.outputIndex+d+p>r.length)throw new Error("Invalid LZO1X block: lookbehind overrun.");l.outputIndex=kC(r,l.outputIndex,v,d),c=p,wd(n,l,r,p)}if(d!==3||l.inputIndex!==n.length||l.outputIndex!==r.length)throw new Error("Invalid LZO1X block: incomplete output.");return r}const wx=16,Sx=8,AC=24*1024*1024,db=new Uint8Array(new Uint32Array([16909060]).buffer)[0]===4,Rh=new Uint32Array(65536);for(let n=0;n<Rh.length;n+=1){const a=Math.round((n>>11&31)*255/31),r=Math.round((n>>5&63)*255/63),l=Math.round((n&31)*255/31);Rh[n]=db?(a|r<<8|l<<16|4278190080)>>>0:(a<<24|r<<16|l<<8|255)>>>0}function Fr(n,a){return n[a]|n[a+1]<<8}function NC(n,a){const r=Number(a);if(!Number.isSafeInteger(r)||r<wx||r>AC)throw new Error(`Invalid Mode 5 packet length: ${a}.`);const l=n instanceof Uint8Array?n:new Uint8Array(n),c=ub(l,r);if(c[0]!==76||c[1]!==68||c[2]!==53||c[3]!==68)throw new Error("Invalid Mode 5 packet magic.");if(c[4]!==1)throw new Error(`Unsupported Mode 5 packet version: ${c[4]}.`);const d=(c[5]&1)!==0,m=Fr(c,6),p=Fr(c,8),v=Fr(c,10),g=Fr(c,12);if(m<=0||p<=0||m>3840||p>2160)throw new Error(`Invalid Mode 5 frame size: ${m}x${p}.`);if(v<=0||v>256||g>8192)throw new Error(`Invalid Mode 5 tile header: ${v}/${g}.`);const w=[];let y=wx;for(let b=0;b<g;b+=1){if(y+Sx>c.length)throw new Error("Mode 5 tile header is truncated.");const C=Fr(c,y),j=Fr(c,y+2),A=Fr(c,y+4),N=Fr(c,y+6);y+=Sx;const k=A*N*2;if(A<=0||N<=0||A>v||N>v||C+A>m||j+N>p||y+k>c.length)throw new Error(`Invalid Mode 5 tile ${b}.`);w.push({x:C,y:j,width:A,height:N,pixels:c.subarray(y,y+k)}),y+=k}if(y!==c.length)throw new Error(`Mode 5 packet has ${c.length-y} trailing bytes.`);return{keyFrame:d,width:m,height:p,tileSize:v,tiles:w}}function MC(n,a,r,l){if(!(n instanceof Uint8ClampedArray)||n.length!==a*r*4||l.width!==a||l.height!==r)throw new Error("Mode 5 canvas state does not match the packet dimensions.");let c=a,d=r,m=0,p=0;const v=new Uint32Array(n.buffer,n.byteOffset,n.byteLength>>>2);for(const g of l.tiles){const w=db&&(g.pixels.byteOffset&1)===0?new Uint16Array(g.pixels.buffer,g.pixels.byteOffset,g.pixels.byteLength>>>1):null;let y=0;for(let b=0;b<g.height;b+=1){let C=(g.y+b)*a+g.x;for(let j=0;j<g.width;j+=1){const A=y<<1,N=w?w[y]:g.pixels[A]|g.pixels[A+1]<<8;v[C]=Rh[N],y+=1,C+=1}}c=Math.min(c,g.x),d=Math.min(d,g.y),m=Math.max(m,g.x+g.width),p=Math.max(p,g.y+g.height)}return l.tiles.length>0?{x:c,y:d,width:m-c,height:p-d}:null}const Oa=new WeakMap,Xc=new WeakMap,Dh=new WeakMap,Zc=new Set,_l=new Set,Zd=new WeakMap,Lh=new WeakMap,_h=new WeakMap,Jd=new WeakMap,fb=4,TC=2,EC=2,RC=2,DC=18,LC=40,_C=0,zC=250,mb=80,Cx=5,IC=150,OC=24,HC=180,BC=1200,FC=18,PC=.65,$C=2e3,UC=500,tp=250,qC=globalThis.LIVEDESK_ENABLE_CANVAS_VISUAL_SAMPLING===!0;let ef=!1;function GC(){return typeof navigator>"u"?!1:/mac/i.test(`${navigator.platform||""} ${navigator.userAgent||""}`)}function VC(){const n=Math.max(1,Number(navigator.hardwareConcurrency||8));return Math.max(4,Math.min(16,Math.round(n/2)))}let Bl={h264DecodeAcceleration:"prefer-hardware",h264HardwareDecoderBudget:VC()};function WC(n){n.h264DecodeAcceleration&&(Bl={...Bl,h264DecodeAcceleration:n.h264DecodeAcceleration}),Number.isFinite(Number(n.h264HardwareDecoderBudget))&&(Bl.h264HardwareDecoderBudget=Math.max(1,Math.min(64,Math.round(Number(n.h264HardwareDecoderBudget)))))}function hb(n,a=Bl.h264DecodeAcceleration){const r=Zd.get(n);return r?.requested===a?(r.actual!=="prefer-hardware"&&_l.delete(n),r.actual):(r&&Zd.delete(n),a!=="prefer-hardware"?(_l.delete(n),a):_l.has(n)?"prefer-hardware":_l.size<Bl.h264HardwareDecoderBudget?(_l.add(n),"prefer-hardware"):"prefer-software")}function mf(n,a){return a!=="prefer-hardware"?!1:(Zd.set(n,{requested:a,actual:"prefer-software"}),_l.delete(n),!0)}function YC(n,a,r,l=64){try{let c=Lh.get(n);c||(c={canvas:document.createElement("canvas"),lastHash:"",initialized:!1},Lh.set(n,c));const d=Math.max(8,Math.min(64,Math.round(l))),m=Math.max(1,Math.round(d*Math.max(1,r)/Math.max(1,a)));(c.canvas.width!==d||c.canvas.height!==m)&&(c.canvas.width=d,c.canvas.height=m);const p=c.canvas.getContext("2d",{willReadFrequently:!0});if(!p)return{visualHash:"",visualChanged:!0};p.drawImage(n,0,0,Math.max(1,a),Math.max(1,r),0,0,d,m);const v=p.getImageData(0,0,d,m).data;let g=2166136261;for(let b=0;b<v.length;b+=4)g^=v[b],g=Math.imul(g,16777619),g^=v[b+1],g=Math.imul(g,16777619),g^=v[b+2],g=Math.imul(g,16777619);const w=(g>>>0).toString(16).padStart(8,"0"),y=!c.initialized||w!==c.lastHash;return c.initialized=!0,c.lastHash=w,{visualHash:w,visualChanged:y}}catch{return{visualHash:"",visualChanged:!0}}}function zh(n,a,r,l=tp,c=64,d){if(!qC&&d)return pb(n,d);let m=_h.get(n);m||(m={lastHash:"",initialized:!1,lastCanvasSampleAt:0},_h.set(n,m));const p=performance.now();if(m.initialized&&l>0&&p-m.lastCanvasSampleAt<l)return{visualHash:m.lastHash,visualChanged:!1};const v=YC(n,a,r,c);return m.initialized=!0,m.lastHash=v.visualHash,m.lastCanvasSampleAt=p,v}function pb(n,a){let r=Jd.get(n);r||(r={lastHash:"",initialized:!1},Jd.set(n,r));const l=String(a.contentHash||""),c=!r.initialized||!l||l!==r.lastHash;return r.initialized=!0,r.lastHash=l,{visualHash:l,visualChanged:c}}function gb(n,a){const r=Dh.get(n);if(r)return r;const l=n.getContext("2d",{alpha:!1,desynchronized:a==="interactive"});if(l){const c=l.getContextAttributes?.(),d={context:l,presentation:c?.desynchronized?"desync":"sync"};return Dh.set(n,d),d}return null}function KC(n){const a=String(n.frameMode||n.mode||"").toLowerCase(),r=String(n.compression||"").toLowerCase(),l=String(n.mimeType||"").toLowerCase();return a==="mode2-lzo"||r==="lzo1x"||l==="application/vnd.livedesk.lzo-rgb565"||a==="mode2-lz4"||String(n.compression||"").toLowerCase()==="lz4"||l==="application/vnd.livedesk.lz4-raw"}function QC(n){return String(n.frameMode||n.mode||"").toLowerCase()==="mode3-h264-hw"||String(n.codec||"").toLowerCase()==="h264"||String(n.mimeType||"").toLowerCase()==="video/h264"}function XC(n){const a=String(n.frameMode||n.mode||"").toLowerCase(),r=String(n.mimeType||"").toLowerCase();return a==="mode5-lzo-delta"||r==="application/vnd.livedesk.lzo-rgb565-delta"}function jx(n,a,r){let l=r,c=a;if(l===15){let d=255;for(;d===255;){if(c>=n.length)throw new Error("Invalid LZ4 block: length overrun.");d=n[c],c+=1,l+=d}}return{length:l,cursor:c}}function ZC(n,a){const r=new Uint8Array(a);let l=0,c=0;for(;l<n.length;){const d=n[l];l+=1;const m=jx(n,l,d>>4);l=m.cursor;const p=m.length;if(l+p>n.length||c+p>r.length)throw new Error("Invalid LZ4 block: literal overrun.");if(r.set(n.subarray(l,l+p),c),l+=p,c+=p,l>=n.length)break;if(l+2>n.length)throw new Error("Invalid LZ4 block: missing offset.");const v=n[l]|n[l+1]<<8;if(l+=2,v<=0||v>c)throw new Error("Invalid LZ4 block: bad match offset.");const g=jx(n,l,d&15);l=g.cursor;const w=g.length+4;if(c+w>r.length)throw new Error("Invalid LZ4 block: match overrun.");let y=c-v;for(let b=0;b<w;b+=1)r[c]=r[y],c+=1,y+=1}if(c!==r.length)throw new Error("Invalid LZ4 block: incomplete output.");return r}function JC(n){const a=Math.max(1,Math.floor(n.width||0)),r=Math.max(1,Math.floor(n.height||0)),l=String(n.compression||"").toLowerCase(),c=String(n.pixelFormat||n.codec||"").toLowerCase();if(l==="lzo1x"||String(n.frameMode||n.mode||"").toLowerCase()==="mode2-lzo"||String(n.mimeType||"").toLowerCase()==="application/vnd.livedesk.lzo-rgb565"){const w=Math.max(1,Math.floor(n.bytesPerPixel||2)),y=a*r*2,b=Math.floor(n.uncompressedByteLength||y);if(w!==2||b!==y)throw new Error(`Invalid mode2 RGB565 frame size: ${b} for ${a}x${r}.`);if(c&&c!=="rgb565le"&&c!=="rgb565")throw new Error(`Unsupported mode2 pixel format: ${c}`);const C=ub(n.payload,y),j=new Uint8ClampedArray(a*r*4);for(let A=0,N=0;A<C.length;A+=2,N+=4){const k=C[A]|C[A+1]<<8,T=k>>11&31,R=k>>5&63,q=k&31;j[N]=T<<3|T>>2,j[N+1]=R<<2|R>>4,j[N+2]=q<<3|q>>2,j[N+3]=255}return new ImageData(j,a,r)}const m=Math.max(1,Math.floor(n.bytesPerPixel||4)),p=Math.max(a*r*m,Math.floor(n.uncompressedByteLength||0)),v=ZC(n.payload,p);if(m!==4)throw new Error(`Unsupported mode2 pixel size: ${m}`);const g=new Uint8ClampedArray(a*r*4);if(c==="rgba32"||c==="rgba")g.set(v.subarray(0,g.length));else for(let w=0,y=0;y<g.length;w+=4,y+=4)g[y]=v[w+2],g[y+1]=v[w+1],g[y+2]=v[w],g[y+3]=v[w+3];return new ImageData(g,a,r)}function kx(n,a="smooth"){const r=window.VideoDecoder;if(!r||!window.EncodedVideoChunk)throw new Error("WebCodecs H.264 decode is not supported in this browser.");const l=Oa.get(n);if(l&&l.decoder.state!=="closed"&&l.latencyMode===a)return l;l&&_s(n);let c;return c={decoder:new r({output:m=>{if(Oa.get(n)!==c){m.close();return}const p=Number(m.timestamp||0);c.outputSerial+=1;let v=c.pendingFrames.get(p);if(v)c.pendingFrames.delete(p);else if(c.pendingFrames.size>0){const j=c.pendingFrames.entries().next().value;j&&(c.pendingFrames.delete(j[0]),v=j[1],c.timestampFallbacks+=1)}const g=m.displayWidth||m.codedWidth||n.width||960,w=m.displayHeight||m.codedHeight||n.height||540,y=Number(v?.frame.durationUs||0),b=Number(m.duration||0),C=Math.max(16,Math.min(250,(y>0?y:b||83333)/1e3));for(c.targetPaintIntervalMs=C,c.decodedFrames.push({videoFrame:m,pending:v,decodedAt:performance.now(),width:g,height:w,durationMs:C}),c.lastOutputAt=performance.now();c.decodedFrames.length>ap(c);)tf(c,c.decodedFrames.shift());vb(c),c.renderTimer!==null&&c.renderScheduledAt>0&&performance.now()-c.renderScheduledAt>UC&&(typeof document>"u"||document.visibilityState==="visible")&&(window.cancelAnimationFrame(c.renderTimer),c.renderTimer=null,c.renderScheduledAt=0),c.renderTimer!==null&&c.decodedFrames.length>=fb&&(window.cancelAnimationFrame(c.renderTimer),c.renderTimer=null,c.renderScheduledAt=0),nf(n,c)},error:()=>{Oa.get(n)===c&&(mf(n,c.hardwareAcceleration),np(c),Zc.delete(n),Oa.delete(n))}}),configured:!1,configKey:"",codec:"",hardwareAcceleration:hb(n),latencyMode:a,keyFrameSeen:!1,droppedForLatency:0,pendingFrames:new Map,decodedFrames:[],renderTimer:null,renderScheduledAt:0,flushTimer:null,flushInFlight:!1,flushCount:0,timestampFallbacks:0,inputSerial:0,outputSerial:0,lastFlushInputSerial:0,lastOutputAt:0,lastPaintAt:0,lastInputAt:0,interactiveBufferPrimed:!1,interactiveBufferStartedAt:0,interactiveBufferWaitCount:0,interactiveBufferWaitMs:0,interactiveQueueDrainCount:0,lastInputFrameSeq:void 0,targetPaintIntervalMs:1e3/12,nextChunkTimestampUs:0,healthSampleStartedAt:performance.now(),healthInputSerial:0,healthOutputSerial:0},Oa.set(n,c),Zc.add(n),c}function np(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 tf(n,a){a&&(a.videoFrame.close(),n.droppedForLatency+=1)}function ap(n){return n.latencyMode==="interactive"?EC:String(n.decodedFrames[0]?.pending?.frame.frameMode||n.decodedFrames[0]?.pending?.frame.mode||"").toLowerCase()==="mode4-h264-atlas"?TC:fb}function vb(n,a=performance.now()){const r=ap(n);for(;n.decodedFrames.length>r;)tf(n,n.decodedFrames.shift());const l=n.latencyMode==="interactive"?mb:zC;let c=n.decodedFrames[0];for(;n.decodedFrames.length>1&&c?.pending&&a-c.pending.queuedAt>l;)tf(n,n.decodedFrames.shift()),c=n.decodedFrames[0]}function xb(n,a){if(a.hardwareAcceleration!=="prefer-hardware"||a.flushTimer!==null||a.flushInFlight)return;const r=a.latencyMode==="interactive"?OC:IC,l=a.latencyMode==="interactive";a.flushTimer=window.setTimeout(async()=>{a.flushTimer=null;const c=performance.now();for(const[p,v]of a.pendingFrames.entries())c-v.queuedAt>$C&&a.pendingFrames.delete(p);if(Oa.get(n)!==a||a.decoder.state!=="configured"||a.pendingFrames.size===0||a.inputSerial<=a.lastFlushInputSerial||!l&&a.lastOutputAt>0&&c-a.lastOutputAt<r)return;const d=a.inputSerial,m=performance.now();a.flushInFlight=!0,a.flushCount+=1;try{await a.decoder.flush(),a.lastFlushInputSerial=Math.max(a.lastFlushInputSerial,d)}catch{Oa.get(n)===a&&qd(a)}finally{a.flushInFlight=!1;const p=performance.now()-m;if(l&&p>=HC&&a.hardwareAcceleration==="prefer-hardware"){ef=!0,mf(n,a.hardwareAcceleration),_s(n);return}Oa.get(n)===a&&a.inputSerial>d&&a.pendingFrames.size>0&&(l||performance.now()-a.lastOutputAt>=r)&&xb(n,a)}},r)}function Ax(n,a,r){const l=performance.now();try{(n.width!==r.width||n.height!==r.height)&&(n.width=r.width,n.height=r.height);const c=gb(n,a.latencyMode);if(c?.context.drawImage(r.videoFrame,0,0,r.width,r.height),r.pending){const d=performance.now(),p=a.latencyMode==="interactive"?pb(n,r.pending.frame):zh(n,r.width,r.height,tp,64,r.pending.frame);try{a.onPaint?.(r.pending.frame,{deviceId:r.pending.frame.deviceId,frameSeq:r.pending.frame.frameSeq,mode:r.pending.frame.frameMode||r.pending.frame.mode||r.pending.frame.codec||r.pending.frame.mimeType,width:r.width,height:r.height,byteLength:r.pending.frame.byteLength,queuedForMs:Math.max(0,l-r.pending.queuedAt),decodedForMs:Math.max(0,r.decodedAt-r.pending.queuedAt),scheduledForMs:Math.max(0,l-r.decodedAt),drawMs:Math.max(0,d-l),queueSize:r.pending.queueSize,renderQueueSize:a.decodedFrames.length,droppedForLatency:a.droppedForLatency,h264DecodeAcceleration:a.hardwareAcceleration,decoderLabel:a.hardwareAcceleration,decoderFlushCount:a.flushCount,decoderTimestampFallbacks:a.timestampFallbacks,decoderInputCount:a.inputSerial,decoderOutputCount:a.outputSerial,targetPaintIntervalMs:a.targetPaintIntervalMs,canvasPresentation:c?.presentation||"sync",interactiveBufferWaitCount:a.interactiveBufferWaitCount,interactiveBufferWaitMs:a.interactiveBufferWaitMs,interactiveQueueDrainCount:a.interactiveQueueDrainCount,visualHash:p.visualHash,visualChanged:p.visualChanged,paintedAt:d})}catch{}}a.lastPaintAt=performance.now()}finally{r.videoFrame.close()}}function nf(n,a){if(a.renderTimer!==null||a.decodedFrames.length===0)return;const r=Math.max(16,Math.min(250,a.targetPaintIntervalMs||1e3/12)),l=()=>{if(a.renderTimer=null,a.renderScheduledAt=0,a.decodedFrames.length===0)return;const c=performance.now();if(vb(a,c),a.decodedFrames.length===0)return;if(a.latencyMode==="interactive"){const v=a.targetPaintIntervalMs<=LC,g=a.targetPaintIntervalMs<=20;if(g&&!a.interactiveBufferPrimed){a.interactiveBufferStartedAt<=0&&(a.interactiveBufferStartedAt=c,a.interactiveBufferWaitCount+=1);const A=a.decodedFrames.length>=RC,N=c-a.interactiveBufferStartedAt>=DC;if(!A&&!N){a.renderScheduledAt=performance.now(),a.renderTimer=window.requestAnimationFrame(l);return}a.interactiveBufferWaitMs+=Math.max(0,c-a.interactiveBufferStartedAt),a.interactiveBufferPrimed=!0}else g||(a.interactiveBufferPrimed=!0);const w=a.decodedFrames[0],y=w?.pending?Math.max(0,c-w.pending.queuedAt):0,b=a.lastPaintAt>0?a.lastPaintAt+r:c;if(!(!v||c+Cx>=b||y>=mb)){a.renderScheduledAt=performance.now(),a.renderTimer=window.requestAnimationFrame(l);return}const j=a.decodedFrames.shift();if(j)try{Ax(n,a,j)}catch{}a.decodedFrames.length===0&&(a.interactiveQueueDrainCount+=1,a.interactiveBufferPrimed=!1,a.interactiveBufferStartedAt=0),nf(n,a);return}const d=a.lastPaintAt>0?a.lastPaintAt+r:c+_C;if(!(c+Cx>=d||a.decodedFrames.length>=Math.max(1,ap(a)-1))){a.renderScheduledAt=performance.now(),a.renderTimer=window.requestAnimationFrame(l);return}const p=a.decodedFrames.shift();if(p)try{Ax(n,a,p)}catch{}nf(n,a)};a.renderScheduledAt=performance.now(),a.renderTimer=window.requestAnimationFrame(l)}function yb(n,a){if(Oa.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;)tf(a,a.decodedFrames.shift());return a.lastPaintAt=0,a.interactiveBufferPrimed=!1,a.interactiveBufferStartedAt=0,nf(n,a),!0}function Jm(){if(!(typeof document>"u"||document.visibilityState!=="visible"))for(const n of Zc){const a=Oa.get(n);if(!a||a.decoder.state==="closed"){Zc.delete(n);continue}yb(n,a)}}typeof document<"u"&&typeof window<"u"&&(document.addEventListener("visibilitychange",Jm),window.addEventListener("focus",Jm),window.addEventListener("pageshow",Jm));function _s(n){_l.delete(n),Zc.delete(n),Jd.delete(n);const a=Oa.get(n);if(a){Oa.delete(n);try{np(a),a.decoder.state!=="closed"&&a.decoder.close()}catch{}}}function _c(n){n&&(Zd.delete(n),Dh.delete(n),_h.delete(n),Lh.delete(n),Jd.delete(n),Xc.delete(n),_s(n))}function qd(n,a=1){try{n.decoder.state!=="closed"&&n.decoder.reset()}catch{}n.configured=!1,n.configKey="",n.keyFrameSeen=!1,n.pendingFrames.clear(),np(n),n.lastPaintAt=0,n.lastOutputAt=0,n.lastInputAt=0,n.interactiveBufferPrimed=!1,n.interactiveBufferStartedAt=0,n.lastInputFrameSeq=void 0,n.nextChunkTimestampUs=0,n.healthSampleStartedAt=performance.now(),n.healthInputSerial=n.inputSerial,n.healthOutputSerial=n.outputSerial,n.droppedForLatency+=Math.max(1,Math.min(1e4,Math.floor(a)))}function Sd(n,a,r,l){n.decoder.configure(a),n.configured=!0,n.configKey=r,n.codec=a.codec,n.hardwareAcceleration=l,n.keyFrameSeen=!1,n.nextChunkTimestampUs=0,n.lastInputFrameSeq=void 0}function ej(n,a){if(a.latencyMode!=="interactive"||a.hardwareAcceleration!=="prefer-hardware")return!1;const r=performance.now();if(r-a.healthSampleStartedAt<BC)return!1;const l=a.inputSerial-a.healthInputSerial,c=a.outputSerial-a.healthOutputSerial;return a.healthSampleStartedAt=r,a.healthInputSerial=a.inputSerial,a.healthOutputSerial=a.outputSerial,l<FC||c/Math.max(1,l)>=PC?!1:(ef=!0,mf(n,a.hardwareAcceleration),_s(n),!0)}function eh(n,a=1){if(!n)return!1;const r=Oa.get(n);return r?(r.droppedForLatency+=Math.max(1,Math.min(1e4,Math.floor(a))),_s(n),!0):!1}function tj(n){if(!n)return!1;const a=Oa.get(n);return a?yb(n,a):!1}function nj(n,a,r,l="interactive"){_s(n);const c=performance.now(),d=NC(a.payload,a.uncompressedByteLength||0),m=String(a.streamId||"mode5");let p=Xc.get(n);if(!p||p.streamId!==m||p.width!==d.width||p.height!==d.height){const A=new Uint8ClampedArray(d.width*d.height*4);for(let N=3;N<A.length;N+=4)A[N]=255;p={streamId:m,width:d.width,height:d.height,rgba:A,imageData:new ImageData(A,d.width,d.height),keyFrameSeen:!1,inputSerial:0,outputSerial:0},Xc.set(n,p)}if(!p)throw new Error("Mode 5 canvas state could not be initialized.");p.inputSerial+=1;const g=Number(a.streamFrameSeq||0);if(g>0&&(p.lastStreamFrameSeq=g),!d.keyFrame&&!p.keyFrameSeen)return;d.keyFrame&&(p.keyFrameSeen=!0);const w=MC(p.rgba,p.width,p.height,d),y=performance.now();(n.width!==p.width||n.height!==p.height)&&(n.width=p.width,n.height=p.height);const b=gb(n,l),C=performance.now();w&&b?.context.putImageData(p.imageData,0,0,w.x,w.y,w.width,w.height);const j=performance.now();p.outputSerial+=1,r?.(a,{deviceId:a.deviceId,frameSeq:a.frameSeq,mode:a.frameMode||a.mode||a.mimeType,width:p.width,height:p.height,byteLength:a.byteLength,queuedForMs:Math.max(0,j-c),decodedForMs:Math.max(0,y-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:b?.presentation||"sync",interactiveBufferWaitCount:0,interactiveBufferWaitMs:0,interactiveQueueDrainCount:0,visualHash:String(a.contentHash||""),visualChanged:Number(a.deltaVisualTileCount||0)>0,paintedAt:j})}const th=[{code:30,maxFrameSize:1620,maxMacroblocksPerSecond:40500},{code:31,maxFrameSize:3600,maxMacroblocksPerSecond:108e3},{code:32,maxFrameSize:5120,maxMacroblocksPerSecond:216e3},{code:40,maxFrameSize:8192,maxMacroblocksPerSecond:245760},{code:41,maxFrameSize:8192,maxMacroblocksPerSecond:245760},{code:42,maxFrameSize:8704,maxMacroblocksPerSecond:522240},{code:50,maxFrameSize:22080,maxMacroblocksPerSecond:589824},{code:51,maxFrameSize:36864,maxMacroblocksPerSecond:983040},{code:52,maxFrameSize:36864,maxMacroblocksPerSecond:2073600}];function Nx(n,a){for(let r=Math.max(0,a);r+3<n.length;r+=1)if(!(n[r]!==0||n[r+1]!==0)){if(n[r+2]===1)return{index:r,length:3};if(n[r+2]===0&&n[r+3]===1)return{index:r,length:4}}return null}function aj(n){let a=0;for(;a<n.length;){const r=Nx(n,a);if(!r)break;const l=r.index+r.length,c=Nx(n,l),d=c?.index??n.length;if(l<d&&(n[l]&31)===7){const m=[];let p=0;for(let v=l+1;v<d;v+=1){const g=n[v];if(p>=2&&g===3){p=0;continue}m.push(g),p=g===0?p+1:0}if(m.length>=3)return`avc1.${m.slice(0,3).map(v=>v.toString(16).toUpperCase().padStart(2,"0")).join("")}`}a=c?c.index:n.length}return""}function sj(n,a,r,l,c=""){const d=Math.ceil(n/16)*Math.ceil(a/16),m=r>0?1e6/r:30,p=d*m,v=th.find(g=>d<=g.maxFrameSize&&p<=g.maxMacroblocksPerSecond)||th[th.length-1];return aj(l)||c||`avc1.42E0${v.code.toString(16).toUpperCase().padStart(2,"0")}`}function ij(n,a,r,l,c="smooth"){Xc.delete(n);const d=String(a.h264Format||"").toLowerCase()==="avc"?"avc":"annexb",m=Math.max(1,Math.floor(a.width||960)),p=Math.max(1,Math.floor(a.height||540)),v=Math.max(1,Math.floor(a.durationUs||1e6/12));let g=kx(n,c);const w=sj(m,p,v,a.payload,g.codec),y=String(a.frameMode||a.mode||"").toLowerCase(),b=c==="interactive"&&l==="prefer-hardware"&&GC(),j=y==="mode4-h264-atlas"?"prefer-software":hb(n,c==="interactive"&&(ef||b)?"prefer-software":l),A=[a.streamId||"",a.commandId||"",m,p,w,d,j,c].join("|");g.onPaint=r,g.configured&&g.decoder.state!=="configured"&&(g.configured=!1,g.configKey=""),g.configured&&g.configKey!==A&&(_s(n),g=kx(n,c),g.onPaint=r);const N={codec:w,codedWidth:m,codedHeight:p,hardwareAcceleration:j,optimizeForLatency:!0,avc:{format:d}};g.configured||Sd(g,N,A,j);const k=a.isKeyFrame===!0||String(a.chunkType||"").toLowerCase()==="key";Number(a.frameSeq||0);const T=Number(a.streamFrameSeq||0);if(T>0&&g.lastInputFrameSeq!==void 0){if(T<=g.lastInputFrameSeq){if(!k||T===g.lastInputFrameSeq)return;qd(g,g.lastInputFrameSeq-T+1),Sd(g,N,A,j)}if(T>g.lastInputFrameSeq+1){if(qd(g,T-g.lastInputFrameSeq-1),!k)return;Sd(g,N,A,j)}}if(T>0&&(g.lastInputFrameSeq=T),!k&&!g.keyFrameSeen)return;k&&(g.keyFrameSeen=!0);const R=Number(g.decoder.decodeQueueSize||0);if(R>8){if(g.latencyMode==="interactive"&&g.hardwareAcceleration==="prefer-hardware"){ef=!0,mf(n,g.hardwareAcceleration),_s(n);return}if(qd(g),!k)return;Sd(g,N,A,j),g.keyFrameSeen=!0}const q=g.nextChunkTimestampUs;g.nextChunkTimestampUs+=v,g.pendingFrames.set(q,{frame:a,queuedAt:performance.now(),queueSize:R}),g.inputSerial+=1,g.lastInputAt=performance.now();const O=new EncodedVideoChunk({type:k?"key":"delta",timestamp:q,duration:v,data:a.payload});try{g.decoder.decode(O)}catch(Y){throw _s(n),Y}xb(n,g),ej(n,g)}async function nh(n,a,r,l,c,d="smooth"){if(XC(a)){r()||nj(n,a,l,d);return}if(QC(a)){r()||ij(n,a,l,c,d);return}if(Xc.delete(n),KC(a)){_s(n);const y=JC(a);if(r())return;(n.width!==y.width||n.height!==y.height)&&(n.width=y.width,n.height=y.height);const b=n.getContext("2d"),C=performance.now();b?.putImageData(y,0,0);const j=performance.now(),A=zh(n,y.width,y.height,tp,64,a);l?.(a,{deviceId:a.deviceId,frameSeq:a.frameSeq,mode:a.frameMode||a.mode||a.codec||a.mimeType,width:y.width,height:y.height,byteLength:a.byteLength,queuedForMs:0,decodedForMs:0,scheduledForMs:0,drawMs:Math.max(0,j-C),queueSize:0,renderQueueSize:0,droppedForLatency:0,h264DecodeAcceleration:Bl.h264DecodeAcceleration,decoderLabel:"lzo-rgb565",decoderFlushCount:0,decoderTimestampFallbacks:0,decoderInputCount:0,decoderOutputCount:0,targetPaintIntervalMs:0,canvasPresentation:"sync",interactiveBufferWaitCount:0,interactiveBufferWaitMs:0,interactiveQueueDrainCount:0,visualHash:A.visualHash,visualChanged:A.visualChanged,paintedAt:j});return}_s(n);const m=new Blob([a.payload],{type:a.mimeType}),p=await createImageBitmap(m);if(r()){p.close();return}const v=a.width||p.width||960,g=a.height||p.height||540;(n.width!==v||n.height!==g)&&(n.width=v,n.height=g);const w=n.getContext("2d");if(w){const y=performance.now();w.clearRect(0,0,v,g),w.drawImage(p,0,0,v,g);const b=performance.now(),C=zh(n,v,g);l?.(a,{deviceId:a.deviceId,frameSeq:a.frameSeq,mode:a.frameMode||a.mode||a.codec||a.mimeType,width:v,height:g,byteLength:a.byteLength,queuedForMs:0,decodedForMs:0,scheduledForMs:0,drawMs:Math.max(0,b-y),queueSize:0,renderQueueSize:0,droppedForLatency:0,h264DecodeAcceleration:Bl.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:b})}p.close()}const Mx="livedesk_remote_host_targets",rj="livedesk_entitlements",sp=new TextDecoder;function lj(n){const r=(Array.isArray(n)?n:[n||Cn]).map(l=>Wr(l||Cn));return[...new Set(r.filter(Boolean))]}function oj(){const[n,a]=u.useState(null),[r,l]=u.useState(!0);return u.useEffect(()=>{let c=!0;const d=window.liveDesk?.auth?.onComplete?.(p=>{p.ok&&p.session&&mt.auth.setSession(p.session)});(window.liveDesk?.auth?.getSession?.()||mt.auth.getSession()).then(p=>{c&&(a(nb(p)),l(!1))});const{data:{subscription:m}}=mt.auth.onAuthStateChange((p,v)=>{a(v),l(!1),window.liveDesk?.auth?.persistSession?.(v)});return()=>{c=!1,d?.(),m.unsubscribe()}},[]),{session:n,loading:r}}function cj(n,a=!0){const[r,l]=u.useState(null),[c,d]=u.useState([]),[m,p]=u.useState(""),[v,g]=u.useState(""),[w,y]=u.useState(0),b=u.useRef(new Map),C=Array.isArray(n)?n.join(`
12
- `):String(n||""),j=u.useMemo(()=>lj(n),[C]),A=u.useMemo(()=>j.find(T=>qc(T)==="loopback")||j[0]||Cn,[j]),N=u.useCallback(async()=>{if(!a){l(null),d([]),g(""),p("");return}let T=null;const R=Date.now(),q=j.filter(O=>(b.current.get(O)||0)<=R);if(q.length===0)throw new Error("No LiveDesk Hub endpoint is reachable. Retrying shortly.");for(const O of q)try{const[Y,_]=await Promise.all([Ge("/api/remote/status",void 0,O),Ge("/api/remote/devices",void 0,O)]);if(!Array.isArray(_.devices))throw new Error("Invalid Hub devices response.");b.current.delete(O),l(Y),d(_.devices),g(O),p("");return}catch(Y){T=Y,b.current.set(O,Date.now()+1e4)}throw g(""),T||new Error("No LiveDesk Hub endpoint is reachable.")},[a,j]),k=u.useCallback(()=>{b.current.clear(),N().catch(T=>{p(T instanceof Error?T.message:String(T))}),y(T=>T+1)},[N]);return u.useEffect(()=>{if(!a){l(null),d([]),g(""),p("");return}let T=!0;const R=async()=>{try{await N()}catch(O){T&&p(O instanceof Error?O.message:String(O))}};R();const q=window.setInterval(R,2500);return()=>{T=!1,window.clearInterval(q)}},[a,N,w]),{status:r,devices:c,error:m,refresh:k,hubBaseUrl:v||A,hubCandidates:j}}function uj(n){const[a,r]=u.useState(null),[l,c]=u.useState(""),d=n?.user?.id||"",m=u.useCallback(async()=>{if(!d){r(null);return}const{data:p,error:v}=await mt.from(Mx).select("*").eq("user_id",d).maybeSingle();if(v){c(v.message);return}r(p),c("")},[d]);return u.useEffect(()=>{m()},[m]),u.useEffect(()=>{if(!d)return;const p=mt.channel(`livedesk-remote-host-targets-${d.replace(/[^a-zA-Z0-9]/g,"")}`).on("postgres_changes",{event:"*",schema:"public",table:Mx,filter:`user_id=eq.${d}`},v=>r(v.new)).subscribe();return()=>{mt.removeChannel(p)}},[d]),{target:a,error:l,refresh:m}}function dj(n){const[a,r]=u.useState(null),[l,c]=u.useState(!1),[d,m]=u.useState(""),p=n?.user?.id||"",v=u.useCallback(async()=>{if(!p){r(null),m(""),c(!1);return}c(!0);const{data:w,error:y}=await mt.from(rj).select("*").eq("user_id",p).eq("product_key","livedesk").maybeSingle();if(y){m(y.message),c(!1);return}r(w),m(""),c(!1)},[p]);u.useEffect(()=>{v()},[v]);const g=u.useMemo(()=>!a||a.status!=="active"?!1:a.expires_at?new Date(a.expires_at).getTime()>Date.now():!0,[a]);return{entitlement:a,licensed:g,loading:l,error:d,refresh:v}}const Gc={totalFrames:0,totalBytes:0,framesPerSecond:0,bytesPerSecond:0,sampleMs:0,lastUpdatedAt:0},fj=2500,mj=3e4,hj=64*1024,pj=6,gj=pj,bb=new Map;function vj(n){return bb.get(n)}const Tx={totalSent:0,totalDropped:0,sentPerSecond:0,droppedPerSecond:0,bufferedAmount:0,lastInputType:"",lastInputSeq:0,lastRoundTripMs:0,lastAgentApplyMs:0,lastUpdatedAt:0};function Ex(n){const a=Date.parse(String(n||""));if(!Number.isFinite(a))return 0;const r=Date.now()-a;return r>0&&r<=mj?r:0}function Rx(n,a,r=Cn,l={}){const[c,d]=u.useState(new Map),[m,p]=u.useState("idle"),[v,g]=u.useState(""),[w,y]=u.useState(Gc),b=u.useRef(new Map),C=u.useRef(new Map),j=u.useRef(0),A=u.useRef(new Map),N=u.useRef({enabled:!1,token:"",reason:""}),k=u.useRef(new Set),[T,R]=u.useState(0),q=u.useRef(l.onFrame),O=u.useRef(l.onStreamReady),Y=u.useRef({totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0}),_=u.useMemo(()=>[...n].sort().join(","),[n]),L=Number.isFinite(l.fps)?Number(l.fps):2,ae=Number.isFinite(l.maxWidth)?Number(l.maxWidth):640,G=Number.isFinite(l.maxHeight)?Number(l.maxHeight):360,te=Number.isFinite(l.quality)?Number(l.quality):45,P=String(l.frameMode||l.mode||"mode3-h264-hw").trim()||"mode3-h264-hw",ye=l.streamPurpose==="control"?"control":"wall",ie=l.forceRestart===!0,K=String(l.forceRestartToken||"").trim(),I=String(l.restartReason||"").trim();N.current={enabled:ie,token:K,reason:I};const Q=u.useMemo(()=>{const de=Object.entries(l.monitorSelections||{}).filter(([me])=>!!me).sort(([me],[ve])=>me.localeCompare(ve));return JSON.stringify(Object.fromEntries(de))},[l.monitorSelections]);u.useEffect(()=>{q.current=l.onFrame},[l.onFrame]),u.useEffect(()=>{O.current=l.onStreamReady},[l.onStreamReady]);const U=u.useCallback((de,me="livedesk-frame-socket-release")=>{de.disposed=!0;try{de.socket.readyState===WebSocket.CONNECTING||de.socket.readyState===WebSocket.OPEN?de.socket.close(1e3,me):de.socket.close()}catch{}},[]),W=u.useCallback(()=>{const de=[...C.current.values()].map(me=>me.socket);if(de.length===0){p("idle");return}if(de.some(me=>me.readyState===WebSocket.OPEN)){p("open");return}if(de.some(me=>me.readyState===WebSocket.CONNECTING)){p("connecting");return}p("closed")},[]),ue=u.useCallback((de,me,ve,Se)=>{if(me.disposed||me.socket.readyState!==WebSocket.OPEN)return!1;try{return me.socket.send(JSON.stringify({...me.payload,type:"restart-live",deviceIds:[de],forceRestart:!0,restartReason:ve,restartToken:Se})),!0}catch{return!1}},[]),be=u.useCallback((de,me)=>{if(!de||de.byteLength<5)return;const ve=Date.now(),Oe=new DataView(de).getUint32(0,!1);if(Oe<=0||Oe+4>de.byteLength)return;const le=new Uint8Array(de,4,Oe),Z=JSON.parse(sp.decode(le));if(Math.max(Ex(Z.receivedAt),Ex(Z.capturedAt))>fj)return;const _e=new Uint8Array(de,4+Oe),se={deviceId:String(Z.deviceId||""),kind:Z.kind==="thumbnail"?"thumbnail":"live",frameSeq:Number(Z.frameSeq||0),streamFrameSeq:Number(Z.streamFrameSeq||0)||void 0,streamId:String(Z.streamId||""),commandId:Z.commandId?String(Z.commandId):void 0,sessionId:Z.sessionId?String(Z.sessionId):void 0,captureGeneration:Number(Z.captureGeneration||0)||void 0,streamPurpose:Z.streamPurpose?String(Z.streamPurpose):void 0,width:Number(Z.width||0),height:Number(Z.height||0),sourceWidth:Number(Z.sourceWidth||0)||void 0,sourceHeight:Number(Z.sourceHeight||0)||void 0,mimeType:String(Z.mimeType||"image/jpeg"),mode:Z.mode?String(Z.mode):void 0,frameMode:Z.frameMode?String(Z.frameMode):void 0,frameProfile:Z.frameProfile?String(Z.frameProfile):void 0,encoding:Z.encoding?String(Z.encoding):void 0,codec:Z.codec?String(Z.codec):void 0,compression:Z.compression?String(Z.compression):void 0,pixelFormat:Z.pixelFormat?String(Z.pixelFormat):void 0,bytesPerPixel:Number(Z.bytesPerPixel||0)||0,uncompressedByteLength:Number(Z.uncompressedByteLength||0)||0,h264Format:Z.h264Format?String(Z.h264Format):void 0,isKeyFrame:Z.isKeyFrame===!0,chunkType:Z.chunkType?String(Z.chunkType):void 0,timestampUs:Number(Z.timestampUs||0)||0,durationUs:Number(Z.durationUs||0)||0,sourceGapMs:Number(Z.sourceGapMs||0)||0,agentSendGapMs:Number(Z.agentSendGapMs||0)||0,agentSendDurationMs:Number(Z.agentSendDurationMs||0)||0,agentSendDurationFrameSeq:Number(Z.agentSendDurationFrameSeq||0)||0,agentPaceMs:Number(Z.agentPaceMs||0)||0,agentQueueBeforePaceMs:Number(Z.agentQueueBeforePaceMs||0)||0,agentFrameAgeMs:Number(Z.agentFrameAgeMs||0)||0,droppedByAgent:Number(Z.droppedByAgent||0)||0,hubIngressDropped:Number(Z.hubIngressDropped||0)||0,hubClientDropped:Number(Z.hubClientDropped||0)||0,hardwareEncoder:Z.hardwareEncoder?String(Z.hardwareEncoder):void 0,platformProfile:Z.platformProfile?String(Z.platformProfile):void 0,monitorIndex:Number.isFinite(Number(Z.monitorIndex))?Number(Z.monitorIndex):void 0,monitorCount:Number.isFinite(Number(Z.monitorCount))?Number(Z.monitorCount):void 0,requestedFps:Number(Z.requestedFps||0)||0,effectiveFps:Number(Z.effectiveFps||0)||0,captureAverageMs:Number(Z.captureAverageMs||0)||0,captureP95Ms:Number(Z.captureP95Ms||0)||0,slowFrameCount:Number(Z.slowFrameCount||0)||0,captureHelperRestarts:Number(Z.captureHelperRestarts||0)||0,capturedAt:String(Z.capturedAt||""),receivedAt:String(Z.receivedAt||""),hubPacketAt:Z.hubPacketAt?String(Z.hubPacketAt):void 0,hubPacketEpochMs:Number.isFinite(Number(Z.hubPacketEpochMs))?Number(Z.hubPacketEpochMs):void 0,browserReceivedEpochMs:ve,byteLength:Number(Z.byteLength||_e.byteLength),contentHash:Z.contentHash?String(Z.contentHash):void 0,captureMs:Number(Z.captureMs||0)||0,captureStageMs:Number(Z.captureStageMs||0)||0,convertMs:Number(Z.convertMs||0)||0,compressMs:Number(Z.compressMs||0)||0,captureSourceSerial:Number(Z.captureSourceSerial||0)||0,captureSourceSkipped:Number(Z.captureSourceSkipped||0)||0,deltaTileSize:Number(Z.deltaTileSize||0)||0,deltaTileCount:Number(Z.deltaTileCount||0)||0,deltaVisualTileCount:Number(Z.deltaVisualTileCount||0)||0,deltaRefreshTileCount:Number(Z.deltaRefreshTileCount||0)||0,deltaTotalTiles:Number(Z.deltaTotalTiles||0)||0,payload:_e};if(!se.deviceId)return;const fe={streamId:me.lastFrameStreamId,commandId:me.lastFrameCommandId,order:me.lastFrameOrder},Ne=Number(se.streamFrameSeq||se.frameSeq||0),Te=!!fe.commandId&&!!se.commandId,Be=fe.streamId===se.streamId&&(!Te||fe.commandId===se.commandId),$e=fe.order;if(Be&&$e>=Ne&&($e===Ne||Te))return;me.lastFrameStreamId=se.streamId,me.lastFrameCommandId=se.commandId||"",me.lastFrameOrder=Ne;const et=Y.current;et.totalFrames+=1,et.totalBytes+=_e.byteLength,et.sampleFrames+=1,et.sampleBytes+=_e.byteLength;const Mt=!b.current.has(se.deviceId);b.current.set(se.deviceId,se),Mt&&d(new Map(b.current)),q.current?.(se)},[]);u.useEffect(()=>{const de=window.setInterval(()=>{const me=performance.now(),ve=Y.current,Se=Math.max(1,me-ve.sampleStartedAt);y({totalFrames:ve.totalFrames,totalBytes:ve.totalBytes,framesPerSecond:ve.sampleFrames*1e3/Se,bytesPerSecond:ve.sampleBytes*1e3/Se,sampleMs:Se,lastUpdatedAt:Date.now()}),d(new Map(b.current)),ve.sampleFrames=0,ve.sampleBytes=0,ve.sampleStartedAt=me},2e3);return()=>{window.clearInterval(de)}},[]),u.useEffect(()=>{const de=_?_.split(",").filter(Boolean):[],me=new Set(de),ve=performance.now();for(const[Se,Oe]of C.current.entries())me.has(Se)||(U(Oe,"livedesk-device-unsubscribed"),C.current.delete(Se),A.current.delete(Se),b.current.delete(Se));if(de.length===0){for(const Se of C.current.values())U(Se,"livedesk-no-devices");C.current.clear(),A.current.clear(),b.current=new Map,d(new Map),g(""),Y.current={totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0},y(Gc),W();return}Y.current.sampleStartedAt<=0&&(Y.current.sampleStartedAt=ve,y({...Gc,lastUpdatedAt:Date.now()}));for(const Se of de){const Oe=l.monitorSelections?.[Se],le=Number.isFinite(Number(Oe))?{[Se]:Number(Oe)}:{},Z={type:"subscribe",deviceIds:[Se],autoStartLive:a,fps:L,maxWidth:ae,maxHeight:G,quality:te,mode:P,frameMode:P,streamPurpose:ye,monitorSelections:le},He=JSON.stringify(Z),_e=C.current.get(Se);if(_e){const Te=_e.socket.readyState===WebSocket.CONNECTING||_e.socket.readyState===WebSocket.OPEN;if(_e.payloadKey===He&&Te&&!_e.disposed)continue}const se=_e&&(_e.socket.readyState===WebSocket.CONNECTING||_e.socket.readyState===WebSocket.OPEN)&&!_e.disposed?_e.handoffFrom&&!_e.handoffCompleted?_e.handoffFrom:_e:void 0;_e&&_e!==se&&U(_e,"livedesk-subscription-superseded");const fe=new WebSocket(df(`/api/remote/frames/ws?devices=${encodeURIComponent(Se)}`,r));fe.binaryType="arraybuffer";const Ne={socket:fe,payload:Z,payloadKey:He,generation:j.current+1,disposed:!1,handoffFrom:se,handoffCompleted:!1,lastFrameStreamId:"",lastFrameCommandId:"",lastFrameOrder:-1};j.current=Ne.generation,C.current.set(Se,Ne),fe.addEventListener("open",()=>{if(Ne.disposed||C.current.get(Se)!==Ne){U(Ne,"livedesk-stale-frame-socket");return}g("");const Te=N.current,Be=Te.enabled&&(!Te.token||A.current.get(Se)!==Te.token);fe.send(JSON.stringify({...Ne.payload,forceRestart:Be,restartReason:Be?Te.reason:"",restartToken:Be?Te.token:""})),Be&&Te.token&&A.current.set(Se,Te.token);const $e=Ne.handoffFrom;Ne.handoffFrom=void 0,Ne.handoffCompleted=!0,$e&&!$e.disposed&&U($e,"livedesk-subscription-replaced"),W()}),fe.addEventListener("message",Te=>{if(Ne.disposed||C.current.get(Se)!==Ne)return;if(typeof Te.data=="string"){try{const $e=JSON.parse(Te.data);if($e?.type==="RemoteFrameSubscriptionError")g(String($e.error||"control-stream-start-failed"));else if($e?.type==="RemoteFrameLiveAutoStart"){const Mt=(Array.isArray($e.skipped)?$e.skipped:[]).find(ke=>ke?.deviceId===Se);if(Mt)g(String(Mt.reason||"control-stream-start-failed"));else if(Array.isArray($e.started)){const ke=$e.started.find(Ye=>Ye?.deviceId===Se);ke&&(g(""),ke.ready===!0&&ke.streamPurpose==="control"&&ke.sessionId&&ke.commandId&&Number(ke.captureGeneration||0)>0&&O.current?.({deviceId:Se,sessionId:String(ke.sessionId),streamId:String(ke.streamId||""),streamPurpose:"control",commandId:String(ke.commandId),captureGeneration:Number(ke.captureGeneration),monitorIndex:Number(ke.monitorIndex||0)}))}}else $e?.type==="RemoteFrameStreamReady"&&$e.deviceId===Se&&$e.streamPurpose==="control"&&$e.sessionId&&$e.commandId&&Number($e.captureGeneration||0)>0&&(g(""),O.current?.({deviceId:Se,sessionId:String($e.sessionId),streamId:String($e.streamId||""),streamPurpose:"control",commandId:String($e.commandId),captureGeneration:Number($e.captureGeneration),monitorIndex:Number($e.monitorIndex||0)}))}catch{}return}const Be=Te.data instanceof ArrayBuffer?Te.data:null;Be&&(g(""),be(Be,Ne))}),fe.addEventListener("error",()=>{Ne.disposed||C.current.get(Se)!==Ne||p("connecting")}),fe.addEventListener("close",()=>{const Te=!Ne.disposed;Ne.disposed=!0;const Be=C.current.get(Se);let $e=!1;if(Be===Ne){const et=Ne.handoffFrom;Ne.handoffFrom=void 0,et&&!et.disposed&&(et.socket.readyState===WebSocket.CONNECTING||et.socket.readyState===WebSocket.OPEN)?(C.current.set(Se,et),$e=!0):C.current.delete(Se)}if(W(),Te&&Be===Ne&&!$e){const et=window.setTimeout(()=>{k.current.delete(et),R(Mt=>Mt+1)},750);k.current.add(et)}})}W()},[a,U,_,L,P,be,r,G,ae,Q,l.monitorSelections,te,T,ye,W]),u.useEffect(()=>{if(!ie||!K)return;const de=_?_.split(",").filter(Boolean):[];for(const me of de){if(A.current.get(me)===K)continue;const ve=C.current.get(me);!ve||!ue(me,ve,I,K)||A.current.set(me,K)}},[_,ie,K,I,ue]),u.useEffect(()=>()=>{for(const de of C.current.values())U(de,"livedesk-hook-unmount");C.current.clear();for(const de of k.current)window.clearTimeout(de);k.current.clear()},[U]);const X=u.useCallback((de,me="browser-stale")=>{const ve=Array.isArray(de)&&de.length>0?de:_.split(",").filter(Boolean);if(ve.length===0)return!1;let Se=!1;for(const Oe of ve){const le=C.current.get(Oe);!le||le.socket.readyState!==WebSocket.OPEN||(Se=ue(Oe,le,me,`${Date.now()}-${Math.random().toString(36).slice(2)}`)||Se)}return Se},[_,ue]),$=u.useCallback((de,me="browser-reconnect")=>{const ve=Array.isArray(de)&&de.length>0?de:_.split(",").filter(Boolean);if(ve.length===0)return!1;let Se=!1;for(const Oe of ve){const le=C.current.get(Oe);le&&(U(le,`livedesk-${me}`),C.current.delete(Oe),A.current.delete(Oe),b.current.delete(Oe),Se=!0)}return Se&&d(new Map(b.current)),R(Oe=>Oe+1),W(),!0},[U,_,W]);return{frames:c,state:m,error:v,stats:w,restartLive:X,reconnectLive:$}}function xj(n,a,r=Cn,l={}){const[c,d]=u.useState(null),[m,p]=u.useState(null),[v,g]=u.useState("idle"),[w,y]=u.useState(Gc),b=u.useRef(null),C=u.useRef(l.onFrame),j=u.useRef(null),A=u.useRef(0),N=u.useRef({totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0}),k=u.useMemo(()=>[...new Set(n.filter(Boolean))].join(","),[n]),T=u.useMemo(()=>[...new Set((l.captureDeviceIds||n).filter(Boolean))].join(","),[n,l.captureDeviceIds]),R=u.useMemo(()=>JSON.stringify(l.monitorSelections||{}),[l.monitorSelections]),q=u.useMemo(()=>({deviceIds:k.split(",").filter(Boolean),captureDeviceIds:T.split(",").filter(Boolean),fps:Number(l.fps||20),width:Number(l.width||1920),height:Number(l.height||1080),tileWidth:Number(l.tileWidth||320),tileHeight:Number(l.tileHeight||180),monitorSelections:l.monitorSelections||{}}),[T,k,R,l.fps,l.height,l.monitorSelections,l.tileHeight,l.tileWidth,l.width]),O=u.useMemo(()=>JSON.stringify(q),[q]),Y=u.useRef(q);Y.current=q;const _=a&&q.deviceIds.length>0,L=u.useCallback(G=>G.readyState!==WebSocket.OPEN?!1:(G.send(JSON.stringify({type:"configure",...Y.current})),!0),[]);u.useEffect(()=>{C.current=l.onFrame},[l.onFrame]),u.useEffect(()=>{const G=window.setInterval(()=>{const te=N.current,P=performance.now(),ye=Math.max(1,P-te.sampleStartedAt);y({totalFrames:te.totalFrames,totalBytes:te.totalBytes,framesPerSecond:te.sampleFrames*1e3/ye,bytesPerSecond:te.sampleBytes*1e3/ye,sampleMs:ye,lastUpdatedAt:Date.now()});const ie=j.current;ie&&ie.frameSeq!==A.current&&(A.current=ie.frameSeq,d(ie)),te.sampleFrames=0,te.sampleBytes=0,te.sampleStartedAt=P},1e3);return()=>window.clearInterval(G)},[]),u.useEffect(()=>{if(!_){b.current?.close(),b.current=null,d(null),j.current=null,A.current=0,p(null),g("idle"),y(Gc);return}let G=!1,te=0;const P=()=>{if(G)return;const ye=new WebSocket(df("/api/remote/atlas/ws",r));ye.binaryType="arraybuffer",b.current=ye,g("connecting"),ye.addEventListener("open",()=>{N.current.sampleStartedAt=performance.now(),g("open"),L(ye)}),ye.addEventListener("message",ie=>{if(typeof ie.data=="string"){try{const I=JSON.parse(ie.data);I?.type==="Mode4AtlasLayout"&&p({layoutVersion:Number(I.layoutVersion||0),width:Number(I.width||1920),height:Number(I.height||1080),columns:Number(I.columns||1),rows:Number(I.rows||1),tiles:Array.isArray(I.tiles)?I.tiles:[]})}catch{}return}const K=ie.data instanceof ArrayBuffer?ie.data:null;if(!(!K||K.byteLength<5))try{const I=Date.now(),U=new DataView(K).getUint32(0,!1);if(U<=0||U+4>K.byteLength)return;const W=JSON.parse(sp.decode(new Uint8Array(K,4,U))),ue=new Uint8Array(K,4+U),be={deviceId:String(W.deviceId||"__livedesk_mode4_atlas__"),kind:"live",frameSeq:Number(W.frameSeq||0),streamFrameSeq:Number(W.streamFrameSeq||0)||void 0,streamId:String(W.streamId||"mode4-atlas"),commandId:W.commandId?String(W.commandId):void 0,width:Number(W.width||1920),height:Number(W.height||1080),sourceWidth:Number(W.sourceWidth||W.width||1920),sourceHeight:Number(W.sourceHeight||W.height||1080),mimeType:String(W.mimeType||"video/h264"),mode:String(W.mode||"mode4-h264-atlas"),frameMode:String(W.frameMode||"mode4-h264-atlas"),frameProfile:String(W.frameProfile||"mode4-h264-atlas-v1"),encoding:String(W.encoding||"video-atlas"),codec:String(W.codec||"h264"),compression:String(W.compression||"video/h264"),h264Format:String(W.h264Format||"annexb"),isKeyFrame:W.isKeyFrame===!0,chunkType:String(W.chunkType||""),timestampUs:Number(W.timestampUs||0),durationUs:Number(W.durationUs||0),hardwareEncoder:W.hardwareEncoder?String(W.hardwareEncoder):void 0,platformProfile:W.platformProfile?String(W.platformProfile):void 0,capturedAt:String(W.capturedAt||""),receivedAt:String(W.receivedAt||""),hubPacketAt:W.hubPacketAt?String(W.hubPacketAt):void 0,hubPacketEpochMs:Number(W.hubPacketEpochMs||0)||void 0,browserReceivedEpochMs:I,byteLength:ue.byteLength,layoutVersion:Number(W.layoutVersion||0),atlasComposeMs:Number(W.atlasComposeMs||0),atlasPoolStarved:Number(W.atlasPoolStarved||0),atlasReadyTiles:Number(W.atlasReadyTiles||0),atlasTileCount:Number(W.atlasTileCount||0),atlasInputRevision:Number(W.atlasInputRevision||0),atlasSourceNewestAtEpochMs:Number(W.atlasSourceNewestAtEpochMs||0),atlasSourceOldestAtEpochMs:Number(W.atlasSourceOldestAtEpochMs||0),atlasSourceMaxAgeMs:Number(W.atlasSourceMaxAgeMs||0),payload:ue},X=N.current;X.totalFrames+=1,X.totalBytes+=ue.byteLength,X.sampleFrames+=1,X.sampleBytes+=ue.byteLength,j.current=be,A.current===0&&(A.current=be.frameSeq,d(be)),C.current?.(be)}catch{}}),ye.addEventListener("error",()=>g("error")),ye.addEventListener("close",()=>{b.current===ye&&(b.current=null),!G&&(g("closed"),te=window.setTimeout(P,1200))})};return P(),()=>{G=!0,window.clearTimeout(te),b.current?.close(),b.current=null}},[_,r,L]),u.useEffect(()=>{if(!_)return;const G=b.current;G&&L(G)},[O,_,L]);const ae=u.useCallback(()=>{const G=b.current;return G?L(G):!1},[L]);return{frame:c,layout:m,state:v,stats:w,refreshInputs:ae}}function yj(n,a=Cn){const r=u.useRef(null),l=u.useRef(0),c=u.useRef(0),d=u.useRef(new Map),[m,p]=u.useState("idle"),[v,g]=u.useState(""),[w,y]=u.useState(Tx),b=u.useRef({totalSent:0,totalDropped:0,sampleSent:0,sampleDropped:0,sampleStartedAt:0,lastInputType:"",lastInputSeq:0,lastRoundTripMs:0,lastAgentApplyMs:0});u.useEffect(()=>{if(!n){r.current?.close(),r.current=null,c.current=0,p("idle"),g(""),y(Tx);return}let j=!1,A=0;const N=()=>{if(j)return;const k=new WebSocket(df("/api/remote/input/ws",a));r.current=k,b.current.sampleStartedAt=performance.now(),p("connecting"),g(""),k.addEventListener("open",()=>{j||r.current!==k||(g(""),p("open"))}),k.addEventListener("message",T=>{if(!(j||r.current!==k||typeof T.data!="string"))try{const R=JSON.parse(T.data);if(R?.type==="RemoteInputError"){g(String(R.error||R.result?.error||"Remote input failed.")),p("error");return}if(R?.type!=="RemoteInputApplied")return;const q=Number(R.inputSeq||0),O=d.current.get(q);O!==void 0&&(b.current.lastRoundTripMs=Math.max(0,performance.now()-O),d.current.delete(q)),b.current.lastInputSeq=q,b.current.lastAgentApplyMs=Math.max(0,Number(R.agentApplyMs||0))}catch{}}),k.addEventListener("close",()=>{j||r.current!==k||(r.current=null,p("closed"),A=window.setTimeout(N,1200))}),k.addEventListener("error",()=>{!j&&r.current===k&&p("error")})};return N(),()=>{j=!0,window.clearTimeout(A);const k=r.current;r.current=null,k?.close(),d.current.clear()}},[n,a]),u.useEffect(()=>{if(!n)return;const j=window.setInterval(()=>{const A=performance.now(),N=b.current,k=Math.max(1,A-N.sampleStartedAt);y({totalSent:N.totalSent,totalDropped:N.totalDropped,sentPerSecond:N.sampleSent*1e3/k,droppedPerSecond:N.sampleDropped*1e3/k,bufferedAmount:r.current?.bufferedAmount||0,lastInputType:N.lastInputType,lastInputSeq:N.lastInputSeq,lastRoundTripMs:N.lastRoundTripMs,lastAgentApplyMs:N.lastAgentApplyMs,lastUpdatedAt:Date.now()}),N.sampleSent=0,N.sampleDropped=0,N.sampleStartedAt=A},1e3);return()=>window.clearInterval(j)},[n]);const C=u.useCallback((j,A)=>{const N=r.current;if(!N||N.readyState!==WebSocket.OPEN||!j)return!1;const k=String(A.type||"").toLowerCase(),T=k==="pointermove",q=T||k==="wheel",O=b.current;if(T&&N.bufferedAmount>hj)return O.totalDropped+=1,O.sampleDropped+=1,O.lastInputType="pointermove-drop",!1;const Y=l.current+1;l.current=Y;const _=Date.now(),L=!q||Y-c.current>=gj;for(L&&(d.current.set(Y,performance.now()),q&&(c.current=Y)),T||bb.set(j,{inputSeq:Y,inputType:k||"input",sentAt:performance.now()});d.current.size>256;){const ae=d.current.keys().next().value;if(ae===void 0)break;d.current.delete(ae)}return N.send(JSON.stringify({type:"input",requestId:q?"":crypto.randomUUID(),fireAndForget:q,deviceId:j,input:{...A,inputSeq:Y,requestAck:L,issuedAtEpochMs:_,issuedAt:new Date(_).toISOString()}})),O.totalSent+=1,O.sampleSent+=1,O.lastInputType=k||"input",!0},[]);return{state:m,sendInput:C,stats:w,error:v}}function bj(n){const a=String(n||"").toLowerCase();return a.includes("audio/pcm")||a.includes("audio/l16")||a.includes("f32le")||a.includes("s16le")}const Cd={queuedMs:0,browserAgeMs:0,captureAgeMs:0,captureStatusAgeMs:0,silentForMs:0,captureAlive:!1,helperAlive:!1,captureRestartCount:0,localProcessingAgeMs:0,lastPacketAgeMs:0,lastAcceptedAgeMs:0,framesReceived:0,drops:0,resyncs:0,pendingDecodes:0,lastFrameSeq:0,audioContextState:"closed",stalledCount:0,automaticRestarts:0,lastUpdatedAt:0},wj=.08,Sj=.25,Cj=.02,Dx=300,jj=4,jd=1500,ah=5e3,kj=2e3,Aj=1e4,kd=[0,1e3,3e3];function Lx(n){const a=Date.parse(String(n||""));return Number.isFinite(a)?Math.max(0,Date.now()-a):0}function Nj(n,a,r){const l=Math.max(1,Math.min(8,Math.floor(a.channels||2))),c=Math.max(8e3,Math.min(192e3,Math.floor(a.sampleRate||48e3))),d=String(a.mimeType||"").toLowerCase(),m=d.includes("s16le")||d.includes("audio/l16"),p=m?2:4,v=Math.floor(r.byteLength/p),g=Math.floor(v/l),w=n.createBuffer(l,g,c),y=new DataView(r);for(let b=0;b<l;b+=1){const C=w.getChannelData(b);for(let j=0;j<g;j+=1){const N=(j*l+b)*p;C[j]=m?Math.max(-1,Math.min(1,y.getInt16(N,!0)/32768)):Math.max(-1,Math.min(1,y.getFloat32(N,!0)))}}return w}function Mj(n,a,r=Cn){const l=u.useRef(null),c=u.useRef(0),[d,m]=u.useState("idle"),[p,v]=u.useState(null),[g,w]=u.useState(Cd),[y,b]=u.useState("");return u.useEffect(()=>{if(!a||!n){m("idle"),v(null),w(Cd),b("");return}m("connecting"),v(null),w(Cd),b("");const C=window.AudioContext||window.webkitAudioContext;if(!C){m("unsupported"),w(Cd),b("Audio playback is not supported in this browser.");return}const j=new C;l.current=j,c.current=j.currentTime;const A=new WebSocket(df("/api/remote/audio/ws?devices="+encodeURIComponent(n),r));A.binaryType="arraybuffer";const N=new Set,k={browserAgeMs:0,captureAgeMs:0,captureStatusAgeMs:0,silentForMs:0,captureAlive:!1,helperAlive:!1,captureRestartCount:0,localProcessingAgeMs:0,lastPacketAt:0,lastAcceptedAt:0,framesReceived:0,drops:0,resyncs:0,pendingDecodes:0,lastFrameSeq:0,audioContextState:String(j.state),stalledCount:0,automaticRestarts:0,activeStreamId:"",lastCaptureStatusAt:0,lastPcmAtEpochMs:0};let T=!1,R=0,q=!1,O=0,Y=0;const _=(I=!0)=>{for(const Q of N)try{Q.stop()}catch{}N.clear(),I&&(c.current=j.currentTime+wj)},L=()=>{k.audioContextState=String(j.state),!T&&(k.audioContextState==="suspended"||k.audioContextState==="interrupted"?m("suspended"):k.audioContextState==="closed"&&(m("error"),b("The browser audio context is closed. Toggle Remote Audio off and on to recover.")))},ae=async()=>{if(T||String(j.state)==="closed")return!1;try{if(String(j.state)!=="running"&&await j.resume(),k.audioContextState=String(j.state),!T&&!q&&k.audioContextState==="running"){const I=k.lastAcceptedAt>0&&performance.now()-k.lastAcceptedAt<=jd,Q=k.lastCaptureStatusAt>0&&performance.now()-k.lastCaptureStatusAt<=ah&&k.captureAlive&&k.helperAlive;m(I?"playing":Q?"silent":"open")}return k.audioContextState==="running"}catch(I){return T||(m("suspended"),b(I instanceof Error?"Audio playback is suspended: "+I.message:"Audio playback is suspended.")),!1}},G=async()=>{if(T||q||A.readyState!==WebSocket.OPEN)return;if(O>=kd.length){m("error"),b("Remote audio stopped sending frames. Toggle Audio off and on to retry.");return}const I=O;O+=1,q=!0,k.stalledCount+=1,k.automaticRestarts+=1,m("reconnecting");try{const Q=await Ge("/api/remote/devices/"+encodeURIComponent(n)+"/audio/stop",{method:"POST",body:JSON.stringify({})},r);if(Q.ok===!1)throw new Error(Q.error||"Remote audio stop failed.");if(T)return;const U=await Ge("/api/remote/devices/"+encodeURIComponent(n)+"/audio/start",{method:"POST",body:JSON.stringify({streamId:"audio-restart-"+Date.now(),mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},r);if(U.ok===!1)throw new Error(U.error||"Remote audio start failed.");const W=performance.now();R=W,k.lastPacketAt=W,k.lastAcceptedAt=0,k.lastCaptureStatusAt=0,k.lastPcmAtEpochMs=0,k.captureAlive=!1,k.helperAlive=!1,k.silentForMs=0,Y=W+(kd[I+1]??3e3),b(""),T||m("open")}catch(Q){T||(Y=performance.now()+(kd[I+1]??3e3),m("error"),b(Q instanceof Error?"Remote audio restart failed: "+Q.message:"Remote audio restart failed."))}finally{q=!1}},te=()=>{k.drops+=1},P=window.setInterval(()=>{if(T)return;const I=performance.now(),Q=k.lastPacketAt>0?Math.max(0,I-k.lastPacketAt):R>0?Math.max(0,I-R):0,U=k.lastAcceptedAt>0?Math.max(0,I-k.lastAcceptedAt):0,W=k.lastCaptureStatusAt>0?Math.max(0,I-k.lastCaptureStatusAt):0,ue=A.readyState===WebSocket.OPEN,be=k.lastCaptureStatusAt>0,X=be&&W<=ah,$=be&&(!k.captureAlive||!k.helperAlive)&&W>kj,de=be&&W>ah,me=!be&&R>0&&I-R>Aj,ve=R>0&&(k.lastAcceptedAt<=0?I-R>jd:U>jd);ue&&R>0&&($||de||me)?O>=kd.length&&!q?(m("error"),b("Remote audio capture heartbeat stopped. Toggle Audio off and on to retry.")):!q&&I>=Y?G():q||m("stalled"):ue&&ve&&!q&&k.audioContextState!=="suspended"&&k.audioContextState!=="interrupted"&&m(X?"silent":"open"),w({queuedMs:Math.max(0,(c.current-j.currentTime)*1e3),browserAgeMs:k.browserAgeMs,captureAgeMs:k.captureAgeMs,captureStatusAgeMs:W,silentForMs:k.silentForMs,captureAlive:k.captureAlive,helperAlive:k.helperAlive,captureRestartCount:k.captureRestartCount,localProcessingAgeMs:k.localProcessingAgeMs,lastPacketAgeMs:Q,lastAcceptedAgeMs:U,framesReceived:k.framesReceived,drops:k.drops,resyncs:k.resyncs,pendingDecodes:k.pendingDecodes,lastFrameSeq:k.lastFrameSeq,audioContextState:k.audioContextState,stalledCount:k.stalledCount,automaticRestarts:k.automaticRestarts,lastUpdatedAt:Date.now()})},250),ye=()=>{L(),(String(j.state)==="suspended"||String(j.state)==="interrupted")&&ae()},ie=()=>{document.visibilityState==="visible"&&ae()},K=()=>{ae()};return j.addEventListener("statechange",ye),document.addEventListener("visibilitychange",ie),window.addEventListener("pageshow",K),window.addEventListener("pointerdown",K),window.addEventListener("keydown",K),m("connecting"),b(""),L(),A.addEventListener("open",()=>{T||(R=performance.now(),k.lastPacketAt=R,k.lastAcceptedAt=0,k.lastCaptureStatusAt=0,k.lastPcmAtEpochMs=0,k.captureAlive=!1,k.helperAlive=!1,k.silentForMs=0,m("open"),A.send(JSON.stringify({type:"subscribe",deviceIds:[n]})),ae())}),A.addEventListener("message",I=>{if(typeof I.data=="string")return;const Q=I.data instanceof ArrayBuffer?I.data:null;if(!Q||Q.byteLength<5)return;const U=performance.now();k.lastPacketAt=U,(async()=>{try{const ue=new DataView(Q).getUint32(0,!1);if(ue<=0||ue+4>Q.byteLength){te();return}const be=new Uint8Array(Q,4,ue),X=JSON.parse(sp.decode(be)),$=Q.slice(4+ue),de=String(X.frameKind||X.kind||"").toLowerCase();if(X.type==="remote.audio.status"||de==="audio-status"){if(k.lastCaptureStatusAt=U,k.captureAlive=X.captureAlive===!0,k.helperAlive=X.helperAlive===!0,k.captureRestartCount=Math.max(0,Number(X.restartCount||0)||0),k.lastPcmAtEpochMs=Math.max(0,Number(X.lastPcmAtEpochMs||0)||0),k.silentForMs=Math.max(0,Number(X.silentForMs||0)||0),k.captureAgeMs=k.lastPcmAtEpochMs>0?Math.max(0,Date.now()-k.lastPcmAtEpochMs):k.silentForMs,k.captureAlive&&k.helperAlive){if(O=0,Y=0,!q){b("");const ve=String(j.state)==="running",Se=k.lastAcceptedAt>0&&performance.now()-k.lastAcceptedAt<=jd;m(ve?Se?"playing":"silent":"suspended")}}else q||m("stalled");return}const me={deviceId:String(X.deviceId||""),frameSeq:Number(X.frameSeq||0),streamId:String(X.streamId||""),mimeType:String(X.mimeType||"audio/webm;codecs=opus"),sampleRate:Number(X.sampleRate||48e3),channels:Number(X.channels||2),capturedAt:String(X.capturedAt||""),receivedAt:String(X.receivedAt||""),byteLength:Number(X.byteLength||$.byteLength),payload:$};if(!me.deviceId||T)return;if(performance.now()-U>Dx){te();return}if(k.pendingDecodes>=jj){te();return}k.pendingDecodes+=1;try{const ve=bj(me.mimeType)?Nj(j,me,$):await j.decodeAudioData($.slice(0));if(k.localProcessingAgeMs=Math.max(0,performance.now()-U),T)return;if(k.localProcessingAgeMs>Dx){te();return}if(me.frameSeq>0&&me.frameSeq<=k.lastFrameSeq){te();return}if(k.activeStreamId&&me.streamId!==k.activeStreamId&&me.frameSeq<=k.lastFrameSeq){te();return}me.streamId&&me.streamId!==k.activeStreamId&&(k.activeStreamId=me.streamId,k.lastFrameSeq=0,_());const Se=j.currentTime;Math.max(0,c.current-Se)>Sj&&(_(),k.resyncs+=1);const le=j.createBufferSource();le.buffer=ve,le.connect(j.destination),N.add(le),le.onended=()=>{N.delete(le),le.onended=null};const Z=Math.max(j.currentTime+Cj,c.current);le.start(Z),c.current=Z+ve.duration,k.browserAgeMs=Lx(me.receivedAt),k.captureAgeMs=Lx(me.capturedAt),k.lastAcceptedAt=performance.now(),k.framesReceived+=1,k.lastFrameSeq=me.frameSeq,O=0,Y=0,v(me),ae();const He=String(j.state)==="running";He&&b(""),m(He?"playing":"suspended")}finally{k.pendingDecodes=Math.max(0,k.pendingDecodes-1)}}catch(W){T||(m("error"),b(W instanceof Error?W.message:String(W)))}})()}),A.addEventListener("error",()=>{T||(m("error"),b("Remote audio WebSocket error."))}),A.addEventListener("close",()=>{T||m("closed")}),()=>{T=!0,window.clearInterval(P),j.removeEventListener("statechange",ye),document.removeEventListener("visibilitychange",ie),window.removeEventListener("pageshow",K),window.removeEventListener("pointerdown",K),window.removeEventListener("keydown",K),_(!1),A.close(),j.close().catch(()=>{}),l.current===j&&(l.current=null)}},[n,a,r]),{state:d,lastFrame:p,stats:g,error:y}}const Tj=3;function _x(n,a,r){const l=Math.max(1,Number(r)||1),c=Math.max(0,Math.min(l,Number(n)-Number(a))),d=Math.min(l/2,Tj);return c<=d?0:c>=l-d?1:c/l}function Ej(n,a,r){return{normalizedX:_x(n,r.left,r.width),normalizedY:_x(a,r.top,r.height)}}const li=Object.freeze({smallDirectDeviceLimit:4,interactiveDirectFps:30,controlWallReuseMaxFps:30,scalableAtlasInputFps:8,atlasOutputFps:20,maxDirectFramesPerSecond:96,directDecodeAcceleration:"prefer-software",directLatencyMode:"interactive",configuredLatencyMode:"smooth"});function Rj(n,a){const r=Math.max(0,Math.floor(Number(a)||0));return n===!0&&r>0&&r<=li.smallDirectDeviceLimit}function zc({mode4Enabled:n,directMode4WallEnabled:a,isMac:r}){return!n||a||r?"direct":"atlas"}function Dj({mode4Enabled:n,directMode4WallEnabled:a,adaptiveFps:r,directDeviceCount:l}){const c=Math.max(1,Math.floor(Number(r)||1));if(!n)return c;if(a)return Math.max(li.interactiveDirectFps,c);const d=Math.max(1,Math.floor(Number(l)||1));return Math.max(1,Math.min(c,Math.floor(li.maxDirectFramesPerSecond/d)))}function Lj(n,a){return n?{acceleration:li.directDecodeAcceleration,latencyMode:li.directLatencyMode}:{acceleration:a,latencyMode:li.configuredLatencyMode}}const Ih={revision:0,settings:{connection:{usePinToAddDevices:!0,pinValidityMinutes:30,rotatePinAfterPairing:!0,allowNewDevices:!0,approveNewDevices:!0,startWithComputer:!0,keepRunningInTray:!0,showConnectionNotifications:!0},security:{accessMode:"trusted-only",requireEncryptedConnections:!0,allowInternetConnections:!1,allowLanConnections:!0,allowUnencryptedLanFallback:!1,requireNewDeviceApproval:!0,requireAdministratorForSecurityChanges:!0,visibleControlIndicator:!0,lockOnControlEnd:!0,disconnectIdleControlSessions:!0,idleControlMinutes:30,keepSessionHistory:!0,sessionHistoryDays:30},control:{allowKeyboardMouse:!0,allowSystemShortcuts:!0,allowClipboardText:!0,allowRemoteRestart:!1,reconnectAfterRemoteRestart:!0,allowSwitchingMonitors:!0,showConnectionToolbar:!0,showRemoteCursor:!0,openControlOnDoubleClick:!0,startRemoteAudioWithControl:!1,fitRemoteScreen:!0,rememberLastMonitor:!0,keepControlReadyBetweenPages:!0},wall:{performanceMode:"auto",autoStart:!0,connectedOnly:!1,keepEmptySlots:!0,showDeviceStatus:!0,showPerformanceDetails:!1,pauseHiddenTiles:!0,reduceWhenHidden:!0,autoAdjustTileQuality:!0,rememberDevicePositions:!0},filesAudio:{allowFileTransfer:!0,allowFolderSync:!1,askBeforeReceivingFiles:!0,openReceivedFolder:!1,notifyTransferComplete:!0,allowOverwrite:!1,defaultReceiveFolder:"Desktop/LiveDeskFiles",maxFileSizeBytes:1073741824,allowRemoteAudio:!0,startAudioMuted:!1,rememberVolume:!0,automaticallyRecoverAudio:!0,showAudioTroubleshooting:!1,rollingBufferEnabled:!1,recordingQuality:"standard",timelapseIntervalSeconds:10,includeRemoteCursor:!0,captureSaveLocation:"LiveDesk Captures",captureAutoDelete:"never"},agent:{enabled:!1,defaultPermissionMode:"safe-auto",askBeforeDestructive:!0,allowProcessManagement:!0,allowServiceManagement:!0,allowFileChanges:!0,allowCommandExecution:!1,allowSoftwareInstallation:!1,allowPowerActions:!1,keepAuditHistory:!0,timeoutMinutes:10},advanced:{wallFrameMode:"auto",wallFps:20,wallMaxWidth:960,wallMaxHeight:540,wallQuality:55,controlFrameMode:"mode3-h264-hw",controlFps:30,controlMaxWidth:1920,controlMaxHeight:1080,controlQuality:60,transport:"auto",allowPlainLanFallback:!1,verboseLogs:!1,frameStatistics:!1}}},_j=[{id:"connection",label:"Connection",icon:Hl},{id:"security",label:"Security",icon:Lt},{id:"control",label:"Control",icon:Yt},{id:"wall",label:"Wall",icon:Kc},{id:"files-audio",label:"Files & Audio",icon:Ro},{id:"agent",label:"Agent",icon:Ls},{id:"advanced",label:"Advanced",icon:Qd}];function Ml(n,a){return n?.settings?.[a]||Ih.settings[a]}function ft({icon:n,title:a,description:r,children:l,disabled:c=!1,recommended:d=!1}){return s.jsxs("div",{className:`product-setting-row ${c?"disabled":""}`,children:[s.jsx("div",{className:"product-setting-control",children:l}),n&&s.jsx("span",{className:"product-setting-icon",children:s.jsx(n,{size:17})}),s.jsxs("div",{className:"product-setting-copy",children:[s.jsx("strong",{children:a}),d&&s.jsx("em",{children:"Recommended"}),s.jsx("small",{children:r})]})]})}function kt({checked:n,onChange:a,disabled:r=!1,label:l}){return s.jsxs("label",{className:"product-switch",children:[s.jsx("input",{"aria-label":l,type:"checkbox",checked:n,disabled:r,onChange:c=>a(c.target.checked)}),s.jsx("span",{})]})}function $i({value:n,onChange:a,options:r,disabled:l=!1,label:c}){return s.jsx("select",{"aria-label":c,value:String(n),disabled:l,onChange:d=>a(d.target.value),children:r.map(([d,m])=>s.jsx("option",{value:d,children:m},d))})}function zj({hubUrl:n="",runtimeRole:a="hub",runtimeDeviceId:r="",sessionAccessToken:l="",initialTab:c="connection",pin:d,wall:m,control:p,agent:v,advancedExtras:g,captureGallery:w}){const[y,b]=u.useState(c),[C,j]=u.useState(null),[A,N]=u.useState("loading"),[k,T]=u.useState(""),[R,q]=u.useState("idle"),[O,Y]=u.useState("");u.useEffect(()=>{let ve=!0;return N("loading"),Ge("/api/settings",void 0,n).then(Se=>{ve&&(j({revision:Number(Se.revision||0),updatedAt:Se.updatedAt,settings:Se.settings}),N("saved"))}).catch(Se=>{ve&&(T(Se instanceof Error?Se.message:String(Se)),j(Ih),N("failed"))}),()=>{ve=!1}},[n]);const _=async(ve,Se,Oe)=>{const le=C||Ih,Z=le,He={...le,settings:{...le.settings,[ve]:{...Ml(le,ve),[Se]:Oe}}};j(He),N("saving"),T("");try{const _e=await Ge("/api/settings",{method:"PATCH",body:JSON.stringify({revision:le.revision,[ve]:{[Se]:Oe}})},n);j({revision:_e.revision,updatedAt:_e.updatedAt,settings:_e.settings}),N("saved")}catch(_e){j(Z),N("failed"),T(_e instanceof Error?_e.message:String(_e))}},L=(ve,Se)=>Oe=>{_(ve,Se,Oe)},ae=async()=>{if(a!=="hub"||!r||!l){q("failed"),Y("Sign in to this Hub before changing its runtime role.");return}q("changing"),Y("");try{const ve=await Ge("/api/runtime/status",void 0,n);await Ge("/api/runtime/role",{method:"POST",headers:{Authorization:`Bearer ${l}`},body:JSON.stringify({role:"client"})},n),q("accepted"),await ab({baseUrl:n,targetRole:"client",previousRuntimePid:Number(ve.runtimePid||0),allowedStates:["running","waiting-auth"]}),uC(5179)}catch(ve){q("failed"),Y(ve instanceof Error?ve.message:String(ve))}},G=Ml(C,"security"),te=Ml(C,"connection"),P=Ml(C,"control"),ye=Ml(C,"wall"),ie=Ml(C,"filesAudio"),K=Ml(C,"agent"),I=u.useMemo(()=>G.allowInternetConnections===!1?{label:"Local only",tone:"local",detail:"Internet connections are disabled."}:G.requireEncryptedConnections&&G.requireNewDeviceApproval&&G.accessMode==="trusted-only"?{label:"Protected",tone:"protected",detail:"Encrypted connections and trusted-device approval are active."}:{label:"Needs attention",tone:"attention",detail:"Review access and encryption settings before sharing this Hub."},[G]),Q=`settings-panel-${y}`,U=s.jsxs("div",{className:"settings-tab-content product-settings-content",children:[s.jsxs("section",{className:"product-settings-hero",children:[s.jsxs("div",{children:[s.jsxs("span",{className:"settings-eyebrow",children:[s.jsx(Hl,{size:14})," Connection"]}),s.jsx("h2",{children:"Connect a device"}),s.jsx("p",{children:"Use the short PIN on the computer you want to add. The PIN is temporary and can be replaced at any time."})]}),s.jsxs("div",{className:"product-save-state",role:"status",children:[s.jsx(Ky,{size:14})," ",A==="saving"?"Saving":A==="failed"?"Failed":A==="loading"?"Loading":"Saved"]})]}),d,s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Connection behavior"}),s.jsx("h3",{children:"New device access"})]}),s.jsx(_o,{size:20})]}),s.jsx(ft,{icon:_o,title:"Use PIN to add new devices",description:"Allow temporary PIN pairing from the client.",recommended:!0,children:s.jsx(kt,{checked:!!te.usePinToAddDevices,onChange:L("connection","usePinToAddDevices"),label:"Use PIN to add new devices"})}),s.jsx(ft,{icon:Lt,title:"Approve new devices on this Hub",description:"Ask for approval before an unfamiliar computer becomes trusted.",children:s.jsx(kt,{checked:!!te.approveNewDevices,onChange:L("connection","approveNewDevices"),label:"Approve new devices"})}),s.jsx(ft,{icon:gn,title:"Show connection notifications",description:"Show a short notice when a computer connects or leaves.",children:s.jsx(kt,{checked:!!te.showConnectionNotifications,onChange:L("connection","showConnectionNotifications"),label:"Show connection notifications"})})]}),s.jsxs("section",{className:"settings-section-card runtime-role-settings",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Runtime role"}),s.jsx("h3",{children:"Use this computer as a Client"})]}),s.jsx(Qd,{size:20})]}),s.jsx("p",{className:"settings-help",children:"This stops the Hub listener, saves the Client role in Supabase, and restarts LiveDesk through the unified launcher."}),R==="accepted"?s.jsx("p",{className:"settings-help runtime-role-success",children:"Role change accepted. LiveDesk is restarting as Client."}):O?s.jsx("p",{className:"settings-help runtime-role-error",role:"alert",children:O}):null,s.jsx("button",{className:"settings-reset",onClick:()=>{ae()},disabled:R==="changing"||a!=="hub",type:"button",children:R==="changing"?"Switching role…":"Switch this computer to Client"})]})]}),W=s.jsxs("div",{className:"settings-tab-content product-settings-content",children:[s.jsxs("section",{className:`security-status-card ${I.tone}`,children:[s.jsxs("div",{children:[s.jsx("span",{children:"Security status"}),s.jsx("strong",{children:I.label}),s.jsx("small",{children:I.detail})]}),s.jsx(Lt,{size:28})]}),s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Access mode"}),s.jsx("h3",{children:"Who may use this Hub?"})]}),s.jsx(Ds,{size:20})]}),s.jsx(ft,{icon:Lt,title:"Access mode",description:"Choose the default boundary for remote sessions.",recommended:!0,children:s.jsx($i,{value:String(G.accessMode),onChange:L("security","accessMode"),label:"Access mode",options:[["trusted-only","Trusted devices only"],["ask-every-time","Ask every time"],["view-only","View only"],["block-remote-access","Block remote access"]]})}),s.jsx(ft,{icon:Hl,title:"Require encrypted connections",description:"External connections cannot disable this protection.",recommended:!0,children:s.jsx(kt,{checked:!!G.requireEncryptedConnections,onChange:L("security","requireEncryptedConnections"),label:"Require encrypted connections"})}),s.jsx(ft,{icon:Hl,title:"Allow internet connections",description:"Keep off unless you intentionally expose this Hub beyond the LAN.",children:s.jsx(kt,{checked:!!G.allowInternetConnections,onChange:L("security","allowInternetConnections"),label:"Allow internet connections"})}),s.jsx(ft,{icon:Yt,title:"Allow LAN connections",description:"Permit connections from the local network.",children:s.jsx(kt,{checked:!!G.allowLanConnections,onChange:L("security","allowLanConnections"),label:"Allow LAN connections"})}),s.jsx(ft,{icon:Lt,title:"Require approval for new devices",description:"New computers must be approved before remote access is granted.",children:s.jsx(kt,{checked:!!G.requireNewDeviceApproval,onChange:L("security","requireNewDeviceApproval"),label:"Require approval for new devices"})})]}),s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Session protection"}),s.jsx("h3",{children:"End sessions safely"})]}),s.jsx(gn,{size:20})]}),s.jsx(ft,{icon:Yt,title:"Show an indicator while Control is active",description:"Make active remote control visible on the local computer.",children:s.jsx(kt,{checked:!!G.visibleControlIndicator,onChange:L("security","visibleControlIndicator"),label:"Show Control indicator"})}),s.jsx(ft,{icon:Ds,title:"Lock the remote computer when Control ends",description:"Protect the local screen after a Control session.",children:s.jsx(kt,{checked:!!G.lockOnControlEnd,onChange:L("security","lockOnControlEnd"),label:"Lock after Control ends"})}),s.jsx(ft,{icon:gn,title:"Disconnect idle Control sessions",description:"Automatically close inactive Control sessions.",children:s.jsx(kt,{checked:!!G.disconnectIdleControlSessions,onChange:L("security","disconnectIdleControlSessions"),label:"Disconnect idle sessions"})}),s.jsx(ft,{icon:gn,title:"Idle timeout",description:"Time before an inactive Control session closes.",disabled:!G.disconnectIdleControlSessions,children:s.jsx($i,{value:Number(G.idleControlMinutes),onChange:ve=>L("security","idleControlMinutes")(Number(ve)),disabled:!G.disconnectIdleControlSessions,label:"Idle timeout",options:[["5","5 minutes"],["15","15 minutes"],["30","30 minutes"],["60","1 hour"],["1440","Never"]]})})]})]}),ue=s.jsxs("div",{className:"settings-tab-content product-settings-content",children:[s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Remote use"}),s.jsx("h3",{children:"What can a connected user do?"})]}),s.jsx(Yt,{size:20})]}),s.jsx(ft,{icon:Yt,title:"Keyboard and mouse control",description:"Allow the Hub to send keyboard and pointer input.",recommended:!0,children:s.jsx(kt,{checked:!!P.allowKeyboardMouse,onChange:L("control","allowKeyboardMouse"),label:"Keyboard and mouse control"})}),s.jsx(ft,{icon:YS,title:"System shortcuts",description:"Allow shortcut keys such as Alt-Tab and the system key.",children:s.jsx(kt,{checked:!!P.allowSystemShortcuts,onChange:L("control","allowSystemShortcuts"),label:"System shortcuts"})}),s.jsx(ft,{icon:_o,title:"Clipboard text sharing",description:"Share plain text through the remote session.",children:s.jsx(kt,{checked:!!P.allowClipboardText,onChange:L("control","allowClipboardText"),label:"Clipboard text sharing"})}),s.jsx(ft,{icon:gn,title:"Remote restart",description:"Allow restart requests from Control.",disabled:!P.allowKeyboardMouse,children:s.jsx(kt,{checked:!!P.allowRemoteRestart,onChange:L("control","allowRemoteRestart"),disabled:!P.allowKeyboardMouse,label:"Remote restart"})}),s.jsx(ft,{icon:Yt,title:"Switching monitors",description:"Allow the viewer to select another connected display.",children:s.jsx(kt,{checked:!!P.allowSwitchingMonitors,onChange:L("control","allowSwitchingMonitors"),label:"Switching monitors"})})]}),s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Session behavior"}),s.jsx("h3",{children:"Make Control predictable"})]}),s.jsx(Hn,{size:20})]}),s.jsx(ft,{icon:Yt,title:"Open Control on double-click",description:"Double-clicking a Wall tile opens its Control view.",children:s.jsx(kt,{checked:!!P.openControlOnDoubleClick,onChange:L("control","openControlOnDoubleClick"),label:"Open Control on double-click"})}),s.jsx(ft,{icon:gn,title:"Start audio with Control",description:"Keep audio muted by default for new sessions.",children:s.jsx(kt,{checked:!!P.startRemoteAudioWithControl,onChange:L("control","startRemoteAudioWithControl"),label:"Start audio with Control"})}),s.jsx(ft,{icon:Yt,title:"Fit remote screen to window",description:"Scale the remote display to the available Control area.",children:s.jsx(kt,{checked:!!P.fitRemoteScreen,onChange:L("control","fitRemoteScreen"),label:"Fit remote screen"})}),s.jsx(ft,{icon:gn,title:"Keep Control ready between pages",description:"Faster reconnection for 1 minute.",recommended:!0,children:s.jsx(kt,{checked:!!P.keepControlReadyBetweenPages,onChange:L("control","keepControlReadyBetweenPages"),label:"Keep Control ready between pages"})})]})]}),be=s.jsxs("div",{className:"settings-tab-content product-settings-content",children:[s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Performance mode"}),s.jsx("h3",{children:"Let LiveDesk choose the best path"})]}),s.jsx(Kc,{size:20})]}),s.jsx(ft,{icon:Ls,title:"Performance mode",description:"Automatic mode balances responsiveness and image quality.",recommended:!0,children:s.jsx($i,{value:String(ye.performanceMode),onChange:L("wall","performanceMode"),label:"Performance mode",options:[["auto","Auto"],["responsive","Prioritize responsiveness"],["quality","Prioritize image quality"],["custom","Custom"]]})}),s.jsx("p",{className:"settings-help",children:"Streaming details are available under Advanced for diagnostics and development."})]}),s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Wall behavior"}),s.jsx("h3",{children:"What should the Wall show?"})]}),s.jsx(gn,{size:20})]}),[["autoStart","Start Wall automatically","Start a live view when a computer connects."],["connectedOnly","Show only connected devices","Hide disconnected slots."],["keepEmptySlots","Keep empty slots visible","Preserve the layout when a device leaves."],["showDeviceStatus","Show device status on tiles","Display compact machine status."],["showPerformanceDetails","Show performance details","Show advanced frame diagnostics on tiles."],["pauseHiddenTiles","Pause hidden tiles","Reduce capture work for tiles outside the visible area."],["reduceWhenHidden","Reduce activity when the window is hidden","Lower background work when the browser is not visible."],["autoAdjustTileQuality","Automatically adjust tile quality","Adapt tile quality to Wall size and load."]].map(([ve,Se,Oe])=>s.jsx(ft,{icon:Yt,title:Se,description:Oe,children:s.jsx(kt,{checked:!!ye[ve],onChange:L("wall",ve),label:Se})},ve))]})]}),X=s.jsxs("div",{className:"settings-tab-content product-settings-content",children:[s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"File permissions"}),s.jsx("h3",{children:"Move files deliberately"})]}),s.jsx(Ro,{size:20})]}),s.jsx(ft,{icon:Ro,title:"Allow file transfer",description:"Permit Hub-to-device file delivery.",recommended:!0,children:s.jsx(kt,{checked:!!ie.allowFileTransfer,onChange:L("filesAudio","allowFileTransfer"),label:"Allow file transfer"})}),s.jsx(ft,{icon:Kc,title:"Allow folder sync",description:"Enable recurring folder synchronization.",disabled:!ie.allowFileTransfer,children:s.jsx(kt,{checked:!!ie.allowFolderSync,onChange:L("filesAudio","allowFolderSync"),disabled:!ie.allowFileTransfer,label:"Allow folder sync"})}),s.jsx(ft,{icon:Lt,title:"Ask before receiving files",description:"Require local confirmation before a transfer is written.",children:s.jsx(kt,{checked:!!ie.askBeforeReceivingFiles,onChange:L("filesAudio","askBeforeReceivingFiles"),label:"Ask before receiving files"})}),s.jsx(ft,{icon:Ro,title:"Allow overwrite",description:"Permit replacing an existing destination file.",children:s.jsx(kt,{checked:!!ie.allowOverwrite,onChange:L("filesAudio","allowOverwrite"),label:"Allow overwrite"})})]}),s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Audio permissions"}),s.jsx("h3",{children:"Remote sound"})]}),s.jsx(gn,{size:20})]}),s.jsx(ft,{icon:gn,title:"Allow remote audio",description:"Permit audio capture from connected computers.",recommended:!0,children:s.jsx(kt,{checked:!!ie.allowRemoteAudio,onChange:L("filesAudio","allowRemoteAudio"),label:"Allow remote audio"})}),s.jsx(ft,{icon:gn,title:"Start audio muted",description:"New audio sessions begin silent.",children:s.jsx(kt,{checked:!!ie.startAudioMuted,onChange:L("filesAudio","startAudioMuted"),label:"Start audio muted"})}),s.jsx(ft,{icon:gn,title:"Automatically recover audio",description:"Recover from temporary capture or transport stalls.",children:s.jsx(kt,{checked:!!ie.automaticallyRecoverAudio,onChange:L("filesAudio","automaticallyRecoverAudio"),label:"Automatically recover audio"})})]}),s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Capture defaults"}),s.jsx("h3",{children:"Screen recording"})]}),s.jsx(Yt,{size:20})]}),s.jsx(ft,{icon:gn,title:"Keep a Last 30s buffer",description:"Keep recent video in memory only until you explicitly save it.",children:s.jsx(kt,{checked:!!ie.rollingBufferEnabled,onChange:L("filesAudio","rollingBufferEnabled"),label:"Keep a Last 30s buffer"})}),s.jsx(ft,{icon:gn,title:"Recording quality",description:"Choose the WebM bitrate profile.",children:s.jsx($i,{value:String(ie.recordingQuality),onChange:L("filesAudio","recordingQuality"),label:"Recording quality",options:[["standard","Standard"],["high","High"]]})}),s.jsx(ft,{icon:gn,title:"Timelapse interval",description:"Capture one frame at the selected interval.",children:s.jsx($i,{value:Number(ie.timelapseIntervalSeconds),onChange:ve=>L("filesAudio","timelapseIntervalSeconds")(Number(ve)),label:"Timelapse interval",options:[["5","5 seconds"],["10","10 seconds"],["30","30 seconds"],["60","60 seconds"]]})}),s.jsx(ft,{icon:Yt,title:"Include remote cursor",description:"Include the cursor indicator when the source provides it.",children:s.jsx(kt,{checked:!!ie.includeRemoteCursor,onChange:L("filesAudio","includeRemoteCursor"),label:"Include remote cursor"})}),s.jsx(ft,{icon:Ro,title:"Capture save location",description:"Captures are stored inside the Hub capture library.",children:s.jsx($i,{value:String(ie.captureSaveLocation),onChange:L("filesAudio","captureSaveLocation"),label:"Capture save location",options:[[String(ie.captureSaveLocation||"LiveDesk Captures"),"LiveDesk Captures"]]})}),s.jsx(ft,{icon:Ro,title:"Automatic deletion",description:"Keep saved captures until you delete them.",children:s.jsx($i,{value:String(ie.captureAutoDelete),onChange:L("filesAudio","captureAutoDelete"),label:"Automatic deletion",options:[["never","Never"],["7-days","After 7 days"],["30-days","After 30 days"]]})})]}),w]}),$=s.jsxs("div",{className:"settings-tab-content product-settings-content",children:[s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Agent safety"}),s.jsx("h3",{children:"AI workstation operations"})]}),s.jsx(Ls,{size:20})]}),s.jsx(ft,{icon:Ls,title:"Enable AI Agent on devices",description:"Allow Agent runs to reach connected workstations.",recommended:!0,children:s.jsx(kt,{checked:!!K.enabled,onChange:L("agent","enabled"),label:"Enable AI Agent"})}),s.jsx(ft,{icon:Lt,title:"Default permission mode",description:"Safe Auto keeps destructive operations behind approval.",children:s.jsx($i,{value:String(K.defaultPermissionMode),onChange:L("agent","defaultPermissionMode"),label:"Default Agent permission mode",options:[["ask","Ask"],["safe-auto","Safe Auto"],["full-access","Full Access"],["custom","Custom"]]})}),s.jsx(ft,{icon:Lt,title:"Ask before destructive operations",description:"Locked on for Safe Auto and destructive actions.",disabled:!K.enabled,children:s.jsx(kt,{checked:!!K.askBeforeDestructive,onChange:L("agent","askBeforeDestructive"),disabled:!K.enabled,label:"Ask before destructive operations"})}),s.jsx(ft,{icon:gn,title:"Keep Agent audit history",description:"Retain an inspectable record of Agent runs.",children:s.jsx(kt,{checked:!!K.keepAuditHistory,onChange:L("agent","keepAuditHistory"),label:"Keep Agent audit history"})}),s.jsx(ft,{icon:gn,title:"Stop Agent tasks after timeout",description:"Maximum runtime for one task.",children:s.jsx($i,{value:Number(K.timeoutMinutes),onChange:ve=>L("agent","timeoutMinutes")(Number(ve)),label:"Agent task timeout",options:[["1","1 minute"],["5","5 minutes"],["10","10 minutes"],["30","30 minutes"],["60","1 hour"]]})})]}),s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Detailed permissions"}),s.jsx("h3",{children:"Capabilities"})]}),s.jsx(Lt,{size:20})]}),[["allowProcessManagement","Allow process management"],["allowServiceManagement","Allow service management"],["allowFileChanges","Allow file changes"],["allowCommandExecution","Allow command execution"],["allowSoftwareInstallation","Allow software installation"],["allowPowerActions","Allow power actions"]].map(([ve,Se])=>s.jsx(ft,{icon:Lt,title:Se,description:ve.includes("allowCommand")||ve.includes("Installation")||ve.includes("Power")?"Disabled by default for safety.":"Applied by the Hub and checked again by the Client.",children:s.jsx(kt,{checked:!!K[ve],onChange:L("agent",ve),label:Se})},ve))]}),s.jsx("p",{className:"settings-help",children:"The existing Codex runtime and audit controls remain available below in Advanced and the Agent diagnostics panel."})]}),me=y==="connection"?U:y==="security"?W:y==="control"?ue:y==="wall"?be:y==="files-audio"?X:y==="agent"?s.jsxs(s.Fragment,{children:[$,v]}):s.jsxs("div",{className:"settings-tab-content product-settings-content",children:[g,s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Developer controls"}),s.jsx("h3",{children:"Streaming and diagnostics"})]}),s.jsx(Qd,{size:20})]}),s.jsx("p",{className:"settings-help",children:"Codec, frame rate, resolution, quality, Atlas layout, and decoder preferences are intentionally kept here."}),m,p]})]});return s.jsxs("section",{className:"settings-page",children:[s.jsx("div",{className:"settings-page-tabs",role:"tablist","aria-label":"LiveDesk settings",children:_j.map(({id:ve,label:Se,icon:Oe})=>s.jsxs("button",{className:y===ve?"active":"",id:`settings-tab-${ve}`,role:"tab","aria-selected":y===ve,"aria-controls":`settings-panel-${ve}`,tabIndex:y===ve?0:-1,onClick:()=>b(ve),type:"button",children:[s.jsx(Oe,{size:16}),Se]},ve))}),k&&s.jsx("div",{className:"agent-settings-alert error",role:"alert",children:k}),s.jsx("section",{className:"settings-page-panel",id:Q,role:"tabpanel","aria-labelledby":`settings-tab-${y}`,tabIndex:0,children:me})]})}function Ij({children:n}){return s.jsx("div",{className:"settings-tab-content",children:n})}function Oj({children:n}){return s.jsx("div",{className:"settings-tab-content",children:n})}function Hj({children:n}){return s.jsx("div",{className:"settings-tab-content",children:n})}const wb={enabled:!0,provider:"codex",codexModelId:"",codexReasoningEffort:"medium",codexTaskTimeoutMs:6e5,codexMaxToolCalls:20,codexWorkingDirectory:"",codexResumeSessions:!0,codexShowDetailedEvents:!0,deterministicParserFirst:!0,generateSummary:!0,fallbackSummary:!0,includeRawDeviceDetails:!1,baseUrl:"https://opencode.ai/zen/go/v1",defaultModelId:"deepseek-v4-flash"};function zx(n){return{...wb,...n||{}}}function Bj({hubUrl:n}){const[a,r]=u.useState(wb),[l,c]=u.useState(null),[d,m]=u.useState(""),[p,v]=u.useState(""),[g,w]=u.useState(""),[y,b]=u.useState("");u.useEffect(()=>{let L=!0;return Ge("/api/settings/agent",void 0,n).then(ae=>{L&&(c(ae.settings),r(zx(ae.settings)))}).catch(ae=>{L&&b(ae instanceof Error?ae.message:String(ae))}),()=>{L=!1}},[n]);const C=(L,ae)=>r(G=>({...G,[L]:ae})),j=L=>{c(L),r(zx(L))},A=async()=>{v("save"),b(""),w("");try{const L={...a};d.trim()&&(L.apiKey=d.trim());const ae=await Ge("/api/settings/agent",{method:"PUT",body:JSON.stringify(L)},n);j(ae.settings),m(""),w("Agent settings saved.")}catch(L){b(L instanceof Error?L.message:String(L))}finally{v("")}},N=async()=>{v("reset"),b("");try{const L=await Ge("/api/settings/agent/reset",{method:"POST",body:JSON.stringify({})},n);j(L.settings),w("Codex defaults restored.")}catch(L){b(L instanceof Error?L.message:String(L))}finally{v("")}},k=async()=>{v("test"),b(""),w("");try{const L=await Ge("/api/settings/agent/test",{method:"POST",body:JSON.stringify({})},n),ae=await Ge("/api/settings/agent",void 0,n);j(ae.settings),w(`Codex connection verified with ${L.connection?.modelName||"the configured model"}${L.connection?.latencyMs?` in ${L.connection.latencyMs} ms.`:"."}`)}catch(L){b(L instanceof Error?L.message:String(L))}finally{v("")}},T=async()=>{v("clear-key"),b("");try{const L=await Ge("/api/settings/agent/api-key",{method:"DELETE"},n);j(L.settings),m(""),w("The optional OpenCode Go key was removed.")}catch(L){b(L instanceof Error?L.message:String(L))}finally{v("")}},R=l?.codexInstallation==="installed"&&l.codexAuth==="signed-in",q=l?.securityStatus,O=q?.state||"unavailable",Y=O==="verified"?"Verified":O==="configured"?"Configured":"Unavailable",_=[["Codex home",q?.isolatedCodexHome],["Environment variables",q?.restrictedEnvironment],["LiveDesk MCP only",q?.livedeskMcpOnly],["Selected-device scope",q?.selectedDeviceScopeEnforced],["Fail-closed execution",q?.failClosed]];return s.jsxs("div",{className:"settings-tab-content agent-settings-content",children:[s.jsx("section",{className:"settings-section-card agent-enable-card",children:s.jsxs("label",{className:"settings-toggle agent-enable-toggle",children:[s.jsx("input",{type:"checkbox",checked:a.enabled,onChange:L=>C("enabled",L.target.checked)}),s.jsx("span",{children:"Enable Agent AI"})]})}),y&&s.jsx("div",{className:"agent-settings-alert error",role:"alert",children:y}),g&&s.jsx("div",{className:"agent-settings-alert success",role:"status",children:g}),s.jsxs("div",{className:"settings-section-grid",children:[s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Provider"}),s.jsx("h3",{children:"Codex is the default"})]}),s.jsx(_o,{size:20})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"Agent provider"}),s.jsxs("select",{value:a.provider,onChange:L=>C("provider",L.target.value),children:[s.jsx("option",{value:"codex",children:"Codex SDK"}),s.jsx("option",{value:"opencode-go",children:"OpenCode Go (optional legacy)"})]})]}),s.jsxs("div",{className:"agent-connection-row",children:[s.jsx("span",{className:`agent-connection-dot ${R?"connected":l?.codexAuth==="not-signed-in"?"unavailable":""}`}),s.jsx("span",{children:l?.codexInstallation==="not-installed"?"Codex SDK not installed":l?.codexAuth==="signed-in"?"Codex CLI signed in":l?.codexAuth==="not-signed-in"?"Codex CLI sign-in required":"Codex status not tested"}),s.jsxs("button",{className:"settings-reset",onClick:()=>{k()},disabled:p!==""||a.provider!=="codex",type:"button",children:[s.jsx(KS,{size:15})," ",p==="test"?"Testing":"Test connection"]})]}),s.jsxs("p",{className:"settings-help",children:[s.jsx(QS,{size:12})," Authentication is owned by the installed Codex CLI. LiveDesk never asks for or stores a ChatGPT token."]}),l?.codexPath&&s.jsxs("p",{className:"settings-help",children:["CLI: ",l.codexPath]})]}),s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Codex runtime"}),s.jsx("h3",{children:"Model and reasoning"})]}),s.jsx(XS,{size:20})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"Model"}),s.jsx("input",{value:a.codexModelId,onChange:L=>C("codexModelId",L.target.value),placeholder:"Codex default",disabled:a.provider!=="codex"})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"Reasoning effort"}),s.jsxs("select",{value:a.codexReasoningEffort,onChange:L=>C("codexReasoningEffort",L.target.value),disabled:a.provider!=="codex",children:[s.jsx("option",{value:"minimal",children:"Minimal"}),s.jsx("option",{value:"low",children:"Low"}),s.jsx("option",{value:"medium",children:"Medium"}),s.jsx("option",{value:"high",children:"High"}),s.jsx("option",{value:"xhigh",children:"Extra high"})]})]}),s.jsxs("div",{className:"settings-field-grid",children:[s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"Task timeout (ms)"}),s.jsx("input",{type:"number",min:"30000",max:"1800000",step:"10000",value:a.codexTaskTimeoutMs,onChange:L=>C("codexTaskTimeoutMs",Number(L.target.value)),disabled:a.provider!=="codex"})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"Max tool calls"}),s.jsx("input",{type:"number",min:"1",max:"100",value:a.codexMaxToolCalls,onChange:L=>C("codexMaxToolCalls",Number(L.target.value)),disabled:a.provider!=="codex"})]})]})]}),s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Workspace"}),s.jsx("h3",{children:"Restricted execution context"})]}),s.jsx(Lt,{size:20})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"Working directory"}),s.jsx("input",{value:l?.agentWorkspacePath||a.codexWorkingDirectory,readOnly:!0})]}),s.jsxs("label",{className:"settings-toggle",children:[s.jsx("input",{type:"checkbox",checked:a.codexResumeSessions,onChange:L=>C("codexResumeSessions",L.target.checked),disabled:a.provider!=="codex"}),s.jsx("span",{children:"Allow session resume"})]}),s.jsxs("label",{className:"settings-toggle",children:[s.jsx("input",{type:"checkbox",checked:a.codexShowDetailedEvents,onChange:L=>C("codexShowDetailedEvents",L.target.checked),disabled:a.provider!=="codex"}),s.jsx("span",{children:"Show detailed Codex events"})]}),s.jsx("p",{className:"settings-help",children:"The agent receives no project path or arbitrary filesystem directory. It can call LiveDesk MCP tools only."})]})]}),a.provider==="opencode-go"&&s.jsxs("section",{className:"settings-section-card agent-legacy-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Developer fallback"}),s.jsx("h3",{children:"OpenCode Go"})]}),s.jsx(_o,{size:20})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"Base URL"}),s.jsx("input",{value:a.baseUrl,onChange:L=>C("baseUrl",L.target.value)})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"API key"}),s.jsx("input",{type:"password",value:d,onChange:L=>m(L.target.value),placeholder:l?.hasApiKey?l.apiKeyPreview:"Stored only in the Hub",autoComplete:"new-password"})]}),s.jsxs("div",{className:"settings-action-row",children:[s.jsxs("button",{className:"settings-reset",onClick:()=>{T()},disabled:p!==""||!l?.hasApiKey,type:"button",children:[s.jsx(Xh,{size:15})," Clear key"]}),s.jsx("span",{className:"settings-help",children:"This provider does not run the Codex MCP tool loop."})]})]}),s.jsxs("div",{className:"settings-section-grid",children:[s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Agent behavior"}),s.jsx("h3",{children:"Predictable operation"})]}),s.jsx(Hn,{size:20})]}),s.jsxs("label",{className:"settings-toggle",children:[s.jsx("input",{type:"checkbox",checked:a.deterministicParserFirst,onChange:L=>C("deterministicParserFirst",L.target.checked)}),s.jsx("span",{children:"Use deterministic parser before Codex"})]}),s.jsxs("label",{className:"settings-toggle",children:[s.jsx("input",{type:"checkbox",checked:a.generateSummary,onChange:L=>C("generateSummary",L.target.checked)}),s.jsx("span",{children:"Generate task summaries"})]}),s.jsxs("label",{className:"settings-toggle",children:[s.jsx("input",{type:"checkbox",checked:a.fallbackSummary,onChange:L=>C("fallbackSummary",L.target.checked)}),s.jsx("span",{children:"Fallback to deterministic summaries"})]}),s.jsxs("label",{className:"settings-toggle",children:[s.jsx("input",{type:"checkbox",checked:a.includeRawDeviceDetails,onChange:L=>C("includeRawDeviceDetails",L.target.checked)}),s.jsx("span",{children:"Include raw device details in summaries"})]})]}),s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Safety"}),s.jsx("h3",{children:"Locked execution boundary"})]}),s.jsx(Lt,{size:20})]}),["Arbitrary shell commands","PowerShell and Bash","Filesystem writes, deletes, and installs","Reboot, shutdown, and process termination","Network access and web search"].map(L=>s.jsxs("div",{className:"agent-safety-row",children:[s.jsx(Yy,{size:15}),s.jsx("span",{children:L}),s.jsx("strong",{children:"Blocked"})]},L)),_.map(([L])=>s.jsxs("div",{className:"agent-safety-row",children:[s.jsx(Lt,{size:15}),s.jsx("span",{children:L}),s.jsx("strong",{className:O==="unavailable"?"agent-safety-failed":O==="configured"?"agent-safety-configured":"agent-safety-verified",children:Y})]},L)),s.jsx("p",{className:"settings-help",children:"Configured means the boundary is present but has not completed runtime verification. Test the connection or start an Agent run to verify it."})]})]}),s.jsxs("div",{className:"settings-action-row agent-settings-actions",children:[s.jsxs("button",{className:"settings-reset",onClick:()=>{N()},disabled:p!=="",type:"button",children:[s.jsx($c,{size:15})," Reset defaults"]}),s.jsxs("button",{className:"text-button primary",onClick:()=>{A()},disabled:p!=="",type:"button",children:[s.jsx(Ky,{size:15})," ",p==="save"?"Saving":"Save Agent settings"]})]})]})}new Date().valueOf();function oi(n){const[a,r]=u.useState(n),l=u.useRef(n);return u.useEffect(()=>{if(l.current!==n){if(Array.isArray(l.current)&&Array.isArray(n)&&l.current.length===0&&n.length===0)return;l.current=n,r(n)}},[n]),[a,r]}function ip(n,a){return typeof n=="function"?typeof a=="object"?n(a):n():n}function Bo(n,a="data-id"){let r=n;for(!r.tagName&&n.target&&(r=n.target);r;){if(r.getAttribute&&r.getAttribute(a))return r;r=r.parentNode}return null}function Fj(n,a="data-id"){const r=Bo(n,a);return r?r.getAttribute(a):null}function Jc(n,a="data-id"){const r=Bo(n,a);return r?hf(r,a):null}function hf(n,a="data-id"){const r=n.getAttribute(a);return r?Pj(r):null}function Bn(n){return typeof n=="string"?":"+n:n}function Pj(n){if(n.startsWith(":"))return n.substring(1);const a=n*1;return isNaN(a)?n:a}function $j(){return{detect:()=>!0,addEvent:function(n,a,r){return n.addEventListener(a,r),()=>n.removeEventListener(a,r)},addGlobalEvent:function(n,a){return document.addEventListener(n,a),()=>document.removeEventListener(n,a)},getTopNode:function(){return window.document.body}}}var Ba=$j();function rp(n){Object.assign(Ba,n)}function Ix(n,a,r){function l(c){const d=Bo(c);if(!d)return;const m=hf(d);if(typeof a=="function")return a(m,c);let p,v=c.target;for(;v!=d;){if(p=v.dataset?v.dataset.action:null,p&&a[p]){a[p](m,c);return}v=v.parentNode}a[r]&&a[r](m,c)}Ba.addEvent(n,r,l)}function Fo(n,a){Ix(n,a,"click"),a.dblclick&&Ix(n,a.dblclick,"dblclick")}function Uj(n,a){for(let r=n.length-1;r>=0;r--)if(n[r]===a){n.splice(r,1);break}}function qj(n,a,r){for(let l=0;l<Vi.length;l++){if(l===r)continue;const c=Vi[l],d=c.props.parent?.();if(d&&n.contains(d)&&c.node.contains(a))return!0}return!1}var Sb=new Date,af=!1,Ad=[],Vi=[],Ox=n=>{const a=n.target;if(af||!a.isConnected){af=!1;return}for(let r=Vi.length-1;r>=0;r--){const{node:l,date:c,props:d}=Vi[r];if(!(c>Sb)&&!l.contains(a)&&l!==a&&(qj(l,a,r)||(d.callback&&d.callback(n),d.modal||n.defaultPrevented)))break}},Gj=n=>{Sb=new Date,af=!0;for(let a=Vi.length-1;a>=0;a--){const{node:r}=Vi[a];if(!r.contains(n.target)&&r!==n.target){af=!1;break}}};function ci(n,a){Ad.length||(Ad=[Ba.addGlobalEvent("click",Ox,n),Ba.addGlobalEvent("contextmenu",Ox,n),Ba.addGlobalEvent("mousedown",Gj,n)]),typeof a!="object"&&(a={callback:a});const r={node:n,date:new Date,props:a};return Vi.push(r),{destroy(){Uj(Vi,r),Vi.length||(Ad.forEach(l=>l()),Ad=[])}}}var Nd=n=>n.indexOf("bottom")!==-1,Md=n=>n.indexOf("left")!==-1,Td=n=>n.indexOf("right")!==-1,sh=n=>n.indexOf("top")!==-1,Hx=n=>n.indexOf("fit")!==-1,Ic=n=>n.indexOf("overlap")!==-1,Vj=n=>n.split("-").every(a=>["center","fit"].indexOf(a)>-1),Wj=n=>{const a=n.match(/(start|center|end)/);return a?a[0]:null};function Yj(n,a){let r=0;const l=Ba.getTopNode(n);for(;n&&n!==l;){const c=getComputedStyle(n).position;if((c==="absolute"||c==="relative"||c==="fixed")&&(r=parseInt(getComputedStyle(n).zIndex)||0),n=n.parentNode,n===a)break}return r}var Mn,ra,Oc,Qn;function Cb(n,a,r="bottom",l=0,c=0){if(!n)return null;Mn=l,ra=c,Oc="auto";let d=0,m=0,p=r;const v=jb(n),g=Ic(r)?Ba.getTopNode(n):v;if(!v)return null;const w=v.getBoundingClientRect(),y=n.getBoundingClientRect(),b=g.getBoundingClientRect(),C=window.getComputedStyle(g),j={left:0,top:0,bottom:0,right:0};for(const q in j){const O=`border-${q}-width`;j[q]=parseFloat(C.getPropertyValue(O))}if(a){const q=Yj(a,v);d=Math.max(q+1,20)}if(a){if(Qn=a.getBoundingClientRect(),Hx(r)&&(Oc=Qn.width+"px"),r!=="point")if(Vj(r))Hx(r)?Mn=0:(Mn=b.width/2,m=1),ra=(b.height-y.height)/2;else{const q=Ic(r)?0:1;Mn=Td(r)?Qn.right+q:Qn.left-q,ra=Nd(r)?Qn.bottom+1:Qn.top;const O=Wj(r);O&&(Td(r)||Md(r)?O==="center"?ra-=(y.height-Qn.height)/2:O==="end"&&(ra-=y.height-Qn.height):(Nd(r)||sh(r))&&(O==="center"?Mn-=(y.width-Qn.width)/2:O==="end"&&(Mn-=y.width-Qn.width),Ic(r)||(Mn+=1)))}}else Qn={left:l,right:l,top:c,bottom:c};const A=(Md(r)||Td(r))&&(Nd(r)||sh(r));Md(r)&&(m=2);const N=Mn-y.width-b.left;a&&Md(r)&&!A&&N<0&&(Mn=Qn.right,m=0,p=p.replace("left","right"));const k=Mn+y.width*(1-m/2)-b.right;if(k>0)if(!Td(r))Mn=b.right-j.right-y.width;else{const q=Qn.left-b.x-y.width;a&&!A&&q>=0?(Mn=Qn.left-y.width,p=p.replace("right","left")):Mn-=k+j.right}m&&(Mn=Math.round(Mn-y.width*m/2));const T=N<0||k>0||!A;sh(r)&&(ra=Qn.top-y.height,a&&ra<b.y&&T&&(ra=Qn.bottom,p=p.replace("top","bottom")));const R=ra+y.height-b.bottom;return R>0&&(a&&Nd(r)&&T?(ra-=y.height+Qn.height+1,p=p.replace("bottom","top")):ra-=R+j.bottom),Mn-=w.left+j.left,ra-=w.top+j.top,Mn=(Ic(r)?Mn:Math.max(Mn,0))+g.scrollLeft,ra=(Ic(r)?ra:Math.max(ra,0))+g.scrollTop,Oc=Oc||"auto",{at:p,x:Mn,y:ra,z:d,width:Oc}}function jb(n){const a=Ba.getTopNode(n);for(n&&(n=n.parentElement);n;){const r=getComputedStyle(n).position;if(n===a||r==="relative"||r==="absolute"||r==="fixed")return n;n=n.parentNode}return null}function Kj(n){const a=[];let r=n;const l=Ba.getTopNode(n);for(;r&&r!==l&&!r.getAttribute("data-wx-portal-root");)getComputedStyle(r).position==="absolute"&&a.push(r),r=r.parentNode;return a}var Bx=new Date().valueOf();function lp(){return Bx+=1,Bx}function oa(n){return n<10?"0"+n:n.toString()}function Qj(n){const a=oa(n);return a.length==2?"0"+a:a}function kb(n){const a=Math.floor(n/11)*11;return{start:a,end:a+11}}function ih(n){const a=(n.getDay()+6)%7,r=new Date(n.valueOf());r.setDate(n.getDate()+(3-a)),r.setHours(0,0,0,0);const l=new Date(r.getFullYear(),0,1),c=Math.round((r.getTime()-l.getTime())/864e5);return 1+Math.floor(c/7)}var Fx=["",""];function Xj(n,a,r){switch(n){case"%d":return oa(a.getDate());case"%m":return oa(a.getMonth()+1);case"%j":return a.getDate();case"%n":return a.getMonth()+1;case"%y":return oa(a.getFullYear()%100);case"%Y":return a.getFullYear();case"%D":return r.dayShort[a.getDay()];case"%l":return r.dayFull[a.getDay()];case"%M":return r.monthShort[a.getMonth()];case"%F":return r.monthFull[a.getMonth()];case"%h":return oa((a.getHours()+11)%12+1);case"%g":return(a.getHours()+11)%12+1;case"%G":return a.getHours();case"%H":return oa(a.getHours());case"%i":return oa(a.getMinutes());case"%a":return((a.getHours()>11?r.pm:r.am)||Fx)[0];case"%A":return((a.getHours()>11?r.pm:r.am)||Fx)[1];case"%s":return oa(a.getSeconds());case"%S":return Qj(a.getMilliseconds());case"%W":return oa(ih(a));case"%w":{const l=r.weekStart??1;if(l===1)return oa(ih(a));const c=(a.getDay()-l+7)%7,d=(1-l+7)%7,m=new Date(a.valueOf());return m.setDate(a.getDate()+(d-c)),oa(ih(m))}case"%c":{let l=a.getFullYear()+"";return l+="-"+oa(a.getMonth()+1),l+="-"+oa(a.getDate()),l+="T",l+=oa(a.getHours()),l+=":"+oa(a.getMinutes()),l+=":"+oa(a.getSeconds()),l}case"%Q":return Math.floor(a.getMonth()/3)+1;default:return n}}var Zj=/%[a-zA-Z]/g;function zo(n,a){return typeof n=="function"?n:function(r){return r?(r.getMonth||(r=new Date(r)),n.replace(Zj,l=>Xj(l,r,a))):""}}function Px(n){return n&&typeof n=="object"&&!Array.isArray(n)}function Oh(n,a){for(const r in a){const l=a[r];Px(n[r])&&Px(l)?n[r]=Oh({...n[r]},a[r]):n[r]=a[r]}return n}function tu(n){return{getGroup(a){const r=n[a];return l=>r&&r[l]||l},getRaw(){return n},extend(a,r){if(!a)return this;let l;return r?l=Oh({...a},n):l=Oh({...n},a),tu(l)}}}var Jj=eb();const ek="en-US",tk={monthFull:["January","February","March","April","May","June","July","August","September","October","November","December"],monthShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayFull:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],hours:"Hours",minutes:"Minutes",done:"Done",clear:"Clear",today:"Today",am:["am","AM"],pm:["pm","PM"],weekStart:0,clockFormat:24},nk={ok:"OK",cancel:"Cancel",select:"Select","No data":"No data","Rows per page":"Rows per page","Total pages":"Total pages"},ak={timeFormat:"%H:%i",dateFormat:"%m/%d/%Y",monthYearFormat:"%F %Y",yearFormat:"%Y"},Ab={core:nk,calendar:tk,formats:ak,lang:ek},op=u.createContext(""),Nb=u.createContext({}),zs=u.createContext(null),Mb=u.createContext(null),Pn=Object.freeze(Object.defineProperty({__proto__:null,fieldId:Mb,helpers:Nb,i18n:zs,theme:op},Symbol.toStringTag,{value:"Module"}));function Tb(n){const a=u.useContext(Mb),[r]=u.useState(()=>n||a||lp());return r}function Vc({type:n="",css:a="",icon:r="",disabled:l=!1,title:c="",tooltip:d,text:m="",children:p,onClick:v}){const g=u.useMemo(()=>{let y=n?n.split(" ").filter(b=>b!=="").map(b=>"wx-"+b).join(" "):"";return a+(a?" ":"")+y},[n,a]),w=y=>{v&&v(y)};return s.jsxs("button",{title:c,className:`wx-2ZWgb4 wx-button ${g} ${r&&!p?"wx-icon":""}`,disabled:l,onClick:w,"data-tooltip-text":d,children:[r&&s.jsx("i",{className:"wx-2ZWgb4 "+r}),p||m||" "]})}function sk({id:n,label:a="",inputValue:r="",value:l=!1,onChange:c,disabled:d=!1,css:m=""}){const p=Tb(n),[v,g]=oi(l),w=({target:y})=>{const b=y.checked;g(b),c&&c({value:b,inputValue:r})};return s.jsxs("div",{className:`wx-2IvefP wx-checkbox ${m}`,children:[s.jsx("input",{type:"checkbox",id:p,disabled:d,className:"wx-2IvefP wx-check",checked:v,value:r,onChange:w}),s.jsxs("label",{htmlFor:p,className:"wx-2IvefP wx-label",children:[s.jsx("span",{className:"wx-2IvefP wx-before"}),a&&s.jsx("span",{className:"wx-2IvefP wx-after",children:a})]})]})}function cp({theme:n="",target:a,children:r}){const l=u.useRef(null),c=u.useRef(null),[d,m]=u.useState(null);l.current||(l.current=document.createElement("div"));const p=u.useContext(op);return u.useEffect(()=>{m(a||ik(c.current)||Ba.getTopNode(c.current))},[c.current]),s.jsxs(s.Fragment,{children:[s.jsx("span",{ref:c,style:{display:"none"}}),c.current&&d?Jj.createPortal(s.jsx("div",{className:`wx-3ZWsT0 wx-${n||p}-theme`,children:r}),d):null]})}function ik(n){const a=Ba.getTopNode(n);for(;n&&n!==a&&!n.getAttribute("data-wx-portal-root");)n=n.parentNode;return n}function rk({left:n=0,top:a=0,at:r="bottom",parent:l=null,width:c="auto",css:d="",onCancel:m,children:p,trackScroll:v=!1}){const[g,w]=u.useState(0),[y,b]=u.useState(0),[C,j]=u.useState("auto"),[A,N]=u.useState(!1),k=u.useRef(null),T=u.useRef(null),R=u.useRef(m);u.useEffect(()=>{R.current=m},[m]);function q(Y){return l&&(c+"").indexOf("%")>-1?c.replace(/(\d+)%/,(_,L)=>(L=L*l.offsetWidth/100+"px",c.replace(_,L))):c&&c!=="auto"?c:Y}const O=u.useCallback(()=>{if(!k.current)return;const Y=Cb(k.current,l,r,n,a);Y&&(w(Y.x),b(Y.y),j(q(Y.width)))},[k,l,r,n,a,c]);return u.useLayoutEffect(()=>{const Y=L=>{R.current&&L.target!==T.current&&k.current&&!k.current.contains(L.target)&&R.current(L)};let _;return requestAnimationFrame(()=>{O(),N(!0),v&&k.current&&(T.current=jb(k.current),T.current&&T.current.addEventListener("scroll",Y,!0)),l&&(_=new ResizeObserver(O),_.observe(l))}),()=>{v&&T.current&&T.current.removeEventListener("scroll",Y,!0),_?.disconnect()}},[]),u.useLayoutEffect(()=>{O()},[l,r,n,a]),u.useEffect(()=>{const Y=_=>{R.current&&R.current(_)};if(k.current)return ci(k.current,{callback:Y,parent:()=>l}).destroy},[l]),s.jsx("div",{ref:k,className:["wx-37M6Fj","wx-popup",d].filter(Boolean).join(" "),style:{position:"absolute",visibility:A?"visible":"hidden",top:y+"px",left:g+"px",width:C},children:p})}function lk({position:n="bottom",align:a="start",autoFit:r=!0,onCancel:l=null,width:c="100%",css:d="",children:m}){const p=u.useRef(null),[v,g]=u.useState(n),[w,y]=u.useState(a),b=u.useRef(l);return u.useEffect(()=>{b.current=l},[l]),u.useEffect(()=>{if(r){const C=p.current;if(C){const j=C.getBoundingClientRect(),A=document.body.getBoundingClientRect();j.right>=A.right&&y("end"),j.bottom>=A.bottom&&g("top")}}},[]),u.useEffect(()=>{if(p.current){const C=j=>{b.current&&b.current(j)};return ci(p.current,C).destroy}},[]),s.jsx("div",{ref:p,className:["wx-dropdown",`wx-${v}-${w}`,d||"","wx-aaaVytZW"].filter(Boolean).join(" "),style:{width:c},children:m})}function up({position:n="bottom",align:a="start",autoFit:r=!0,inline:l=!1,onCancel:c,width:d="100%",children:m,...p}){const[v,g]=u.useState(void 0),w=u.useRef(null),y=u.useMemo(()=>`${n}-${a}`,[n,a]);return u.useLayoutEffect(()=>{w.current&&g(w.current.parentNode)},[]),s.jsxs(s.Fragment,{children:[v&&(l?s.jsx(lk,{onCancel:c,position:n,align:a,autoFit:r,width:d,...p,children:m}):s.jsx(cp,{children:s.jsx(rk,{parent:v,at:y,onCancel:c,width:d,...p,children:m})})),s.jsx("span",{ref:w,className:"wx-portal-node wx-32GZ52"})]})}function pf(){return tu(Ab)}function ok(){let n=null,a=!1,r=!1,l,c,d,m;const p=(y,b,C,j,A)=>{l=y,c=b,d=C,m=j,r=A},v=y=>{n=y,a=n!==null,d(n)},g=(y,b)=>{if(!r&&y!==null&&l){const C=l.querySelectorAll(".wx-list > .wx-item")[y];C&&(C.scrollIntoView({block:"nearest"}),b&&b.preventDefault())}},w=(y,b)=>{const C=y===null?null:Math.max(0,Math.min(n+y,c.length-1));C!==n&&(v(C),l?g(C,b):requestAnimationFrame(()=>g(C,b)))};return{move:y=>{const b=Jc(y),C=c.findIndex(j=>j.id===b);C!==n&&v(C)},keydown:(y,b)=>{switch(y.code){case"Enter":a?m():v(0);break;case"Space":a||v(0);break;case"Escape":d(n=null);break;case"Tab":d(n=null);break;case"ArrowDown":w(a?1:b||0,y);break;case"ArrowUp":w(a?-1:b||0,y);break}},init:p,navigate:w}}const $x=10,ck=u.memo(function({data:n,checkboxes:a,itemTemplate:r,value:l}){return s.jsxs(s.Fragment,{children:[a&&s.jsx(sk,{id:n.id,css:"wx-list-checkbox",value:l&&l.includes(n.id)}),r?ip(r,{option:n}):n.label]})});function Ux({visibleItems:n,visibleRange:a,navIndex:r,checkboxes:l,itemTemplate:c,value:d,measureRefCallback:m}){return n.map((p,v)=>{const g=a.start+v;return s.jsx("div",{ref:v===0?m:void 0,className:`wx-233fr7 wx-item ${g===r?"wx-focus":""}`,"data-id":p.id,children:s.jsx(ck,{data:p,checkboxes:l,itemTemplate:c,value:d})},p.id)})}function gf({items:n=[],children:a,onSelect:r,onReady:l,virtualized:c=!1,checkboxes:d,multiselect:m,value:p,...v}){const g=u.useRef(),w=u.useRef(!1),y=u.useRef(ok()),[b,C]=u.useState(null),j=u.useRef(b),[A,N]=u.useState(0),[k,T]=u.useState(24),R=u.useRef(!1),q=(u.useContext(zs)||pf()).getGroup("core"),O=u.useRef(n);u.useEffect(()=>{O.current=n},[n]);const Y=u.useRef(p);u.useEffect(()=>{Y.current=p},[p]);const _=u.useRef(0);u.useEffect(()=>{_.current=k},[k]);const L=u.useCallback(X=>{X&&X.stopPropagation();const $=O.current,de=Y.current,me=j.current;let ve;const Se=$[me]?.id;m?de&&de.includes(Se)?ve=de.filter(Oe=>Oe!==Se):ve=[...de||[],Se]:ve=Se,r&&r({id:ve})},[m,r]),ae=u.useRef(L);u.useEffect(()=>{ae.current=L},[L]);const G=u.useCallback(X=>{if(g.current){let $=X*_.current-g.current.clientHeight+_.current;N($),g.current.scrollTop=$}},[_.current]),te=u.useCallback(X=>{g.current=X,c&&(X&&!w.current&&j.current!==null&&requestAnimationFrame(()=>{g.current&&(G(j.current),w.current=!0)}),X||(w.current=!1))},[G]),P=u.useCallback(X=>{if(!X||R.current)return;const $=X.getBoundingClientRect().height;$&&(T($),_.current=$,R.current=!0)},[]);u.useEffect(()=>{y.current.init(g.current,n,X=>{C(X),j.current=X},X=>ae.current(X),c)},[n,g.current,c]),u.useEffect(()=>{const X=(de,me)=>{y.current.navigate(de,me),G(j.current)},$=(de,me)=>{const ve=j.current,Se=O.current;if(ve!==0&&ve!==Se.length-1&&(de.key==="ArrowDown"||de.key==="ArrowUp")&&de.preventDefault(),y.current.keydown(de,me),g.current){const Oe=g.current.scrollTop<=j.current*_.current,le=g.current.scrollTop+g.current.clientHeight>=j.current*_.current+_.current;Oe?le||G(j.current):(g.current.scrollTop=j.current*_.current,N(g.current.scrollTop))}};l&&l({navigate:c?X:y.current.navigate,keydown:c?$:y.current.keydown,move:y.current.move})},[]);const ye=u.useRef(0),ie=u.useRef(n);ie.current!==n&&(ie.current=n,ye.current+=1);const K=u.useCallback(()=>{y.current.navigate(null)},[y]),I=u.useCallback(X=>{c&&N(X.target.scrollTop)},[c]),Q=u.useMemo(()=>Math.ceil((g.current?.clientHeight||0)/k),[k,A]),U=u.useMemo(()=>{if(!c)return{start:0,end:n.length};if(!n.length)return{start:0,end:0};const X=Math.floor(A/k),$=X+Q;return{start:Math.max(0,X-$x),end:Math.min(n.length,$+$x)}},[c,n,A,k,Q]),W=u.useMemo(()=>{if(!c)return n;const{start:X,end:$}=U;return n.slice(X,$).map(de=>({...de}))},[c,n,U]),ue=U.start*k,be=n.length*k;return u.useEffect(()=>{c&&N(0)},[n,c]),u.useEffect(()=>{b===null&&(w.current=!1)},[b]),b===null?null:s.jsx(up,{onCancel:K,...v,children:s.jsx("div",{className:"wx-233fr7 wx-list",ref:te,onClick:L,onMouseMove:y.current.move,onScroll:I,children:n.length?c?s.jsx("div",{className:"wx-233fr7 wx-list-wrapper",style:{height:`${be}px`},children:s.jsx("div",{className:"wx-233fr7 wx-list-content",style:{transform:`translateY(${ue}px)`},children:s.jsx(Ux,{visibleRange:U,visibleItems:W,navIndex:b,measureRefCallback:P,checkboxes:d,itemTemplate:a,value:p})})}):s.jsx(Ux,{visibleRange:U,visibleItems:W,navIndex:b,measureRefCallback:P,checkboxes:d,itemTemplate:a,value:p}):s.jsx("div",{className:"wx-233fr7 wx-no-data",children:q("No data")})})},ye.current)}function dp({value:n="",id:a,readonly:r=!1,focus:l=!1,select:c=!1,type:d="text",placeholder:m="",disabled:p=!1,error:v=!1,title:g="",tooltip:w,css:y="",icon:b="",clear:C=!1,onChange:j}){const A=Tb(a),[N,k]=oi(n),T=u.useRef(null),R=u.useMemo(()=>b&&y.indexOf("wx-icon-left")===-1?"wx-icon-right "+y:y,[b,y]),q=u.useMemo(()=>b&&y.indexOf("wx-icon-left")!==-1,[b,y]);u.useEffect(()=>{const ae=setTimeout(()=>{l&&T.current&&T.current.focus(),c&&T.current&&T.current.select()},1);return()=>clearTimeout(ae)},[l,c]);const O=u.useCallback(ae=>{const G=ae.target.value;k(G),j&&j({value:G,input:!0})},[j]),Y=u.useCallback(ae=>j&&j({value:ae.target.value}),[j]);function _(ae){ae.stopPropagation(),k(""),j&&j({value:""})}let L=d;return d!=="password"&&d!=="number"&&(L="text"),u.useEffect(()=>{const ae=Y,G=T.current;return G.addEventListener("change",ae),()=>{G&&G.removeEventListener("change",ae)}},[Y]),s.jsxs("div",{className:`wx-hQ64J4 wx-text ${R} ${v?"wx-error":""} ${p?"wx-disabled":""} ${C?"wx-clear":""}`,"data-tooltip-text":w,children:[s.jsx("input",{className:"wx-hQ64J4 wx-input",ref:T,id:A,readOnly:r,disabled:p,placeholder:m,type:L,title:g,value:N,onInput:O}),C&&!p&&N?s.jsxs(s.Fragment,{children:[s.jsx("i",{className:"wx-hQ64J4 wx-icon wxi-close",onClick:_}),q&&s.jsx("i",{className:`wx-hQ64J4 wx-icon ${b}`})]}):b?s.jsx("i",{className:`wx-hQ64J4 wx-icon ${b}`}):null]})}function uk({date:n,type:a,part:r,onShift:l}){const{calendar:c,formats:d}=u.useContext(zs).getRaw(),m=n.getFullYear(),p=u.useMemo(()=>{switch(a){case"month":return zo(d.monthYearFormat,c)(n);case"year":return zo(d.yearFormat,c)(n);case"duodecade":{const{start:g,end:w}=kb(m),y=zo(d.yearFormat,c);return`${y(new Date(g,0,1))} - ${y(new Date(w,11,31))}`}default:return""}},[n,a,m,c,d]);function v(){l&&l({diff:0,type:a})}return s.jsxs("div",{className:"wx-8HQVQV wx-header",children:[r!=="right"?s.jsx("i",{className:"wx-8HQVQV wx-pager wxi-angle-left",onClick:()=>l&&l({diff:-1,type:a})}):s.jsx("span",{className:"wx-8HQVQV wx-spacer"}),s.jsx("span",{className:"wx-8HQVQV wx-label",onClick:v,children:p}),r!=="left"?s.jsx("i",{className:"wx-8HQVQV wx-pager wxi-angle-right",onClick:()=>l&&l({diff:1,type:a})}):s.jsx("span",{className:"wx-8HQVQV wx-spacer"})]})}function fp({onClick:n,children:a}){return s.jsx("button",{className:"wx-3s8W4d wx-button",onClick:n,children:a})}function dk({value:n,current:a,part:r="",markers:l=null,css:c="",onCancel:d,onChange:m}){const p=(u.useContext(zs)||pf()).getRaw().calendar,v=(p.weekStart||7)%7,g=p.dayShort.slice(v).concat(p.dayShort.slice(0,v)),w=(O,Y,_)=>new Date(O.getFullYear(),O.getMonth()+(Y||0),O.getDate()+(_||0));let y=r!=="normal";function b(O){const Y=O.getDay();return Y===0||Y===6}function C(){const O=w(a,0,1-a.getDate());return O.setDate(O.getDate()-(O.getDay()-(v-7))%7),O}function j(){const O=w(a,1,-a.getDate());return O.setDate(O.getDate()+(6-O.getDay()+v)%7),O}const A=u.useRef(0);function N(O,Y){Y.timeStamp!==A.current&&(A.current=Y.timeStamp,Y.stopPropagation(),m&&m(new Date(O)),d&&d())}const k=u.useMemo(()=>r=="normal"?[n?w(n).valueOf():0]:n?[n.start?w(n.start).valueOf():0,n.end?w(n.end).valueOf():0]:[0,0],[r,n]),T=u.useMemo(()=>{const O=C(),Y=j(),_=a.getMonth();let L=[];for(let ae=O;ae<=Y;ae.setDate(ae.getDate()+1)){const G={day:ae.getDate(),in:ae.getMonth()===_,date:ae.valueOf()};let te="";if(te+=G.in?"":" wx-inactive",te+=k.indexOf(G.date)>-1?" wx-selected":"",y){const P=G.date==k[0],ye=G.date==k[1];P&&!ye?te+=" wx-left":ye&&!P&&(te+=" wx-right"),G.date>k[0]&&G.date<k[1]&&(te+=" wx-inrange")}if(te+=b(ae)?" wx-weekend":"",l){const P=l(ae);P&&(te+=" "+P)}L.push({...G,css:te})}return L},[a,k,y,l]),R=u.useRef(null);let q=u.useRef({});return q.current.click=N,u.useEffect(()=>{Fo(R.current,q.current)},[]),s.jsxs("div",{className:`wx-398RBS wx-month ${c}`,children:[s.jsx("div",{className:"wx-398RBS wx-weekdays",children:g.map(O=>s.jsx("div",{className:"wx-398RBS wx-weekday",children:O},O))}),s.jsx("div",{className:"wx-398RBS wx-days",ref:R,children:T.map(O=>s.jsx("div",{className:`wx-398RBS wx-day ${O.css} ${O.in?"":"wx-out"}`,"data-id":O.date,children:O.day},O.date))})]})}function fk({value:n,current:a,part:r,onCancel:l,onChange:c,onShift:d}){const m=u.useRef(new Date),[p,v]=oi(n||m.current),[g,w]=oi(a||m.current),y=u.useContext(zs).getRaw().calendar,b=y.monthShort||[],C=u.useMemo(()=>g.getMonth(),[g]),j=u.useCallback((k,T)=>{if(k!=null){T.stopPropagation();const R=new Date(g);R.setMonth(k),w(R),d&&d({current:R})}r==="normal"&&v(new Date(g)),l&&l()},[g,r,d,l]),A=u.useCallback(()=>{const k=new Date(Eb(p,r)||g);k.setMonth(g.getMonth()),k.setFullYear(g.getFullYear()),c&&c(k)},[p,g,r,c]),N=u.useCallback(k=>{const T=k.target.closest("[data-id]");if(T){const R=parseInt(T.getAttribute("data-id"),10);j(R,k)}},[j]);return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"wx-34U8T8 wx-months",onClick:N,children:b.map((k,T)=>s.jsx("div",{className:"wx-34U8T8 wx-month"+(C===T?" wx-current":""),"data-id":T,children:k},T))}),s.jsx("div",{className:"wx-34U8T8 wx-buttons",children:s.jsx(fp,{onClick:A,children:y.done})})]})}const rh="wx-1XEF33",mk=({value:n,current:a,onCancel:r,onChange:l,onShift:c,part:d})=>{const m=u.useContext(zs).getRaw().calendar,[p,v]=oi(a),[g,w]=oi(n),y=u.useMemo(()=>p.getFullYear(),[p]),b=u.useMemo(()=>{const{start:k,end:T}=kb(y),R=[];for(let q=k;q<=T;++q)R.push(q);return R},[y]),C={click:j};function j(k,T){if(k){T.stopPropagation();const R=new Date(p);R.setFullYear(k),v(R),c&&c({current:R})}d==="normal"&&w(new Date(p)),r&&r()}function A(){const k=new Date(Eb(g,d)||p);k.setFullYear(p.getFullYear()),l&&l(k)}const N=u.useRef(null);return u.useEffect(()=>{N.current&&Fo(N.current,C)},[]),s.jsxs(s.Fragment,{children:[s.jsx("div",{className:rh+" wx-years",ref:N,children:b.map((k,T)=>s.jsx("div",{className:rh+` wx-year ${y==k?"wx-current":""} ${T===0?"wx-prev-decade":""} ${T===11?"wx-next-decade":""}`,"data-id":k,children:k},T))}),s.jsx("div",{className:rh+" wx-buttons",children:s.jsx(fp,{onClick:A,children:m.done})})]})},qx={month:{component:dk,next:pk,prev:hk},year:{component:fk,next:vk,prev:gk},duodecade:{component:mk,next:yk,prev:xk}};function hk(n){return n=new Date(n),n.setMonth(n.getMonth()-1),n}function pk(n){return n=new Date(n),n.setMonth(n.getMonth()+1),n}function gk(n){return n=new Date(n),n.setFullYear(n.getFullYear()-1),n}function vk(n){return n=new Date(n),n.setFullYear(n.getFullYear()+1),n}function xk(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 Eb(n,a){let r;if(a==="normal")r=n;else{const{start:l,end:c}=n;a==="left"?r=l:a=="right"?r=c:r=l&&c}return r}const bk=["clear","today"];function wk(n){if(n==="done")return-1;if(n==="clear")return null;if(n==="today")return new Date}function Sk({value:n,current:a,onCurrentChange:r,part:l="normal",markers:c=null,buttons:d,css:m="",onShift:p,onChange:v}){const g=u.useContext(zs).getGroup("calendar"),[w,y]=u.useState("month"),b=Array.isArray(d)?d:d?bk:[],C=(T,R)=>{T.preventDefault(),v&&v({value:R})},j=()=>{w==="duodecade"?y("year"):w==="year"&&y("month")},A=T=>{const{diff:R,current:q}=T;if(R===0){w==="month"?y("year"):w==="year"&&y("duodecade");return}if(R){const O=qx[w];r(R>0?O.next(a):O.prev(a))}else q&&r(q);p&&p()},N=T=>{y("month"),v&&v({select:!0,value:T})},k=u.useMemo(()=>qx[w].component,[w]);return s.jsx("div",{className:`wx-2Gr4AS wx-calendar ${l!=="normal"&&l!=="both"?"wx-part":""} ${m}`,children:s.jsxs("div",{className:"wx-2Gr4AS wx-wrap",children:[s.jsx(uk,{date:a,part:l,type:w,onShift:A}),s.jsxs("div",{children:[s.jsx(k,{value:n,current:a,onCurrentChange:r,part:l,markers:c,onCancel:j,onChange:N,onShift:A}),w==="month"&&b.length>0&&s.jsx("div",{className:"wx-2Gr4AS wx-buttons",children:b.map(T=>s.jsx("div",{className:"wx-2Gr4AS wx-button-item",children:s.jsx(fp,{onClick:R=>C(R,wk(T)),children:g(T)})},T))})]})]})})}function mp(n){let{words:a=null,optional:r=!1,children:l}=n,c=u.useContext(zs);const d=u.useMemo(()=>{let m=c;return(!m||!m.extend)&&(m=tu(Ab)),a!==null&&(m=m.extend(a,r)),m},[a,r,c]);return s.jsx(zs.Provider,{value:d,children:l})}function Gx(n,a,r,l){if(!n||l){const c=a?new Date(a):new Date;c.setDate(1),r(c)}else if(n.getDate()!==1){const c=new Date(n);c.setDate(1),r(c)}}const Ck=["clear","today"];function Rb({value:n,current:a,markers:r=null,buttons:l=Ck,css:c="",onChange:d}){const[m,p]=oi(n),[v,g]=oi(a);u.useEffect(()=>{Gx(v,m,g,!1)},[m,v]);const w=u.useCallback(b=>{const C=b.value;C?(p(new Date(C)),Gx(v,new Date(C),g,!0)):p(null),d&&d({value:C?new Date(C):null})},[d,v]),y=u.useCallback(b=>{g(b)},[g]);return v?s.jsx(mp,{children:s.jsx(Sk,{value:m,current:v,markers:r,buttons:l,css:c,onChange:w,onCurrentChange:y})}):null}function jk(n){return n||(n={}),n.width||(n.width="unset"),n}const kk=["clear","today"];function Ak({value:n,id:a,disabled:r=!1,error:l=!1,placeholder:c="",format:d="",buttons:m=kk,css:p="",title:v="",tooltip:g,editable:w=!1,clear:y=!1,onChange:b,dropdown:C={}}){const{calendar:j,formats:A}=(u.useContext(zs)||pf()).getRaw(),N=d||A?.dateFormat;let k=typeof N=="function"?N:zo(N,j);const[T,R]=u.useState(n),[q,O]=u.useState(!1);u.useEffect(()=>{R(n)},[n]);function Y(){O(!1)}function _(G){const te=G===T||G&&T&&G.valueOf()===T.valueOf()||!G&&!T;R(G),te||b&&b({value:G}),setTimeout(Y,1)}const L=u.useMemo(()=>T?k(T):"",[T,k]);function ae({value:G,input:te}){if(!w&&!y||te)return;let P=typeof w=="function"?w(G):G?new Date(G):null;P=isNaN(P)?T||null:P||null,_(P)}return u.useEffect(()=>{const G=Y;return window.addEventListener("scroll",G),()=>window.removeEventListener("scroll",G)},[]),s.jsxs("div",{className:"wx-1lKOFG wx-datepicker",onClick:()=>O(!0),children:[s.jsx(dp,{css:`wx-date-input ${p}`,title:v,tooltip:g,value:L,id:a,readonly:!w,disabled:r,error:l,placeholder:c,onInput:Y,onChange:ae,icon:"wxi-calendar",clear:y}),q&&!r&&s.jsx(up,{onCancel:Y,...jk(C),children:s.jsx(Rb,{buttons:m,value:T,onChange:G=>_(G.value)})})]})}function Nk({value:n="",options:a=[],textOptions:r=null,placeholder:l="",disabled:c=!1,error:d=!1,title:m="",tooltip:p,textField:v="label",clear:g=!1,css:w="",children:y,onChange:b,dropdown:C={}}){const j=u.useRef(null),A=u.useRef(null);let[N,k]=oi(n);function T(_){j.current=_.navigate,A.current=_.keydown}const R=u.useMemo(()=>N||N===0?(r||a).find(_=>_.id===N):null,[N,r,a]),q=u.useCallback(({id:_})=>{(_||_===0)&&(k(_),j.current(null),b&&b({value:_}))},[k,b]),O=u.useCallback(_=>{_.stopPropagation(),k(""),b&&b({value:""})},[k,b]),Y=u.useCallback(()=>a.findIndex(_=>_.id===N),[a,N]);return s.jsxs("div",{className:`wx-2YgblL wx-richselect ${w} ${d?"wx-2YgblL wx-error":""} ${c?"wx-2YgblL wx-disabled":""} ${y?"":"wx-2YgblL wx-nowrap"}`,title:m,onClick:()=>j.current(Y()),onKeyDown:_=>A.current(_,Y()),tabIndex:0,"data-tooltip-text":p,children:[s.jsx("div",{className:"wx-2YgblL wx-label",children:R?y?y(R):R[v]:l?s.jsx("span",{className:"wx-2YgblL wx-placeholder",children:l}):" "}),g&&!c&&N?s.jsx("i",{className:"wx-2YgblL wx-icon wxi-close",onClick:O}):s.jsx("i",{className:"wx-2YgblL wx-icon wxi-angle-down"}),!c&&s.jsx(gf,{items:a,onReady:T,onSelect:q,...C,children:({option:_})=>y?y(_):_[v]})]})}const Mk=({options:n=[],value:a="",css:r="",children:l,onChange:c})=>{const[d,m]=u.useState(a),p=v=>{m(v),c&&c({value:v})};return u.useEffect(()=>{m(a)},[a]),s.jsx("div",{className:`wx-0hMO7P wx-segmented ${r}`,children:n.map(v=>s.jsx("button",{className:`wx-0hMO7P wx-segment ${v.css} ${v.id===d?"wx-selected":""}`,title:v.title,onClick:()=>p(v.id),"data-tooltip-text":v.tooltip,children:l?ip(l,{option:v}):s.jsxs(s.Fragment,{children:[v.icon&&s.jsx("i",{className:`wx-0hMO7P wx-icon ${v.icon} ${v.label?"":"wx-only"}`}),v.label&&s.jsx("span",{className:"wx-0hMO7P wx-label",children:v.label})]})},v.id))})};function Tk({notice:n={}}){function a(){n.remove&&n.remove()}return s.jsxs("div",{className:`wx-11sNg5 wx-notice wx-${n.type?n.type:""}`,role:"status","aria-live":"polite",children:[s.jsx("div",{className:"wx-11sNg5 wx-text",children:n.text}),s.jsx("div",{className:"wx-11sNg5 wx-button",children:s.jsx("i",{className:"wx-11sNg5 wxi-close",onClick:a})})]})}function Ek({data:n=[]}){return s.jsx("div",{className:"wx-3nwoO9 wx-notices",children:n.map(a=>s.jsx(Tk,{notice:a},a.id))})}function Hh({title:n="",buttons:a=["cancel","ok"],header:r,children:l,footer:c,css:d="",onConfirm:m,onCancel:p}){const v=(u.useContext(zs)||pf()).getGroup("core"),g=u.useRef(null);u.useEffect(()=>{g.current?.focus()},[]);function w(b){switch(b.code){case"Enter":{const C=b.target.tagName;if(C==="TEXTAREA"||C==="BUTTON")return;m&&m({event:b});break}case"Escape":p&&p({event:b});break}}function y(b,C){const j={event:b,button:C};C==="cancel"?p&&p(j):m&&m(j)}return s.jsx("div",{className:`wx-1FxkZa wx-modal ${d}`,ref:g,tabIndex:0,onKeyDown:w,children:s.jsxs("div",{className:"wx-1FxkZa wx-window",children:[r||(n?s.jsx("div",{className:"wx-1FxkZa wx-header",children:n}):null),s.jsx("div",{children:l}),c||a&&s.jsx("div",{className:"wx-1FxkZa wx-buttons",children:a.map(b=>s.jsx("div",{className:"wx-1FxkZa wx-button",children:s.jsx(Vc,{type:`block ${b==="ok"?"primary":"secondary"}`,onClick:C=>y(C,b),children:v(b)})},b))})]})})}function Rk({children:n},a){const[r,l]=u.useState(null),[c,d]=u.useState([]);return u.useImperativeHandle(a,()=>({showModal:m=>{const p={...m};return l(p),new Promise((v,g)=>{p.resolve=w=>{l(null),v(w)},p.reject=w=>{l(null),g(w)}})},showNotice:m=>{m={...m},m.id=m.id||lp(),m.remove=()=>d(p=>p.filter(v=>v.id!==m.id)),m.expire!=-1&&setTimeout(m.remove,m.expire||5100),d(p=>[...p,m])}}),[]),s.jsxs(s.Fragment,{children:[n,r&&s.jsx(Hh,{title:r.title,buttons:r.buttons,onConfirm:r.resolve,onCancel:r.reject,children:r.message}),s.jsx(Ek,{data:c})]})}const Dk=u.forwardRef(Rk);function Lk(n){let{children:a}=n,r=u.useRef();const l=u.useMemo(()=>({showNotice:c=>r.current.showNotice(c),showModal:c=>r.current.showModal(c)}),[]);return s.jsx(Nb.Provider,{value:l,children:s.jsx(Dk,{ref:r,children:a})})}const _k=({value:n=!1,type:a="",icon:r="",disabled:l=!1,iconActive:c="",onClick:d,title:m="",tooltip:p,css:v="",text:g="",textActive:w="",children:y,active:b,onChange:C})=>{const[j,A]=oi(n),N=u.useMemo(()=>(j?"pressed":"")+(a?" "+a:""),[j,a]),k=u.useCallback(T=>{let R=!j;d&&d(T),T.defaultPrevented||(A(R),C&&C({value:R}))},[j,d,C]);return j&&b?s.jsx(Vc,{title:m,tooltip:p,text:j&&w||g,css:v,type:N,icon:j&&c||r,onClick:k,disabled:l,children:ip(b,{value:j})}):y?s.jsx(Vc,{title:m,tooltip:p,text:j&&w||g,css:v,type:N,icon:j&&c||r,onClick:k,disabled:l,children:y}):s.jsx(Vc,{title:m,tooltip:p,text:j&&w||g,css:v,type:N,icon:j&&c||r,onClick:k,disabled:l})};function zk(){return s.jsx(s.Fragment,{})}function Vx(n){const{fonts:a=!0,children:r}=n;return s.jsx(op.Provider,{value:"willow",children:s.jsxs(s.Fragment,{children:[r&&r&&s.jsx("div",{className:"wx-theme wx-willow-theme",children:r}),a&&s.jsxs(s.Fragment,{children:[s.jsx("link",{rel:"preconnect",href:"https://cdn.svar.dev",crossOrigin:"true"}),s.jsx(zk,{}),s.jsx("link",{rel:"stylesheet",href:"https://cdn.svar.dev/fonts/wxi/wx-icons.css"})]})]})})}rp(Ba);const hp={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 Db=class{constructor(n){this._nextHandler=null,this._dispatch=n,this.exec=this.exec.bind(this)}async exec(n,a){return this._dispatch(n,a),this._nextHandler&&await this._nextHandler.exec(n,a),a}setNext(n){return this._nextHandler=n}};new Date().valueOf();var Ik=class{constructor(n){const a={id:0,$level:0,data:[],parent:null},r=new Map;r.set(0,a),this._pool=r,n&&n.length&&this.parse(n,0)}parse(n,a){const r=this._pool;for(let c=0;c<n.length;c++){const d=n[c];d.parent=d.parent||a,d.data=null,r.set(d.id,d)}for(let c=0;c<n.length;c++){const d=n[c],m=r.get(d.parent);m&&(m.data||(m.data=[]),m.data.push(d))}const l=r.get(a);this.setLevel(l,l.$level+1,!1)}add(n,a){const r=this._pool.get(n.parent||0);n.$level=r.$level+1,this._pool.set(n.id,n),r.data?a===-1?r.data=[...r.data,n]:Wx(r,a,n):r.data=[n]}addAfter(n,a){if(!a)return this.add(n,-1);const r=this.byId(a),l=this.byId(r.parent),c=Ed(l,r.id)+1;n.parent=l.id,n.$level=l.$level+1,this.add(n,c)}remove(n){const a=this._pool.get(n);this._remove(a);const r=this._pool.get(a.parent);r.data=r.data.filter(l=>l.id!=n),this._clearBranch(r)}_remove(n){n.data&&n.data.forEach(a=>this._remove(a)),this._pool.delete(n.id)}update(n,a){let r=this._pool.get(n);const l=this._pool.get(r.parent),c=Ed(l,r.id);r={...r,...a},l&&c>=0&&(l.data[c]=r,l.data=[...l.data]),this._pool.set(r.id,r)}move(n,a,r){const l=this._pool.get(n),c=a==="child",d=this._pool.get(r),m=d.$level+(c?1:0);if(!l||!d)return;const p=this._pool.get(l.parent),v=c?d:this._pool.get(d.parent);v.data||(v.data=[]);const g=Ed(p,l.id);Ok(p,g);const w=c?v.data.length:Ed(v,d.id)+(a==="after"?1:0);if(Wx(v,w,l),p.id===v.id&&g===w)return null;l.parent=v.id,l.$level!==m&&(l.$level=m,this.setLevel(l,m+1,!0)),this.update(l.id,l),this._clearBranch(p)}_clearBranch(n){n.data&&!n.data.length&&(n.open&&delete n.open,this.update(n.id,{data:null}))}toArray(){const n=[],a=this._pool.get(0).data;return a&&Lb(a,n),n}byId(n){return this._pool.get(n)}getBranch(n){return this._pool.get(n).data}forEach(n){this._pool.forEach((a,r)=>{r!==0&&n(a)})}eachChild(n,a){const r=this.byId(a);!r||!r.data||r.data.forEach((l,c)=>{n(this.byId(l.id),c),this.eachChild(n,l.id)})}setLevel(n,a,r){n.data&&(n.data=n.data.map(l=>(r&&(l={...l},this._pool.set(l.id,l)),l.$level=a,l.data&&this.setLevel(l,a+1,r),l)))}};function Lb(n,a){n.forEach(r=>{a.push(r),r.open===!0&&Lb(r.data,a)})}function Ok(n,a){const r=[...n.data];r.splice(a,1),n.data=r}function Wx(n,a,r){const l=[...n.data];l.splice(a,0,r),n.data=l}function Ed(n,a){return n?.data.findIndex(r=>r.id===a)}var _b=2,Hk=class{constructor(a){a&&(this._writable=a.writable,this._async=a.async),this._values={},this._state={}}setState(a,r=0){const l={};return this._wrapProperties(a,this._state,this._values,"",l,r),l}getState(){return this._values}getReactive(){return this._state}_wrapProperties(a,r,l,c,d,m){for(const p in a){const v=r[p],g=l[p],w=a[p];if(v&&(g===w&&typeof w!="object"||w instanceof Date&&g instanceof Date&&g.getTime()===w.getTime()))continue;const y=c+(c?".":"")+p;v?(v.__parse(w,y,d,m)&&(l[p]=w),m&_b?d[y]=v.__trigger:v.__trigger()):(w&&w.__reactive?r[p]=this._wrapNested(w,w,y,d):r[p]=this._wrapWritable(w),l[p]=w),d[y]=d[y]||null}}_wrapNested(a,r,l,c){const d=this._wrapWritable(a);return this._wrapProperties(a,d,r,l,c,0),d.__parse=(m,p,v,g)=>(this._wrapProperties(m,d,r,p,v,g),!1),d}_wrapWritable(a){const r=[],l=function(){for(let c=0;c<r.length;c++)r[c](a)};return{subscribe:c=>(r.push(c),this._async?setTimeout(c,1,a):c(a),()=>{const d=r.indexOf(c);d>=0&&r.splice(d,1)}),__trigger:()=>{r.length&&(this._async?setTimeout(l,1):l())},__parse:function(c){return a=c,!0}}}};function Yx(n,a){return Object.defineProperty(n,"__reactive",{value:!0,enumerable:!1,writable:!1}),n}var Bk=class{constructor(a,r,l,c){typeof a=="function"?this._setter=a:this._setter=a.setState.bind(a),this._routes=r,this._parsers=l,this._prev={},this._triggers=new Map,this._sources=new Map,this._routes.forEach(d=>{d.in.forEach(m=>{const p=this._triggers.get(m)||[];p.push(d),this._triggers.set(m,p)}),d.out.forEach(m=>{const p=this._sources.get(m)||{};d.in.forEach(v=>p[v]=!0),this._sources.set(m,p)})}),this._routes.forEach(d=>{d.length=Math.max(...d.in.map(m=>zb(m,this._sources,1)))}),this._bus=c}init(a){const r={};for(const l in a)if(this._prev[l]!==a[l]){const c=this._parsers[l];r[l]=c?c(a[l]):a[l]}this._prev=this._prev?{...this._prev,...a}:{...a},this.setState(r),this._bus&&this._bus.exec("init-state",r)}setStateAsync(a){const r=this._setter(a,_b);return this._async?Object.assign(this._async.signals,r):this._async={signals:r,timer:setTimeout(this._applyState.bind(this),1)},r}_applyState(){const a=this._async;if(a){this._async=null,this._triggerUpdates(a.signals,[]);for(const r in a.signals){const l=a.signals[r];l&&l()}}}setState(a,r=[]){const l=this._setter(a);return this._triggerUpdates(l,r),l}_triggerUpdates(a,r){const l=Object.keys(a),c=!r.length;r=r||[];for(let d=0;d<l.length;d++){const m=l[d],p=this._triggers.get(m);p&&p.forEach(v=>{r.indexOf(v)==-1&&r.push(v)})}c&&this._execNext(r)}_execNext(a){for(;a.length;){a.sort((l,c)=>l.length<c.length?1:-1);const r=a[a.length-1];a.splice(a.length-1),r.exec(a)}}};function zb(n,a,r){const l=a.get(n);if(!l)return r;const c=Object.keys(l).map(d=>zb(d,a,r+1));return Math.max(...c)}var Fk=class{constructor(){this._nextHandler=null,this._handlers={},this._tag=new WeakMap,this.exec=this.exec.bind(this)}on(a,r,l){let c=this._handlers[a];c?l&&l.intercept?c.unshift(r):c.push(r):c=this._handlers[a]=[r],l&&l.tag&&this._tag.set(r,l.tag)}intercept(a,r,l){this.on(a,r,{...l,intercept:!0})}detach(a){for(const r in this._handlers){const l=this._handlers[r];for(let c=l.length-1;c>=0;c--)this._tag.get(l[c])===a&&l.splice(c,1)}}async exec(a,r){const l=this._handlers[a];if(l)for(let c=0;c<l.length;c++){const d=l[c](r);if(d===!1||d&&d.then&&await d===!1)return}return this._nextHandler&&await this._nextHandler.exec(a,r),r}setNext(a){return this._nextHandler=a}};const Mo=1024;function eu(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 Kx(n,a){a||(a={key:"name",order:"asc"});const r=n.filter(m=>m.type==="folder"),l=n.filter(m=>m.type!=="folder"),c=r.sort(Qx(a)),d=l.sort(Qx(a));return[...c,...d]}function Pk(n,a){return typeof n=="string"?n.localeCompare(a,void 0,{numeric:!0}):typeof n=="object"?n.getTime()-a.getTime():(n??0)-(a??0)}function $k(n,a){return typeof n=="string"?-n.localeCompare(a,void 0,{numeric:!0}):typeof a=="object"?a.getTime()-n.getTime():(a??0)-(n??0)}function Qx({key:n,order:a}){const r=a==="asc"?Pk:$k;return(l,c)=>r(l[n],c[n])}function pp(n,a){const r=n==="/"?1:n.split("/").length;return r>=a.length?null:a[r].id}function Uk(n){return n.length>1?n[n.length-2].id:null}let qk=class extends Ik{constructor(a){const r={id:"/",name:"My files",open:!0,$level:1,parent:0,ext:"",type:"folder"};super([r]),this.parse(a,"/")}parse(a,r,l){!a||!a.length||(a.forEach(c=>this.parseId(c,l?r:void 0)),super.parse(a,r))}parseId(a,r){if(a.parent===0)return;const l=a.id,c=l.lastIndexOf("/");if(a.parent=r??(c===0?"/":l.slice(0,c)),a.name=l.slice(c+1),a.type=a.type||"file",a.type!=="folder"){const d=a.name.lastIndexOf("."),m=d!==-1?a.name.slice(d+1):"";a.ext=m!=="new"?m?.toLocaleLowerCase():""}}getParents(a){const r=[];let l=this.byId(a);if(!l)return r;for(;l.id!==0;)r.push(l),l=this.byId(l.parent);return r.reverse()}findFiles(a,r="/"){const l=[],c=a.toLocaleLowerCase();return this.eachChild(d=>{d.name.toLowerCase().indexOf(c)!==-1&&l.push(d)},r),l}add(a,r){const l=this.byId(a.parent||"/"),c=a.data?[...a.data]:null;a.data=null,super.add(a,r??l.data?l.data.length:0),c&&c.forEach(d=>this.add(d))}renameFiles(a,r,l){const c=this.byId(a),d=this.normalizeFile(c,r),m=[];return d.data?.forEach(p=>m.push(this.renameFiles(p.id,d.id,l))),m.length&&(d.data=m),l[a]=d.id,d}copyFiles(a,r,l){const c={};return a.forEach(d=>{const m=this.renameFiles(d,r,c);this.add(m),l&&this.remove(d),c[d]=m.id}),c}moveFiles(a,r){if(this.byId(a[0]).parent!==r)return this.copyFiles(a,r,!0)}serialize(a="/"){const r=[],l=this.byId(a);return l?(l.data?.forEach(c=>{const{id:d,date:m,type:p,size:v,lazy:g}=c,w={id:d,date:m,type:p??"file"};g&&(w.lazy=g),v&&(w.size=v),r.push(w);const y=this.serialize(d);y.length&&r.push(...y)}),r):null}normalizeFile(a,r){const l=a.name,c=l.lastIndexOf("."),d=c!==-1?l.slice(c+1):"",m=d?`.${d}`:"";let p=c!==-1?l.slice(0,c):l,v=r+(r==="/"?"":"/")+p;for(;this.byId(v+m);){const g=".new";v+=g,p+=g}return{...a,id:v+m,name:p+m,parent:r,ext:d.toLocaleLowerCase()}}},Gk=class extends Hk{in;_router;constructor(a){super({writable:a,async:!1});const r=[];for(let d=0;d<2;d++)r.push({in:["data",`panels.${d}.path`],out:[`panels.${d}._crumbs`],exec:m=>{const{data:p,panels:v}=this.getState(),g=[];g[d]={_crumbs:p.getParents(v[d].path)},this.setState({panels:g},m)}}),r.push({in:["data",`panels.${d}.path`,`panels.${d}._sorts`,"search"],out:[`panels.${d}._files`],exec:m=>{const{data:p,panels:v,search:g}=this.getState();let w;g?w=p.findFiles(g,v[d].path):w=p.byId(v[d].path)?.data||[];const{path:y,_sorts:b}=v[d];w=Kx(w,b[y]);const C=[];C[d]={_files:w},this.setState({panels:C},m)}}),r.push({in:["data",`panels.${d}.selected`,`panels.${d}._sorts`],out:[`panels.${d}._selected`],exec:m=>{const{data:p,panels:v}=this.getState(),g=[];v[d].selected.forEach(j=>{const A=p.byId(j);A&&g.push(A)});const{path:w,_sorts:y}=v[d],b=Kx(g,y[w]),C=[];C[d]={_selected:b},this.setState({panels:C},m)}});this._router=new Bk(super.setState.bind(this),r,{data:d=>new qk(d)});const l=this.in=new Fk;l.on("select-file",({id:d,toggle:m,range:p,panel:v,type:g})=>{const{panels:w,activePanel:y}=this.getState();typeof v>"u"&&(v=y),d||(m=p=!1);let b=[...w[v].selected];if(m){const j=b.indexOf(d);j===-1?b.push(d):b.splice(j,1)}else if(p&&w[v]._lastSelected){const j=w[v]._files;let A=j.findIndex(T=>T.id==w[v]._lastSelected),N=j.findIndex(T=>T.id==d);N<A&&([A,N]=[N,A]);const k=j.slice(A,N+1).map(T=>T.id);b=[...new Set([...b,...k])]}else b=d?[d]:[];const C=[];C[v]={selected:b,_lastSelected:d,_selectNavigation:g==="navigation"},this.setState({panels:C})}),l.on("set-path",({id:d,panel:m,selected:p})=>{const{data:v,activePanel:g}=this.getState(),w=v.byId(d);if(w){const y=[];typeof m>"u"&&(m=g),y[m]={path:d},this.setState({panels:y}),l.exec("select-file",{panel:m}),p&&p.forEach(b=>l.exec("select-file",{id:b,panel:m,toggle:!0})),w.lazy&&l.exec("request-data",{id:d})}}),l.on("provide-data",({id:d,data:m})=>{const{mode:p,data:v}=this.getState(),g=v.byId(d);g&&(g.lazy||(g.data=[]),g.lazy=!1,v.parse(m,d,p==="search"),this.setState({data:v}))}),l.on("open-tree-folder",({id:d,mode:m})=>{const{data:p}=this.getState();p.update(d,{open:m}),this.setState({data:p})}),l.on("show-preview",({mode:d})=>{this.setState({preview:d})}),l.on("rename-file",d=>{const{id:m,name:p}=d,{data:v,panels:g}=this.getState(),w=v.byId(m);if(w.name!==p){w.name=p;const y=v.normalizeFile(w,w.parent);d.newId=y.id,y.data=null,v.add(y);let b={[m]:y.id};w.data?.forEach(j=>b={...v.moveFiles([j.id],y.id),...b});const C=g.map(j=>({selected:j.selected,_crumbs:j._crumbs,_lastSelected:j._lastSelected,_sorts:j._sorts}));v.remove(m),this._updatePanels(C,b),this.setState({data:v,panels:C})}}),l.on("create-file",d=>{const{file:m,parent:p}=d,{data:v}=this.getState(),g=v.normalizeFile(m,p);g.type=m.type||"file",d.newId=g.id,v.add(g),this.setState({data:v}),l.exec("select-file",{id:g.id})}),l.on("delete-files",({ids:d})=>{const{data:m,panels:p}=this.getState(),v=p.map(g=>({selected:g.selected,_crumbs:g._crumbs,_lastSelected:g._lastSelected,_sorts:g._sorts}));d.forEach(g=>m.remove(g)),this._updatePanels(v,{}),this.setState({data:m,panels:v})}),l.on("copy-files",d=>{const{ids:m,target:p}=d;if(this._isPlacedIntoSelf(m,p)){console.error("You cannot copy a folder into itself"),d.skipProvider=!0;return}const{data:v,panels:g,activePanel:w}=this.getState(),y=v.copyFiles(m,p);d.newIds=m.map(b=>y[b]),this.setState({data:v}),g[w].path==p&&(l.exec("select-file",{}),m.forEach(b=>{l.exec("select-file",{id:y[b],toggle:!0})}))}),l.on("move-files",d=>{const{ids:m,target:p}=d;if(this._isPlacedIntoSelf(m,p)){console.error("You cannot move a folder into itself"),d.skipProvider=!0;return}const{data:v,panels:g,activePanel:w}=this.getState(),y=v.moveFiles(m,p);if(y){d.newIds=m.map(C=>y[C]);const b=g.map(C=>({selected:C.selected,_crumbs:C._crumbs,_lastSelected:C._lastSelected,_sorts:C._sorts}));this._updatePanels(b,y,!0),this.setState({data:v,panels:b}),g[w].path==p&&(l.exec("select-file",{}),m.forEach(C=>{l.exec("select-file",{id:y[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 v={mode:d,search:"",panels:p};c=null,this.setState(v)}),l.on("set-active-panel",({panel:d})=>{this.setState({activePanel:d})}),l.on("sort-files",({key:d,order:m,panel:p,path:v})=>{const{activePanel:g,panels:w}=this.getState();p=p??g,v=v??w[p].path;const y=[];y[p]={_sorts:{...w[p]._sorts,[v]:{key:d,order:m}}},this.setState({panels:y})}),this.initOnce()}initOnce(){const a=[];for(let l=0;l<2;l++)a[l]=Yx({_crumbs:[],_files:[],_selected:[],_sorts:{},path:"/",selected:[],...a[l]});const r={panels:Yx(a),data:[],search:""};this._router.init(r)}init(a){const r={...a};this._router.init(r)}setState(a,r){return this._router.setState(a,r)}getFile(a){const{data:r}=this.getState();return r.byId(a)||null}serialize(a){const{data:r}=this.getState();return r.serialize(a)}_updatePanels(a,r,l){const{data:c}=this.getState();a.forEach(d=>{const m=[];d.selected.forEach(g=>{c.byId(g)?m.push(g):!l&&r[g]&&m.push(r[g])}),d.selected=m,c.byId(d._lastSelected)||(d._lastSelected=l?null:r[d._lastSelected]||null);const p={};Object.keys(d._sorts).forEach(g=>{c.byId(g)?p[g]=d._sorts[g]:r[g]&&!l&&(p[r[g]]=d._sorts[g])}),d._sorts=p;const v=d._crumbs[d._crumbs.length-1];v?.id!=="/"&&(r[v.id]?d.path=r[v.id]:c.byId(v.id)||(d.path="/"))})}_isPlacedIntoSelf(a,r){return a.some(l=>l===r||this.getState().data.getParents(r).some(c=>c.id===l))}};function Vk(n){switch(n){case"body":return[{icon:"wxi-content-paste",text:"Paste",hotkey:"Ctrl+V",id:"paste"}];case"add":return[{icon:"mdi mdi-folder-plus-outline",text:"Add new file",id:"add-file"},{icon:"mdi mdi-file-plus-outline",text:"Add new folder",id:"add-folder"},{icon:"mdi mdi-file-upload-outline",text:"Upload file",id:"upload",comp:"upload"}];case"multiselect":return[{icon:"wxi-content-copy",text:"Copy",hotkey:"Ctrl+C",id:"copy"},{icon:"wxi-content-cut",text:"Cut",hotkey:"Ctrl+X",id:"move"},{comp:"separator"},{icon:"wxi-close",text:"Delete",hotkey:"Delete",id:"delete"}];default:return[n==="folder"?null:{icon:"wxi-download",text:"Download",hotkey:"Ctrl+D",id:"download"},{icon:"wxi-content-copy",text:"Copy",hotkey:"Ctrl+C",id:"copy"},{icon:"wxi-content-cut",text:"Cut",hotkey:"Ctrl+X",id:"move"},{icon:"wxi-content-paste",text:"Paste",hotkey:"Ctrl+V",id:"paste"},{comp:"separator"},{icon:"wxi-edit",text:"Rename",hotkey:"Ctrl+R",id:"rename"},{icon:"wxi-close",text:"Delete",hotkey:"Delete",id:"delete"}].filter(a=>a!==null)}}function Wk(n,a="data-id"){let r=n;for(!r.tagName&&n.target&&(r=n.target);r;){if(r.getAttribute&&r.getAttribute(a))return r;r=r.parentNode}return null}function Yk(n,a="data-id"){const r=Wk(n,a);return r?r.getAttribute(a):null}new Date().valueOf();function Kk(n,a){const{api:r}=a;function l(d,m){const p=a.getPanel(),v=p.selected,g=m.ctrlKey||m.metaKey,w=m.shiftKey;let y;const b=v?.[0]?r.getFile(v[0]):null;v?.length?v.length>1?y=a.menuOptions("multiselect"):y=a.menuOptions(b.type,b):y=a.menuOptions("body");const C=`${g?"ctrl+":""}${w?"shift+":""}${d}`,j=y?y.find(N=>N.hotkey?.toLowerCase()===C):!1,A=a.performAction;if(j)switch(C){case"ctrl+c":A("copy");break;case"ctrl+x":A("move");break;case"ctrl+v":A("paste",b);break;case"delete":A("delete");break;case"ctrl+r":m.preventDefault(),A("rename",b);break;case"ctrl+d":m.preventDefault(),A("download",b);break;default:j.handler?.({context:b})}switch(d){case"enter":{if(g||w)break;const{_crumbs:N,_selectNavigation:k}=p;if(k){const T=Uk(N);if(T){const R=pp(T,N);r.exec("set-path",{id:T,selected:[R]})}}else if(v.length===1){const T=r.getFile(v[0]);T&&r.exec(T.type==="folder"?"set-path":"open-file",{id:T.id})}break}case"arrowup":case"arrowleft":{const{_files:N,_selected:k,path:T,_selectNavigation:R}=p;let q;if(k.length){const O=k.at(0).id,Y=N.findIndex(_=>_.id===O);if(Y!==-1){const _=Y-1;N[_]?q=N[_].id:T!=="/"&&!(g||w)&&r.exec("select-file",{type:"navigation"})}}else{if(R)break;if(T!=="/"){r.exec("select-file",{type:"navigation"});break}q=N.at(0)?.id}q&&r.exec("select-file",{id:q,toggle:g,range:w});break}case"arrowdown":case"arrowright":{const{_files:N,_selected:k,path:T,_selectNavigation:R}=p;let q;if(k.length){const O=k.at(-1).id,Y=N.findIndex(_=>_.id===O);if(Y!==-1){const _=Y+1;N[_]&&(q=N[_].id)}}else{if(T!=="/"&&!R){r.exec("select-file",{type:"navigation"});break}q=N.at(0)?.id}q&&r.exec("select-file",{id:q,toggle:g,range:w});break}}}function c(d){const m=d.code.replace("Key","").toLowerCase();l(m,d),m=="tab"&&setTimeout(()=>{const p=document.activeElement;p.className.indexOf("table")!=-1&&r.exec("set-active-panel",{panel:+Yk(p,"data-panel")})})}return n.addEventListener("keydown",c),{destroy:()=>{n.removeEventListener("keydown",c)}}}function Qk(n,a="data-id"){let r=n;for(!r.tagName&&n.target&&(r=n.target);r;){if(r.getAttribute&&r.getAttribute(a))return r;r=r.parentNode}return null}function Xk(n,a="data-id"){const r=n.getAttribute(a);return r?Zk(r):null}function Zk(n){if(n.startsWith(":"))return n.substring(1);const a=n*1;return isNaN(a)?n:a}function Jk(){return{detect:()=>!0,addEvent:function(n,a,r){return n.addEventListener(a,r),()=>n.removeEventListener(a,r)},addGlobalEvent:function(n,a){return document.addEventListener(n,a),()=>document.removeEventListener(n,a)},getTopNode:function(){return window.document.body}}}var e1=Jk();new Date().valueOf();function Ib(n){const[a,r]=u.useState(n),l=u.useRef(n);return u.useEffect(()=>{if(l.current!==n){if(Array.isArray(l.current)&&Array.isArray(n)&&l.current.length===0&&n.length===0)return;l.current=n,r(n)}},[n]),[a,r]}function t1(n,a,r){const[l,c]=u.useState(()=>a);return n||console.warn(`Writable ${r} is not defined`),u.useEffect(()=>n?n.subscribe(m=>{c(()=>m)}):void 0,[n]),l}function lt(n,a){const r=n.getState(),l=n.getReactiveState();return t1(l[a],r[a],a)}function n1(n,a){const r=u.useRef(a);r.current=a;const[l,c]=u.useState(1);return u.useEffect(()=>n.subscribe(m=>{r.current=m,c(p=>p+1)}),[n]),[r.current,l]}function fs(n,a){const r=n.getState(),l=n.getReactiveState();return n1(l[a],r[a])}function Ob(n){const a={};return n.split(";").forEach(r=>{const[l,c]=r.split(":");if(c){let d=l.trim();d.indexOf("-")&&(d=d.replace(/-([a-z])/g,(m,p)=>p.toUpperCase())),a[d]=c.trim()}}),a}function Hb(n){let a=n,r=[];return{subscribe:p=>{r.push(p),p(a)},unsubscribe:p=>{r=r.filter(v=>v!==p)},set:p=>{a=p,r.forEach(v=>v(a))},update:p=>{a=p(a),r.forEach(v=>v(a))}}}function Xx(n,a,r){function l(c){const d=Qk(c);if(!d)return;const m=Xk(d);if(typeof a=="function")return a(m,c);let p,v=c.target;for(;v!=d;){if(p=v.dataset?v.dataset.action:null,p&&a[p]){a[p](m,c);return}v=v.parentNode}a[r]&&a[r](m,c)}return e1.addEvent(n,r,l)}function a1(n,a){const r=[Xx(n,a,"click")];return a.dblclick&&r.push(Xx(n,a.dblclick,"dblclick")),()=>{r.forEach(l=>l())}}function Bb(n,a){return n.map((r,l)=>{const c=a(r,l);return r.data&&r.data.length&&(c.data=Bb(r.data,a)),c}).filter(Boolean)}function Fb(n,a){const r=[];return n.forEach(l=>{if(l.data){const c=Fb(l.data,a);c.length&&r.push({...l,data:c})}else a(l)&&r.push(l)}),r}function s1(n){return Bb(n,(a,r)=>{const l={...a,id:a.id||lp()};return l.type&&(l.comp=l.type),l.comp==="separator"&&n[r-1]?.comp==="separator"?null:l})}const Pb={};function i1(n){return Pb[n]||n}function r1(n,a){Pb[n]=a}function l1({onClick:n,onShow:a,option:r}){const l=u.useRef(null),c=u.useCallback(()=>{a(r.data?r.id:!1,l.current)},[a,r]),d=u.useCallback(p=>{if(r.data){p.stopPropagation(),a(r.id,l.current);return}n(p)},[n,a,r]),m=u.useMemo(()=>r&&r.comp?i1(r.comp):null,[r]);return s.jsxs("div",{ref:l,className:`wx-cDCz9rZQ wx-option ${r.css||""} ${r.disabled?"wx-disabled":""}`,"data-id":Bn(r.id),onMouseEnter:c,onClick:d,children:[r.icon?s.jsx("i",{className:`wx-cDCz9rZQ wx-icon ${r.icon}`}):null,r.comp?m?s.jsx(m,{item:r,option:r}):null:s.jsxs("span",{className:"wx-cDCz9rZQ wx-value",children:[" ",r.text," "]}),r.subtext?s.jsx("span",{className:"wx-cDCz9rZQ wx-subtext",children:r.subtext}):null,r.data?s.jsx("i",{className:"wx-cDCz9rZQ wx-sub-icon wxi-angle-right"}):null]})}function gp({options:n,left:a=0,top:r=0,at:l="bottom",parent:c=null,mount:d=null,context:m=null,css:p="",onClick:v,onCancel:g}){const[w,y]=u.useState(-1e4),[b,C]=u.useState(-1e4),[j,A]=u.useState(20),[N,k]=u.useState(),T=u.useRef(null),[R,q]=u.useState(!1),[O,Y]=u.useState(null),_=u.useCallback(()=>{const ie=Cb(T.current,c,l,a,r);ie&&(y(ie.x),C(ie.y),k(ie.width));let K=ie?.z??20;const I=c?Kj(c):[];let Q=0;for(const U of I){const W=parseInt(getComputedStyle(U).zIndex,10);W>Q&&(Q=W)}Q>=K&&(K=Q+1),A(K)},[c,l,a,r]);u.useEffect(()=>{d&&d(_)},[]);const L=u.useCallback(()=>{q(!1)},[]),ae=u.useCallback((ie,K)=>{q(ie),Y(K)},[]),G=u.useMemo(()=>s1(n),[n]);u.useEffect(()=>{_()},[c,_]);const te=u.useRef(v),P=u.useRef(g),ye=u.useRef(c);return u.useEffect(()=>{te.current=v},[v]),u.useEffect(()=>{P.current=g},[g]),u.useEffect(()=>{ye.current=c},[c]),u.useEffect(()=>{if(!T.current)return;function ie(K){P.current?P.current(K):te.current&&te.current({action:null,option:null})}return ci(T.current,{callback:ie,modal:!0,parent:()=>ye.current}).destroy},[]),s.jsx("div",{ref:T,"data-wx-menu":"true",className:`wx-XMmAGqVx wx-menu ${p}`,style:{position:"absolute",top:b+"px",left:w+"px",width:N,zIndex:j},onMouseLeave:L,children:G.map(ie=>s.jsxs(u.Fragment,{children:[ie.comp==="separator"?s.jsx("div",{className:"wx-XMmAGqVx wx-separator"}):s.jsx(l1,{option:ie,onShow:ae,onClick:K=>{if(!ie.data&&!K.defaultPrevented){const I={context:m,action:ie,option:ie,event:K};ie.handler&&ie.handler(I),v&&v(I),K.stopPropagation()}}}),ie.data&&R===ie.id?s.jsx(gp,{css:p,options:ie.data,at:"right-overlap",parent:O,context:m,onClick:v,onCancel:g}):null]},ie.id))})}const $b=u.forwardRef(function(n,a){const{options:r,at:l="bottom",resolver:c=null,dataKey:d="contextId",filter:m=null,css:p="",children:v,onClick:g}=n,[w,y]=u.useState(null),[b,C]=u.useState(null),[j,A]=u.useState(0),[N,k]=u.useState(0),T=u.useRef(null),R=u.useMemo(()=>`data-${d.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}`,[d]),q=u.useMemo(()=>w!==null&&m?Fb(r,L=>m(L,w)):r,[w,m,r]);function O(L){C(null),g&&g(L)}function Y(L){if(T.current===L){T.current=null;return}C(null),g&&g({action:null,option:null})}const _=u.useCallback((L,ae)=>{if(!L){C(null);return}if(L.defaultPrevented)return;const G=L.target;if(G&&G.dataset&&G.dataset.menuIgnore)return;if(b&&b===G){C(null),L.preventDefault();return}A(L.clientX+1),k(L.clientY+1);let te=typeof ae<"u"?ae:Jc(G,R);c&&(te=c(te,L),!te)||(y(te),C(G),T.current=L.nativeEvent||L,L.preventDefault())},[b,R,c]);return u.useImperativeHandle(a,()=>({show:_}),[_]),s.jsxs(s.Fragment,{children:[v?s.jsx("span",{onClick:_,"data-menu-ignore":"true",children:typeof v=="function"?v():v}):null,b?s.jsx(cp,{children:s.jsx(gp,{css:p,at:l,top:N,left:j,parent:b,context:w,onClick:O,onCancel:Y,options:q},b)}):null]})}),o1=u.forwardRef(function(n,a){const{options:r,at:l="bottom",css:c="",children:d,onClick:m}=n,[p,v]=u.useState(null),g=u.useRef(null);function w(j){v(null),m&&m(j)}function y(j){if(g.current===j){g.current=null;return}v(null),m&&m({action:null,option:null})}const b=u.useCallback(j=>{v(j.target),g.current=j.nativeEvent||j,j.preventDefault()},[]);u.useImperativeHandle(a,()=>({show:b}),[b]);function C(j){let A=j.target;for(;!A.dataset.menuIgnore;)v(A),A=A.parentNode}return s.jsxs(s.Fragment,{children:[s.jsx("span",{onClick:C,"data-menu-ignore":"true",children:d}),p?s.jsx(cp,{children:s.jsx(gp,{css:c,at:l,parent:p,options:r,onClick:w,onCancel:y})}):null]})}),c1=u.forwardRef(function(n,a){const{options:r,at:l="bottom",resolver:c=null,dataKey:d="contextId",filter:m=null,css:p="",children:v,onClick:g}=n,w=u.useRef(null),y=u.useCallback((b,C)=>{w.current.show(b,C)},[]);return u.useImperativeHandle(a,()=>({show:y}),[y]),s.jsxs(s.Fragment,{children:[v?s.jsx("span",{onContextMenu:y,"data-menu-ignore":"true",children:v}):null,s.jsx($b,{css:p,at:l,options:r,resolver:c,dataKey:d,filter:m,ref:w,onClick:g})]})}),u1={uploader:{B:"B",KB:"KB",MB:"MB",GB:"GB",TB:"TB",PB:"PB",EB:"EB","Drop files here or":"Drop files here or","select files":"select files"}};let d1=class{constructor(a,r,l,c,d){this.setFiles=a,this.setReady=r,this.setSignal=l,this.setDrag=c,d&&d.length&&this.setFiles(d)}open(a){this.setSignal(["click",a||{}])}getState(){let a="server";const r=this.files;for(let l=0;l<r.length;l++){if(r[l].status==="client")return"client";r[l].status==="error"&&(a="error")}return a}droparea(a,r){r=r||{};const l=()=>{r.dragEnter&&r.dragEnter(),this.setDrag(!0)},c=()=>{r.dragLeave&&r.dragLeave(),this.setDrag(!1)},d=p=>{p.preventDefault()},m=p=>{p.preventDefault(),this.setDrag(!1),this.setSignal(["drop",r,p]),r.dragLeave&&r.dragLeave(),r.drop&&r.drop()};return a.addEventListener("dragenter",l),a.addEventListener("dragleave",c),a.addEventListener("dragover",d,!0),a.addEventListener("drop",m,!0),()=>{a.removeEventListener("dragenter",l),a.removeEventListener("dragleave",c),a.removeEventListener("dragover",d,!0),a.removeEventListener("drop",m,!0)}}updateFile(a,r){const l=this.files.findIndex(d=>d.id===a);if(l===-1)return;const c=[...this.files];return c[l]={...c[l],...r},this.files=c,this.setFiles(this.files),this.files[l]}deleteFile(a){this.files=this.files.filter(r=>r.id!==a),this.setFiles(this.files)}addFile(a,r){r?this.files=[...this.files,a]:this.files=[a],this.setFiles(this.files)}deleteAll(){this.files=[],this.setFiles(this.files)}};function Ub(n){const[a,r]=u.useState([]),[l,c]=u.useState(Promise.resolve(null)),[d,m]=u.useState(null),[p,v]=u.useState(!1),g=u.useRef();return g.current||(g.current=new d1(r,c,m,v,n)),g.current.files=a,g.current.ready=l,g.current.signal=d,g.current.drag=p,g.current}function f1(n,a){{if(n){const r=n.getGroup(a);if(r)return r}return tu(u1).getGroup(a)}}const m1=()=>Math.random().toString(36).substr(2,9),h1=({data:n,accept:a="",multiple:r=!0,folder:l=!1,uploadURL:c="",apiOnly:d=!1,disabled:m=!1,children:p,onChange:v,onUpload:g})=>{const w=u.useRef(null),y=u.useRef(null),[b,C]=u.useState({}),j=Ub(),A=n||j,N=u.useContext(Pn.i18n),k=f1(N,"uploader");u.useEffect(()=>{w.current&&l&&(w.current.webkitdirectory=!0)},[l]),u.useEffect(()=>{if(!d&&y.current&&!m)return A.droparea(y.current)},[d,m,y]);const T=G=>{const te=new FormData;return te.append("upload",G.file),fetch(c,{method:"POST",body:te}).then(P=>P.json()).then(P=>({id:G.id,...P}),()=>({id:G.id,status:"error"})).catch(P=>(console.log(P),{id:G.id,status:"error"}))},R=(G,te)=>{const P=A.updateFile(G,te),ye={...P,status:A.getState()};P&&P.uploaded&&P.uploaded(ye),g&&g(ye),P.temp&&A.deleteFile(P.id)},q=G=>{if(!G)return;const te=typeof c=="function"?c(G):T(G);A.setReady(te.then(P=>{P.status=P.status||"server",R(G.id,P)}).catch(P=>{R(G.id,{status:"error",error:P})}))},O=(G,te)=>{const P={...te||b,id:m1(),status:"client",name:G.name,file:G};P.selected&&P.selected(P),v&&v(P),A.addFile(P,r),q(P),w.current&&(w.current.value="")},Y=(G,te,P)=>{G.isFile?G.file(ye=>{O(ye,P)}):G.isDirectory&&G.createReader().readEntries(ye=>{ye.forEach(ie=>{Y(ie,te+ie.name+"/",P)})})},_=G=>{Array.from(G.target.files).forEach(te=>O(te))},L=(G,te)=>{Array.from(G.dataTransfer.items).forEach(P=>{const ye=P.webkitGetAsEntry();ye&&Y(ye,"",te)})},ae=()=>{w.current&&w.current.click()};return u.useEffect(()=>{if(A.signal){const[G,te,P]=A.signal;C(te),G==="click"?ae():G==="drop"&&L(P,te),A.setSignal(null)}},[A.signal]),d?s.jsxs(s.Fragment,{children:[s.jsx("input",{type:"file",className:"wx-at1A8tb8 wx-input",ref:w,onChange:_,accept:a,multiple:r,disabled:m}),p]}):s.jsxs("div",{className:`wx-at1A8tb8 wx-label ${A.drag?"wx-active":""} ${m?"wx-disabled":""}`,ref:y,children:[s.jsx("input",{type:"file",className:"wx-at1A8tb8 wx-input",ref:w,onChange:_,accept:a,multiple:r,disabled:m}),p||s.jsx("div",{className:"wx-at1A8tb8 wx-dropzone",children:s.jsxs("span",{children:[k("Drop files here or")," ",s.jsx("span",{className:"wx-at1A8tb8 wx-action",onClick:ae,children:k("select files")})]})})]})};new Date().valueOf();function p1(n,a){if(Object.keys(n).length!==Object.keys(a).length)return!1;for(const r in a){const l=n[r],c=a[r];if(!vf(l,c))return!1}return!0}function vf(n,a){if(typeof n=="number"||typeof n=="string"||typeof n=="boolean"||n===null)return n===a;if(typeof n!=typeof a||(n===null||a===null)&&n!==a||n instanceof Date&&a instanceof Date&&n.getTime()!==a.getTime())return!1;if(typeof n=="object")if(Array.isArray(n)&&Array.isArray(a)){if(n.length!==a.length)return!1;for(let r=n.length-1;r>=0;r--)if(!vf(n[r],a[r]))return!1;return!0}else return p1(n,a);return n===a}function Bh(n){if(typeof n!="object"||n===null)return n;if(n instanceof Date)return new Date(n);if(n instanceof Array)return n.map(Bh);const a={};for(const r in n)a[r]=Bh(n[r]);return a}var qb=2,g1=class{constructor(n){n&&(this._writable=n.writable,this._async=n.async),this._values={},this._state={}}setState(n,a=0){const r={};return this._wrapProperties(n,this._state,this._values,"",r,a),r}getState(){return this._values}getReactive(){return this._state}_wrapProperties(n,a,r,l,c,d){for(const m in n){const p=a[m],v=r[m],g=n[m];if(p&&(v===g&&typeof g!="object"||g instanceof Date&&v instanceof Date&&v.getTime()===g.getTime()))continue;const w=l+(l?".":"")+m;p?(p.__parse(g,w,c,d)&&(r[m]=g),d&qb?c[w]=p.__trigger:p.__trigger()):(g&&g.__reactive?a[m]=this._wrapNested(g,g,w,c):a[m]=this._wrapWritable(g),r[m]=g),c[w]=c[w]||null}}_wrapNested(n,a,r,l){const c=this._wrapWritable(n);return this._wrapProperties(n,c,a,r,l,0),c.__parse=(d,m,p,v)=>(this._wrapProperties(d,c,a,m,p,v),!1),c}_wrapWritable(n){const a=[],r=function(){for(let l=0;l<a.length;l++)a[l](n)};return{subscribe:l=>(a.push(l),this._async?setTimeout(l,1,n):l(n),()=>{const c=a.indexOf(l);c>=0&&a.splice(c,1)}),__trigger:()=>{a.length&&(this._async?setTimeout(r,1):r())},__parse:function(l){return n=l,!0}}}},v1=class{constructor(n,a,r,l){typeof n=="function"?this._setter=n:this._setter=n.setState.bind(n),this._routes=a,this._parsers=r,this._prev={},this._triggers=new Map,this._sources=new Map,this._routes.forEach(c=>{c.in.forEach(d=>{const m=this._triggers.get(d)||[];m.push(c),this._triggers.set(d,m)}),c.out.forEach(d=>{const m=this._sources.get(d)||{};c.in.forEach(p=>m[p]=!0),this._sources.set(d,m)})}),this._routes.forEach(c=>{c.length=Math.max(...c.in.map(d=>Gb(d,this._sources,1)))}),this._bus=l}init(n){const a={};for(const r in n)if(this._prev[r]!==n[r]){const l=this._parsers[r];a[r]=l?l(n[r]):n[r]}this._prev=this._prev?{...this._prev,...n}:{...n},this.setState(a),this._bus&&this._bus.exec("init-state",a)}setStateAsync(n){const a=this._setter(n,qb);return this._async?Object.assign(this._async.signals,a):this._async={signals:a,timer:setTimeout(this._applyState.bind(this),1)},a}_applyState(){const n=this._async;if(n){this._async=null,this._triggerUpdates(n.signals,[]);for(const a in n.signals){const r=n.signals[a];r&&r()}}}setState(n,a=[]){const r=this._setter(n);return this._triggerUpdates(r,a),r}_triggerUpdates(n,a){const r=Object.keys(n),l=!a.length;a=a||[];for(let c=0;c<r.length;c++){const d=r[c],m=this._triggers.get(d);m&&m.forEach(p=>{a.indexOf(p)==-1&&a.push(p)})}l&&this._execNext(a)}_execNext(n){for(;n.length;){n.sort((r,l)=>r.length<l.length?1:-1);const a=n[n.length-1];n.splice(n.length-1),a.exec(n)}}};function Gb(n,a,r){const l=a.get(n);if(!l)return r;const c=Object.keys(l).map(d=>Gb(d,a,r+1));return Math.max(...c)}var x1=class{constructor(){this._nextHandler=null,this._handlers={},this._tag=new WeakMap,this.exec=this.exec.bind(this)}on(n,a,r){let l=this._handlers[n];l?r&&r.intercept?l.unshift(a):l.push(a):l=this._handlers[n]=[a],r&&r.tag&&this._tag.set(a,r.tag)}intercept(n,a,r){this.on(n,a,{...r,intercept:!0})}detach(n){for(const a in this._handlers){const r=this._handlers[a];for(let l=r.length-1;l>=0;l--)this._tag.get(r[l])===n&&r.splice(l,1)}}async exec(n,a){const r=this._handlers[n];if(r)for(let l=0;l<r.length;l++){const c=r[l](a);if(c===!1||c&&c.then&&await c===!1)return}return this._nextHandler&&await this._nextHandler.exec(n,a),a}setNext(n){return this._nextHandler=n}};function y1(n){return a=>a[n]}function b1(n){return(a,r)=>a[n]=r}function Vr(n,a){return(a.getter||y1(a.id))(n)}function lh(n,a,r){return(a.setter||b1(a.id))(n,r)}function w1(n,a){const r=document.createElement("a");r.href=URL.createObjectURL(n),r.download=a,document.body.appendChild(r),r.click(),document.body.removeChild(r)}function Gr(n,a){let r=Vr(n,a)??"";return a.template?r=a.template(r,n,a):a.optionsMap&&(Array.isArray(r)?r=r.map(l=>a.optionsMap.get(l)).join(", "):r=a.optionsMap.get(r)),typeof r>"u"?"":r+""}function S1(n,a){const r=/\n|"|;|,/;let l="";const c=a.rows||`
13
- `,d=a.cols||" ",m=n._columns,p=n.flatData;a.header!==!1&&m[0].header&&(l=Zx("header",m,l,d,c));for(let v=0;v<p.length;v++){const g=[];for(let w=0;w<m.length;w++){let y=Gr(p[v],m[w]);r.test(y)&&(y='"'+y.replace(/"/g,'""')+'"'),g.push(y)}l+=(l?c:"")+g.join(d)}return a.footer!==!1&&m[0].footer&&(l=Zx("footer",m,l,d,c)),l}function Zx(n,a,r,l,c){const d=/\n|"|;|,/;for(let m=0;m<a[0][n].length;m++){const p=[];for(let v=0;v<a.length;v++){let g=(a[v][n][m].text||"")+"";d.test(g)&&(g='"'+g.replace(/"/g,'""')+'"'),p.push(g)}r+=(r?c:"")+p.join(l)}return r}const C1="portrait",j1=100,k1="a4",A1={a3:{width:11.7,height:16.5},a4:{width:8.27,height:11.7},letter:{width:8.5,height:11}};function N1(n,a){const r=[];let l=[],c=0;const d=n.filter(p=>!p.hidden),m=M1(a);return d.forEach((p,v)=>{c+p.width<=m?(c+=p.width,l.push(p)):(l.length&&r.push(l),l=[p],c=p.width),v===d.length-1&&l.length&&r.push(l)}),r}function Jx(n,a,r){const l=[];return n.forEach((c,d)=>{const m=c[a];for(let p=0;p<r.length;p++){l[p]||(l[p]=[]);const v={...m[p]};if(l[p][d]!==null){if(!d&&!v.rowspan&&!v.colspan){let g=1,w=n[d+g][a][p],y=v.width;for(;!w.rowspan&&!w.colspan;)g++,w=n[d+g][a][p],y+=w.width;v.colspan=g,v.width=y,v.height=r[p]}if(l[p].push(v),!v.collapsed&&v.colspan>1){let g=v.colspan-1;if(v.colspan+d>n.length){const w=v.colspan-(v.colspan+d-n.length);v.colspan=w,v.width=n.slice(d,d+g+1).reduce((y,b)=>y+b.width,0),w>1&&(g=w-1)}for(let w=0;w<g;w++)l[p].push(null)}if(v.rowspan>1){const g=v.rowspan;for(let w=1;w<g;w++)l[p+w]||(l[p+w]=[]),l[p+w].push(null)}}}if(c.collapsed)for(let p=0;p<l.length;p++){const v=l[p],g=v[d];if(g&&g.collapsed){if(v[d]=null,!p)break}else{const w=g||v.findLast(y=>y?.colspan>=1);w&&(w.colspan=w.colspan-1,w.width=w.width-c.width)}}}),l.map(c=>c.filter(d=>d&&d.colspan!==0))}function M1(n){const{mode:a,ppi:r,paper:l}=n,{width:c,height:d}=A1[l];return T1(a==="portrait"?c:d,r)}function T1(n,a){return n*a}function E1(n={}){const{mode:a,ppi:r,paper:l}=n;return{mode:a||C1,ppi:r||j1,paper:l||k1}}function Vb(n,a){return n.flexgrow?`min-width:${a}px;width:auto`:`width:${n.width}px; max-width:${n.width}px; height:${n.height}px`}function R1(n,a,r){let l=n[r.id];if(r.filter.type==="richselect"&&l){const c=r.filter.config?.options||a.find(({id:d})=>d==r.id).options;c&&(l=c.find(({id:d})=>d==l).label)}return l??""}const ey=["resize-column","hide-column","update-cell"],D1=["delete-row","update-row","update-cell"],L1=["move-item"],_1=["resize-column","move-item"];class z1{undo=[];redo=[];progress={};in;getState;setState;_previousValues={};constructor(a,r,l){this.in=a,this.getState=r,this.setState=l,this.setHandlers(),this.resetStateHistory()}getHandlers(){return{"add-row":{handler:a=>({action:"delete-row",data:{id:a.id},source:{action:"add-row",data:a}})},"delete-row":{handler:a=>{const{id:r}=a,{data:l}=this.getPrev(),c=l.findIndex(d=>d.id===r);return{action:"add-row",data:{id:r,row:l[c],before:c<l.length-1?l[c+1].id:void 0},source:{action:"delete-row",data:a}}}},"update-cell":{handler:a=>{const{id:r,column:l}=a,c=this.getRow(r),d=this.getColumn(l),m=Vr(c,d);return vf(m,a.value)?null:{action:"update-cell",data:{id:r,column:l,value:m},source:{action:"update-cell",data:a}}}},"update-row":{handler:a=>{const{id:r,row:l}=a,c=this.getRow(r);for(const d in l)Object.keys(c).includes(d)||(c[d]=void 0);return{action:"update-row",data:{id:r,row:c},source:{action:"update-row",data:a}}}},"copy-row":{handler:a=>{const{id:r}=a,{data:l}=this.getState(),c=l.findIndex(m=>m.id===r),d=l[c];return{action:"delete-row",data:{id:r},source:{action:"add-row",data:{id:r,row:d,before:c<l.length-1?l[c+1].id:void 0}}}}},"resize-column":{handler:a=>{const{id:r,width:l}=a,c=this.getColumn(r),{_sizes:d}=this.getState();return{action:"resize-column",data:{id:r,width:c.width??d.columnWidth},source:{action:"resize-column",data:{id:r,width:l}}}}},"hide-column":{handler:a=>{const{id:r}=a,l=this.getColumn(r);return{action:"hide-column",data:{id:r,mode:l.hidden},source:{action:"hide-column",data:a}}}},"collapse-column":{handler:a=>{const{id:r,row:l,mode:c}=a;return{action:"collapse-column",data:{id:r,row:l,mode:typeof c=="boolean"?!c:c},source:{action:"collapse-column",data:a}}}},"move-item":{handler:a=>{const{id:r,target:l,mode:c}=a,{flatData:d}=this.getPrev(),m=d.findIndex(p=>p.id===r);return{action:"move-item",data:{id:r,target:d[m+(m?-1:1)].id,mode:m?"after":"before"},source:{action:"move-item",data:{id:r,target:l,mode:c}}}}},"open-row":{handler:a=>{const{id:r,nested:l}=a;return{action:"close-row",data:{id:r,nested:l},source:{action:"open-row",data:a}}}},"close-row":{handler:a=>{const{id:r,nested:l}=a;return{action:"open-row",data:{id:r,nested:l},source:{action:"close-row",data:a}}}}}}resetHistory(){this.undo=[],this.redo=[],this.progress={},this.resetStateHistory()}getPrev(){return this._previousValues}setHandlers(){const a=this.getHandlers();for(const r in a)this.in.intercept(r,l=>{if(!(l.eventSource==="undo"||l.eventSource==="redo"||l.skipUndo)){if(_1.includes(r)){(l.inProgress&&!this.progress[r]||typeof l.inProgress!="boolean")&&(L1.includes(r)&&this.setPrev("flatData"),ey.includes(r)&&this.setPrev("columns")),this.progress[r]=l.inProgress;return}D1.includes(r)&&this.setPrev("data"),ey.includes(r)&&this.setPrev("columns")}}),this.in.on(r,l=>{if(l.eventSource==="undo"||l.eventSource==="redo"||l.skipUndo||l.inProgress)return;const c=a[r].handler(l);c&&this.addToHistory(c)})}setPrev(a){this._previousValues[a]=Bh(this.getState()[a])}addToHistory(a){this.undo.push(a),this.redo=[],this.setStateHistory()}handleUndo(){if(!this.undo.length)return;const a=this.undo.pop();this.redo.push({...a.source,source:a}),this.in.exec(a.action,{...a.data,eventSource:"undo"}),this.setStateHistory()}handleRedo(){if(!this.redo.length)return;const a=this.redo.pop();this.undo.push({...a.source,source:a}),this.in.exec(a.action,{...a.data,eventSource:"redo"}),this.setStateHistory()}resetStateHistory(){this.setState({history:{undo:0,redo:0}})}setStateHistory(){this.setState({history:{undo:this.undo.length,redo:this.redo.length}})}getRow(a){const{data:r}=this.getPrev();return this.getState().tree?this.getTreeRow(r,a):r.find(l=>l.id===a)}getTreeRow(a,r){for(let l=0;l<a.length;l++){if(a[l].id===r)return a[l];if(a[l].data){const c=this.getTreeRow(a[l].data,r);if(c)return c}}return null}getColumn(a){const{columns:r}=this.getPrev();return r.find(l=>l.id===a)}}function Wb(n,a){return typeof n>"u"||n===null?-1:typeof a>"u"||a===null?1:n===a?0:n>a?1:-1}function I1(n,a){return-Wb(n,a)}function O1(n,a){if(typeof a.sort=="function")return function(l,c){const d=a.sort(l,c);return n==="asc"?d:-d};const r=n==="asc"?Wb:I1;return function(l,c){return r(Vr(l,a),Vr(c,a))}}function H1(n,a){if(!n||!n.length)return;const r=n.map(l=>{const c=a.find(d=>d.id==l.key);return O1(l.order,c)});return n.length===1?r[0]:function(l,c){for(let d=0;d<r.length;d++){const m=r[d](l,c);if(m!==0)return m}return 0}}const Rd=28,B1=20;function F1(){if(typeof document>"u")return"willow";const n=document.querySelector('[class^="wx"][class$="theme"]');return n?n.className.substring(3,n.className.length-6):"willow"}function sf(n,a,r,l,c){const d=document.createElement("div"),m=document.createElement("div"),p=document.body;c=c?`${c}px`:"auto";let v,g;m.className=a,d.classList.add(`wx-${r}-theme`),d.style.cssText=`height:auto;position:absolute;top:0px;left:100px;overflow:hidden;width=${c};white-space:nowrap;`,d.appendChild(m),p.appendChild(d),typeof n!="object"&&(n=[n]);for(let w=0;w<n.length;w++){m.innerText=n[w]+"";const y=d.getBoundingClientRect(),b=Math.ceil(y.width)+(l&&l.length?l[w]:0),C=Math.ceil(y.height);v=Math.max(v||0,b),g=Math.max(g||0,C)}return d.remove(),{width:v,height:g}}function ty(n,a,r,l,c){const d=[];for(let m=0;m<n.length;m++){const p=n[m][a],v=p.length;for(let g=0;g<v;g++){const{text:w,vertical:y,collapsed:b,rowspan:C,css:j}=p[g];if(!w){d[g]=Math.max(d[g]||0,l);continue}let A=0;if(y&&!b){let N=`wx-measure-cell-${a}`;if(N+=j?` ${j}`:"",A=sf(w,N,c).width,(C>1||!p[g+1])&&r>g+1){const k=C||r-g,T=d.slice(g,g+k).reduce((R,q)=>R+q,0);if(T<A){const R=Math.ceil((A-T)/k);for(let q=g;q<g+k;q++)d[q]=(d[q]||l)+R}continue}}d[g]=Math.max(d[g]||l,A)}}return d}function P1(n,a,r){const l=[],c=[];let d="wx-measure-cell-body";d+=n.css?` ${n.css}`:"";for(let m=0;m<a.length;m++){const p=a[m],v=Gr(p,n);v&&(l.push(v),n.treetoggle?c.push(a[m].$level*Rd+(a[m].$count?Rd:0)+(n.draggable?Rd:0)):n.draggable&&c.push(Rd))}return sf(l,d,r,c).width}function $1(n,a){const r="wx-measure-cell-header",l=n.sort?B1:0;let c=n.header;if(typeof c=="string")return sf(c,r,a).width+l;let d;Array.isArray(c)||(c=[c]);for(let m=0;m<c.length;m++){const p=c[m],v=typeof p=="string"?p:p.text,g=r+(typeof p=="string"?"":` ${p.css}`);let w=sf(v,g,a).width;m===c.length-1&&(w+=l),d=Math.max(d||0,w)}return d}const U1={text:(n,a)=>n?n.toString().toLowerCase().indexOf(a.toLowerCase())!==-1:!a,richselect:(n,a)=>typeof a!="number"&&!a?!0:n==a,datepicker:(n,a)=>a?n&&G1(n,a):!0,multiselect:(n,a)=>!a||a?.length===0?!0:Array.isArray(n)?n?.some(r=>a.includes(r)):n&&a.includes(n)};function Yb(n){return U1[n]}function q1(n,a){const r=[];for(const l in n){const c=a.find(v=>v.id==l),{config:d,type:m}=c.header.find(v=>v.filter).filter,p=n[l];r.push(v=>{const g=Vr(v,c);return d?.handler?d.handler(g,p):Yb(m)(g,p)})}return l=>{for(let c=0;c<r.length;c++)if(!r[c](l))return!1;return!0}}function G1(n,a){return n.getFullYear()===a.getFullYear()&&n.getMonth()===a.getMonth()&&n.getDate()===a.getDate()}let V1=class extends g1{in;_router;_branches;_xlsxWorker;_historyManager;constructor(a){super({writable:a,async:!1});const r={rowHeight:37,columnWidth:160,headerHeight:36,footerHeight:36};this._router=new v1(super.setState.bind(this),[{in:["columns","sizes","_skin"],out:["_columns","_sizes"],exec:c=>{const{columns:d,sizes:m,_skin:p}=this.getState(),v=this.copyColumns(d),g=v.reduce((b,C)=>Math.max(C.header.length,b),0),w=v.reduce((b,C)=>Math.max(C.footer.length,b),0);v.forEach(this.setCollapsibleColumns);const y=this.normalizeSizes(v,m,g,w,p);for(let b=0;b<v.length;b++)this.normalizeColumns(v,b,"header",g,y),this.normalizeColumns(v,b,"footer",w,y);this.setState({_columns:v,_sizes:y},c)}},{in:["data","tree","_filterIds"],out:["flatData","_rowHeightFromData"],exec:c=>{const{data:d,tree:m,dynamic:p,_filterIds:v}=this.getState(),g=v&&new Set(v),w=m?this.flattenRows(d,[],v):g?d.filter(b=>g.has(b.id)):d,y=!p&&w.some(b=>b.rowHeight);this.setState({flatData:w,_rowHeightFromData:y},c)}}],{sizes:c=>({...r,...c})});const l=this.in=new x1;l.on("close-editor",({ignore:c})=>{const{editor:d}=this.getState();d&&(c||l.exec("update-cell",d),this.setState({editor:null}))}),l.on("open-editor",({id:c,column:d})=>{let m=this.getState().editor;m&&l.exec("close-editor",{});const p=this.getRow(c),v=d?this.getColumn(d):this.getNextEditor(p);if(v?.editor){let g=v.editor;if(typeof g=="function"&&(g=g(p,v)),!g)return;m={column:v.id,id:c,value:Vr(p,v)??"",renderedValue:Gr(p,v),type:g.type||g},typeof g=="object"&&g.config&&(m.config=g.config,g.config.options&&(m.options=g.config.options)),v.options&&!m.options&&(m.options=v.options),this.setState({editor:m})}}),l.on("editor",({value:c})=>{let d=this.getState().editor;if(d){d={...d},d.value=c;const m=this.getColumn(d.column),p={...this.getRow(d.id)};lh(p,m,c),d.renderedValue=Gr(p,m),this.setState({editor:d})}}),l.on("add-row",c=>{const d=this.getState();let{data:m}=d;const{select:p,_filterIds:v}=d,{row:g,before:w,after:y,select:b}=c;if(c.id=g.id=c.id||g.id||Dd(),w||y){const j=w||y,A=m.findIndex(N=>N.id===j);m=[...m],m.splice(A+(y?1:0),0,c.row)}else m=[...m,c.row];const C={data:m};v&&(C._filterIds=[...v,c.id]),this.setState(C),!(typeof b=="boolean"&&!b)&&(b||p)&&l.exec("select-row",{id:g.id,show:!0})}),l.on("delete-row",c=>{const{data:d,selectedRows:m,focusCell:p,editor:v}=this.getState(),{id:g}=c,w={data:d.filter(y=>y.id!==g)};this.isSelected(g)&&(w.selectedRows=m.filter(y=>y!==g)),v?.id===g&&(w.editor=null),this.setState(w),p?.row===g&&this.in.exec("focus-cell",{eventSource:"delete-row"})}),l.on("update-cell",c=>{const d=this.getState();let{data:m}=d;m=[...m];const{tree:p}=d,{id:v,column:g,value:w}=c,y=this.getColumn(g);if(p){const b={...this._branches[v]};lh(b,y,w);const C=this.updateTreeRow(b);b.$parent===0&&(m=C)}else{const b=m.findIndex(j=>j.id===v),C={...m[b]};lh(C,y,w),m[b]=C}this.setState({data:m})}),l.on("update-row",c=>{let{data:d}=this.getState();const{id:m,row:p}=c,v=d.findIndex(g=>g.id===m);d=[...d],d[v]={...d[v],...p},this.setState({data:d})}),l.on("select-row",({id:c,toggle:d,range:m,mode:p,show:v,column:g})=>{const w=this.getState(),{focusCell:y}=w;let{selectedRows:b}=w;if(b.length||(m=d=!1),m){const{data:C}=this.getState();let j=C.findIndex(N=>N.id===b[b.length-1]),A=C.findIndex(N=>N.id===c);j>A&&([j,A]=[A,j]),C.slice(j,A+1).forEach(N=>{this.isSelected(N.id)||b.push(N.id)})}else if(d&&this.isSelected(c)){if(p===!0)return;b=b.filter(C=>C!==c)}else if(d){if(p===!1)return;b.push(c)}else b=[c];this.setState({selectedRows:[...b]}),y?.row!==c&&this.in.exec("focus-cell",{eventSource:"select-row"}),v&&this.in.exec("scroll",{row:c,column:g})}),this.in.on("focus-cell",c=>{const{row:d,column:m,eventSource:p}=c,{_columns:v,split:g}=this.getState();d&&m?(this.setState({focusCell:{row:d,column:m}}),p!=="click"&&((!g.left||v.findIndex(w=>w.id===c.column)>=g.left)&&(!g.right||v.findIndex(w=>w.id===c.column)<v.length-g.right)?this.in.exec("scroll",{row:d,column:m}):this.in.exec("scroll",{row:d}))):this.setState({focusCell:null})}),l.on("resize-column",c=>{const{id:d,auto:m,maxRows:p,inProgress:v}=c;if(v===!1)return;let g=c.width||0;const w=[...this.getState().columns],y=this.getColumn(d);if(m){if(m==="data"||m===!0){const{flatData:b,_skin:C}=this.getState();let j=b.length;p&&(j=Math.min(p,j));const A=b.slice(0,j);g=P1(y,A,C)}if(m==="header"||m===!0){const{_skin:b}=this.getState();g=Math.max($1(y,b),g)}}y.width=Math.max(17,g),delete y.flexgrow,this.setState({columns:w})}),l.on("hide-column",c=>{const{id:d,mode:m}=c,p=[...this.getState().columns],v=this.getColumn(d),g=p.reduce((w,y)=>w+(y.hidden?0:1),0);!m||g>1?(v.hidden=!v.hidden,this.setState({columns:p})):c.skipUndo=!0}),l.on("sort-rows",c=>{const{key:d,add:m,sort:p}=c,v=this.getState(),{columns:g,data:w,tree:y}=v;if(p){const T=[...w];T.sort(p),this.setState({data:T});return}const{order:b="asc"}=c;let C=v.sortMarks;const j=Object.keys(C),A=j.length;!m||!A||A===1&&C[d]?C={[d]:{order:b}}:(A===1&&(C[j[0]]={...C[j[0]],index:0}),C={...C,[d]:{order:b,index:typeof m=="number"?m:C[d]?.index??A}});const N=Object.keys(C).sort((T,R)=>C[T].index-C[R].index).map(T=>({key:T,order:C[T].order}));this.setState({sortMarks:C});const k=H1(N,g);if(k){const T=[...w];y?this.sortTree(T,k):T.sort(k),this.setState({data:T})}}),l.on("filter-rows",c=>{const{value:d,key:m,filter:p}=c;if(!Object.keys(c).length){this.setState({filterValues:{},_filterIds:null});return}const v=this.getState(),{data:g,tree:w,_columns:y}=v;let b=v.filterValues;const C={};m&&(b={...b,[m]:d},C.filterValues=b);const j=p??q1(b,y);let A=[];w?A=this.filterTree(g,j,A):g.forEach(N=>{j(N)&&A.push(N.id)}),C._filterIds=A,this.setState(C)}),l.on("collapse-column",c=>{const{id:d,row:m,mode:p}=c,v=[...this.getState().columns],g=this.getColumn(d).header,w=Array.isArray(g)?g[m]:g;typeof w=="object"&&(w.collapsed=p??!w.collapsed,this.setState({columns:v}))}),l.on("move-item",c=>{const{id:d,inProgress:m}=c;let{target:p,mode:v="after"}=c;const{data:g,flatData:w,tree:y}=this.getState(),b=w.findIndex(A=>A.id===d);let C;if(v==="up"||v==="down"){if(v==="up"){if(b===0)return;C=b-1,v="before"}else if(v==="down"){if(b===w.length-1)return;C=b+1,v="after"}p=w[C]&&w[C].id}else C=w.findIndex(A=>A.id===p);if(b===-1||C===-1||m===!1)return;let j;y||(j=this.moveItem(d,p,g,v)),this.setState({data:y?this.normalizeTreeRows(j):j})}),l.on("copy-row",c=>{const{id:d,target:m,mode:p="after"}=c,v=this.getState(),{flatData:g,_filterIds:w}=v;let{data:y}=v;const b=this.getRow(d);if(!b)return;const C={...b,id:Dd()};c.id=C.id;const j=g.findIndex(N=>N.id===m);if(j===-1)return;y.splice(j+(p==="after"?1:0),0,C),y=[...y];const A={data:y};w&&(A._filterIds=[...w,C.id]),this.setState(A)}),l.on("open-row",c=>{const{id:d,nested:m}=c;this.toggleBranch(d,!0,m)}),l.on("close-row",c=>{const{id:d,nested:m}=c;this.toggleBranch(d,!1,m)}),l.on("export-data",c=>new Promise((d,m)=>{const p=c.format||"csv",v=`${c.fileName||"data"}.${p}`;if(p==="csv"){const g=S1(this.getState(),c.csv||{});c.download!==!1?w1(new Blob(["\uFEFF"+g],{type:"text/csv"}),v):c.result=g,d(!0)}else m()})),l.on("hotkey",({key:c,event:d,isInput:m})=>{switch(c){case"arrowup":{const{flatData:p,focusCell:v,select:g}=this.getState();if(d.preventDefault(),m)return;const w=v?v.column:this._getFirstVisibleColumn()?.id,y=v?this.getPrevRow(v.row)?.id:p[p.length-1]?.id;w&&y&&(this.in.exec("focus-cell",{row:y,column:w,eventSource:"key"}),g&&this.in.exec("select-row",{id:y}));break}case"arrowdown":{const{flatData:p,focusCell:v,select:g}=this.getState();if(d.preventDefault(),m)return;const w=v?v.column:this._getFirstVisibleColumn()?.id,y=v?this.getNextRow(v.row)?.id:p[0]?.id;w&&y&&(this.in.exec("focus-cell",{row:y,column:w,eventSource:"key"}),g&&this.in.exec("select-row",{id:y}));break}case"arrowright":{const{focusCell:p}=this.getState();if(m)return;if(d.preventDefault(),p){const v=this.getNextColumn(p.column,!0)?.id;v&&this.in.exec("focus-cell",{row:p.row,column:v,eventSource:"key"})}break}case"arrowleft":{const{focusCell:p}=this.getState();if(m)return;if(d.preventDefault(),p){const v=this.getPrevColumn(p.column,!0)?.id;v&&this.in.exec("focus-cell",{row:p.row,column:v,eventSource:"key"})}break}case"tab":{const{editor:p,focusCell:v,select:g}=this.getState();if(p){d.preventDefault();const w=p.column;let y=p.id,b=this.getNextEditor(this.getRow(y),this.getColumn(w));if(!b){const C=this.getNextRow(y);C&&(y=C.id,b=this.getNextEditor(C))}b&&(this.in.exec("open-editor",{id:y,column:b.id}),this.in.exec("focus-cell",{row:y,column:b.id,eventSource:"key"}),g&&!this.isSelected(y)&&this.in.exec("select-row",{id:y}))}else v&&this.in.exec("focus-cell",{eventSource:"key"});break}case"shift+tab":{const{editor:p,focusCell:v,select:g}=this.getState();if(p){d.preventDefault();const w=p.column;let y=p.id,b=this.getPrevEditor(this.getRow(y),this.getColumn(w));if(!b){const C=this.getPrevRow(y);C&&(y=C.id,b=this.getPrevEditor(C))}b&&(this.in.exec("open-editor",{id:y,column:b.id}),this.in.exec("focus-cell",{row:y,column:b.id,eventSource:"key"}),g&&!this.isSelected(y)&&this.in.exec("select-row",{id:y}))}else v&&this.in.exec("focus-cell",{eventSource:"key"});break}case"escape":{const{editor:p}=this.getState();p&&(this.in.exec("close-editor",{ignore:p.type!="multiselect"}),this.in.exec("focus-cell",{row:p.id,column:p.column,eventSource:"key"}));break}case"f2":{const{editor:p,focusCell:v}=this.getState();!p&&v&&this.in.exec("open-editor",{id:v.row,column:v.column});break}case"enter":{const{focusCell:p,tree:v}=this.getState();if(!m&&v&&p&&this.getColumn(p.column).treetoggle){const g=this.getRow(p.row);if(!g.data)return;this.in.exec(g.open?"close-row":"open-row",{id:p.row,nested:!0})}break}case"home":{const{editor:p,focusCell:v}=this.getState();if(!p&&v){d.preventDefault();const g=this._getFirstVisibleColumn()?.id;this.in.exec("focus-cell",{row:v.row,column:g,eventSource:"key"})}break}case"ctrl+home":{const{editor:p,focusCell:v,flatData:g,select:w}=this.getState();if(!p&&v){d.preventDefault();const y=g[0]?.id,b=this._getFirstVisibleColumn()?.id;y&&b&&(this.in.exec("focus-cell",{row:y,column:b,eventSource:"key"}),w&&!this.isSelected(y)&&this.in.exec("select-row",{id:y}))}break}case"end":{const{editor:p,focusCell:v}=this.getState();if(!p&&v){d.preventDefault();const g=this._getLastVisibleColumn()?.id,w=v.row;this.in.exec("focus-cell",{row:w,column:g,eventSource:"key"})}break}case"ctrl+end":{const{editor:p,focusCell:v,flatData:g,select:w}=this.getState();if(!p&&v){d.preventDefault();const y=g.at(-1).id,b=this._getLastVisibleColumn()?.id;y&&b&&(this.in.exec("focus-cell",{row:y,column:b,eventSource:"key"}),w&&!this.isSelected(y)&&this.in.exec("select-row",{id:y}))}break}case"ctrl+z":{this.in.exec("undo",{});break}case"ctrl+y":{this.in.exec("redo",{});break}}}),l.on("scroll",c=>{const{_columns:d,split:m,_sizes:p,flatData:v,dynamic:g,_rowHeightFromData:w}=this.getState();let y=-1,b=-1,C=0,j=0;if(c.column){y=0;const A=d.findIndex(N=>N.id===c.column);C=d[A].width;for(let N=m.left??0;N<A;N++){const k=d[N];k.hidden||(y+=k.width)}}if(c.row&&!g){const A=v.findIndex(N=>N.id===c.row);A>=0&&(w?(b=v.slice(0,A).reduce((N,k)=>N+(k.rowHeight||p.rowHeight),0),j=v[A].rowHeight):b=p.rowHeight*A)}this.setState({scroll:{top:b,left:y,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=E1(c);this.setState({_print:d}),this.setStateAsync({_print:null})}),l.on("undo",()=>{this._historyManager?.handleUndo()}),l.on("redo",()=>{this._historyManager?.handleRedo()}),this.initOnce()}getXlsxWorker(a){if(!this._xlsxWorker){const r=window.URL.createObjectURL(new Blob([`importScripts('${a}');`],{type:"text/javascript"}));this._xlsxWorker=new Promise(l=>{const c=new Worker(r);c.addEventListener("message",d=>{d.data.type==="init"&&l(c)})})}return this._xlsxWorker}initOnce(){const a={sortMarks:{},_filterIds:null,data:[],filterValues:{},scroll:null,scrollLeft:0,scrollTop:0,editor:null,focusCell:null,_print:null,history:{undo:0,redo:0},search:null};this._router.init(a)}init(a){a.hasOwnProperty("_skin")&&!a._skin&&(a._skin=F1()),a.columns&&a.columns.forEach(r=>{r.options&&(r.optionsMap=new Map(r.options.map(l=>[l.id,l.label])))}),vf(this.getState().data,a.data)||(a.tree?a.data=this.normalizeTreeRows(a.data):a.data=this.normalizeRows(a.data),this.setState({_filterIds:null,filterValues:{},sortMarks:{},search:null}),this._historyManager&&this._historyManager.resetHistory()),a.tree&&(a.undo=!1,a.reorder=!1),a.split?.right&&(a.split.right=0),a.undo&&!this._historyManager&&(this._historyManager=new z1(this.in,this.getState.bind(this),this.setState.bind(this))),this._router.init({...a})}setState(a,r){return this._router.setState(a,r)}setStateAsync(a){this._router.setStateAsync(a)}getRow(a){const{tree:r}=this.getState();return r?this._branches[a]:this.getState().data.find(l=>l.id===a)}getRowIndex(a,r){return r||(r=this.getState().flatData),r.findIndex(l=>l.id===a)}getNextRow(a){const r=this.getState().flatData,l=this.getRowIndex(a,r);return r[l+1]}getPrevRow(a){const r=this.getState().flatData,l=this.getRowIndex(a,r);return r[l-1]}getColumn(a){return this.getState().columns.find(r=>r.id===a)}getNextColumn(a,r){const l=this.getState()._columns,c=l.findIndex(d=>d.id===a);return r?this._getFirstVisibleColumn(c+1):l[c+1]}getPrevColumn(a,r){const l=this.getState()._columns,c=l.findIndex(d=>d.id===a);return r?this._getLastVisibleColumn(c-1):l[c-1]}_getFirstVisibleColumn(a){const r=this.getState()._columns;let l=a??0;for(;l<r.length&&(r[l]?.hidden||r[l]?.collapsed);)l++;return r[l]}_getLastVisibleColumn(a){const r=this.getState()._columns;let l=a??r.length-1;for(;l<r.length&&(r[l]?.hidden||r[l]?.collapsed);)l--;return r[l]}isCellEditable(a,r){const{editor:l,hidden:c}=r;return!l||c?!1:typeof l=="function"?l(a,r):!0}getNextEditor(a,r){let l=this.getState().columns;if(r){const c=l.findIndex(d=>d.id===r.id);l=l.slice(c+1)}return l.find(c=>this.isCellEditable(a,c))}getPrevEditor(a,r){let l=this.getState().columns;if(r){const c=l.findLastIndex(d=>d.id===r.id);l=l.slice(0,c)}return l.findLast(c=>this.isCellEditable(a,c))}toggleBranch(a,r,l){let c=this._branches[a],{data:d}=this.getState();if(d=[...d],a!==0){c={...c,open:r};const m=this.updateTreeRow(c);c.$parent===0&&(d=m)}l&&c.data?.length&&c.data.forEach(m=>{const p=this.toggleKids(m,r,l);a===0&&(d=p)}),this.setState({data:d})}toggleKids(a,r,l){a={...a,open:r};const c=this.updateTreeRow(a);return l&&a.data?.length&&a.data.forEach(d=>{this.toggleKids(d,r,l)}),c}updateTreeRow(a){const r=a.id;this._branches[r]=a;const l=this._branches[a.$parent],c=l.data.findIndex(d=>d.id===r);return l.data=[...l.data],l.data[c]=a,l.data}isSelected(a){return this.getState().selectedRows.indexOf(a)!==-1}findAndRemove(a,r){for(let l=0;l<a.length;l++){if(a[l].id===r)return a.splice(l,1)[0];if(a[l].data){const c=[...a[l].data],d=this.findAndRemove(c,r);if(d)return a[l]={...a[l],data:c},d}}return null}insertItem(a,r,l,c){for(let d=0;d<a.length;d++){if(a[d].id===r){const m=a[d],p=c==="before"?d:d+1;if(m.data){if(c==="before"){const v=d>0?a[d-1]:null;return v?.data&&v.open?a[d-1]={...v,data:[...v.data,l]}:a.splice(p,0,l),!0}else if(m.open)return a[d]={...m,data:[l,...m.data]},!0}return a.splice(p,0,l),!0}if(a[d].data&&(a[d]={...a[d],data:[...a[d].data]},this.insertItem(a[d].data,r,l,c)))return!0}return!1}moveItem(a,r,l,c){const d=[...l],m=this.findAndRemove(d,a);return this.insertItem(d,r,m,c),d}copyColumns(a){const r=[];for(let l=0;l<a.length;l++){const c={...a[l]};this.copyHeaderFooter(c,"header"),this.copyHeaderFooter(c,"footer"),r[l]=c}return r}copyHeaderFooter(a,r){let l=a[r];l=Array.isArray(l)?[...l]:[l],l.forEach((c,d)=>{l[d]=typeof c=="string"?{text:c}:{...c}}),a[r]=l}setCollapsibleColumns(a,r,l){let c=a.header;for(let d=0;d<c.length;d++){const m=c[d];if(m.collapsible&&m.collapsed){if(m.collapsible!=="first"){a.collapsed=!0,a.width=36,m.vertical=!0;const v=c.length-d;c=c.slice(0,d+1),c[d].rowspan=v}const p=m.colspan;if(p){const v=c[d+1];let g=1;v&&v.colspan&&!v.collapsed&&(g=v.colspan);for(let w=g;w<p;w++){const y=l[r+w];y&&(y.hidden=!0)}}}}}normalizeColumns(a,r,l,c,d){const m=a[r];m.width||(m.width=m.flexgrow?17:d.columnWidth),m._colindex=r+1;const p=m[l],v=d[`${l}RowHeights`];for(let g=0;g<c;g++){const w=p[g];w.id=m.id,g===p.length-1&&(w.rowspan=w.rowspan?Math.min(w.rowspan,c-g):c-g);for(let y=1;y<w.rowspan;y++){p.splice(g+y,0,{_hidden:!0});for(let b=1;b<w.colspan;b++)a[r+b][l].splice(g+y,0,{})}if(w.rowspan){const y=(w.rowspan===c?v:v.slice(g,w.rowspan+g)).reduce((b,C)=>b+C,0);w.height=y,g+w.rowspan!=c&&w.height--}if(w.colspan){let y=m.width,b=m.flexgrow||0;const C=w.colspan;for(let j=1;j<C;j++){const A=a[r+j];A&&(A.hidden?w.colspan-=1:A.flexgrow?b+=A.flexgrow:y+=A.width||d.columnWidth),b?w.flexgrow=b:w.width=y}}else w.width=m.width,w.flexgrow=m.flexgrow;l==="header"&&w.filter&&typeof w.filter=="string"&&(w.filter={type:w.filter})}p.length>c&&(p.length=c),m[l]=p}normalizeRows(a){for(let r=0;r<a.length;r++)a[r].id||(a[r].id=Dd());return a}normalizeTreeRows(a,r,l){return!r&&!l&&(this._branches={0:{data:a}}),a.forEach(c=>{c.id||(c.id=Dd()),c.$level=r||0,c.$parent=l||0,this._branches[c.id]=c,c.data&&(c.data.length?(c.$count=c.data.length,this.normalizeTreeRows(c.data,c.$level+1,c.id)):(delete c.data,delete c.$count,delete c.open))}),a}sortTree(a,r){a.sort(r),a.forEach(l=>{l.data&&this.sortTree(l.data,r)})}filterTree(a,r,l){return a.forEach(c=>{r(c)&&l.push(c.id),c.data&&this.filterTree(c.data,r,l)}),l}flattenRows(a,r,l){const c=r;return a.forEach(d=>{(!l||l.includes(d.id))&&c.push(d),d.data?.length&&d.open!==!1&&this.flattenRows(d.data,c,l)}),c}createFilter(a){const{_columns:r}=this.getState(),l=[];for(const c in a){const d=r.find(g=>g.id==c),{config:m,type:p}=d.header.find(g=>g.filter).filter,v=a[c];l.push(g=>{const w=Vr(g,d);return m?.handler?m.handler(w,v):Yb(p)(w,v)})}return c=>{for(let d=0;d<l.length;d++)if(!l[d](c))return!1;return!0}}searchRows(a,r){a=a.trim().toLowerCase();const l={};if(!a)return l;const{flatData:c,columns:d}=this.getState(),m=r?d.filter(p=>r[p.id]):d;return c.forEach(p=>{const v={};m.forEach(g=>{const w=Gr(p,g);String(w).toLowerCase().includes(a)&&(v[g.id]=!0)}),Object.keys(v).length&&(l[p.id]=v)}),l}normalizeSizes(a,r,l,c,d){const m=ty(a,"header",l,r.headerHeight,d),p=ty(a,"footer",c,r.footerHeight,d),v=m.reduce((w,y)=>w+y,0),g=p.reduce((w,y)=>w+y,0);return{...r,headerRowHeights:m,footerRowHeights:p,headerHeight:v,footerHeight:g}}},W1=new Date().valueOf();function Dd(){return"temp://"+W1++}function Y1(n,a="data-id"){let r=n;for(!r.tagName&&n.target&&(r=n.target);r;){if(r.getAttribute&&r.getAttribute(a))return r;r=r.parentNode}return null}new Date().valueOf();var K1=class{constructor(){this.store=new Map}configure(n,a){this.node=a;for(const r in n)if(n[r]){const l=r.toLowerCase().replace(/[ ]/g,""),c=n[r];this.store.set(l,c)}}},Io=[],Q1={subscribe:n=>{X1();const a=new K1;return Io.push(a),n(a),()=>{const r=Io.findIndex(l=>l===a);r>=0&&Io.splice(r,1)}}},ny=!1;function X1(){ny||(ny=!0,document.addEventListener("keydown",n=>{if(Io.length&&(n.ctrlKey||n.altKey||n.metaKey||n.shiftKey||n.key.length>1||n.key===" ")){const a=[];n.ctrlKey&&a.push("ctrl"),n.altKey&&a.push("alt"),n.metaKey&&a.push("meta"),n.shiftKey&&a.push("shift");let r=n.code.replace("Key","").toLocaleLowerCase();n.key===" "&&(r="space"),a.push(r);const l=a.join("+");for(let c=Io.length-1;c>=0;c--){const d=Io[c],m=d.store.get(l)||d.store.get(r);m&&d.node.contains(n.target)&&m(n,{key:l,evKey:r})}}}))}const Z1={tab:!0,"shift+tab":!0,arrowup:!0,arrowdown:!0,arrowright:!0,arrowleft:!0,enter:!0,escape:!0,f2:!0,home:!0,end:!0,"ctrl+home":!0,"ctrl+end":!0,"ctrl+z":!0,"ctrl+y":!0};function J1(n,{keys:a,exec:r}){if(!a)return;function l(m){const p=m.target;return p.tagName==="INPUT"||p.tagName==="TEXTAREA"||Y1(p,"data-header-id")?.classList.contains("wx-filter")||!!p.closest(".wx-cell.wx-editor")}const c={};for(const m in a){const p=a[m];typeof p<"u"&&(typeof p=="function"?c[m]=p:p&&(c[m]=v=>{const g=l(v);r({key:m,event:v,isInput:g})}))}const d=Q1.subscribe(m=>{m.configure(c,n)});return{destroy:()=>{d()}}}function eA(n,a){let r=null;a.scroll.subscribe(l=>{if(!l||l===r)return;r=l;const{left:c,top:d,height:m,width:p}=l,v=a.getHeight(),g=a.getWidth(),w=a.getScrollMargin();if(d>=0){const y=n.scrollTop;d<y?n.scrollTop=d:d+m>y+v&&(n.scrollTop=d-v+m)}if(c>=0){const y=n.scrollLeft;c<y?n.scrollLeft=c:c+p>y+g-w&&(n.scrollLeft=c-g+p+w)}}),a.scrollLeft?.subscribe?.(l=>{requestAnimationFrame(()=>{Math.abs(n.scrollLeft-l)>1&&(n.scrollLeft=l)})}),a.scrollTop?.subscribe?.(l=>{requestAnimationFrame(()=>{Math.abs(n.scrollTop-l)>1&&(n.scrollTop=l)})})}const Xa=u.createContext(null);function tA(n,a){const r=new ResizeObserver(l=>{requestAnimationFrame(()=>a(l[0].contentRect))});return r.observe(n.parentNode),{destroy(){r.disconnect()}}}const ay=5,nA=700;function Gd(n){const a=n.getBoundingClientRect(),r=document.body,l=a.top+r.scrollTop-r.clientTop||0,c=a.left+r.scrollLeft-r.clientLeft||0;return{y:Math.round(l),x:Math.round(c),width:n.offsetWidth,height:n.offsetHeight}}function Fh(n,a){const r=Gd(a);return{x:n.clientX-r.x,y:n.clientY-r.y}}function aA(n,a){const r=a.current;let l=null,c,d,m=!1,p=!1;const v=document.createElement("DIV");v.className="wx-drag-zone",v.setAttribute("tabindex",-1);function g(){clearTimeout(c),c=null}function w(_){const L=Bo(_);L&&(l={container:v,sourceNode:_.target,from:hf(L),pos:Fh(_,n)},d=l.pos,y(_))}function y(_){if(!l)return;const L=l.pos=Fh(_,n);if(!m){if(!p&&!_?.target?.getAttribute("draggable-data")&&Math.abs(d.x-L.x)<ay&&Math.abs(d.y-L.y)<ay)return;if(O(_)===!1)return Y()}if(p){const ae=window.scrollX||document.documentElement.scrollLeft||document.body.scrollLeft,G=window.scrollY||document.documentElement.scrollTop||document.body.scrollTop;l.targetNode=document.elementFromPoint(_.pageX-ae,_.pageY-G)}else l.targetNode=_.target;r.move&&r.move(_,l),v.style.left=-(l.offset?l.offset.x:0)+"px",v.style.top=l.pos.y+(l.offset?l.offset.y:0)+"px"}function b(_){v.parentNode&&v.parentNode.removeChild(v),v.innerHTML="",m&&r.end&&r.end(_,l),l=d=null,Y()}function C(_){r.getReorder&&!r.getReorder()||_.button===0&&(q(_),window.addEventListener("mousemove",j),window.addEventListener("mouseup",A),w(_))}function j(_){y(_)}function A(_){b(_)}function N(_){if(r.getReorder&&!r.getReorder())return;c=setTimeout(()=>{p=!0,w(_.touches[0])},nA),q(_);function L(){c&&g(),_.target.removeEventListener("touchmove",k),_.target.removeEventListener("touchend",L),b(_)}_.target.addEventListener("touchmove",k),_.target.addEventListener("touchend",L),n.addEventListener("contextmenu",T)}function k(_){m?(_.preventDefault(),y(_.touches[0])):c&&g()}function T(_){if(m||c)return _.preventDefault(),!1}function R(_){_.preventDefault()}function q(_){if(!r.getDraggableInfo)return;const{hasDraggable:L}=r.getDraggableInfo();(!L||_.target.getAttribute("draggable-data"))&&(document.body.style.userSelect="none",document.body.style.webkitUserSelect="none")}function O(_){if(m=!0,r.start){if(r.start(_,l)===!1)return!1;n.appendChild(v),document.body.style.cursor="move"}}function Y(_){m=p=!1,document.body.style.cursor="",document.body.style.userSelect="",document.body.style.webkitUserSelect="",window.removeEventListener("mousemove",j),window.removeEventListener("mouseup",A),_&&(n.removeEventListener("mousedown",C),n.removeEventListener("touchstart",N),n.removeEventListener("dragstart",R))}return n.addEventListener("mousedown",C),n.addEventListener("touchstart",N),n.addEventListener("dragstart",R),{destroy(){Y(!0)}}}const sA=.004;function iA(){return{dirX:0,dirY:0,scrollSpeedFactor:1}}function rA(n,a,r,l){const{node:c,left:d,top:m,bottom:p,sense:v,xScroll:g,yScroll:w}=l,y=Fh(n,c);r.scrollState||(r.scrollState=iA());let b=0,C=0;y.x<d+v?b=-1:y.x>a.width-v&&(b=1),y.y<m+Math.round(v/2)?C=-1:y.y>a.height-p-Math.round(v/2)&&(C=1),(r.scrollState.dirX!==b||r.scrollState.dirY!==C)&&(Kb(r),r.scrollState.dirX=b,r.scrollState.dirY=C),(g&&r.scrollState.dirX!==0||w&&r.scrollState.dirY!==0)&&lA(r,l,{x:r.scrollState.dirX,y:r.scrollState.dirY})}function lA(n,a,r){n.autoScrollTimer||(n.autoScrollTimer=setTimeout(()=>{n.activeAutoScroll=setInterval(oA,15,n,a,r)},250))}function Kb(n){n.scrollSpeedFactor=1,n.autoScrollTimer&&(n.autoScrollTimer=clearTimeout(n.autoScrollTimer),n.activeAutoScroll=clearInterval(n.activeAutoScroll))}function oA(n,a,r){const{x:l,y:c}=r;n.scrollSpeedFactor+=sA,l!==0&&uA(n,a,l),c!==0&&cA(n,a,c)}function cA(n,a,r){const l=a.node.scrollTop;Qb(l+Math.round(a.sense/3)*n.scrollSpeedFactor*r,"scrollTop",a)}function uA(n,a,r){const l=a.node.scrollLeft;Qb(l+Math.round(a.sense/3)*n.scrollSpeedFactor*r,"scrollLeft",a)}function Qb(n,a,r){r.node[a]=n}function xf(n,a,r,l,c,d){const m={};return n&&(m.width=`${n}px`,m.minWidth=`${n}px`),a&&(m.flexGrow=a),d&&(m.height=`${d}px`),r&&(m.position="sticky",r.left&&(m.left=`${l}px`),r.right&&(m.right=`${c}px`)),m}function Xb(n,a,r){let l="";if(n.fixed)for(const c in n.fixed){let d=n.fixed[c]===-1;!d&&n.fixed.leftSize&&a.colspan&&(d=a.colspan+n._colindex-1===n.fixed.leftSize),l+=d?"wx-shadow ":"wx-fixed "}return l+=a.rowspan>1?"wx-rowspan ":"",l+=a.colspan>1?"wx-colspan ":"",l+=a.vertical?"wx-vertical ":"",l+=r?r(n)+" ":"",l}function dA(n){const{row:a,column:r,cellStyle:l=null,columnStyle:c=null,children:d,focusable:m}=n,p=u.useContext(Xa),v=lt(p,"focusCell"),g=lt(p,"search"),w=lt(p,"reorder"),y=u.useMemo(()=>g?.rows[a.id]&&g.rows[a.id][r.id],[g,a.id,r.id]),b=u.useMemo(()=>xf(r.width,r.flexgrow,r.fixed,r.left,r.right),[r.width,r.flexgrow,r.fixed,r.left,r.right]);function C(O,Y){let _="wx-cell";return _+=r.fixed?" "+(r.fixed===-1?"wx-shadow":"wx-fixed"):"",_+=O?" "+O(r):"",_+=Y?" "+Y(a,r):"",_+=r.treetoggle?" wx-tree-cell":"",_}const j=u.useMemo(()=>C(c,l),[c,l,r,a]),A=u.useMemo(()=>typeof r.draggable=="function"?r.draggable(a,r)!==!1:r.draggable,[r,a]),N=u.useRef(null);u.useEffect(()=>{N.current&&m&&v?.row===a.id&&v?.column===r.id&&N.current.focus()},[v,m,a.id,r.id]);const k=u.useCallback(()=>{m&&!v&&p.exec("focus-cell",{row:a.id,column:r.id,eventSource:"focus"})},[p,m,v,a.id,r.id]);function T(O){const Y=new RegExp(`(${g.value.trim()})`,"gi");return String(O).split(Y).map(_=>({text:_,highlight:Y.test(_)}))}const R=u.useMemo(()=>{const O=r.fixed&&r.fixed.left===-1||r.fixed.right===-1,Y=r.fixed&&r.fixed.right;return[j,O?"wx-shadow":"",Y?"wx-fixed-right":""].filter(Boolean).join(" ")},[j,r]),q=r.cell;return s.jsxs("div",{className:"wx-TSCaXsGV "+R,ref:N,onFocus:k,style:b,"data-row-id":Bn(a.id),"data-col-id":Bn(r.id),tabIndex:m?"0":"-1",role:"gridcell","aria-colindex":r._colindex,"aria-readonly":r.editor?void 0:!0,children:[w&&r.draggable?A?s.jsx("i",{"draggable-data":"true",className:"wx-TSCaXsGV wx-draggable wxi-drag"}):s.jsx("i",{className:"wx-TSCaXsGV wx-draggable-stub"}):null,r.treetoggle?s.jsxs(s.Fragment,{children:[s.jsx("span",{style:{marginLeft:`${a.$level*28}px`}}),a.$count?s.jsx("i",{"data-action":"toggle-row",className:`wx-TSCaXsGV wx-table-tree-toggle wxi-menu-${a.open!==!1?"down":"right"}`}):null]}):null,q?s.jsx(q,{api:p,row:a,column:r,onAction:({action:O,data:Y})=>p.exec(O,Y)}):d?d():y?s.jsx("span",{children:T(Gr(a,r)).map(({highlight:O,text:Y},_)=>O?s.jsx("mark",{className:"wx-TSCaXsGV wx-search",children:Y},_):s.jsx("span",{children:Y},_))}):Gr(a,r)]})}function sy(n,a){let r,l;function c(p){r=p.clientX,n.style.opacity=1,document.body.style.cursor="ew-resize",document.body.style.userSelect="none",window.addEventListener("mousemove",d),window.addEventListener("mouseup",m),a&&a.down&&a.down(n)}function d(p){l=p.clientX-r,a&&a.move&&a.move(l)}function m(){n.style.opacity="",document.body.style.cursor="",document.body.style.userSelect="",a&&a.up&&a.up(l),window.removeEventListener("mousemove",d),window.removeEventListener("mouseup",m)}return n.addEventListener("mousedown",c),{destroy(){n.removeEventListener("mousedown",c)}}}function fA({filter:n,column:a,action:r,filterValue:l}){function c({value:d}){r({value:d,key:a.id})}return s.jsx(dp,{...n.config??{},value:l,onChange:c})}function mA({filter:n,column:a,action:r,filterValue:l}){const c=u.useContext(Xa),d=lt(c,"flatData"),m=u.useMemo(()=>n?.config?.options||a?.options||v(),[n,a,d]),p=u.useMemo(()=>n?.config?.template,[n]);function v(){const y=[];return d.forEach(b=>{const C=Vr(b,a);y.includes(C)||y.push(C)}),y.map(b=>({id:b,label:b}))}function g({value:y}){r({value:y,key:a.id})}function w(y){y.key!=="Tab"&&y.preventDefault()}return s.jsx("div",{style:{width:"100%"},onKeyDown:w,children:s.jsx(Nk,{placeholder:"",clear:!0,...n?.config??{},options:m,value:l,onChange:g,children:y=>p?p(y):y.label})})}function hA({filter:n,column:a,action:r,filterValue:l}){function c({value:d}){r({value:d,key:a.id})}return s.jsx("div",{className:"wx-aaaK5VYO",style:{width:"100%"},children:s.jsx(Ak,{placeholder:"",clear:!0,...n?.config??{},value:l,onChange:c})})}function Zb(n){const{value:a,options:r=[],placeholder:l="",clear:c=!1,text:d=null,template:m=null,cell:p=null,dropdown:v={},autoOpen:g=!1,onChange:w,onAction:y}=n,[b,C]=Ib(a||[]),j=u.useMemo(()=>(b||[]).map(G=>r.find(te=>te.id===G)).filter(Boolean),[b,r]),A=u.useRef(null),N=u.useRef(null),[k,T]=u.useState(null),R=()=>{const G=b||[];if(!G.length)return 0;const te=r.find(P=>G.includes(P.id));return te?r.indexOf(te):0};function q(G){N.current=G.navigate,T(()=>G.keydown),g&&G.navigate(R())}u.useEffect(()=>{g&&(A.current?.focus(),typeof window<"u"&&window.getSelection&&window.getSelection().removeAllRanges())},[]);function O({id:G}){C(G),w&&w({value:G})}function Y(G){G.stopPropagation(),C([]),w&&w({value:[]})}function _(){N.current?.(R())}function L(){N.current?.(null)}function ae(G){k?.(G,R())}return s.jsxs("div",{ref:A,className:"wx-multiselect wx-aadNNOwy",onClick:_,onKeyDown:ae,tabIndex:0,children:[s.jsx("div",{className:"wx-label wx-aadNNOwy",children:m?m(j):p?s.jsx(p,{data:j,onAction:y}):d?s.jsx("span",{className:"wx-text wx-aadNNOwy",children:d}):j.length?s.jsx("span",{className:"wx-text wx-aadNNOwy",children:j.map(G=>G.label).join(", ")}):l?s.jsx("span",{className:"wx-placeholder wx-aadNNOwy",children:l}):" "}),c&&b?.length?s.jsx("i",{className:"wx-icon wxi-close wx-aadNNOwy",onClick:Y}):s.jsx("i",{className:"wx-icon wxi-angle-down wx-aadNNOwy"}),s.jsx(gf,{items:r,onReady:q,onSelect:O,multiselect:!0,checkboxes:!0,value:b||[],onCancel:L,...v,children:({option:G})=>s.jsx("div",{className:"wx-option wx-aadNNOwy",children:m?m(G):p?s.jsx(p,{data:G,onAction:y}):G.label})})]})}function pA({filter:n,column:a,action:r,filterValue:l}){const c=u.useContext(Pn.i18n)?.getGroup("grid")||tu(hp).getGroup("grid"),d=u.useMemo(()=>({clear:!0,...n?.config||{}}),[n]),m=u.useMemo(()=>d.options||a.options,[d,a]),p=u.useMemo(()=>{const w=l?.length;return w?w<3?l.map(y=>a.optionsMap.get(y)).join(", "):w+" "+c("selected"):""},[l,a,c]);function v({value:w}){r({value:w,key:a.id})}function g(w){w.key!=="Tab"&&w.preventDefault()}return s.jsx("div",{style:{width:"100%"},onKeyDown:g,children:s.jsx(Zb,{placeholder:"",...d,options:m,value:l||[],text:p,onChange:v})})}const gA={text:fA,richselect:mA,datepicker:hA,multiselect:pA};function vA({filter:n,column:a}){const r=u.useContext(Xa),l=lt(r,"filterValues");function c(m){r.exec("filter-rows",m)}const d=u.useMemo(()=>gA[n.type],[n.type]);return s.jsx(d,{filter:n,column:a,action:c,filterValue:l[a.id]})}function xA(n){const{cell:a,column:r,row:l,lastRow:c,sortRow:d,columnStyle:m,bodyHeight:p,hasSplit:v}=n,g=u.useContext(Xa),w=lt(g,"sortMarks"),y=u.useMemo(()=>w?w[r.id]:void 0,[w,r.id]),b=u.useRef(),C=u.useCallback(ie=>{b.current=a.flexgrow?ie.parentNode.clientWidth:a.width},[a.flexgrow,a.width]),j=u.useCallback((ie,K)=>{g.exec("resize-column",{id:a.id,width:Math.max(1,(b.current||0)+ie),inProgress:K})},[g,a.id]),A=u.useCallback(ie=>j(ie,!0),[j]),N=u.useCallback(ie=>j(ie,!1),[j]),k=u.useCallback(ie=>{if(!r.sort||a.filter)return;let K=y?.order;K&&(K=K==="asc"?"desc":"asc"),g.exec("sort-rows",{key:a.id,add:ie.ctrlKey||ie.metaKey,order:K})},[g,a.id,a.filter,r.sort,y?.order]),T=u.useCallback(ie=>{ie&&ie.stopPropagation(),g.exec("collapse-column",{id:a.id,row:l})},[g,a.id,l]),R=u.useCallback(ie=>{ie.key==="Enter"&&T()},[T]),q=u.useCallback(ie=>{ie.key==="Enter"&&!a.filter&&k(ie)},[k,a.filter]),O=u.useMemo(()=>a.collapsed&&r.collapsed,[a.collapsed,r.collapsed]),Y=u.useMemo(()=>O&&!v&&a.collapsible!=="header",[O,v,a.collapsible]),_=u.useMemo(()=>Y?{top:-p/2,position:"absolute"}:{},[Y,p]),L=u.useMemo(()=>xf(a.width,a.flexgrow,r.fixed,r.left,a.right??r.right,a.height+(O&&Y?p:0)),[a.width,a.flexgrow,r.fixed,r.left,a.right,r.right,a.height,O,Y,p]),ae=u.useMemo(()=>Xb(r,a,m),[r,a,m]),G=u.useCallback(()=>Object.fromEntries(Object.entries(a).filter(([ie])=>ie!=="cell")),[a]),te=`wx-cell ${ae} ${a.css||""} wx-collapsed`,P=["wx-cell",ae,a.css||"",a.filter?"wx-filter":"",r.fixed&&r.fixed.right?"wx-fixed-right":""].filter(Boolean).join(" "),ye=u.useRef(null);return u.useEffect(()=>{const ie=ye.current;if(!ie)return;const K=sy(ie,{down:C,move:A,up:N});return()=>{typeof K=="function"&&K()}},[C,A,N,sy]),O?s.jsx("div",{className:"wx-RsQD74qC "+te,style:L,role:"button","aria-label":`Expand column ${a.text||""}`,"aria-expanded":!a.collapsed,tabIndex:0,onKeyDown:R,onClick:T,"data-header-id":Bn(r.id),children:s.jsx("div",{className:"wx-RsQD74qC wx-text",style:_,children:a.text||""})}):s.jsxs("div",{className:"wx-RsQD74qC "+P,style:L,onClick:k,"data-header-id":Bn(r.id),tabIndex:!a._hidden&&r.sort&&!a.filter?0:void 0,role:"columnheader","aria-colindex":r._colindex,"aria-colspan":a.colspan>1?a.colspan:void 0,"aria-rowspan":a.rowspan>1?a.rowspan:void 0,"aria-sort":!y?.order||a.filter?"none":y?.order==="asc"?"ascending":"descending",onKeyDown:q,children:[a.collapsible?s.jsx("div",{className:"wx-RsQD74qC wx-collapse",role:"button","aria-label":a.collapsed?"Expand column":"Collapse column","aria-expanded":!a.collapsed,tabIndex:0,onKeyDown:R,onClick:T,children:s.jsx("i",{className:`wx-RsQD74qC wxi-angle-${a.collapsed?"down":"right"}`})}):null,a.cell?(()=>{const ie=a.cell;return s.jsx(ie,{api:g,cell:G(),column:r,row:l,onAction:({action:K,data:I})=>g.exec(K,I)})})():a.filter?s.jsx(vA,{filter:a.filter,column:r}):s.jsx("div",{className:"wx-RsQD74qC wx-text",children:a.text||""}),r.resize&&c&&!a._hidden?s.jsx("div",{className:"wx-RsQD74qC wx-grip",role:"presentation","aria-label":"Resize column",ref:ye,onClick:ie=>ie.stopPropagation(),children:s.jsx("div",{})}):null,d?s.jsx("div",{className:"wx-RsQD74qC wx-sort",children:y?s.jsxs(s.Fragment,{children:[typeof y.index<"u"?s.jsx("div",{className:"wx-RsQD74qC wx-order",children:y.index+1}):null,s.jsx("i",{className:`wx-RsQD74qC wxi-arrow-${y.order==="asc"?"up":"down"}`})]}):null}):null]})}function yA({cell:n,column:a,row:r,columnStyle:l}){const c=u.useContext(Xa),d=u.useMemo(()=>xf(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(()=>Xb(a,n,l),[a,n,l]),p=u.useCallback(()=>Object.fromEntries(Object.entries(n||{}).filter(([g])=>g!=="cell")),[n]),v=`wx-6Sdi3Dfd wx-cell ${m||""} ${n?.css||""}`+(a?.fixed&&a?.fixed.right?" wx-fixed-right":"");return s.jsx("div",{className:v,style:d,children:!a?.collapsed&&!n?.collapsed?n?.cell?Zh.createElement(n.cell,{api:c,cell:p(),column:a,row:r,onAction:({action:g,data:w})=>c.exec(g,w)}):s.jsx("div",{className:"wx-6Sdi3Dfd wx-text",children:n?.text||""}):null})}function iy({deltaLeft:n,contentWidth:a,columns:r,type:l="header",columnStyle:c,bodyHeight:d}){const m=u.useContext(Xa),p=lt(m,"_sizes"),v=lt(m,"split"),g=u.useMemo(()=>p?.[`${l}RowHeights`],[p,l]),w=u.useMemo(()=>{let A=[];if(r&&r.length){const N=r[0][l].length;for(let k=0;k<N;k++){let T=0;A.push([]),r.forEach((R,q)=>{const O={...R[l][k]};T||A[k].push(O),O.colspan>1?T=O.colspan-1:T&&T--})}}return A},[r,l]),y=u.useMemo(()=>v?.left||v?.right,[v]);function b(A){return r.find(N=>N.id===A)}function C(A,N){let k=N;return A.rowspan&&(k+=A.rowspan-1),k===w.length-1}function j(A,N,k){if(!k.sort)return!1;for(let T=w.length-1;T>=0;T--){const R=k.header[T];if(!R.filter&&!R._hidden)return N===T}return C(A,N)}return s.jsx("div",{className:`wx-sAsPVaUK wx-${l}`,style:{paddingLeft:`${n}px`,width:`${a}px`},role:"rowgroup",children:w.map((A,N)=>s.jsx("div",{className:l==="header"?"wx-sAsPVaUK wx-h-row":"wx-sAsPVaUK wx-f-row",style:{height:`${g?.[N]}px`,display:"flex"},role:"row",children:A.map(k=>{const T=b(k.id);return l==="header"?s.jsx(xA,{cell:k,columnStyle:c,column:T,row:N,lastRow:C(k,N),bodyHeight:d,sortRow:j(k,N,T),hasSplit:y},k.id):s.jsx(yA,{cell:k,columnStyle:c,column:b(k.id),row:N},k.id)})},N))})}function bA({overlay:n}){const a=u.useContext(Xa);function r(c){return typeof c=="function"}const l=n;return s.jsx("div",{className:"wx-1ty666CQ wx-overlay",children:r(n)?s.jsx(l,{onAction:({action:c,data:d})=>a.exec(c,d)}):n})}function wA(n){const{editor:a,onSave:r,onApply:l}=n,[c,d]=u.useState(a?.value||""),{type:m="text"}=u.useMemo(()=>a?.config||{},[a]),p=u.useRef(null);u.useEffect(()=>{p.current&&p.current.focus()},[]),u.useEffect(()=>{if(!p.current)return;const w=ci(p.current,()=>r(!0));return()=>w.destroy()},[r]);function v(){p.current&&(d(p.current.value),l(p.current.value))}function g({key:w}){w==="Enter"&&r()}return s.jsx("input",{className:"wx-e7Ao5ejY wx-text",onInput:v,onKeyDown:g,ref:p,type:m,value:c})}function SA({editor:n,onAction:a,onSave:r,onApply:l,onCancel:c}){const[d,m]=u.useState(n?.value),[p,v]=u.useState(n?.renderedValue),[g,w]=u.useState(n?.options||[]),y=u.useMemo(()=>n?.config?.template,[n]),b=u.useMemo(()=>n?.config?.cell,[n]),C=u.useMemo(()=>n?.config?.dropdown||{},[n]),j=u.useMemo(()=>({trackScroll:!0,...C}),[C]),A=u.useMemo(()=>(g||[]).findIndex(_=>_.id===d),[g,d]),N=u.useRef(null),k=u.useRef(null),T=u.useCallback(_=>{N.current=_.navigate,k.current=_.keydown,N.current(A)},[A,N]),R=u.useCallback(_=>{const L=_?.target?.value??"";v(L);const ae=L?(n?.options||[]).filter(G=>(G.label||"").toLowerCase().includes(L.toLowerCase())):n?.options||[];w(ae),ae.length?N.current(-1/0):N.current(null)},[n]),q=u.useRef(null);u.useEffect(()=>{q.current&&q.current.focus()},[]);const O=u.useRef(r);u.useEffect(()=>{O.current=r},[r]),u.useEffect(()=>{if(!q.current)return;const _=ci(q.current,()=>O.current(!0));return()=>_.destroy()},[]),u.useEffect(()=>{m(n?.value),v(n?.renderedValue),w(n?.options||[])},[n]);const Y=u.useCallback(({id:_})=>{l(_),r()},[l,r]);return s.jsxs(s.Fragment,{children:[s.jsx("input",{className:"wx-0UYfSd1x wx-input",ref:q,value:p??"",onChange:R,onKeyDown:_=>k.current?k.current(_,A):void 0}),s.jsx(gf,{items:g,onReady:T,onSelect:Y,...j,onCancel:c,children:({option:_})=>y?y(_):b?s.jsx(b,{data:_,onAction:a}):_.label})]})}function CA({editor:n,onAction:a,onSave:r,onApply:l,onCancel:c}){const[d]=u.useState(()=>n.value||new Date),{template:m,cell:p,dropdown:v={}}=n?.config||{},g=u.useMemo(()=>({trackScroll:!0,width:"auto",...v}),[v]);function w({value:j}){l(j),r()}const y=u.useRef(null),[b,C]=u.useState(null);return u.useEffect(()=>{y.current&&y.current.focus(),typeof window<"u"&&window.getSelection&&window.getSelection().removeAllRanges()},[]),u.useEffect(()=>{if(!b)return;const j=ci(b,()=>r(!0));return()=>j.destroy()},[b,r]),s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"wx-lNWNYUb6 wx-value",ref:y,tabIndex:0,onClick:c,onKeyDown:j=>j.preventDefault(),children:m?m(d):p?s.jsx(p,{data:n.value,onAction:a}):s.jsx("span",{className:"wx-lNWNYUb6 wx-text",children:n.renderedValue})}),s.jsx(up,{...g,onCancel:c,children:s.jsx("div",{ref:C,className:"wx-lNWNYUb6",children:s.jsx(Rb,{value:d,onChange:w,buttons:n.config?.buttons})})})]})}function jA(n){const{editor:a}=n,r=n.onAction??n.onaction,l=n.onSave??n.onsave,c=n.onApply??n.onapply,d=n.onCancel??n.oncancel,m=a.config||{},{dropdown:p={}}=m,v=u.useMemo(()=>({trackScroll:!0,...p}),[p]),[g]=u.useState(a.options.find(R=>R.id===a.value)),[w]=u.useState(a.value),[y]=u.useState(a.options),b=u.useMemo(()=>y.findIndex(R=>R.id===w),[y,w]);function C({id:R}){c(R),l()}let j;const[A,N]=u.useState();function k(R){j=R.navigate,N(()=>R.keydown),j(b)}const T=u.useRef(null);return u.useEffect(()=>{T.current&&T.current.focus(),typeof window<"u"&&window.getSelection&&window.getSelection().removeAllRanges()},[]),u.useEffect(()=>{if(!T.current)return;const R=ci(T.current,()=>l(!0));return()=>R.destroy()},[l]),s.jsxs(s.Fragment,{children:[s.jsx("div",{ref:T,className:"wx-ywGRk611 wx-value",tabIndex:0,onClick:d,onKeyDown:R=>{A(R,b),R.preventDefault()},children:m.template?m.template(g):m.cell?(()=>{const R=m.cell;return s.jsx(R,{data:g,onAction:r})})():s.jsx("span",{className:"wx-ywGRk611 wx-text",children:a.renderedValue})}),s.jsx(gf,{items:y,onReady:k,onSelect:C,...v,onCancel:d,children:({option:R})=>m.template?m.template(R):m.cell?(()=>{const q=m.cell;return s.jsx(q,{data:R,onAction:r})})():R.label})]})}function kA(n){const{editor:a,onAction:r,onSave:l,onApply:c}=n,d=a?.config||{},m=a?.options??[],p=a?.value||[],v=a?.renderedValue,g=u.useMemo(()=>({trackScroll:!0,...d.dropdown||{}}),[d]);function w({value:b}){c(b)}const y=u.useRef(null);return u.useEffect(()=>{if(!y.current)return;const b=ci(y.current,()=>l(!0));return()=>b.destroy()},[l]),s.jsx("div",{ref:y,className:"wx-value wx-aacZ4gNU",onClick:()=>l(!0),children:s.jsx(Zb,{value:p,options:m,text:v,template:d.template,cell:d.cell,clear:d.clear,dropdown:g,autoOpen:!0,onChange:w,onAction:r})})}const AA={text:wA,combo:SA,datepicker:CA,richselect:jA,multiselect:kA};function NA({column:n,row:a}){const r=u.useContext(Xa),l=lt(r,"editor"),c=u.useCallback((j,A)=>{r.exec("close-editor",{ignore:j}),A&&r.exec("focus-cell",{...A,eventSource:"click"})},[r]),d=u.useCallback(j=>{const A=j?null:{row:l?.id,column:l?.column};c(!1,A)},[l,c]),m=u.useCallback(()=>{c(!0,{row:l?.id,column:l?.column})},[l,c]),p=u.useCallback(j=>{r.exec("editor",{value:j})},[r]),v=u.useCallback(j=>{j.key==="Enter"&&l&&(n.editor.type==="multiselect"?p(l.value):m())},[l,n.editor,m,p]),g=u.useMemo(()=>xf(n.width,n.flexgrow,n.fixed,n.left,n.right),[n.width,n.flexgrow,n.fixed,n.left,n.right]),w=u.useMemo(()=>{let j=n.editor;if(typeof j=="function"&&(j=j(a,n)),!j)return null;let A=typeof j=="string"?j:j.type;return AA[A]},[n,a]),y=u.useRef(null);u.useEffect(()=>{y.current&&typeof g=="string"&&y.current.setAttribute("style",g)},[g]);const b=typeof a.$parent<"u"?"gridcell":"cell",C=typeof a.$parent<"u"?!n.editor:void 0;return s.jsx("div",{className:"wx-8l724t2g wx-cell wx-editor",ref:y,style:typeof g=="object"&&g!==null?g:void 0,role:b,"aria-readonly":C,tabIndex:-1,onClick:j=>j.stopPropagation(),onDoubleClick:j=>j.stopPropagation(),onKeyDown:v,children:w?s.jsx(w,{editor:l,onSave:d,onApply:p,onCancel:m,onAction:({action:j,data:A})=>r.exec(j,A)}):null})}function ry(n){const{columns:a,type:r,columnStyle:l}=n,c=u.useContext(Xa),{filterValues:d,_columns:m,_sizes:p}=c.getState();function v(g){return l?" "+l(g):""}return s.jsx(s.Fragment,{children:a.map((g,w)=>s.jsx("tr",{children:g.map(y=>{const b=m.find(A=>A.id===y.id),C=`wx-print-cell-${r}${v(b)}${y.filter?" wx-print-cell-filter":""}${y.vertical?" wx-vertical":""}`,j=y.cell;return s.jsx("th",{style:Ob(Vb(y,p.columnWidth)),className:"wx-Gy81xq2u "+C,rowSpan:y.rowspan,colSpan:y.colspan,children:j?s.jsx(j,{api:c,cell:Object.fromEntries(Object.entries(y).filter(([A])=>A!=="cell")),column:b,row:w}):y.filter?s.jsx("div",{className:"wx-Gy81xq2u wx-print-filter",children:R1(d,m,y)}):s.jsx("div",{className:"wx-Gy81xq2u wx-text",children:y.text??""})},y.id)})},w))})}function MA(n){const{columns:a,rowStyle:r,columnStyle:l,cellStyle:c,header:d,footer:m,reorder:p}=n,v=u.useContext(Xa),{flatData:g,_sizes:w}=v.getState(),y=d&&Jx(a,"header",w.headerRowHeights),b=m&&Jx(a,"footer",w.footerRowHeights);function C(A,N){let k="";return k+=l?" "+l(N):"",k+=c?" "+c(A,N):"",k}function j(A,N){return typeof N.draggable=="function"?N.draggable(A,N)!==!1:N.draggable}return s.jsxs("table",{className:`wx-8NTMLH0z wx-print-grid ${a.some(A=>A.flexgrow)?"wx-flex-columns":""}`,children:[d?s.jsx("thead",{children:s.jsx(ry,{columns:y,type:"header",columnStyle:l})}):null,s.jsx("tbody",{children:g.map((A,N)=>s.jsx("tr",{className:"wx-8NTMLH0z wx-row"+(r?" "+r(A):""),style:{height:`${A.rowHeight||w.rowHeight}px`},children:a.map(k=>k.collapsed?null:s.jsxs("td",{className:`wx-8NTMLH0z wx-print-cell wx-cell ${C(A,k)}`,style:Ob(Vb(k,w.columnWidth)),children:[p&&k.draggable?s.jsx("span",{className:"wx-8NTMLH0z wx-print-draggable",children:j(A,k)?s.jsx("i",{className:"wx-8NTMLH0z wxi-drag"}):null}):null,k.treetoggle?s.jsxs(s.Fragment,{children:[s.jsx("span",{style:{marginLeft:A.$level*28+"px"}}),A.$count?s.jsx("i",{className:`wx-8NTMLH0z wx-print-grid-tree-toggle wxi-menu-${A.open!==!1?"down":"right"}`}):null]}):null,k.cell?(()=>{const T=k.cell;return s.jsx(T,{api:v,row:A,column:k})})():s.jsx("span",{children:Gr(A,k)})]},k.id))},N))}),m?s.jsx("tfoot",{children:s.jsx(ry,{columns:b,type:"footer",columnStyle:l})}):null]})}function TA(n){const{config:a,...r}=n,l=u.useContext(Xa),{_skin:c,_columns:d}=l.getState(),m=u.useMemo(()=>N1(d,a),[]),p=u.useRef(null);return u.useEffect(()=>{const v=document.body;v.classList.add("wx-print");const g=p.current;if(!g)return;const w=g.cloneNode(!0);v.appendChild(w);const y=`@media print { @page { size: ${a.paper} ${a.mode}; }`,b=document.createElement("style");b.setAttribute("type","text/css"),b.setAttribute("media","print"),document.getElementsByTagName("head")[0].appendChild(b),b.appendChild(document.createTextNode(y)),window.print(),b.remove(),v.classList.remove("wx-print"),w.remove()},[]),s.jsx("div",{className:`wx-4zwCKA7C wx-${c}-theme wx-print-container`,ref:p,children:m.map((v,g)=>s.jsx("div",{className:"wx-4zwCKA7C wx-print-grid-wrapper",children:s.jsx(MA,{columns:v,...r})},g))})}function EA(n){const{header:a,footer:r,overlay:l,multiselect:c,onreorder:d,rowStyle:m,columnStyle:p,cellStyle:v,autoRowHeight:g,resize:w,clientWidth:y,clientHeight:b,responsiveLevel:C,hotkeys:j}=n,A=u.useContext(Xa),N=lt(A,"dynamic"),k=lt(A,"_columns"),T=lt(A,"flatData"),R=lt(A,"split"),q=lt(A,"_sizes"),[O,Y]=fs(A,"selectedRows"),_=lt(A,"select"),L=lt(A,"editor"),ae=lt(A,"scrollLeft"),G=lt(A,"scrollTop"),te=lt(A,"tree"),P=lt(A,"focusCell"),ye=lt(A,"_print"),ie=lt(A,"undo"),K=lt(A,"reorder"),I=lt(A,"_rowHeightFromData"),[Q,U]=u.useState(0);u.useEffect(()=>{U(Is())},[]);const[W,ue]=u.useState(0),be=u.useMemo(()=>(k||[]).some(ne=>!ne.hidden&&ne.flexgrow),[k]),X=u.useMemo(()=>q?.rowHeight||0,[q]),$=u.useRef(null),[de,me]=u.useState(null),[ve,Se]=u.useState(null),Oe=u.useMemo(()=>{let ne=[],Ae=0;return R&&R.left&&(ne=(k||[]).slice(0,R.left).filter(qe=>!qe.hidden).map(qe=>({...qe})),ne.forEach(qe=>{qe.fixed={left:1,leftSize:R.left},qe.left=Ae,Ae+=qe.width}),ne.length&&(ne[ne.length-1].fixed.left=-1)),{columns:ne,width:Ae}},[R,k]),le=u.useMemo(()=>{let ne=[],Ae=0;if(R&&R.right){ne=(k||[]).slice(R.right*-1).filter(qe=>!qe.hidden).map(qe=>({...qe}));for(let qe=ne.length-1;qe>=0;qe--){const ot=ne[qe];ot.fixed={right:1},ot.right=Ae,Ae+=ot.width}ne.length&&(ne[0].fixed={right:-1})}return{columns:ne,width:Ae}},[R,k]),Z=u.useMemo(()=>{const ne=(k||[]).slice(R?.left||0,(k||[]).length-(R?.right??0)).filter(Ae=>!Ae.hidden);return ne.forEach(Ae=>{Ae.fixed=0}),ne},[k,R]),He=u.useMemo(()=>(k||[]).reduce((ne,Ae)=>(Ae.hidden||(ne+=Ae.width),ne),0),[k]),_e=1;function se(ne,Ae,qe){let ot=Ae,Jt=ne;if(Z.length){let Ut=Z.length;for(let Ze=ne;Ze>=0;Ze--)Z[Ze][qe].forEach(jt=>{jt.colspan>1&&Ze>ne-jt.colspan&&Ze<Ut&&(Ut=Ze)});if(Ut!==Z.length&&Ut<ne){for(let Ze=Ut;Ze<ne;Ze++)ot-=Z[Ze].width;Jt=Ut}}return{index:Jt,delta:ot}}const fe=u.useMemo(()=>{let ne,Ae,qe;const ot=ae||0,Jt=(ae||0)+(y||0);let Ut=0,Ze=0,jt=0,Ot=0;Z.forEach((un,dn)=>{ot>jt&&(Ut=dn,Ot=jt),jt=jt+un.width,Jt>jt&&(Ze=dn+_e)});const Vt={header:0,footer:0};for(let un=Ze;un>=Ut;un--)["header","footer"].forEach(dn=>{Z[un]&&Z[un][dn].forEach(Os=>{const ya=Os.colspan;if(ya&&ya>1){const Hs=ya-(Ze-un+1);Hs>0&&(Vt[dn]=Math.max(Vt[dn],Hs))}})});const sn=se(Ut,Ot,"header"),wt=se(Ut,Ot,"footer"),cn=sn.delta,Tt=sn.index,ts=wt.delta,xn=wt.index;return be&&He>(y||0)?ne=Ae=qe=[...Oe.columns,...Z,...le.columns]:(ne=[...Oe.columns,...Z.slice(Ut,Ze+1),...le.columns],Ae=[...Oe.columns,...Z.slice(Tt,Ze+Vt.header+1),...le.columns],qe=[...Oe.columns,...Z.slice(xn,Ze+Vt.footer+1),...le.columns]),{data:ne||[],header:Ae||[],footer:qe||[],d:Ot,df:ts,dh:cn}},[Z,Oe,le,ae,y,be,He]),Ne=u.useMemo(()=>a&&q?.headerHeight||0,[a,q]),Te=u.useMemo(()=>r&&q?.footerHeight||0,[r,q]),Be=u.useMemo(()=>y&&b?He>=y:!1,[y,b,He]),[$e,et]=u.useState(!1),Mt=u.useMemo(()=>(b||0)-Ne-Te-(Be?Q:0),[b,Ne,Te,Be,Q]),ke=u.useMemo(()=>Math.ceil((Mt||0)/(X||1))+1,[Mt,X]),Ye=u.useRef([]),[rt,vt]=u.useState(0),[vn,It]=u.useState(void 0),Zt=u.useMemo(()=>{let ne=0,Ae=0;const qe=2,ot=G||0;if(g){let Ze=ot;for(;Ze>0;)Ze-=Ye.current[ne]||X,ne++;Ae=ot-Ze;for(let jt=Math.max(0,ne-qe-1);jt<ne;jt++)Ae-=Ye.current[ne-jt]||X;ne=Math.max(0,ne-qe)}else{if(I){let Ze=0,jt=0;for(let wt=0;wt<(T||[]).length;wt++){const cn=T[wt].rowHeight||X;if(jt+cn>ot){Ze=wt;break}jt+=cn}ne=Math.max(0,Ze-qe);for(let wt=0;wt<ne;wt++)Ae+=T[wt].rowHeight||X;let Ot=0,Vt=0;for(let wt=Ze+1;wt<(T||[]).length;wt++){const cn=T[wt].rowHeight||X;if(Ot++,Vt+cn>Mt)break;Vt+=cn}const sn=Math.min(N?N.rowCount:(T||[]).length,Ze+Ot+qe);return{d:Ae,start:ne,end:sn}}ne=Math.floor(ot/(X||1)),ne=Math.max(0,ne-qe),Ae=ne*(X||0)}const Jt=N?N.rowCount:(T||[]).length,Ut=Math.min(Jt,ne+(ke||0)+qe);return{d:Ae,start:ne,end:Ut}},[g,I,G,X,N,T,ke,Mt]),ht=u.useMemo(()=>{const ne=N?N.rowCount:(T||[]).length;if(g)return rt+Zt.d+(ne-(vn||0))*(X||0);if(!I)return ne*(X||0);let Ae=0;for(let qe=0;qe<ne;qe++)Ae+=T[qe]?.rowHeight||X;return Ae},[N,T,X,g,I,rt,Zt.d,vn]),$n=u.useRef({});$n.current={clientWidth:y,clientHeight:b,fullHeight:ht,headerHeight:Ne,footerHeight:Te,fullWidth:He,SCROLLSIZE:Q};const Gt=u.useCallback(()=>{const ne=$n.current;et(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(Gt);return()=>window.cancelAnimationFrame(ne)},[W,Gt]),u.useEffect(()=>{Gt()},[b,Gt]);const J=u.useMemo(()=>be&&He<=(y||0)?(y||0)-0-($e?Q:0):He,[be,He,y,$e,Q,Be]),Re=u.useMemo(()=>be&&He<=(y||0)?y||0:J<(y||0)?He+($e?Q:0):-1,[be,He,y,J,$e,Q]),ze=u.useRef({});u.useEffect(()=>{if(N&&(ze.current.start!==Zt.start||ze.current.end!==Zt.end)){const{start:ne,end:Ae}=Zt;ze.current={start:ne,end:Ae},A&&A.exec&&A.exec("request-data",{row:{start:ne,end:Ae}})}},[N,Zt,A]);const je=u.useMemo(()=>N?T||[]:(T||[]).slice(Zt.start,Zt.end),[N,T,Zt]),Xe=u.useMemo(()=>(O||[]).filter(ne=>(je||[]).some(Ae=>Ae.id===ne)),[Y,je]),gt=u.useMemo(()=>Zt.start,[Zt.start]),Ee=u.useRef({top:G,left:ae});Ee.current={top:G,left:ae};const ua=u.useCallback(ne=>{const Ae=ne.target.scrollTop,qe=ne.target.scrollLeft,ot=Ee.current;(Ae!==ot.top||qe!==ot.left)&&A.exec("scroll-to",{top:Ae,left:qe})},[A]),Un=u.useCallback(ne=>{ne.shiftKey&&ne.preventDefault(),$.current&&$.current.focus&&$.current.focus()},[]),tt=u.useCallback(()=>!!(k||[]).find(ne=>!!ne.draggable),[k]),$t=u.useRef(null),an=u.useRef(null),Za=u.useRef({dblclick:(ne,Ae)=>{const qe={id:ne,column:Jc(Ae,"data-col-id")};A.exec("open-editor",qe)},click:(ne,Ae)=>{if(Ae.target.closest("input")||$t.current)return;const qe=Jc(Ae,"data-col-id");if(P?.id!==ne&&A.exec("focus-cell",{row:ne,column:qe,eventSource:"click"}),_===!1)return;const ot=c&&(Ae.ctrlKey||Ae.metaKey),Jt=c&&Ae.shiftKey;(ot||O.length>1||!O.includes(ne))&&A.exec("select-row",{id:ne,toggle:ot,range:Jt})},"toggle-row":ne=>{const Ae=A.getRow(ne);A.exec(Ae.open!==!1?"close-row":"open-row",{id:ne})},"ignore-click":()=>!1}),Ja=u.useMemo(()=>({top:Ne,bottom:Te,left:Oe.width,xScroll:Be,yScroll:$e,sense:g&&ve?ve.offsetHeight:Math.max(q?.rowHeight||0,40),node:$.current&&$.current.firstElementChild}),[Ne,Te,Oe.width,Be,$e,g,ve,q]);function Xn(ne,Ae){const{container:qe,sourceNode:ot,from:Jt}=Ae;if(tt()&&!ot.getAttribute("draggable-data"))return!1;me(Jt),te&&A.getRow(Jt).open&&A.exec("close-row",{id:Jt,nested:!0});const Ut=Bo(ot),Ze=Ut.cloneNode(!0);Ze.classList.remove("wx-selected"),Ze.querySelectorAll("[tabindex]").forEach(sn=>sn.setAttribute("tabindex","-1")),qe.appendChild(Ze),Se(Ze);const jt=(ae||0)-fe.d,Ot=$e?Q:0;qe.style.width=Math.min((y||0)-Ot,be&&He<=(y||0)?J:J-Ot)+jt+"px";const Vt=Gd(Ut);Ae.offset={x:jt,y:-Math.round(Vt.height/2)},an.current||(an.current=ne.clientY)}function Wi(ne,Ae){const{from:qe}=Ae,ot=Ae.pos,Jt=Gd($.current);ot.x=Jt.x;const Ut=Ja.top;if(ot.y<Ut)ot.y=Ut;else{const Ze=Jt.height-(Be&&Q>0?Q:Math.round(Ja.sense/2))-Ja.bottom;ot.y>Ze&&(ot.y=Ze)}if($.current.contains(Ae.targetNode)){const Ze=Bo(Ae.targetNode),jt=Ze&&hf(Ze);if(jt&&jt!==qe){Ae.to=jt;const Ot=g?ve?.offsetHeight:q?.rowHeight;if(ve&&((G||0)===0||ot.y>Ut+Ot-1)){const Vt=Ze.getBoundingClientRect(),sn=Gd(ve).y,wt=Vt.y,cn=sn>wt?-1:1,Tt=cn===1?"after":"before",ts=A.getState().flatData,xn=Math.abs(ts.findIndex(dn=>dn.id===qe)-ts.findIndex(dn=>dn.id===jt)),un=xn!==1?Tt==="before"?"after":"before":Tt;if(xn===1&&(cn===-1&&ne.clientY>an.current||cn===1&&ne.clientY<an.current))return;an.current=ne.clientY,A.exec("move-item",{id:qe,target:jt,mode:un,inProgress:!0})}}d&&d({event:ne,context:Ae})}rA(ne,Jt,Ae,Ja)}function Fe(ne,Ae){const{from:qe,to:ot}=Ae;A.exec("move-item",{id:qe,target:ot,inProgress:!1}),$t.current=setTimeout(()=>{$t.current=0},1),me(null),Se(null),an.current=null,Kb(Ae)}function Is(){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 Ae=ne.offsetWidth-ne.clientWidth;return document.body.removeChild(ne),Ae}const ut=u.useMemo(()=>Re>0?{width:`${Re}px`}:void 0,[Re]),ui=u.useRef(null);function Kt(){Promise.resolve().then(()=>{let ne=0,Ae=gt;const qe=ui.current;qe&&(Array.from(qe.children).forEach((ot,Jt)=>{Ye.current[gt+Jt]=ot.offsetHeight,ne+=ot.offsetHeight,Ae++}),vt(ne),It(Ae))})}u.useEffect(()=>{je&&g&&Kt()},[je,g,gt]);let[H,De]=u.useState();u.useEffect(()=>{if(P&&(!_||!Xe.length||Xe.includes(P.row)))De({...P});else if(je.length&&fe.data.length){if(!H||Xe.length&&!Xe.includes(H.row)||je.findIndex(ne=>ne.id===H.row)===-1||fe.data.findIndex(ne=>ne.id===H.column&&!ne.collapsed)===-1){const ne=Xe[0]||je[0].id,Ae=fe.data.findIndex(qe=>!qe.collapsed);De(Ae!==-1?{row:ne,column:fe.data[Ae].id}:null)}}else De(null)},[P]);const st=u.useRef(null);u.useEffect(()=>{const ne=$.current;if(!ne)return;const Ae=tA(ne,w);return()=>{typeof Ae=="function"&&Ae()}},[w]);const on=u.useRef({});Object.assign(on.current,{start:Xn,move:Wi,end:Fe,getReorder:()=>K,getDraggableInfo:()=>({hasDraggable:tt()})}),u.useEffect(()=>{const ne=$.current;return ne?aA(ne,on).destroy:void 0},[K,$.current]),u.useEffect(()=>{const ne=$.current;return ne?J1(ne,{keys:j!==!1&&{...Z1,"ctrl+z":ie,"ctrl+y":ie,...j},exec:Ae=>A.exec("hotkey",Ae)}).destroy:void 0},[A,ie,j]);const es=u.useRef({scroll:A.getReactiveState().scroll,scrollLeft:A.getReactiveState().scrollLeft,scrollTop:A.getReactiveState().scrollTop});es.current.getWidth=()=>(y||0)-($e?Q:0),es.current.getHeight=()=>Mt,es.current.getScrollMargin=()=>Oe.width+le.width,u.useEffect(()=>{eA(st.current,es.current)},[]);const Tn=u.useRef(null);u.useEffect(()=>{const ne=Tn.current;if(!ne)return;const Ae=[];Ae.push(ci(ne,()=>P&&A.exec("focus-cell",{eventSource:"click"})).destroy),Ae.push(a1(ne,Za.current)),ue(ne.clientHeight);const qe=new ResizeObserver(()=>{ue(ne.clientHeight)});return qe.observe(ne),Ae.push(()=>qe.disconnect()),()=>Ae.forEach(ot=>ot())},[]);const da=`wx-grid ${C?`wx-responsive-${C}`:""}`;return u.useEffect(()=>{P&&(je.some(ne=>ne.id===P.row)&&fe.data.some(ne=>ne.id===P.column&&!ne.collapsed)||A.exec("focus-cell",{eventSource:"destroy"}))},[P,je,fe.data,A]),s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"wx-4VuBwK2D "+da,style:{"--header-height":`${Ne}px`,"--footer-height":`${Te}px`,"--split-left-width":`${Oe.width}px`,"--split-right-width":`${le.width}px`},children:s.jsx("div",{ref:$,className:"wx-4VuBwK2D wx-table-box",style:ut,role:te?"treegrid":"grid","aria-colcount":fe.data.length,"aria-rowcount":je.length,"aria-multiselectable":te&&c?!0:void 0,tabIndex:-1,children:s.jsxs("div",{ref:st,className:"wx-4VuBwK2D wx-scroll",style:{overflowX:Be?"scroll":"hidden",overflowY:$e?"scroll":"hidden"},onScroll:ua,children:[a?s.jsx("div",{className:"wx-4VuBwK2D wx-header-wrapper",children:s.jsx(iy,{contentWidth:J,deltaLeft:fe.dh,columns:fe.header,columnStyle:p,bodyHeight:Mt-+r})}):null,s.jsxs("div",{ref:Tn,className:"wx-4VuBwK2D wx-body",style:{width:`${J}px`,height:`${ht}px`},onMouseDown:ne=>Un(ne),children:[l?s.jsx(bA,{overlay:l}):null,s.jsx("div",{ref:ui,className:"wx-4VuBwK2D wx-data",style:{paddingTop:`${Zt.d}px`,paddingLeft:`${fe.d}px`},children:je.map((ne,Ae)=>{const qe=O.indexOf(ne.id)!==-1,ot=de===ne.id,Jt="wx-row"+(g?" wx-autoheight":"")+(m?" "+m(ne):"")+(qe?" wx-selected":"")+(ot?" wx-inactive":""),Ut=g?{minHeight:`${ne.rowHeight||X}px`}:{height:`${ne.rowHeight||X}px`};return s.jsx("div",{className:"wx-4VuBwK2D "+Jt,"data-id":Bn(ne.id),"data-context-id":Bn(ne.id),style:Ut,role:"row","aria-rowindex":Ae,"aria-expanded":ne.open,"aria-level":te?ne.$level+1:void 0,"aria-selected":te?qe:void 0,tabIndex:-1,children:fe.data.map(Ze=>Ze.collapsed?s.jsx("div",{className:"wx-4VuBwK2D wx-cell wx-collapsed"},Ze.id):L?.id===ne.id&&L.column===Ze.id?s.jsx(NA,{row:ne,column:Ze},Ze.id):s.jsx(dA,{row:ne,column:Ze,columnStyle:p,cellStyle:v,reorder:K,focusable:H?.row===ne.id&&H?.column===Ze.id},Ze.id))},ne.id)})})]}),r&&(T||[]).length?s.jsx(iy,{type:"footer",contentWidth:J,deltaLeft:fe.df,columns:fe.footer,columnStyle:p}):null]})})}),ye?s.jsx(TA,{config:ye,rowStyle:m,columnStyle:p,cellStyle:v,header:a,footer:r,reorder:K}):null]})}const RA=n=>n.split("-").map(a=>a?a.charAt(0).toUpperCase()+a.slice(1):"").join(""),DA=u.forwardRef(function({data:n=[],columns:a=[],rowStyle:r=null,columnStyle:l=null,cellStyle:c=null,selectedRows:d,select:m=!0,multiselect:p=!1,header:v=!0,footer:g=!1,dynamic:w=null,overlay:y=null,reorder:b=!1,onReorder:C=null,autoRowHeight:j=!1,sizes:A,split:N,tree:k=!1,autoConfig:T=!1,init:R=null,responsive:q=null,sortMarks:O,undo:Y=!1,hotkeys:_=null,filterValues:L,...ae},G){const te=u.useRef();te.current=ae;const P=u.useMemo(()=>new V1(Hb),[]),ye=u.useMemo(()=>P.in,[P]),ie=u.useRef(null);ie.current===null&&(ie.current=new Db((le,Z)=>{const He="on"+RA(le);te.current&&te.current[He]&&te.current[He](Z)}),ye.setNext(ie.current));const K=u.useMemo(()=>({getState:P.getState.bind(P),getReactiveState:P.getReactive.bind(P),getStores:()=>({data:P}),exec:ye.exec,setNext:le=>(ie.current=ie.current.setNext(le),ie.current),intercept:ye.intercept.bind(ye),on:ye.on.bind(ye),detach:ye.detach.bind(ye),getRow:P.getRow.bind(P),getColumn:P.getColumn.bind(P)}),[P,ye]),[I,Q]=u.useState(0),[U,W]=u.useState(0),[ue,be]=u.useState(null),[X,$]=u.useState(null),de=u.useMemo(()=>{if(T&&!a.length&&n.length){const le=n[0],Z=[];for(let He in le)if(He!=="id"&&He[0]!=="$"){let _e={id:He,header:He[0].toUpperCase()+He.slice(1)};typeof T=="object"&&(_e={..._e,...T}),Z.push(_e)}return Z}return(X&&X.columns)??a},[T,a,n,X]),me=u.useMemo(()=>(X&&X.sizes)??A,[X,A]),ve=u.useCallback(le=>{if(Q(le.width),W(le.height),q){const Z=Object.keys(q).map(Number).sort((He,_e)=>He-_e).find(He=>le.width<=He)??null;Z!==ue&&($(q[Z]),be(Z))}},[q,ue]),Se=u.useContext(Pn.theme),Oe=u.useRef(0);return u.useEffect(()=>{if(!Oe.current)R&&R(K);else{const le=P.getState();P.init({data:n,columns:de,split:N||le.split,sizes:me||le.sizes,selectedRows:d||le.selectedRows,dynamic:w,tree:k,sortMarks:O||le.sortMarks,filterValues:L||le.filterValues,undo:Y,reorder:b,_skin:Se,_select:m})}Oe.current++},[P,n,de,N,me,d,w,k,O,L,Y,b,Se,m,R,K]),Oe.current===0&&P.init({data:n,columns:de,split:N||{left:0},sizes:me||{},selectedRows:d||[],dynamic:w,tree:k,sortMarks:O||{},filterValues:L||{},undo:Y,reorder:b,_skin:Se,select:m}),u.useImperativeHandle(G,()=>({...K}),[K]),s.jsx(Xa.Provider,{value:K,children:s.jsx(mp,{words:hp,optional:!0,children:s.jsx(EA,{header:v,footer:g,overlay:y,rowStyle:r,columnStyle:l,cellStyle:c,onReorder:C,multiselect:p,autoRowHeight:j,clientWidth:I,clientHeight:U,responsiveLevel:ue,resize:ve,hotkeys:_})})})});rp(Ba);const Fn=u.createContext(null),vp=u.createContext(null),xp=u.createContext(null);function LA({children:n}){const a=u.useContext(Pn.i18n),r=u.useMemo(()=>a.getGroup("filemanager"),[a]),l=u.useContext(Fn),[c]=fs(l,"panels"),d=lt(l,"activePanel"),m=c[d].path,[p,v]=u.useState(null),[g,w]=u.useState(null),[y,b]=u.useState(""),[C,j]=u.useState(""),[A,N]=u.useState(!1);function k(){const O=y.trim();if(!O){N(!0);return}p.add?l.exec("create-file",{file:{...p.item,name:O},parent:m}):C!==O&&l.exec("rename-file",{id:p.item.id,name:O}),T()}function T(){v(null),N(null),j(""),b("")}function R(){l.exec("delete-files",{ids:g.selected}),w(null)}const q=u.useMemo(()=>({showPrompt(O){const Y=O.item.name||(O.item.type==="folder"?r("New folder"):`${r("New file")}.txt`);j(Y),b(Y),v({...O})},showConfirm(O){w({...O})}}),[r]);return s.jsxs(vp.Provider,{value:q,children:[s.jsx(Lk,{children:n}),p?s.jsx(Hh,{title:r(`Enter ${p.item.type} name`),onConfirm:k,onCancel:T,children:s.jsx(dp,{error:A,select:!0,focus:!0,value:y,onChange:({value:O})=>b(O)})}):null,g?s.jsx(Hh,{title:r("Are you sure you want to delete these items:"),onConfirm:R,onCancel:()=>w(null),children:g.selected?s.jsx("ul",{className:"wx-gq7BMzEP wx-list",children:g.selected.map((O,Y)=>s.jsx("li",{children:O},Y))}):null}):null]})}let ly={"7z":!0,rar:!0,zip:!0,css:!0,html:!0,js:!0,php:!0,md:!0,xml:!0,sql:!0,aif:!0,mid:!0,mp3:!0,waw:!0,wma:!0,doc:!0,docx:!0,txt:!0,avi:!0,mov:!0,mp4:!0,mpeg:!0,mpg:!0,pdf:!0,xls:!0,xlsx:!0,gif:!0,jpg:!0,jpeg:!0,png:!0,psd:!0,tiff:!0,svg:!0,folder:!0,file:!0,multiple:!0,search:!0,none:!0};function _A(n){const a=n.lastIndexOf("."),r=a>0&&a<n.length-1?Math.min(10,n.length-a):Math.min(5,n.length),l=n.slice(0,-r),c=n.slice(-r);return[l,c]}function zA({item:n}){const a=u.useContext(Fn),r=u.useContext(Pn.i18n).getGroup("filemanager"),l=u.useContext(Fn).templates,[c]=fs(a,"panels"),d=lt(a,"activePanel"),m=lt(a,"mode"),p=c[d].selected,v=u.useMemo(()=>l.preview(n,214,163),[l,n]),g=u.useMemo(()=>l.icon(n,"big"),[l,n]),[w,y]=u.useMemo(()=>_A(n.name),[n.name]);return s.jsx(s.Fragment,{children:n.id==="/wx-filemanager-parent-link"?m!=="search"?s.jsx("div",{className:"wx-GAOa4kDV wx-back-item",children:s.jsxs("div",{className:`wx-GAOa4kDV wx-back ${n.navigation?"wx-selected":""}`,"data-id":Bn("/wx-filemanager-parent-link"),children:[s.jsx("i",{className:"wx-GAOa4kDV wxi-arrow-left"}),s.jsx("span",{children:r("Back to parent folder")})]})}):null:s.jsxs("div",{className:`wx-GAOa4kDV wx-item ${p?.length&&p.indexOf(n.id)>=0?"wx-selected":""}`,"data-id":Bn(n.id),children:[v?s.jsx("div",{className:"wx-GAOa4kDV wx-preview wx-file-preview",children:s.jsx("img",{className:"wx-GAOa4kDV wx-card-preview",alt:r("A miniature file preview"),src:v})}):g?s.jsx("div",{className:"wx-GAOa4kDV wx-preview wx-file-icon",children:s.jsx("img",{className:"wx-GAOa4kDV wx-card-preview",alt:"",src:g})}):s.jsx("div",{className:"wx-GAOa4kDV wx-preview",children:s.jsx("i",{className:`wx-GAOa4kDV wxi-${n.type}`})}),n.type==="folder"?s.jsxs("div",{className:"wx-GAOa4kDV wx-info",children:[s.jsxs("div",{className:"wx-GAOa4kDV wx-folder-name",children:[s.jsx("span",{className:"wx-GAOa4kDV wx-type",children:r("Folder")}),s.jsxs("span",{className:"wx-GAOa4kDV wx-name",children:[s.jsx("span",{children:w}),s.jsx("span",{children:y})]})]}),s.jsx("div",{"data-action-id":Bn(n.id),className:"wx-GAOa4kDV wx-more",children:s.jsx("i",{className:"wx-GAOa4kDV wxi-dots-v"})})]}):s.jsxs("div",{className:"wx-GAOa4kDV wx-info",children:[s.jsx("div",{className:"wx-GAOa4kDV wx-file-name",children:s.jsxs("span",{className:"wx-GAOa4kDV wx-name",children:[s.jsx("span",{children:w}),s.jsx("span",{children:y})]})}),s.jsx("div",{"data-action-id":Bn(n.id),className:"wx-GAOa4kDV wx-more",children:s.jsx("i",{className:"wx-GAOa4kDV wxi-dots-v"})})]})]})})}function Jb(){const n=u.useContext(Fn),a=u.useContext(Pn.i18n),r=u.useMemo(()=>a.getGroup("filemanager"),[a]),[l]=fs(n,"panels"),c=lt(n,"activePanel"),d=lt(n,"mode"),m=l[c]._files,p=l[c].selected,v=l[c].path,g=l[c]._crumbs,w=l[c]._selectNavigation,y=u.useCallback((T,R)=>{const q=R&&(R.ctrlKey||R.metaKey),O=R&&R.shiftKey;if(T==="/wx-filemanager-parent-link"){if(p.length&&(q||O))return;n.exec("select-file",{type:"navigation"});return}let Y=T==="body"&&R?null:T;const _=R.target.className.indexOf("wx-more")!==-1||R.target.className.indexOf("wxi-dots-v")!==-1;setTimeout(()=>{n.exec("select-file",{id:Y,toggle:q&&!_,range:O&&!_,panel:c})},1)},[n,p,c]),b=u.useCallback(()=>{g.length>1&&n.exec("set-path",{id:g[g.length-2].id,panel:c,selected:[g[g.length-1].id]})},[n,g,c]),C=u.useCallback(T=>{if(T==="/wx-filemanager-parent-link")return b();d==="search"&&n.exec("filter-files",{text:""});const R=m.find(q=>q.id===T);R&&(R.type=="folder"?n.exec("set-path",{id:R.id,panel:c}):n.exec("open-file",{id:R.id}))},[n,b,d,m,c]),j=u.useCallback((T,R)=>{(!p?.length||!p.filter(q=>q?.id===T).length>0)&&y(T,R)},[p,y]),A=u.useMemo(()=>v!=="/"?[{id:"/wx-filemanager-parent-link",name:r("Back to parent folder"),navigation:w},...m]:m,[v,r,w,m]),N=u.useRef(null),k=u.useRef();return u.useEffect(()=>{N.current&&(k.current?(k.current.click=y,k.current._dblclick=C,k.current.context=j):(k.current={click:y,dblclick:T=>k.current._dblclick(T),_dblclick:C,context:j},Fo(N.current,k.current)))},[y,C,j]),d=="search"&&!A.length?s.jsx("div",{className:"wx-iyjASZCY wx-not-found",children:s.jsx("div",{className:"wx-iyjASZCY wx-not-found-text",children:r("Looks like nothing is here")})}):s.jsx("div",{tabIndex:0,className:"wx-iyjASZCY "+("wx-cards"+(v!=="/"&&d!=="search"?" wx-has-back-link":"")),"data-id":Bn("body"),ref:N,children:A.map(T=>s.jsx(zA,{item:T},T.id))})}function Fl({name:n="",spin:a=!1,onClick:r}){return s.jsx("i",{"data-menu-ignore":"true",className:`wx-uwcvNSAG wx-icon wxi-${n} ${a?"wx-spin":""} ${r?"wx-clickable":""}`,onClick:()=>{r&&r()}})}function IA(){const n=u.useContext(Pn.i18n).getGroup("filemanager"),a=u.useContext(Fn),r=lt(a,"activePanel"),[l]=fs(a,"panels"),c=u.useMemo(()=>l[r]._crumbs,[l,r]);function d(){a.exec("filter-files",{text:""})}return s.jsxs("div",{className:"wx-GDJvtROw wx-search",children:[s.jsxs("div",{className:"wx-GDJvtROw wx-toolbar",children:[s.jsx("div",{className:"wx-GDJvtROw wx-back-icon",children:s.jsx(Fl,{name:"angle-left",onClick:d})}),s.jsxs("div",{className:"wx-GDJvtROw wx-text",children:[n("Search results in")," ",Array.isArray(c)&&c.map((m,p)=>s.jsxs(u.Fragment,{children:[p?"/":null,m.id=="/"?n(m.name):m.name]},p))]})]}),s.jsx(Jb,{})]})}function oh({narrowMode:n,extraInfo:a}){const r=u.useContext(Fn),{preview:l,icon:c}=r.templates,d=u.useContext(Pn.i18n),m=u.useMemo(()=>d.getGroup("filemanager"),[d]),p=u.useMemo(()=>zo("%D, %d %F %Y, %H:%i",d.getRaw().calendar),[d]),[v,g]=fs(r,"panels"),w=lt(r,"activePanel"),y=lt(r,"preview"),b=lt(r,"search"),C=u.useMemo(()=>{const _=v&&w!=null&&v[w]?._selected?.length||0;return b&&!_},[b,g,w]),j=u.useMemo(()=>{const _=v&&w!=null?v[w]:null;return _?C?_._files:_._selected:[]},[C,g,w]),A=u.useCallback((_,L)=>(_?`${_} ${m(_>1?"folders":"folder")} `:"")+(L?`${L} ${m(L>1?"files":"file")}`:""),[m]),N=u.useCallback(()=>{r.exec("show-preview",{mode:!y})},[r,y]),k=u.useCallback(_=>_.type==="folder"?m("Folder"):_.ext||m("Unknown file"),[m]),T=u.useMemo(()=>{let _,L,ae,G,te,P,ye,ie;if(j.length===1&&!C){L=j[0],_=L.name;const K=l(L,400,500);K?(ae=K,G=""):(G=c(L,"big"),ae=""),te=L.type!=="folder"}else{if(L=te=null,_="",j.length){let K=0,I=0,Q=0,U=[],W;j.forEach(be=>{typeof be.size>"u"&&(W=!0,K=void 0),W||(K+=be.size),U.push(k(be)),be.type==="folder"?I++:Q++});const ue=new Set(U);P=ue.size>1?m("multiple"):[...ue][0],ye=A(I,Q),ie=K,C||(_=m("Multiple files"))}G=c({type:C?"search":j.length?"multiple":"none"},"big"),ae=""}return{name:_,item:L,previewSrc:ae,iconSrc:G,showDownloadIcon:te,type:P,totalCount:ye,totalSize:ie}},[j,C,l,c,m,k,A]),R=u.useCallback(()=>{r.exec("download-file",{id:j[0].id})},[r,j]),q=u.useCallback(async _=>{if(!a||!_)return null;try{return await a(_)}catch(L){return console.log(L),null}},[a]),[O,Y]=u.useState(null);return u.useEffect(()=>{let _=!1;return Y(null),Promise.resolve(q(T.item)).then(L=>{_||Y(L)}).catch(()=>{_||Y(null)}),()=>{_=!0}},[q,T.item]),s.jsx("div",{className:"wx-O0BTtRrH wx-wrapper",children:j&&j.length?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"wx-O0BTtRrH wx-preview",children:[s.jsxs("div",{className:"wx-O0BTtRrH wx-toolbar",children:[s.jsx("div",{className:"wx-O0BTtRrH wx-name",children:T.name}),s.jsxs("div",{className:"wx-O0BTtRrH wx-icons",children:[T.showDownloadIcon?s.jsx(Fl,{name:"download",onClick:R}):null,n?s.jsx(Fl,{name:"close",onClick:N}):null]})]}),T.previewSrc?s.jsx("div",{className:"wx-O0BTtRrH wx-img-wrapper",children:s.jsx("img",{src:T.previewSrc,alt:m("A miniature file preview")})}):T.iconSrc?s.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:s.jsx("img",{src:T.iconSrc,alt:m("A miniature file preview")})}):s.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:T.item?s.jsx("i",{className:`wx-O0BTtRrH wx-icon wxi-${T.item.type}`}):s.jsx("i",{className:`wx-O0BTtRrH wx-icon wxi-${C?"search":"file-multiple-outline"}`})})]}),s.jsxs("div",{className:"wx-O0BTtRrH wx-info-panel",children:[s.jsx("div",{className:"wx-O0BTtRrH wx-title",children:m(C?"Found":"Information")}),s.jsxs("div",{className:"wx-O0BTtRrH wx-list",children:[T.item?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"wx-O0BTtRrH wx-name",children:m("Type")}),s.jsx("span",{className:"wx-O0BTtRrH wx-value",children:k(T.item)}),typeof T.item.size<"u"?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"wx-O0BTtRrH wx-name",children:m("Size")}),s.jsx("span",{className:"wx-O0BTtRrH wx-value",children:eu(T.item.size)})]}):null,s.jsx("span",{className:"wx-O0BTtRrH wx-name",children:m("Date")}),s.jsxs("span",{className:"wx-O0BTtRrH wx-value",children:[p(T.item.date)," "]})]}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"wx-O0BTtRrH wx-name",children:m("Count")}),s.jsx("span",{className:"wx-O0BTtRrH wx-value",children:T.totalCount}),s.jsx("span",{className:"wx-O0BTtRrH wx-name",children:m("Type")}),s.jsx("span",{className:"wx-O0BTtRrH wx-value",children:T.type}),typeof T.totalSize<"u"?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"wx-O0BTtRrH wx-name",children:m("Size")}),s.jsx("span",{className:"wx-O0BTtRrH wx-value",children:eu(T.totalSize)})]}):null]}),O?Object.entries(O).map(([_,L])=>s.jsxs(Zh.Fragment,{children:[s.jsx("span",{className:"wx-O0BTtRrH wx-name",children:_}),s.jsx("span",{className:"wx-O0BTtRrH wx-value",children:L})]},_)):null]})]})]}):s.jsxs("div",{className:"wx-O0BTtRrH wx-no-info-panel",children:[s.jsxs("div",{className:"wx-O0BTtRrH wx-toolbar",children:[s.jsx("div",{className:"wx-O0BTtRrH wx-name",children:T.name}),s.jsx("div",{className:"wx-O0BTtRrH wx-icons",children:n?s.jsx(Fl,{name:"close",onClick:N}):null})]}),s.jsx("div",{className:"wx-O0BTtRrH wx-no-info-wrapper",children:s.jsxs("div",{className:"wx-O0BTtRrH wx-no-info",children:[T.previewSrc?s.jsx("div",{className:"wx-O0BTtRrH wx-img-wrapper",children:s.jsx("img",{src:T.previewSrc,alt:m("A miniature file preview")})}):T.iconSrc?s.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:s.jsx("img",{src:T.iconSrc,alt:m("A miniature file preview")})}):s.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:s.jsx("i",{className:`wx-O0BTtRrH wx-icon wxi-${C?"search":"message-question-outline"}`})}),s.jsx("span",{className:"wx-O0BTtRrH wx-text",children:C?"":m("Select file or folder to view details")})]})})]})})}function ew({panel:n}){const a=u.useContext(Fn),r=u.useContext(Pn.i18n),l=u.useMemo(()=>r.getGroup("filemanager"),[r]),[c,d]=fs(a,"panels"),m=u.useMemo(()=>c[n]._files,[d,n]),p=u.useMemo(()=>c[n]._crumbs||[],[d,n]);function v(j){const A=pp(j,p);a.exec("set-path",{id:j,panel:n,...A&&{selected:[A]}})}const[g,w]=u.useState(null);u.useEffect(()=>{m&&w(null)},[m]);function y(){w(!0),a.exec("request-data",{id:p[p.length-1].id}),setTimeout(()=>{w(null)},5e3)}const b=u.useRef(null),C=u.useRef();return u.useEffect(()=>{C.current?C.current.click=v:(C.current={click:v},Fo(b.current,C.current))},[v]),s.jsxs("div",{className:"wx-SNY5LTYx wx-breadcrumbs","data-menu-ignore":"true",ref:b,children:[s.jsx("div",{className:"wx-SNY5LTYx wx-refresh-icon",children:s.jsx(Fl,{name:"refresh",spin:!!g,onClick:y})}),p.map((j,A)=>s.jsxs(Zh.Fragment,{children:[A?s.jsx(Fl,{name:"angle-right"}):null,s.jsx("div",{className:"wx-SNY5LTYx wx-item","data-id":Bn(j.id),"data-menu-ignore":"true",children:j.id=="/"?l(j.name):j.name})]},A))]})}function OA({row:n}){const a=u.useContext(Pn.i18n),[r]=u.useState(()=>a.getGroup("filemanager")),l=u.useContext(Fn).templates,[c]=u.useState(()=>l.icon(n,"small"));return s.jsx("div",{className:"wx-qgAqG6sL wx-name-cell",children:n.id==="/wx-filemanager-parent-link"?s.jsxs(s.Fragment,{children:[s.jsx("i",{className:"wx-qgAqG6sL wxi-arrow-left"}),s.jsxs("span",{className:"wx-qgAqG6sL wx-name",children:[" ",r("Back to parent folder")]})]}):s.jsxs(s.Fragment,{children:[c?s.jsx("img",{className:"wx-qgAqG6sL wx-icon",alt:"",src:c,height:"24px",width:"24px"}):s.jsx("i",{className:`wx-qgAqG6sL wxi-${n.type}`}),s.jsxs("span",{className:"wx-qgAqG6sL wx-name",children:[" ",n.name," "]})]})})}function tw({children:n}){const a=u.useContext(Fn),r=lt(a,"activePanel"),l=u.useContext(xp),c=u.useRef(null);let d=u.useRef({});return d.current.drop=()=>{const m=c.current,p=Fj(m,"data-panel");p&&p!=r&&a.exec("set-active-panel",{panel:p*1})},d.current.dragEnter=()=>{const m=c.current;m&&m.classList.toggle("wx-active")},d.current.dragLeave=()=>{const m=c.current;m&&m.classList.toggle("wx-active")},u.useEffect(()=>{const m=c.current;return l.droparea(m,d.current)},[]),s.jsx("div",{className:"wx-LT9X7tb7 wx-upload-area",ref:c,children:n})}function Ph({panel:n,active:a=!1,onClick:r,onContextMenu:l}){const c=u.useContext(Fn),d=u.useContext(Pn.i18n),m=u.useMemo(()=>d.getGroup("filemanager"),[d]),p=u.useMemo(()=>zo("%d %M %Y",d.getRaw().calendar),[d]),[v]=fs(c,"panels"),g=v[n].selected,w=v[n].path,y=v[n]._crumbs,b=v[n]._sorts,C=v[n]._selectNavigation,j=v[n]._files,A=u.useMemo(()=>[{id:"name",header:m("Name"),flexgrow:3,sort:!0,resize:!0,cell:OA},{id:"size",header:m("Size"),width:100,sort:!0,resize:!0,template:P=>typeof P=="number"?eu(P):""},{id:"date",header:m("Date"),width:120,sort:!0,resize:!0,template:P=>P?p(P):""}],[m,p]),N=u.useRef(null),k=u.useRef(null),T=u.useMemo(()=>C?["/wx-filemanager-parent-link"]:[...g],[C,g]);function R(P,ye){if(ye&&ye.target&&ye.target.className&&ye.target.className.indexOf("wx-grip")!==-1)return;const ie=ye&&(ye.ctrlKey||ye.metaKey),K=ye&&ye.shiftKey;if(P==="/wx-filemanager-parent-link"){if(g.length&&(ie||K))return;c.exec("select-file",{type:"navigation"});return}let I=P==="body"&&ye?null:P;!N.current&&!k.current?c.exec("select-file",{id:I,toggle:ie,range:K,panel:n}):(N.current=null,k.current=null)}function q(){y.length>1&&c.exec("set-path",{id:y[y.length-2].id,panel:n,selected:[y[y.length-1].id]})}function O(P){if(P==="/wx-filemanager-parent-link")return q();const ye=j.find(ie=>ie.id===P);ye&&(ye.type==="folder"?c.exec("set-path",{id:ye.id,panel:n}):c.exec("open-file",{id:ye.id}))}function Y(P){const ye=P.key,ie=b[w];let K=ie?"asc":"desc";ie&&ie.key===ye&&(K=ie.order==="asc"?"desc":"asc"),c.exec("sort-files",{key:ye,order:K,panel:n,path:w})}function _(P){P.intercept("sort-rows",ye=>(N.current=!0,Y(ye),!1)),P.intercept("select-row",()=>!1),P.on("resize-column",()=>k.current=!0),P.intercept("hotkey",()=>!1)}const L=u.useMemo(()=>w!=="/"?[{id:"/wx-filemanager-parent-link",name:m("Back to parent folder")},...j]:j,[w,j,m]),ae=u.useMemo(()=>{if(L&&b&&b[w]){const{key:P,order:ye}=b[w];return{[P]:{order:ye}}}},[L,b,w]),G=u.useRef(null),te=u.useRef();return u.useEffect(()=>{te.current?(te.current.click=R,te.current._dblclick=O):(te.current={click:R,dblclick:P=>te.current._dblclick(P),_dblclick:O},Fo(G.current,te.current))},[R,O]),s.jsxs("div",{onClick:r,onContextMenu:l,className:"wx-SSaVhET7 wx-wrapper",children:[s.jsx(ew,{panel:n}),s.jsx("div",{"data-id":Bn("body"),className:`wx-SSaVhET7 wx-list ${a?"wx-active":""}`,ref:G,children:s.jsx(tw,{children:s.jsx(DA,{init:_,data:L,columns:A,selectedRows:T,columnStyle:()=>"wx-SSaVhET7 wx-each-cell",sizes:{rowHeight:42,headerHeight:42},sortMarks:ae})})})]})}function HA(){const n=u.useContext(Fn),a=lt(n,"activePanel");function r(l){n.exec("set-active-panel",{panel:l})}return s.jsxs("div",{className:"wx-L55BfJa2 wx-panels","data-id":Bn("body"),children:[s.jsx("div",{className:"wx-L55BfJa2 wx-item","data-panel":0,children:s.jsx(Ph,{panel:0,active:a==0,onClick:()=>r(0),onContextMenu:()=>r(0)})}),s.jsx("div",{className:"wx-L55BfJa2 wx-item","data-panel":1,children:s.jsx(Ph,{panel:1,active:a==1,onClick:()=>r(1),onContextMenu:()=>r(1)})})]})}function nw({folderIcon:n=!1,folder:a={}}){const r=u.useContext(Fn),[l,c]=fs(r,"panels"),d=lt(r,"activePanel"),m=u.useMemo(()=>l[d].path,[c,d]),p=u.useContext(Pn.i18n),v=u.useMemo(()=>p.getGroup("filemanager"),[p]),g=u.useMemo(()=>!!a.data?.find(C=>C.type==="folder"),[a]),w=u.useMemo(()=>a.id=="/"?v(a.name):a.name,[a,v]),y=u.useMemo(()=>a.$level>1?(a.$level-1)*20:0,[a]),b=a.open;return s.jsxs(s.Fragment,{children:[s.jsxs("li",{"data-id":Bn(a.id),className:`wx-NYfhvGIt wx-folder${m===a.id?" wx-selected":""}`,style:{paddingLeft:`${y}px`},children:[g?s.jsx("i",{className:`wx-NYfhvGIt wx-toggle wxi-${b?"angle-down":"angle-right"}`,"data-action":"toggle"}):s.jsx("span",{className:"wx-NYfhvGIt wx-toggle-placeholder"}),s.jsx("i",{className:"wx-NYfhvGIt "+(n||"wxi-folder")}),s.jsxs("span",{className:"wx-NYfhvGIt wx-name",children:[" ",w," "]})]}),b&&a.data&&a.data.length&&g?s.jsx(s.Fragment,{children:a.data.map(C=>C.type==="folder"?s.jsx(nw,{folder:C},C.id):null)}):null]})}function BA(){const n=u.useContext(Fn),[a,r]=fs(n,"data"),[l,c]=fs(n,"panels"),d=lt(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,r]),v=u.useCallback(C=>{const j=pp(C,m);n.exec("set-path",{id:C,panel:d,...j&&{selected:[j]}})},[n,m,d]),[g,w]=u.useState([]);u.useEffect(()=>{w(a.byId(0).data)},[r]);const y=u.useRef(null),b=u.useRef();return u.useEffect(()=>{b.current?(b.current.click=v,b.current.toggle=p):(b.current={click:v,toggle:p},Fo(y.current,b.current))},[v,p]),s.jsx("ul",{ref:y,className:"wx-LyHJ6R6A",children:g.map(C=>C.type==="folder"?s.jsx(nw,{folder:C},C.id):null)})}function FA(){const n=u.useContext(Fn),a=u.useContext(Pn.i18n),r=u.useMemo(()=>a.getGroup("filemanager"),[a]),l=lt(n,"drive"),c=l?l.used:"",d=l?l.total:"";return c&&d?s.jsxs("div",{className:"wx-DetSyKGG wx-drive",children:[s.jsx("progress",{value:c,max:d,className:"wx-DetSyKGG wx-progress"}),s.jsxs("p",{children:[eu(c)," ",r("of")," ",eu(d)," ",r("used")]})]}):null}function PA({option:n}){const a=u.useContext(Pn.i18n).getGroup("filemanager"),r=u.useContext(xp),l=u.useCallback(()=>{r.open({})},[r]);return s.jsx("div",{className:"wx-9XiKcxq5 wx-upload-button",onClick:l,children:s.jsx("span",{children:a(n.text)})})}function $A({readonly:n,menuOptions:a}){const r=u.useContext(Pn.i18n).getGroup("filemanager"),{showPrompt:l}=u.useContext(vp);u.useEffect(()=>{r1("upload",PA)},[]);function c({action:m}){m&&(m.id==="add-file"?l({item:{type:"file",size:0,date:new Date},add:!0}):m.id==="add-folder"&&l({item:{type:"folder",date:new Date},add:!0}))}const d=u.useMemo(()=>a("add").map(m=>(m.text=r(m.text),m)),[a,r]);return s.jsxs("div",{className:"wx-FlucfALM wx-wrapper",children:[!n&&s.jsx("div",{className:"wx-FlucfALM wx-button",children:s.jsx(o1,{options:d,at:"bottom-fit",onClick:c,children:s.jsx(Vc,{type:"primary block",children:r("Add New")})})}),s.jsx("div",{className:"wx-FlucfALM wx-tree",children:s.jsx(BA,{})}),s.jsx(FA,{})]})}function UA({value:n="",onSearch:a}){const[r,l]=Ib(n),c=u.useContext(Pn.i18n).getGroup("filemanager"),d=u.useRef(null),m=u.useMemo(()=>r!==""?"wxi-close":"wxi-search",[r]);function p(g){const w=g.target.value;l(w),a&&a({value:w})}function v(){l(""),d.current&&d.current.focus(),a&&a({value:""})}return s.jsxs("div",{className:"wx-lUZMtgT1 wx-search-input",children:[s.jsx("i",{className:`wx-lUZMtgT1 wx-icon ${m}`,onClick:v}),s.jsx("input",{type:"text",className:"wx-lUZMtgT1 wx-text",ref:d,value:r,onInput:p,placeholder:c("Search")})]})}function qA({narrowMode:n=!1,onShowTree:a}){const r=u.useContext(Fn),l=u.useContext(Pn.i18n).getGroup("filemanager"),c=lt(r,"mode"),d=lt(r,"preview"),m=lt(r,"search"),p=[{icon:"wxi-view-sequential",id:"table"},{icon:"wxi-view-grid",id:"cards"},{icon:"wxi-view-column",id:"panels"}];function v({value:y}){r.exec("set-mode",{mode:y})}function g(y){y.preventDefault(),r.exec("show-preview",{mode:!d})}function w(y){r.exec("filter-files",{text:y.value})}return s.jsxs("div",{className:"wx-5PZQQztG wx-toolbar",children:[s.jsxs("div",{className:"wx-5PZQQztG wx-left "+(n?"wx-left-narrow":""),children:[n?c==="panels"||c==="search"?null:s.jsx("div",{className:"wx-5PZQQztG wx-sidebar-icon","data-id":Bn("toggle-tree"),children:s.jsx(Fl,{onClick:()=>a&&a(),name:"subtask"})}):s.jsx("div",{className:"wx-5PZQQztG wx-name",children:l("Files")}),s.jsx(UA,{onSearch:w,value:m})]}),s.jsxs("div",{className:"wx-5PZQQztG wx-right",children:[n?null:s.jsx("div",{className:"wx-5PZQQztG wx-preview-icon",children:s.jsx(_k,{onClick:g,value:d,children:s.jsx("i",{className:"wx-5PZQQztG wxi-eye"})})}),s.jsx("div",{className:"wx-5PZQQztG wx-modes",children:s.jsx(Mk,{value:c,options:p,onChange:v})})]})]})}function GA(){const n=u.useContext(Fn),a=lt(n,"activePanel");return s.jsxs("div",{className:"wx-NwohNJzN wx-wrapper",children:[s.jsx(ew,{panel:a}),s.jsx(tw,{children:s.jsx(Jb,{})})]})}function VA({readonly:n=!1,menuOptions:a,extraInfo:r}){const l=u.useRef(null),c=u.useRef(null),[d,m]=u.useState(void 0),[p,v]=u.useState(void 0),[g,w]=u.useState(!1),y=Ub(),b=u.useContext(Fn),{showPrompt:C,showConfirm:j}=u.useContext(vp),A=u.useContext(Pn.i18n),N=u.useMemo(()=>A.getGroup("filemanager"),[A]),k=lt(b,"mode"),T=lt(b,"preview"),R=lt(b,"activePanel"),[q,O]=fs(b,"panels"),Y=u.useMemo(()=>(q&&R!=null?q[R]:null)?.selected??[],[O,R]),_=u.useMemo(()=>(q&&R!=null?q[R]:null)?.path,[O,R]),[L,ae]=u.useState([]);u.useEffect(()=>{const ue=l.current;if(!ue)return;const be=new ResizeObserver(X=>{const $=X[0]?.borderBoxSize?.[0]?.inlineSize;typeof $=="number"&&v($<768)});return be.observe(ue),()=>{be.disconnect()}},[]);const G=u.useCallback(()=>{w(ue=>!ue)},[]),te=u.useCallback(ue=>{p&&Jc(ue)!=="toggle-tree"&&w(!1)},[p]);u.useEffect(()=>{const ue=c.current;if(ue)return ci(ue,te).destroy},[te]),u.useEffect(()=>{const ue=c.current;if(!ue)return;const be=new ResizeObserver(()=>{ue&&m(ue.clientWidth)});return be.observe(ue),ue&&m(ue.clientWidth),()=>{be.disconnect()}},[]);const P=u.useMemo(()=>({icon:"wxi-eye",text:"Preview",id:"preview"}),[]),ye=u.useCallback(ue=>{let be=p?[P]:[];return ue==="file"&&(be=[...be,...a().filter(X=>X.id==="download")]),be},[p,P,a]),ie=u.useRef(null),K=u.useCallback((ue,be,X)=>{const $=X?[be.id]:Y;switch(ue){case"download":b.exec("download-file",{id:be.id});break;case"copy":case"move":ie.current={action:ue,ids:$};break;case"paste":ie.current&&b.exec(ie.current.action==="copy"?"copy-files":"move-files",{ids:ie.current.ids,target:be?.type==="folder"?be.id:_});break;case"rename":C({item:be});break;case"delete":j({selected:$});break;case"preview":b.exec("show-preview",{mode:!T});break}},[b,Y,_,C,j,T]),I=u.useCallback(()=>q?.[R],[q,R]);u.useEffect(()=>{const ue=l.current;if(!ue)return;const be=Kk(ue,{api:b,menuOptions:n?ye:a,performAction:K,getPanel:I});return()=>{typeof be=="function"?be():be&&typeof be.destroy=="function"&&be.destroy()}},[b,n,ye,a,K,I]);const Q=u.useCallback((ue,be)=>{const X=ue?b.getFile(ue):null,$=be.target.closest(".tree-item.folder");let de;if(n)de=ye(X?.type);else{switch(ue){case"body":de=a(ue);break;default:if(X)if(!$&&Y.length>1)de=p?[P,...a("multiselect")]:a("multiselect");else if(ue==="/")de=a("folder",X).filter(me=>me.id==="paste");else{const me=a(X.type,X);me&&(de=p?[P,...me]:me)}}k==="search"&&(de=de?.filter(me=>me.id!=="paste"))}if(X?.id&&(!Y.length||!Y.some(me=>me===X.id))&&!$&&b.exec("select-file",{id:X.id}),de?.length)return de.forEach(me=>{$&&(me.hotkey=""),me.text&&(me.text=N(me.text)),me.hotkey&&(me.subtext=me.hotkey)}),ae(de),X||{}},[b,n,ye,a,Y,p,P,k,N]),U=u.useCallback(ue=>{const{action:be,context:X}=ue;be&&K(be.id,X,!be.hotkey)},[K]);async function W(ue){await Promise.resolve();const{name:be,size:X}=ue.file;b.exec("create-file",{file:{name:be,size:X,date:new Date,file:ue.file},parent:_})}return s.jsx("div",{className:"wx-RJbNonjJ wx-filemanager wx-flex",ref:l,"data-menu-ignore":"false",children:p&&T?s.jsx("div",{className:"wx-RJbNonjJ wx-info-narrow",children:s.jsx(oh,{narrowMode:p,extraInfo:r})}):s.jsxs(s.Fragment,{children:[s.jsx(qA,{narrowMode:p,onShowTree:G}),s.jsx(c1,{dataKey:"id",at:"point",options:L,resolver:Q,onClick:U,children:s.jsxs($b,{dataKey:"actionId",options:L,resolver:Q,onClick:U,children:[s.jsx(h1,{data:y,apiOnly:!0,uploadURL:W}),s.jsx(xp.Provider,{value:y,children:s.jsx("div",{className:"wx-RJbNonjJ wx-content-wrapper wx-flex",children:k!=="panels"&&k!=="search"?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"wx-RJbNonjJ "+["wx-sidebar",p?"wx-sidebar-narrow":"",g?"wx-sidebar-visible":""].filter(Boolean).join(" "),ref:c,children:s.jsx($A,{readonly:n,menuOptions:a})}),s.jsxs("div",{className:"wx-RJbNonjJ wx-content",style:{width:`calc(100% - ${d||0}px - 10px)`},children:[s.jsx("div",{className:`wx-RJbNonjJ wx-content-item${T?"":"-fit"}`,"data-id":Bn("body"),children:k==="table"?s.jsx(Ph,{panel:R}):s.jsx(GA,{})}),T?s.jsx("div",{className:"wx-RJbNonjJ wx-info",children:s.jsx(oh,{extraInfo:r})}):null]})]}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:`wx-RJbNonjJ wx-content-item${T?"":"-fit"}`,children:k==="panels"?s.jsx(HA,{}):s.jsx(IA,{})}),T?s.jsx("div",{className:"wx-RJbNonjJ wx-info",children:s.jsx(oh,{extraInfo:r})}):null]})})})]})})]})})}const WA=n=>n.split("-").map(a=>a?a.charAt(0).toUpperCase()+a.slice(1):"").join("");function YA(n,a){const{type:r,ext:l}=n;if(r==="folder")return!1;let c;return r&&r!=="file"&&ly[r]?c=r:l?c=ly[l]?l:"file":c="unknown",`https://cdn.svar.dev/icons/filemanager/vivid/${a}/${c}.svg`}const KA=u.forwardRef(function(n,a){const{data:r=[],mode:l="cards",drive:c=null,preview:d=!1,panels:m=null,activePanel:p=0,readonly:v=!1,menuOptions:g=Vk,extraInfo:w=null,init:y=null,icons:b=YA,previews:C=null,...j}=n,A=u.useRef();A.current=j;const N=u.useMemo(()=>new Gk(Hb),[]),k=u.useMemo(()=>N.in,[N]),T=u.useRef(null);T.current===null&&(T.current=new Db((O,Y)=>{const _="on"+WA(O);A.current&&A.current[_]&&A.current[_](Y)}),k.setNext(T.current));const R=u.useMemo(()=>({getState:N.getState.bind(N),getReactiveState:N.getReactive.bind(N),getStores:()=>({data:N}),exec:k.exec,setNext:O=>(T.current=T.current.setNext(O),T.current),intercept:k.intercept.bind(k),on:k.on.bind(k),detach:k.detach.bind(k),getFile:N.getFile.bind(N),serialize:N.serialize.bind(N),templates:{preview:C||(()=>null),icon:b==="simple"?(()=>null):b}}),[N,k]),q=u.useRef(0);return u.useEffect(()=>{if(!q.current)y&&y(R);else{const O=N.getState();N.init({data:r,mode:l,drive:c,preview:d,panels:m||O.panels||[],activePanel:p})}q.current++},[N,r,l,c,d,m,p,y,R]),q.current===0&&N.init({data:r,mode:l,drive:c,preview:d,panels:m||[],activePanel:p}),u.useImperativeHandle(a,()=>({...R}),[R]),s.jsx(Fn.Provider,{value:R,children:s.jsx(mp,{words:hp,optional:!0,children:s.jsx(LA,{children:s.jsx(VA,{readonly:v,menuOptions:g,extraInfo:w})})})})});function QA({fonts:n=!0,children:a}){return a?s.jsx(Vx,{fonts:n,children:a}):s.jsx(Vx,{fonts:n})}rp(Ba);function yp(n,a){if(!n||typeof n!="object"||Array.isArray(n))throw new Error(`Invalid Hub ${a} response.`);return n}function nu(n,a,r){const l=yp(n,r);if(!Array.isArray(l[a]))throw new Error(`Invalid Hub ${r} response: ${a} must be an array.`);return l[a]}function XA(n,a,r){const l=yp(n,r);if(!l[a]||typeof l[a]!="object"||Array.isArray(l[a]))throw new Error(`Invalid Hub ${r} response: ${a} must be an object.`);return l[a]}async function ZA(n,a=!1){return nu(await Ge(`/api/remote/filesystem/roots${a?"?refresh=1":""}`,void 0,n),"roots","filesystem roots")}async function ch(n,a){const r=await Ge(`/api/remote/filesystem/entries?id=${encodeURIComponent(n)}`,void 0,a);return{folder:XA(r,"folder","filesystem entries"),entries:nu(r,"entries","filesystem entries")}}async function JA(n,a){return Ge("/api/remote/filesystem/selection/scan",{method:"POST",body:JSON.stringify({itemIds:n})},a)}async function eN(n,a,r,l){return Ge("/api/remote/files/from-hub",{method:"POST",body:JSON.stringify({itemIds:n,deviceIds:a,remoteDirectory:r})},l)}async function tN(n,a=!1){const r=await Ge(`/api/remote/files/jobs?active=${a?"1":"0"}`,void 0,n);return{jobs:nu(r,"jobs","file transfer jobs")}}async function nN(n,a){return Ge(`/api/remote/files/jobs/${encodeURIComponent(n)}`,void 0,a)}async function aN(n,a){return Ge(`/api/remote/files/jobs/${encodeURIComponent(n)}/cancel`,{method:"POST"},a)}async function oy(n){return nu(await Ge("/api/remote/filesystem/shared-folders",void 0,n),"folders","shared folders")}async function sN(n,a){return Ge("/api/remote/filesystem/shared-folders",{method:"POST",body:JSON.stringify({sourceId:n})},a)}async function iN(n,a,r){return Ge(`/api/remote/filesystem/shared-folders/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(a)},r)}async function rN(n,a){return Ge(`/api/remote/filesystem/shared-folders/${encodeURIComponent(n)}`,{method:"DELETE"},a)}async function lN(n,a,r,l){const c=await Ge(`/api/remote/filesystem/shared-folders/${encodeURIComponent(n)}/sync`,{method:"POST",body:JSON.stringify({deviceIds:a,remoteDirectory:r})},l),d=yp(c,"shared folder sync");return{ok:d.ok===!0,jobs:nu(c,"jobs","shared folder sync"),files:Number(d.files||0),totalBytes:Number(d.totalBytes||0)}}function oN(n){return{id:String(n.id),parentId:n.parent,name:n.name,type:n.type==="file"?"file":"folder",size:Number(n.size||0),modifiedAt:n.date?.toISOString()||null,displayPath:String(n.displayPath||n.name),hasChildren:n.lazy===!0||!!n.data?.length,locked:n.locked===!0}}function cy(n){if(!Number.isFinite(n)||n<=0)return"0 B";const a=["B","KB","MB","GB","TB"];let r=n,l=0;for(;r>=1024&&l<a.length-1;)r/=1024,l+=1;return`${r.toFixed(l===0||r>=100?0:1)} ${a[l]}`}function Vd(n){return n.driveType==="network"?"network":n.driveType==="removable"?"removable":"local"}function cN(n){const a=n.filter(r=>Vd(r)==="local");return a.find(r=>/\bC:/i.test(`${r.name} ${r.displayPath||""}`))||a[0]||n[0]||null}function uN({hubUrl:n,roots:a,loading:r,error:l,onRefreshRoots:c,onImportFiles:d,onImportFolder:m,onSelectionChange:p,onShareItem:v,onAddSyncFolder:g,onNotice:w}){const y=u.useRef(null),b=u.useRef("/"),C=u.useRef(0),j=u.useRef([]),A=u.useRef(new Map),[N,k]=u.useState(null),[T,R]=u.useState([]),[q,O]=u.useState([]),[Y,_]=u.useState(0),[L,ae]=u.useState(null),[G,te]=u.useState(!1),[P,ye]=u.useState(""),[ie,K]=u.useState(new Set),I=a.find(se=>se.id===N)||null,Q=T[T.length-1]||null,U=I?Q?.svarPath||`/${I.name}`:null,W=U;u.useEffect(()=>{j.current=T,b.current=W||"/"},[W,T]);const ue=u.useMemo(()=>(A.current.clear(),!I||!W||T.length===0?[]:(T.forEach(se=>A.current.set(se.svarPath,se.hubId)),[...T.map((se,fe)=>({id:se.svarPath,parent:fe===0?"/":T[fe-1].svarPath,type:"folder",name:se.name,date:se.modifiedAt?new Date(se.modifiedAt):void 0,lazy:!1})),...q.map(se=>{const fe=`${W}/${se.name}`;return A.current.set(fe,se.id),{id:fe,parent:W,name:se.name,type:se.type==="file"?"file":"folder",...se.type==="file"?{size:se.size}:{},date:se.modifiedAt?new Date(se.modifiedAt):void 0,lazy:se.type!=="file"&&se.hasChildren===!0,displayPath:se.displayPath,locked:se.locked,driveType:se.driveType,totalBytes:se.totalBytes,freeBytes:se.freeBytes}})])),[I,q,W,T]),be=se=>A.current.get(String(se))||String(se),X=se=>oN({...se,id:be(String(se.id)),parent:be(String(se.parent))}),$=async(se,fe)=>{const Ne=se[se.length-1];if(!Ne)return;const Te=++C.current;te(!0),ye("");try{const Be=await ch(Ne.hubId,n);if(Te!==C.current)return;if(!Array.isArray(Be.entries))throw new Error("Invalid Hub filesystem entries response.");const $e={...Ne,displayPath:Be.folder.displayPath||Ne.displayPath,modifiedAt:Be.folder.modifiedAt||Ne.modifiedAt},et=[...se.slice(0,-1),$e];j.current=et,R(et),O(Be.entries),_(Mt=>Mt+1)}catch(Be){if(Te!==C.current)return;console.error("[LiveDesk FS] folder navigation failed",{folderId:Ne.hubId,error:Be}),ye(Be instanceof Error?`${fe}: ${Be.message}`:`${fe}: Unable to read this folder.`)}finally{Te===C.current&&te(!1)}},de=async se=>{const fe={svarPath:`/${se.name}`,hubId:se.id,name:se.name,displayPath:se.displayPath,modifiedAt:se.modifiedAt},Ne=++C.current;k(se.id),j.current=[fe],R([fe]),b.current=fe.svarPath,O([]),ye(""),te(!0),ae(se.id),K(Te=>{const Be=new Set(Te);return Be.delete(se.id),Be});try{const Te=await ch(se.id,n);if(Ne!==C.current)return;if(!Array.isArray(Te.entries))throw new Error("Invalid Hub filesystem entries response.");const Be={...fe,displayPath:Te.folder.displayPath||fe.displayPath,modifiedAt:Te.folder.modifiedAt||fe.modifiedAt};j.current=[Be],R([Be]),O(Te.entries),_($e=>$e+1)}catch(Te){if(Ne!==C.current)return;console.error("[LiveDesk FS] getEntries failed",{rootId:se.id,error:Te}),K(Be=>new Set(Be).add(se.id)),ye(Te instanceof Error?`${se.name}: ${Te.message}`:`${se.name}: Unable to read this drive.`),w(Te instanceof Error?`${se.name}: ${Te.message}`:`${se.name}: Unable to read this drive.`)}finally{Ne===C.current&&(ae(null),te(!1))}},me=se=>{const fe=j.current;se<0||se>=fe.length||se===fe.length-1||$(fe.slice(0,se+1),fe[se].name)},ve=(se,fe)=>{if(se.type!=="folder")return;const Ne=j.current,Te=Ne.findIndex($e=>$e.svarPath===fe);if(Te<0)return;const Be={svarPath:`${fe}/${se.name}`,hubId:se.id,name:se.name,displayPath:se.displayPath,modifiedAt:se.modifiedAt};$([...Ne.slice(0,Te+1),Be],se.name)},Se=()=>me(j.current.length-2),Oe=se=>{if(se.key!=="Enter"&&se.code!=="Enter"&&se.code!=="NumpadEnter"||se.target?.closest('button, input, textarea, [contenteditable="true"]'))return;const Ne=y.current;if(!Ne)return;const Te=Ne.getState().panels?.flatMap($e=>$e.selected||[])||[];if(Te.length!==1)return;const Be=Ne.getFile(String(Te[0]));Be?.type==="folder"&&(se.preventDefault(),se.stopPropagation(),ve(X(Be),String(Be.parent||b.current)))};u.useEffect(()=>{const se=a.find(fe=>fe.id===N)||cN(a);if(K(fe=>new Set([...fe].filter(Ne=>a.some(Te=>Te.id===Ne)))),!se){k(null),j.current=[],R([]),O([]);return}de(se)},[a]);const le=se=>{y.current=se,se.on("request-data",async({id:fe})=>{const Ne=String(fe),Te=be(Ne);try{const Be=await ch(Te,n);if(!Array.isArray(Be.entries))throw new Error("Invalid Hub filesystem entries response.");const $e=Be.entries.map(et=>{const Mt=`${Ne}/${et.name}`;return A.current.set(Mt,et.id),{id:Mt,parent:Ne,name:et.name,type:et.type==="file"?"file":"folder",...et.type==="file"?{size:et.size}:{},date:et.modifiedAt?new Date(et.modifiedAt):void 0,lazy:et.type!=="file"&&et.hasChildren===!0,displayPath:et.displayPath,locked:et.locked,driveType:et.driveType,totalBytes:et.totalBytes,freeBytes:et.freeBytes}});await se.exec("provide-data",{id:Ne,data:$e})}catch(Be){console.error("[LiveDesk FS] nested getEntries failed",{id:Te,error:Be}),w(Be instanceof Error?Be.message:"Unable to read this folder.")}}),se.intercept("set-path",({id:fe})=>{const Ne=String(fe),Te=j.current.findIndex($e=>$e.svarPath===Ne);if(Te>=0)return me(Te),!1;const Be=se.getFile(Ne);if(Be?.type==="folder")return ve(X(Be),String(Be.parent||b.current)),!1}),se.intercept("open-file",()=>!1),se.on("select-file",()=>{window.setTimeout(()=>{const Te=(se.getState().panels?.flatMap(Be=>Be.selected||[])||[]).map(Be=>se.getFile(Be)).filter(Boolean).map(Be=>X(Be));p(Te.map(Be=>Be.id),Te)},0)})},Z=(se,fe)=>{const Ne=fe?X(fe):null,Te=()=>{const Be=Ne?.type==="file"?String(fe?.parent||b.current):String(fe?.id||b.current);y.current?.exec("request-data",{id:Be})};return se==="body"?[{id:"refresh",text:"Refresh",icon:"mdi mdi-refresh",handler:Te},{id:"properties",text:"Properties",icon:"mdi mdi-information-outline",handler:()=>w("Select a file or folder to view its properties.")}]:se==="multiselect"?[{id:"share",text:"Share to workstations",icon:"mdi mdi-share-variant",handler:()=>{(y.current?.getState().panels?.flatMap($e=>$e.selected||[])||[]).forEach($e=>{const et=y.current?.getFile($e);et&&v(X(et))})}},{id:"refresh",text:"Refresh",icon:"mdi mdi-refresh",handler:Te}]:Ne?[{id:"share",text:"Share to workstations",icon:"mdi mdi-share-variant",handler:()=>v(Ne)},...Ne.type==="folder"?[{id:"sync",text:"Add folder to Sync",icon:"mdi mdi-folder-sync-outline",handler:()=>g(Ne)}]:[],{id:"copy-path",text:"Copy path",icon:"mdi mdi-content-copy",handler:()=>{Ll(Ne.displayPath||Ne.name)}},{id:"refresh",text:"Refresh",icon:"mdi mdi-refresh",handler:Te},{id:"properties",text:"Properties",icon:"mdi mdi-information-outline",handler:()=>w(`${Ne.name}
14
- ${Ne.displayPath||""}`)}]:[]},He=async()=>{try{await c()}catch(se){w(se instanceof Error?se.message:"Unable to refresh Hub drives.")}},_e=[{id:"local",label:"Local drives",icon:zl,roots:a.filter(se=>Vd(se)==="local")},{id:"removable",label:"Removable drives",icon:ZS,roots:a.filter(se=>Vd(se)==="removable")},{id:"network",label:"Network drives",icon:Jh,roots:a.filter(se=>Vd(se)==="network")}];return s.jsxs("section",{className:"hub-file-explorer-panel","aria-label":"Hub file explorer",children:[s.jsxs("div",{className:"hub-file-explorer-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Hub file explorer"}),s.jsxs("strong",{children:[s.jsx(zl,{size:16})," Browse files on this Hub"]})]}),s.jsxs("div",{className:"hub-file-explorer-heading-actions",children:[s.jsx("button",{className:"icon-button",onClick:d,title:"Import files from this browser",type:"button",children:s.jsx(Qy,{size:16})}),s.jsx("button",{className:"icon-button",onClick:m,title:"Import folder from this browser",type:"button",children:s.jsx(JS,{size:16})}),s.jsx("button",{className:"icon-button",onClick:()=>{He()},title:"Refresh drives",type:"button",children:s.jsx(Ho,{size:16})})]})]}),r?s.jsxs("div",{className:"hub-file-explorer-state",children:[s.jsx(zl,{size:24}),s.jsx("strong",{children:"Connecting to LiveDesk Hub file system..."})]}):l?s.jsxs("div",{className:"hub-file-explorer-state error",role:"alert",children:[s.jsx(Ds,{size:24}),s.jsx("strong",{children:l})]}):s.jsxs("div",{className:"hub-file-explorer-content",children:[s.jsxs("aside",{className:"hub-file-explorer-drive-sidebar","aria-label":"Hub drives",children:[s.jsxs("div",{className:"hub-drive-sidebar-title",children:[s.jsx(zl,{size:15}),s.jsx("strong",{children:"This PC"})]}),_e.map(se=>se.roots.length>0&&s.jsxs("section",{className:"hub-drive-group",children:[s.jsxs("h3",{children:[s.jsx(se.icon,{size:13}),se.label]}),s.jsx("div",{className:"hub-drive-list",children:se.roots.map(fe=>{const Ne=se.icon,Te=ie.has(fe.id)||fe.locked===!0;return s.jsxs("button",{className:`hub-drive-item ${N===fe.id?"active":""} ${Te?"unavailable":""}`,onClick:()=>{de(fe)},"aria-pressed":N===fe.id,type:"button",children:[s.jsx("span",{className:"hub-drive-item-icon",children:s.jsx(Ne,{size:16})}),s.jsxs("span",{className:"hub-drive-item-copy",children:[s.jsx("strong",{children:fe.name}),s.jsx("small",{children:fe.displayPath||fe.name}),s.jsxs("em",{children:[cy(fe.freeBytes||0)," free / ",cy(fe.totalBytes||0)]})]}),L===fe.id?s.jsx(ii,{className:"hub-drive-item-status spin",size:15}):Te?s.jsx(sx,{className:"hub-drive-item-status",size:15}):null]},fe.id)})})]},se.id)),a.length===0&&s.jsxs("div",{className:"hub-drive-sidebar-empty",children:[s.jsx(Ds,{size:17}),s.jsx("span",{children:"No drives available."})]})]}),s.jsxs("div",{className:"hub-file-explorer-browser",children:[s.jsxs("div",{className:"hub-file-explorer-navigation",children:[s.jsx("nav",{className:"hub-file-explorer-breadcrumbs","aria-label":"Current Hub folder",children:T.map((se,fe)=>s.jsxs("span",{className:"hub-file-explorer-breadcrumb-item",children:[fe>0&&s.jsx(ep,{size:13,"aria-hidden":"true"}),s.jsx("button",{className:`hub-file-explorer-breadcrumb ${fe===T.length-1?"current":""}`,onClick:()=>me(fe),"aria-current":fe===T.length-1?"location":void 0,type:"button",children:se.name})]},se.svarPath))}),s.jsxs("div",{className:"hub-file-explorer-navigation-actions",children:[G&&s.jsx(ii,{className:"hub-file-explorer-loading-icon spin",size:15,"aria-label":"Loading folder"}),s.jsx("button",{className:"icon-button",onClick:Se,disabled:T.length<=1||G,title:"Back to parent folder",type:"button",children:s.jsx(Uy,{size:16})})]})]}),P&&s.jsxs("div",{className:"hub-file-explorer-folder-error",role:"alert",children:[s.jsx(sx,{size:15}),s.jsx("span",{children:P})]}),s.jsx("div",{className:"hub-file-explorer-svar",onKeyDownCapture:Oe,children:s.jsx(QA,{fonts:!1,children:s.jsx(KA,{data:ue,panels:U?[{path:U,selected:[]}]:void 0,readonly:!0,mode:"table",preview:!1,init:le,icons:"simple",menuOptions:Z},`${I?.id||"no-root"}:${Y}`)})})]})]})]})}class dN extends u.Component{state={error:null};static getDerivedStateFromError(a){return{error:a}}componentDidCatch(a,r){console.error("[LiveDesk] Share Files runtime error",a,r.componentStack)}render(){return this.state.error?s.jsxs("section",{className:"file-share-error-boundary",role:"alert",children:[s.jsx(uf,{size:24}),s.jsx("strong",{children:"Share Files could not be opened."}),s.jsx("span",{children:this.state.error.message||"An unexpected file explorer error occurred."}),s.jsxs("button",{className:"text-button",onClick:this.props.onRetry,type:"button",children:[s.jsx(Ho,{size:15})," Retry"]})]}):this.props.children}}function fN(n){return n.deviceName||n.hostname||n.deviceId}function mN({devices:n,mode:a,selectedIds:r,onModeChange:l,onToggle:c}){const d=new Set(r);return s.jsxs("section",{className:"distribution-targets",children:[s.jsxs("div",{className:"file-share-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Target"}),s.jsx("strong",{children:a==="all"?`${n.length} connected`:`${r.length} selected`})]}),s.jsxs("div",{className:"file-share-tabs compact","aria-label":"File transfer targets",children:[s.jsxs("button",{className:a==="all"?"active":"",onClick:()=>l("all"),type:"button",children:[s.jsx(Qc,{size:14})," All connected"]}),s.jsxs("button",{className:a==="selected"?"active":"",onClick:()=>l("selected"),type:"button",children:[s.jsx(Yt,{size:14})," Selected"]})]})]}),s.jsx("div",{className:"file-share-device-list","aria-label":"Connected workstation targets",children:n.length===0?s.jsx("div",{className:"file-share-empty-inline",children:"No connected workstations."}):n.map(m=>{const p=a==="all"||d.has(m.deviceId);return s.jsxs("label",{className:`file-share-device-option ${p?"selected":""}`,children:[s.jsx("input",{type:"checkbox",checked:p,disabled:a==="all",onChange:()=>c(m.deviceId)}),s.jsx(Yt,{size:20,"aria-hidden":"true"}),s.jsxs("span",{children:[s.jsx("strong",{children:fN(m)}),s.jsxs("small",{children:["Slot ",m.slotNumber?String(m.slotNumber).padStart(3,"0"):"-"," / ",m.platform||"unknown OS"]})]}),s.jsx(Hn,{size:17,"aria-hidden":"true"})]},m.deviceId)})})]})}function hN(n){if(!Number.isFinite(n)||n<=0)return"0 B";const a=["B","KB","MB","GB","TB"];let r=n,l=0;for(;r>=1024&&l<a.length-1;)r/=1024,l+=1;return`${r.toFixed(l===0||r>=100?0:1)} ${a[l]}`}function pN({folders:n,loading:a,busy:r,canSync:l,onSyncAll:c,onSync:d,onToggleAuto:m,onRemove:p,onAdd:v}){return s.jsxs("section",{className:"file-share-sync-panel",children:[s.jsxs("div",{className:"file-share-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Hub folders"}),s.jsx("strong",{children:"Continuous sync"})]}),s.jsxs("button",{className:"text-button compact",onClick:c,disabled:r||!l||n.length===0,type:"button",children:[s.jsx(Pd,{size:15})," ",r?"Syncing":"Sync all"]})]}),a?s.jsx("div",{className:"file-share-empty-state",children:"Loading Hub sync folders..."}):n.length===0?s.jsxs("button",{className:"file-share-empty-state interactive",onClick:v,type:"button",children:[s.jsx(Pd,{size:28}),s.jsx("strong",{children:"Add a selected Hub folder"}),s.jsx("span",{children:"Hub keeps the manifest and can sync while this browser is closed."})]}):s.jsx("div",{className:"file-share-sync-list",children:n.map(g=>s.jsxs("article",{className:`file-share-sync-row state-${g.status}`,children:[s.jsx("div",{className:"file-share-sync-icon",children:s.jsx(Pd,{size:19})}),s.jsxs("div",{className:"file-share-sync-info",children:[s.jsx("strong",{children:g.name}),s.jsx("span",{children:g.displayPath}),s.jsxs("small",{children:[g.fileCount," files / ",hN(g.totalBytes)," · ",g.lastSyncedAt?`Last sync ${sb(g.lastSyncedAt)} ago`:g.message||"Not synced yet"]})]}),s.jsxs("label",{className:"file-share-auto-sync",children:[s.jsx("input",{type:"checkbox",checked:g.autoSync,onChange:()=>m(g)}),s.jsx("span",{children:"Auto"})]}),s.jsxs("button",{className:"text-button compact",onClick:()=>d(g),disabled:r||!l||g.status==="syncing",type:"button",children:[s.jsx(Ho,{size:14})," Sync now"]}),s.jsx("button",{className:"icon-button",onClick:()=>p(g),title:"Remove sync folder",type:"button",children:s.jsx(Xh,{size:15})})]},g.id))})]})}function gN(n){const r=(n.targetMode==="all"?n.devices.map(l=>l.deviceId):n.selectedTargetIds).length>0;return s.jsxs("aside",{className:"file-share-distribution-panel",children:[s.jsxs("div",{className:"file-share-distribution-head",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Distribution"}),s.jsx("strong",{children:"Hub → workstations"})]}),s.jsx(Yc,{size:18})]}),s.jsxs("div",{className:"file-share-tabs",role:"tablist","aria-label":"Distribution mode",children:[s.jsx("button",{className:n.tab==="send"?"active":"",onClick:()=>n.onTabChange("send"),role:"tab","aria-selected":n.tab==="send",type:"button",children:"Send"}),s.jsx("button",{className:n.tab==="sync"?"active":"",onClick:()=>n.onTabChange("sync"),role:"tab","aria-selected":n.tab==="sync",type:"button",children:"Sync"})]}),n.tab==="send"?s.jsxs(s.Fragment,{children:[s.jsx(mN,{devices:n.devices,mode:n.targetMode,selectedIds:n.selectedTargetIds,onModeChange:n.onTargetModeChange,onToggle:n.onTargetToggle}),s.jsxs("label",{className:"file-share-destination",children:[s.jsx("span",{children:"Destination folder"}),s.jsxs("div",{children:[s.jsx(Lo,{size:15}),s.jsx("input",{value:n.remoteDirectory,onChange:l=>n.onRemoteDirectoryChange(l.target.value),placeholder:"Desktop/LiveDeskFiles"})]}),s.jsx("small",{children:"Blank uses Desktop/LiveDeskFiles."})]}),s.jsxs("div",{className:"file-share-selection-summary",children:[s.jsx("span",{children:"Selected"}),s.jsx("strong",{children:n.selectedSummary})]}),s.jsxs("button",{className:"file-share-share-button",onClick:n.onShare,disabled:!n.canShare,type:"button",children:[s.jsx(Yc,{size:17})," Share selected"]}),s.jsxs("button",{className:"file-share-secondary-button",onClick:n.onAddSync,disabled:!n.canAddSync,type:"button",children:[s.jsx(Lo,{size:16})," Add selected folder to Sync"]})]}):s.jsx(pN,{folders:n.folders,loading:n.foldersLoading,busy:n.syncBusy,canSync:r,onSyncAll:n.onSyncAll,onSync:n.onSync,onToggleAuto:n.onToggleAuto,onRemove:n.onRemove,onAdd:n.onAddFolder})]})}function vN(n){if(!Number.isFinite(n)||n<=0)return"0 B";const a=["B","KB","MB","GB","TB"];let r=n,l=0;for(;r>=1024&&l<a.length-1;)r/=1024,l+=1;return`${r.toFixed(l===0||r>=100?0:1)} ${a[l]}`}function uy(n){return n.totalBytes>0?Math.max(0,Math.min(100,Math.round(n.sentBytes/n.totalBytes*100))):n.totalFiles>0?Math.max(0,Math.min(100,Math.round(n.completedFiles/n.totalFiles*100))):n.state==="completed"?100:0}function dy(n){return n.state==="scanning"?"Scanning selected Hub items":n.state==="queued"?"Preparing transfer":n.state==="sending"?`${n.completedFiles}/${n.totalFiles} · ${n.currentPath||"sending"}`:n.state==="completed"?`Sent ${n.totalFiles} file${n.totalFiles===1?"":"s"} to ${n.targetCount} workstation${n.targetCount===1?"":"s"}`:n.state==="partially-failed"?`${n.failedTargets.length} workstation${n.failedTargets.length===1?"":"s"} failed`:n.state==="cancelled"?"Transfer cancelled":n.error||"Transfer failed"}function fy(n){return["completed","partially-failed","failed","cancelled"].includes(n)}function xN({hubUrl:n,devices:a,localFeatureAccess:r,upgradeNotice:l,remoteDirectory:c,onRemoteDirectoryChange:d,targetMode:m,selectedTargetIds:p,onTargetModeChange:v,onTargetToggle:g,filePickerRef:w,folderPickerRef:y,onBrowserFileImport:b,onBrowserFolderImport:C,onNotice:j,onTransferChange:A}){const N=Array.isArray(a)?a:[],[k,T]=u.useState([]),[R,q]=u.useState(!0),[O,Y]=u.useState(""),[_,L]=u.useState([]),[ae,G]=u.useState([]),[te,P]=u.useState(null),[ye,ie]=u.useState(!1),[K,I]=u.useState([]),[Q,U]=u.useState(!0),[W,ue]=u.useState(!1),[be,X]=u.useState("send"),[$,de]=u.useState([]),me=u.useRef(new Set),ve=u.useMemo(()=>m==="all"?N.map(ke=>ke.deviceId):p.filter(ke=>N.some(Ye=>Ye.deviceId===ke)),[N,p,m]),Se=$.find(ke=>!fy(ke.state)),Oe=ae.length===1&&ae[0].type==="folder"?ae[0]:null,le=ae.length===0?"Select files or folders from the Hub explorer.":ye?"Calculating selection size...":te?`${te.files} files, ${te.folders} folders · ${vN(te.totalBytes)}`:`${ae.length} item${ae.length===1?"":"s"} selected`,Z=ke=>{A({id:ke.jobId,state:ke.state,progress:uy(ke),message:dy(ke)})},He=u.useCallback(async()=>{const ke=await ZA(n,!0);return T(ke),Y(""),ke},[n]),_e=async()=>{try{const Ye=(await tN(n,!0)).jobs||[],rt=await Promise.all([...me.current].map(async It=>{try{return await nN(It,n)}catch{return null}})),vt=[...Ye,...rt.filter(Boolean)],vn=[...new Map(vt.map(It=>[It.jobId,It])).values()];de(vn),vn.forEach(Z),vn.filter(It=>fy(It.state)).forEach(It=>me.current.delete(It.jobId))}catch{}};u.useEffect(()=>{let ke=!0;q(!0),Y(""),Promise.all([He(),oy(n).then(rt=>{ke&&I(rt)})]).catch(rt=>{ke&&(Y(rt instanceof Error?"Hub file system is unavailable. Make sure LiveDesk Hub is running on this computer.":"Hub file system is unavailable."),j(rt instanceof Error?rt.message:"Hub file system is unavailable."))}).finally(()=>{ke&&(q(!1),U(!1))}),_e();const Ye=window.setInterval(()=>{_e()},800);return()=>{ke=!1,window.clearInterval(Ye)}},[n,He]),u.useEffect(()=>{if(_.length===0){P(null);return}let ke=!1;return ie(!0),JA(_,n).then(Ye=>{ke||P(Ye)}).catch(Ye=>{ke||j(Ye instanceof Error?Ye.message:"Unable to calculate selected size.")}).finally(()=>{ke||ie(!1)}),()=>{ke=!0}},[n,_.join("|")]);const se=(ke,Ye)=>{L(ke),G(Ye)},fe=ke=>{ke.forEach(Ye=>me.current.add(Ye.jobId)),de(Ye=>[...new Map([...Ye,...ke].map(rt=>[rt.jobId,rt])).values()]),ke.forEach(Z)},Ne=async()=>{if(!r){j(l);return}if(_.length===0){j("Select files or folders from the Hub explorer.");return}if(ve.length===0){j("Choose at least one connected workstation.");return}if(Se){j("A Hub transfer is already running.");return}try{const ke=await eN(_,ve,c.trim(),n);me.current.add(ke.jobId),j("Hub transfer queued."),await _e()}catch(ke){j(ke instanceof Error?ke.message:"Unable to start Hub transfer.")}},Te=async ke=>{const Ye=ke||Oe;if(!Ye||Ye.type!=="folder"){j("Select one folder to add it to Sync.");return}try{const rt=await sN(Ye.id,n);I(vt=>[...vt.filter(vn=>vn.id!==rt.folder.id),rt.folder]),X("sync"),j(`${Ye.name} is ready for Hub sync.`)}catch(rt){j(rt instanceof Error?rt.message:"Unable to add the Hub folder to Sync.")}},Be=async ke=>{if(ve.length===0){j("Choose at least one connected workstation.");return}ue(!0),I(Ye=>Ye.map(rt=>rt.id===ke.id?{...rt,status:"syncing"}:rt));try{const Ye=await lN(ke.id,ve,c.trim(),n);fe(Ye.jobs||[]),j(Ye.jobs?.length?"Hub sync queued.":"No changed files to sync.");const rt=await oy(n);I(rt)}catch(Ye){j(Ye instanceof Error?Ye.message:"Unable to sync the Hub folder."),I(rt=>rt.map(vt=>vt.id===ke.id?{...vt,status:"error",message:"Sync failed"}:vt))}finally{ue(!1)}},$e=async()=>{ue(!0);try{for(const ke of K)await Be(ke)}finally{ue(!1)}},et=async ke=>{try{const Ye=await iN(ke.id,{autoSync:!ke.autoSync},n);I(rt=>rt.map(vt=>vt.id===ke.id?Ye.folder:vt))}catch(Ye){j(Ye instanceof Error?Ye.message:"Unable to update auto sync.")}},Mt=async ke=>{try{await rN(ke.id,n),I(Ye=>Ye.filter(rt=>rt.id!==ke.id))}catch(Ye){j(Ye instanceof Error?Ye.message:"Unable to remove the sync folder.")}};return s.jsxs("section",{className:"livedesk-file-explorer",children:[s.jsx("input",{ref:w,className:"hidden-file-input",type:"file",multiple:!0,onChange:ke=>{ke.currentTarget.files&&b(ke.currentTarget.files),ke.currentTarget.value=""}}),s.jsx("input",{ref:y,className:"hidden-file-input",type:"file",multiple:!0,webkitdirectory:"",directory:"",onChange:ke=>{ke.currentTarget.files&&C(ke.currentTarget.files),ke.currentTarget.value=""}}),s.jsx("div",{className:"file-share-workspace",children:s.jsxs(dN,{onRetry:()=>window.location.reload(),children:[s.jsx(uN,{hubUrl:n,roots:k,loading:R,error:O,onRefreshRoots:He,onImportFiles:()=>w.current?.click(),onImportFolder:()=>y.current?.click(),onSelectionChange:se,onShareItem:ke=>{L([ke.id]),G([ke]),X("send")},onAddSyncFolder:ke=>{L([ke.id]),G([ke]),Te(ke)},onNotice:j}),s.jsx(gN,{devices:N,targetMode:m,selectedTargetIds:p,onTargetModeChange:v,onTargetToggle:g,remoteDirectory:c,onRemoteDirectoryChange:d,selectedEntries:ae,selectedSummary:le,canShare:r&&!Se&&_.length>0&&ve.length>0&&!ye,onShare:()=>{Ne()},canAddSync:!!Oe,onAddSync:()=>{Te()},tab:be,onTabChange:X,folders:K,foldersLoading:Q,syncBusy:W,onSyncAll:()=>{$e()},onSync:ke=>{Be(ke)},onToggleAuto:ke=>{et(ke)},onRemove:ke=>{Mt(ke)},onAddFolder:()=>{Te()}})]})}),Se&&s.jsx("footer",{className:"file-share-workspace-footer",children:s.jsxs("span",{children:[dy(Se)," · ",uy(Se),"% ",s.jsx("button",{className:"icon-button",onClick:()=>{aN(Se.jobId,n).then(ke=>{de(Ye=>Ye.map(rt=>rt.jobId===ke.jobId?ke:rt)),Z(ke)})},title:"Cancel transfer",type:"button",children:s.jsx(Ha,{size:14})})]})})]})}const yN=u.forwardRef(function({value:a,onChange:r,onSubmit:l,onOpenSuggestedTasks:c,suggestedOpen:d=!1,suggestedTaskCount:m,disabled:p=!1,placeholder:v="Ask LiveDesk to work across your machines...",compact:g=!1},w){return s.jsxs("form",{className:"agents-composer",onSubmit:y=>{y.preventDefault(),l()},children:[s.jsx("button",{className:`agents-suggested-trigger ${d?"active":""}`,type:"button","aria-label":m===void 0?"Open Suggested tasks":`Open Suggested tasks (${m} available)`,"aria-expanded":d,onClick:c,disabled:p,children:s.jsx(e0,{size:17})}),s.jsx("textarea",{ref:w,value:a,onChange:y=>r(y.target.value.slice(0,4e3)),placeholder:v,"aria-label":"Ask LiveDesk",rows:g?1:2,disabled:p}),s.jsxs("button",{className:"agents-run-button",type:"submit",disabled:p||!a.trim(),children:[p?s.jsx(ii,{className:"spin",size:16}):s.jsx(Yc,{size:16}),p?"Running":"Run"]})]})}),bN=["read","processControl","serviceControl","applicationControl","fileRead","fileWrite","fileDelete","shell","script","softwareInstall","network","systemPower","systemConfiguration","userAccount"];function rf(n){return n.deviceName?.trim()||n.hostname?.trim()||n.deviceId}function lf(n){return n.connected!==!0?!1:n.synthetic===!0?!0:!n.channels||n.channels.control===!0}function wN(n){return n==="running"||n==="completed"||n==="failed"||n==="cancelled"?n:"queued"}function SN(n){switch(n){case"process.list":return"Process list";case"system.health":return"System health";case"gpu.status":return"GPU status";case"disk.status":return"Disk status";case"service.status":return"Service status";case"diagnostics.collect":return"Diagnostics";case"process.control":return"Process control";case"service.control":return"Service control";case"application.launch":return"Launch application";case"application.close":return"Close application";case"file.read":return"Read file";case"file.write":return"Write file";case"file.delete":return"Delete file";case"file.list":return"List directory";case"command.run":return"Run command";case"script.run":return"Run script";case"software.install":return"Install software";case"network.status":return"Network status";case"system.power":return"Power action";case"system.configure":return"System configuration";case"logs.collect":return"Collect logs"}}function CN(n){return n&&typeof n=="object"&&!Array.isArray(n)?n:null}function Ya(n){return typeof n=="number"&&Number.isFinite(n)?n:null}function Ld(n){const a=Ya(n);return a===null?"":a<1024**2?`${Math.round(a/1024)}K`:a<1024**3?`${(a/1024**2).toFixed(0)}M`:`${(a/1024**3).toFixed(1)}G`}function jN(n){const a=Ya(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 of(n,a){if(a.error)return a.error;const r=CN(a.data),l=kN(a.result||"");if(!r)return l||a.stage||a.status;if(n==="system.health"){const c=typeof r.machine=="string"?r.machine:"",d=Ld(r.freeMemoryBytes),m=Ld(r.totalMemoryBytes),p=Ya(r.totalMemoryBytes)&&Ya(r.freeMemoryBytes)!==null?`${Math.round(Ya(r.freeMemoryBytes)/Ya(r.totalMemoryBytes)*100)}% RAM free`:"";return[c,d&&m?`RAM ${d}/${m}`:"",p,typeof r.platform=="string"?r.platform:""].filter(Boolean).join(" · ")||l||a.status}if(n==="disk.status"){const c=typeof r.root=="string"?r.root:"",d=Ld(r.freeBytes),m=Ya(r.totalBytes)&&Ya(r.freeBytes)!==null?`${Math.round(Ya(r.freeBytes)/Ya(r.totalBytes)*100)}% free`:"";return[c,d&&`${d} free`,m].filter(Boolean).join(" · ")||l||a.status}if(n==="gpu.status"){const c=typeof r.name=="string"&&r.name?r.name:"No GPU provider",d=jN(r.usageRatio),m=Ya(r.temperatureC)!==null?`${Math.round(Ya(r.temperatureC))}°C`:"",p=Ld(r.freeMemoryBytes);return[c,d&&`GPU ${d}`,m,p&&`${p} free`].filter(Boolean).join(" · ")||l||a.status}if(n==="process.list"){const c=Ya(r.count);return c!==null?`${c} matching process${c===1?"":"es"}`:l||a.status}if(n==="network.status"){const c=Array.isArray(r.adapters)?r.adapters.length:null;return c!==null?`${c} active adapter${c===1?"":"s"}`:l||a.status}return l||a.stage||a.status}function my(n,a){const r=of(n,a);return a.status==="failed"||a.status==="cancelled"||/\b(?:warning|failed|error|offline|not running|low|timeout|timed out)\b/i.test(`${a.result||""} ${r}`)}function AN({state:n,operation:a}){const r=n.status==="completed"?ri:n.status==="failed"||n.status==="cancelled"?Ha:n.status==="running"?ii:Xy,l=n.status==="running"?n.stage||"Working":n.status==="completed"?a?of(a,n):n.result||"Completed":n.status==="failed"?n.error||"Failed":n.status==="cancelled"?"Cancelled":"Queued";return s.jsxs("div",{className:`agent-target-row status-${n.status}`,"data-agent-target-id":n.deviceId,children:[s.jsx("span",{className:"agent-target-status","aria-hidden":"true",children:s.jsx(r,{size:15})}),s.jsx("strong",{children:n.deviceName}),s.jsx("span",{className:"agent-target-state",children:n.status[0].toUpperCase()+n.status.slice(1)}),s.jsx("small",{children:l})]})}function NN({operation:n,states:a,status:r,onCancel:l,onRetry:c,busy:d=!1}){const m=["running","queued"].includes(r),[p,v]=u.useState(!1),[g,w]=u.useState("all"),y=u.useMemo(()=>({total:a.length,completed:a.filter(R=>R.status==="completed").length,failed:a.filter(R=>R.status==="failed").length,running:a.filter(R=>R.status==="running").length,queued:a.filter(R=>R.status==="queued").length,cancelled:a.filter(R=>R.status==="cancelled").length}),[a]),b=a.filter(R=>my(n,R)),C=b.filter(R=>R.status==="completed").length,j=y.failed>0,A=b.length>0,N=a.filter(R=>g==="issues"?my(n,R):g==="running"?R.status==="running"||R.status==="queued":g==="completed"?R.status==="completed":g==="failed"?R.status==="failed":!0),k=A&&!m||r==="completed-with-failures"?"Completed with issues":r[0]?.toUpperCase()+r.slice(1),T=a.filter(R=>R.status==="completed").map(R=>of(n,R)).filter(Boolean).filter((R,q,O)=>O.indexOf(R)===q).slice(0,2);return s.jsxs("section",{className:"agent-task-block","aria-label":"Task execution",children:[s.jsxs("div",{className:"agent-task-head",children:[s.jsxs("div",{children:[s.jsx("span",{children:"LiveDesk Agent"}),s.jsx("strong",{children:SN(n)})]}),s.jsx("span",{className:`agent-task-status status-${A?"completed-with-failures":r}`,children:k})]}),s.jsxs("div",{className:"agent-task-summary","aria-label":"Task summary",children:[s.jsxs("strong",{children:[y.total," targets"]}),s.jsxs("span",{className:"summary-completed",children:[y.completed," completed"]}),y.running>0&&s.jsxs("span",{className:"summary-running",children:[y.running," running"]}),y.queued>0&&s.jsxs("span",{children:[y.queued," queued"]}),j&&s.jsxs("span",{className:"summary-failed",children:[y.failed," failed"]}),C>0&&s.jsxs("span",{className:"summary-cancelled",children:[C," warning"]}),y.cancelled>0&&s.jsxs("span",{className:"summary-cancelled",children:[y.cancelled," cancelled"]})]}),T.length>0&&s.jsxs("div",{className:"agent-task-result-preview",title:T.join(" · "),children:[s.jsx("span",{children:"Result"}),T.join(" · ")]}),s.jsx("div",{className:"agent-target-chips","aria-label":"Target status overview",children:a.map((R,q)=>{const O=R.status==="completed"?"✓":R.status==="failed"?"×":R.status==="cancelled"?"!":R.status==="running"?"…":"·";return s.jsxs("span",{className:`agent-target-chip status-${R.status}`,title:`${R.deviceName}: ${of(n,R)}`,"aria-label":`${q+1}. ${R.deviceName}: ${R.status}`,children:[s.jsx("b",{children:String(q+1).padStart(2,"0")}),s.jsx("span",{children:O})]},R.deviceId)})}),a.length>0&&s.jsx("div",{className:"agent-task-details-toggle",children:s.jsxs("button",{type:"button",onClick:()=>v(R=>!R),"aria-expanded":p,children:[p?s.jsx(t0,{size:14}):s.jsx(Zy,{size:14}),p?"Hide details":"Show details"]})}),p&&s.jsxs("div",{className:"agent-task-details",children:[s.jsx("div",{className:"agent-task-filters",role:"tablist","aria-label":"Task result filter",children:["all","issues","running","completed","failed"].map(R=>s.jsx("button",{className:g===R?"active":"",onClick:()=>w(R),role:"tab","aria-selected":g===R,type:"button",children:R==="all"?"All":R==="issues"?"Issues only":R[0].toUpperCase()+R.slice(1)},R))}),s.jsx("div",{className:"agent-task-rows",children:N.length>0?N.map(R=>s.jsx(AN,{operation:n,state:R},R.deviceId)):s.jsx("small",{className:"agent-task-no-results",children:"No targets match this filter."})})]}),(m||j)&&s.jsxs("div",{className:"agent-task-actions",children:[m&&l&&s.jsxs("button",{onClick:l,disabled:d,type:"button",children:[s.jsx(n0,{size:14})," Cancel"]}),!m&&j&&c&&s.jsxs("button",{onClick:c,disabled:d,type:"button",children:[s.jsx($c,{size:14})," Retry failed"]})]})]})}function MN(n){try{return JSON.stringify(n,null,2).slice(0,6e3)}catch{return"{}"}}function TN({approval:n,busy:a=!1,onApprove:r,onReject:l}){return s.jsxs("article",{className:"agent-approval-card","aria-label":"Agent approval required",children:[s.jsxs("div",{className:"agent-approval-head",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Approval required"}),s.jsx("strong",{children:n.toolName})]}),s.jsx("span",{className:`agent-approval-risk risk-${n.risk}`,children:n.risk})]}),s.jsx("p",{children:n.description}),s.jsx("pre",{children:MN(n.arguments)}),s.jsxs("small",{children:["Permission: ",n.permissionMode," · Scope: selected devices only · Expires in 5 minutes"]}),s.jsxs("div",{className:"agent-approval-actions",children:[s.jsxs("button",{className:"reject",disabled:a,onClick:l,type:"button",children:[s.jsx(Ha,{size:14})," Reject"]}),s.jsxs("button",{disabled:a,onClick:()=>r("once"),type:"button",children:[s.jsx(ri,{size:14})," Once"]}),s.jsx("button",{disabled:a,onClick:()=>r("same-action-this-run"),type:"button",children:"Allow same action"}),s.jsx("button",{disabled:a,onClick:()=>r("category-this-run"),type:"button",children:"Allow category"})]}),s.jsxs("div",{className:"agent-approval-scope",children:[s.jsx(uf,{size:13})," Approval is bound to this run, tool, arguments, selected devices, and policy hash."]})]})}function EN(n){return n==="queued"?"Request queued":n==="checking-codex"?"Checking Codex":n==="preparing-tools"?"Preparing tools":n==="thinking"?"Preparing answer":n==="tool-running"?"Working on computers":n==="recovering"?"Retrying safely":n==="waiting-approval"?"Waiting for approval":"Working"}function RN({items:n,onCancel:a,onRetry:r,busyBatchId:l,approvals:c,onApprove:d,onReject:m,busyApprovalId:p,progress:v,emptyTitle:g="Ask LiveDesk to work across your machines.",emptyBody:w="Start with a read-only request such as “모든 PC에서 ComfyUI가 실행 중인지 확인해줘”."}){const y=u.useRef(null),b=u.useRef(!0),C=u.useRef(""),j=n[n.length-1];return u.useLayoutEffect(()=>{const A=y.current;A&&(j?.type==="user"&&j.id!==C.current&&(b.current=!0),C.current=j?.id||"",b.current&&(A.scrollTop=A.scrollHeight))},[c,n,j?.id,j?.type,v?.message,v?.stage]),s.jsxs("section",{className:"agents-conversation","aria-live":"polite",ref:y,onScroll:A=>{const N=A.currentTarget;b.current=N.scrollHeight-N.scrollTop-N.clientHeight<72},children:[c.filter(A=>A.status==="pending").map(A=>s.jsx(TN,{approval:A,busy:p===A.approvalId,onApprove:N=>d(A,N),onReject:()=>m(A)},A.approvalId)),n.length===0&&s.jsxs("div",{className:"agents-empty-conversation",children:[s.jsx("strong",{children:g}),s.jsx("span",{children:w})]}),n.map(A=>{if(A.type==="task"){const N=A;return s.jsx(NN,{operation:N.operation,states:N.states,status:N.status,onCancel:()=>a(N.batchId,N.agentRunId),onRetry:()=>r(N.batchId),busy:l===N.batchId},N.id)}return s.jsxs("article",{className:`agents-message ${A.type}`,children:[s.jsx("span",{children:A.type==="user"?"You":"LiveDesk Agent"}),s.jsx("p",{children:A.text})]},A.id)}),v&&s.jsxs("article",{className:"agents-message agent agents-progress-message",role:"status",children:[s.jsxs("span",{children:[s.jsx(ii,{"aria-hidden":"true",size:15}),EN(v.stage)]}),s.jsx("p",{children:v.message})]})]})}const hy=["Recommended","Health & capacity","Processes & services","AI workloads","Files & configuration","Software & automation","Network & connectivity","Power & maintenance","Troubleshooting & recovery"],Sn=["windows","macos","linux"],Ur={"system.health":{label:"system health",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:Sn},"gpu.status":{label:"GPU status",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:Sn},"disk.status":{label:"disk status",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:Sn},"process.list":{label:"process inspection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:Sn},"service.status":{label:"service inspection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:Sn},"diagnostics.collect":{label:"diagnostics collection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:Sn},"process.control":{label:"process control",permissionCategory:"processControl",readOnly:!1,risk:"high",supportedPlatforms:Sn},"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:Sn},"application.close":{label:"application close",permissionCategory:"applicationControl",readOnly:!1,risk:"medium",supportedPlatforms:Sn},"file.read":{label:"file reading",permissionCategory:"fileRead",readOnly:!0,risk:"low",supportedPlatforms:Sn},"file.write":{label:"file writing",permissionCategory:"fileWrite",readOnly:!1,risk:"high",supportedPlatforms:Sn},"file.delete":{label:"file deletion",permissionCategory:"fileDelete",readOnly:!1,risk:"critical",supportedPlatforms:Sn},"file.list":{label:"directory listing",permissionCategory:"fileRead",readOnly:!0,risk:"low",supportedPlatforms:Sn},"command.run":{label:"command execution",permissionCategory:"shell",readOnly:!1,risk:"critical",supportedPlatforms:Sn},"script.run":{label:"script execution",permissionCategory:"script",readOnly:!1,risk:"high",supportedPlatforms:Sn},"software.install":{label:"software installation",permissionCategory:"softwareInstall",readOnly:!1,risk:"high",supportedPlatforms:Sn},"network.status":{label:"network inspection",permissionCategory:"network",readOnly:!0,risk:"low",supportedPlatforms:Sn},"system.power":{label:"power control",permissionCategory:"systemPower",readOnly:!1,risk:"critical",supportedPlatforms:Sn},"system.configure":{label:"system configuration",permissionCategory:"systemConfiguration",readOnly:!1,risk:"critical",supportedPlatforms:Sn},"logs.collect":{label:"log collection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:Sn}};new Set(Object.keys(Ur));const DN={Recommended:["recommended","overview","fleet","요약","추천"],"Health & capacity":["health","capacity","performance","상태","성능","용량"],"Processes & services":["process","service","application","프로세스","서비스","앱"],"AI workloads":["ai","gpu","comfyui","ollama","인공지능","모델"],"Files & configuration":["file","config","directory","파일","설정","폴더"],"Software & automation":["software","install","automation","프로그램","설치","자동화"],"Network & connectivity":["network","connection","adapter","네트워크","연결","어댑터"],"Power & maintenance":["power","maintenance","restart","전원","유지보수","재시작"],"Troubleshooting & recovery":["troubleshooting","recovery","incident","문제해결","복구","장애"]},py=["low","medium","high","critical"];function LN(n){return n.reduce((a,r)=>{const l=Ur[r].risk;return py.indexOf(l)>py.indexOf(a)?l:a},"low")}function _N(n){return Sn.filter(a=>n.every(r=>Ur[r].supportedPlatforms.includes(a)))}function Pe(n,a,r,l,c,d,m={}){const p=m.description||l,v=c.flatMap(w=>w.split(".")),g=[...new Set([...DN[a],...d,...v])];return{id:n,category:a,title:r,prompt:l,description:p,requiredOperations:c,risk:m.risk||LN(c),targetSupport:m.targetSupport||"single-or-multiple",supportedPlatforms:m.supportedPlatforms||_N(c),keywords:g,recommended:m.recommended??!1,enabled:!0}}const aw=[Pe("recommended-fleet-health","Recommended","Summarize current target health","Summarize system health, GPU, and disk capacity for the current target workstations.",["system.health","gpu.status","disk.status"],["summary","overview"],{recommended:!0}),Pe("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}),Pe("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}),Pe("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}),Pe("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}),Pe("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}),Pe("recommended-recover-ai","Recommended","Recover stopped AI workers","Find stopped AI workers and relaunch the registered worker application or service on the target workstation.",["process.list","application.launch","service.control"],["recover","start","ai worker"],{targetSupport:"single",recommended:!0}),Pe("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}),Pe("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","높은 사용량"]),Pe("health-uptime","Health & capacity","Review workstation uptime","Show uptime, boot time, and current system health for the target workstations.",["system.health"],["uptime","boot","가동시간"]),Pe("health-gpu-temperature","Health & capacity","Check GPU temperature","Check GPU temperature and thermal warnings on the current targets.",["gpu.status"],["thermal","temperature","발열"]),Pe("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"]),Pe("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","디스크"]),Pe("health-gpu-compare","Health & capacity","Compare GPU capacity","Compare GPU model, memory, temperature, and utilization across the current targets.",["gpu.status"],["compare","graphics","capacity"]),Pe("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","경고"]),Pe("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"]),Pe("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","실행 중"]),Pe("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"]),Pe("process-stop-named","Processes & services","Stop a named process","Stop process named [process name] on the target workstation after checking its current state.",["process.list","process.control"],["stop","terminate","종료"],{targetSupport:"single"}),Pe("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"}),Pe("process-launch-app","Processes & services","Launch a registered application","Launch the registered application [application] on the target workstation with [arguments].",["application.launch"],["launch","open","실행"],{targetSupport:"single"}),Pe("process-close-app","Processes & services","Close an application","Close application [application] on the target workstation and report whether it exited cleanly.",["application.close","process.list"],["close","exit","앱 종료"],{targetSupport:"single"}),Pe("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","서비스 상태"]),Pe("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"}),Pe("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"]),Pe("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"}),Pe("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"}),Pe("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"]),Pe("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"]),Pe("ai-worker-logs","AI workloads","Collect AI worker logs","Collect recent logs and relevant log files for the AI worker on the target workstation.",["logs.collect","file.list","file.read"],["logs","diagnostics","worker"],{targetSupport:"single"}),Pe("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"]),Pe("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"}),Pe("files-list-directory","Files & configuration","List a directory","List files and folders under [path] on the target workstation.",["file.list"],["directory","folder","list","목록"],{targetSupport:"single"}),Pe("files-read-config","Files & configuration","Read a configuration file","Read the relevant settings from configuration file [path] on the target workstation.",["file.read"],["config","settings","read","구성"]),Pe("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"]),Pe("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"}),Pe("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"}),Pe("files-compare-config","Files & configuration","Compare configuration files","Read configuration file [path] on the target workstation and compare it with [reference path].",["file.read"],["compare","diff","configuration"]),Pe("files-set-environment","Files & configuration","Set an environment variable","Set environment variable [name] to [value] for the target workstation and verify the resulting configuration.",["system.configure","file.read"],["environment","variable","env","환경변수"],{targetSupport:"single"}),Pe("files-archive-diagnostics","Files & configuration","Write a diagnostic manifest","Collect selected diagnostics and write a manifest file to [path] on the target workstation.",["diagnostics.collect","file.write"],["manifest","export","diagnostic file"],{targetSupport:"single"}),Pe("software-winget-install","Software & automation","Install software with winget","Install package [package name] with winget on the Windows target workstation, then verify it.",["software.install","process.list"],["winget","windows","install","설치"],{targetSupport:"single",supportedPlatforms:["windows"]}),Pe("software-apt-install","Software & automation","Install software with apt","Install package [package name] with apt on the Linux target workstation, then verify it.",["software.install","process.list"],["apt","linux","package","설치"],{targetSupport:"single",supportedPlatforms:["linux"]}),Pe("software-brew-install","Software & automation","Install software with Homebrew","Install package [package name] with brew on the macOS target workstation, then verify it.",["software.install","process.list"],["brew","homebrew","macos","설치"],{targetSupport:"single",supportedPlatforms:["macos"]}),Pe("software-npm-install","Software & automation","Install an npm package","Install npm package [package name] on the target workstation and verify the installed version.",["software.install","command.run"],["npm","node","package"],{targetSupport:"single"}),Pe("software-run-script","Software & automation","Run a registered script","Run the registered script [script path] on the target workstation and report its result.",["script.run"],["script","automation","registered"],{targetSupport:"single"}),Pe("software-run-command","Software & automation","Run a command on one target","Run command [command] on the target workstation and return its exit status and output.",["command.run"],["command","shell","terminal"],{targetSupport:"single"}),Pe("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"]),Pe("software-toolchain-setup","Software & automation","Set up a toolchain","Install the requested package [package name], configure [change], and verify the toolchain on the target workstation.",["software.install","system.configure","process.list"],["toolchain","setup","developer"],{targetSupport:"single"}),Pe("network-adapter-status","Network & connectivity","Check network adapters","Show adapter state, address, and link information for the current targets.",["network.status"],["adapter","ethernet","wifi","네트워크 상태"]),Pe("network-disconnected","Network & connectivity","Find disconnected targets","Find current targets with disconnected or degraded network adapters.",["network.status"],["disconnected","offline","연결 끊김"]),Pe("network-link-speed","Network & connectivity","Check link speed","Report network link speed and duplex information for the current targets.",["network.status"],["speed","bandwidth","duplex"]),Pe("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"]),Pe("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"]),Pe("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"]),Pe("network-compare","Network & connectivity","Compare target connectivity","Compare adapter state, addresses, and link speed across the current targets.",["network.status"],["compare","inventory","connectivity"]),Pe("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"]),Pe("power-lock","Power & maintenance","Lock the workstation","Lock the target workstation and report the resulting power action status.",["system.power"],["lock","security","잠금"],{targetSupport:"single",risk:"critical"}),Pe("power-logoff","Power & maintenance","Log off the workstation","Log off the target workstation after warning that interactive sessions will close.",["system.power"],["logoff","session","로그오프"],{targetSupport:"single",risk:"critical"}),Pe("power-sleep","Power & maintenance","Put the workstation to sleep","Put the target workstation to sleep after confirming the requested delay of [delay].",["system.power"],["sleep","suspend","절전"],{targetSupport:"single",risk:"critical"}),Pe("power-restart","Power & maintenance","Restart the workstation","Restart the target workstation after confirming that active work may be interrupted.",["system.power"],["restart","reboot","재부팅"],{targetSupport:"single",risk:"critical"}),Pe("power-shutdown","Power & maintenance","Shut down the workstation","Shut down the target workstation after confirming that active work may be interrupted.",["system.power"],["shutdown","power off","종료"],{targetSupport:"single",risk:"critical"}),Pe("power-maintenance-restart","Power & maintenance","Restart after maintenance","Check the target workstation, restart it after maintenance, and verify that it returns online.",["system.health","system.power","network.status"],["maintenance","reboot","verify"],{targetSupport:"single",risk:"critical"}),Pe("power-timezone","Power & maintenance","Set the workstation timezone","Set the target workstation timezone to [timezone] and verify the resulting system configuration.",["system.configure"],["timezone","clock","시간대"],{targetSupport:"single",risk:"critical"}),Pe("power-persistent-environment","Power & maintenance","Persist an environment variable","Persist environment variable [name] with value [value] for the target workstation and verify it.",["system.configure"],["environment","persistent","환경변수"],{targetSupport:"single",risk:"critical"}),Pe("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"}),Pe("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"}),Pe("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"}),Pe("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"}),Pe("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"}),Pe("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"}),Pe("recovery-network-instability","Troubleshooting & recovery","Recover network instability","Collect network diagnostics, inspect network services, and report the safest recovery action for the target workstation.",["network.status","service.status","diagnostics.collect"],["network","unstable","네트워크 복구"],{targetSupport:"single"}),Pe("recovery-incident-report","Troubleshooting & recovery","Create a full incident report","Create a full incident report from health, process, service, network, and log evidence for the current targets.",["system.health","process.list","service.status","network.status","logs.collect"],["incident","report","장애 보고서"])],uh={read:"allow",processControl:"allow",serviceControl:"allow",applicationControl:"ask",fileRead:"allow",fileWrite:"allow",fileDelete:"ask",shell:"ask",script:"ask",softwareInstall:"ask",network:"allow",systemPower:"ask",systemConfiguration:"ask",userAccount:"deny"};function zN(n,a){return n==="safe-auto"?uh:n==="full-access"?{...uh,processControl:"allow",serviceControl:"allow",applicationControl:"allow",fileDelete:"allow",shell:"allow",script:"allow",softwareInstall:"allow",systemPower:"allow",systemConfiguration:"allow"}:n==="custom"&&a?a:{...uh,processControl:"ask",serviceControl:"ask",applicationControl:"ask",fileWrite:"ask",network:"ask"}}function IN(n,a,r){const l=zN(a,r),c=n.requiredOperations.map(d=>l[Ur[d].permissionCategory]);if(c.includes("deny")){const d=n.requiredOperations.find(m=>l[Ur[m].permissionCategory]==="deny");return{state:"blocked",label:"Blocked",reason:`This task requires ${Ur[d].label}, which is blocked by the current permission policy.`}}return c.includes("ask")?{state:"approval",label:"Approval required",reason:"This task requires approval before the requested changes can reach a workstation."}:n.requiredOperations.every(d=>Ur[d].readOnly)?{state:"read-only",label:"Read only"}:a==="full-access"?{state:"full-access",label:"Full Access"}:{state:"auto",label:"Auto allowed"}}function ON(n){const a=String(n||"").trim().toLowerCase();return a==="windows"||a==="win32"||a==="win32nt"?"windows":a==="macos"||a==="macosx"||a==="darwin"||a==="osx"?"macos":a==="linux"?"linux":null}function HN(n,a,r){const l=new Set(r);return n.filter(c=>c.connected&&(a==="all"||a==="auto"||l.has(c.deviceId)))}function BN(n,a){const r=ON(n.platform);if(!r||!a.supportedPlatforms.includes(r))return!1;const l=n.capabilities?.agentTools;return!Array.isArray(l)||l.length===0?a.requiredOperations.every(c=>Ur[c].readOnly):a.requiredOperations.every(c=>l.includes(c))}function sw(n,a,r,l,c,d){const m=IN(n,c,d),p=HN(a,r,l),v=p.map(C=>C.deviceId),g={...m,available:!1,availableDeviceIds:[],unsupportedDeviceIds:v,risk:n.risk,supportedPlatforms:n.supportedPlatforms};if(p.length===0)return{...g,reason:"Select at least one connected workstation."};if(n.targetSupport==="single"&&p.length!==1)return{...g,reason:"This task supports one workstation at a time."};if(m.state==="blocked")return g;const w=p.filter(C=>BN(C,n)),y=w.map(C=>C.deviceId),b=v.filter(C=>!y.includes(C));return w.length===0?{...g,unsupportedDeviceIds:b,reason:"No current target supports the required platform and client capabilities."}:{...g,available:!0,availableDeviceIds:y,unsupportedDeviceIds:b}}function FN(n,a,r,l,c,d){return n.filter(m=>m.enabled&&sw(m,a,r,l,c,d).available).length}const dh="livedesk.agentPromptRecent",fh="livedesk.agentPromptFavorites",PN={Recommended:Ls,"Health & capacity":gn,"Processes & services":l0,"AI workloads":Wy,"Files & configuration":r0,"Software & automation":Qd,"Network & connectivity":Jh,"Power & maintenance":Lt,"Troubleshooting & recovery":i0};function gy(n){if(typeof window>"u")return[];try{const a=JSON.parse(window.localStorage.getItem(n)||"[]");return Array.isArray(a)?a.filter(r=>typeof r=="string"):[]}catch{return[]}}function _d(n,a){try{window.localStorage.setItem(n,JSON.stringify(a))}catch{}}function mh(n){return n==="all"?"All tasks":n==="recent"?"Recent":n==="favorites"?"Favorites":n==="read-only"?"Read only":n==="auto"?"Auto allowed":n==="approval"?"Approval required":n==="full-access"?"Full Access":n==="available"?"Available":n==="unavailable"?"Unavailable":n}function $N(n){return n==="all"?"All":n==="recent"?"Recent":n==="favorites"?"Favorites":n==="read-only"?"Read only":n==="auto"?"Auto":n==="approval"?"Approval":n==="full-access"?"Full access":n==="available"?"Available":n==="unavailable"?"Unavailable":{Recommended:"Recommended","Health & capacity":"Health","Processes & services":"Processes","AI workloads":"AI","Files & configuration":"Files","Software & automation":"Software","Network & connectivity":"Network","Power & maintenance":"Power","Troubleshooting & recovery":"Recovery"}[n]}function UN(n,a,r){if(!r.trim())return!0;const l=r.trim().toLowerCase();return[n.title,n.prompt,n.description,n.category,n.risk,a.label,...n.keywords,...n.requiredOperations,...n.supportedPlatforms].join(" ").toLowerCase().includes(l)}function qN(n){return`permission-${n}`}function GN(n){return n==="low"?"Low risk":n==="medium"?"Medium risk":n==="high"?"High risk":"Critical risk"}function VN(n){return n==="windows"?"Windows":n==="macos"?"macOS":"Linux"}function WN({devices:n,targetMode:a,selectedIds:r,permissionMode:l,customCategories:c,onSelectPrompt:d,onClose:m}){const[p,v]=u.useState(""),[g,w]=u.useState("all"),[y,b]=u.useState(()=>gy(dh)),[C,j]=u.useState(()=>gy(fh)),[A,N]=u.useState(0),[k,T]=u.useState(""),R=u.useRef(null),q=u.useRef(null),O=u.useMemo(()=>aw.filter(K=>K.enabled),[]),Y=u.useMemo(()=>new Map(O.map(K=>[K.id,sw(K,n,a,r,l,c)])),[c,n,l,r,a,O]),_=u.useMemo(()=>[...Y.values()].filter(K=>K.available).length,[Y]),L=u.useMemo(()=>n.filter(K=>K.connected&&(a==="all"||a==="auto"||r.includes(K.deviceId))).length,[n,r,a]),ae=u.useMemo(()=>{const K=O.filter(I=>UN(I,Y.get(I.id),p));return g==="recent"?y.map(I=>K.find(Q=>Q.id===I)).filter(I=>!!I):g==="favorites"?C.map(I=>K.find(Q=>Q.id===I)).filter(I=>!!I):g==="all"?K:K.filter(I=>{const Q=Y.get(I.id);return g==="read-only"?Q.state==="read-only":g==="auto"?Q.state==="auto":g==="approval"?Q.state==="approval":g==="full-access"?Q.state==="full-access":g==="available"?Q.available:g==="unavailable"?!Q.available:I.category===g})},[Y,C,g,y,p,O]),G=u.useMemo(()=>g!=="all"?[{category:mh(g),templates:ae}]:hy.map(K=>({category:K,templates:ae.filter(I=>I.category===K)})).filter(K=>K.templates.length>0),[g,ae]);u.useEffect(()=>{N(K=>Math.min(K,Math.max(0,ae.length-1)))},[ae.length]),u.useEffect(()=>{_d(dh,y)},[y]),u.useEffect(()=>{_d(fh,C)},[C]),u.useEffect(()=>{q.current?.focus();const K=Q=>{Q.target instanceof Node&&!R.current?.contains(Q.target)&&m()},I=Q=>{Q.key==="Escape"&&(Q.preventDefault(),m())};return document.addEventListener("pointerdown",K),document.addEventListener("keydown",I),()=>{document.removeEventListener("pointerdown",K),document.removeEventListener("keydown",I)}},[m]);const te=K=>{const I=Y.get(K.id);if(!I.available){T(I.reason||"This task is not available for the current targets and permission policy.");return}const Q=[K.id,...y.filter(U=>U!==K.id)].slice(0,10);b(Q),_d(dh,Q),d(K.prompt),m()},P=K=>{j(I=>{const Q=I.includes(K)?I.filter(U=>U!==K):[K,...I];return _d(fh,Q),Q})},ye=K=>{K.key==="ArrowDown"?(K.preventDefault(),N(I=>Math.min(I+1,Math.max(0,ae.length-1)))):K.key==="ArrowUp"?(K.preventDefault(),N(I=>Math.max(I-1,0))):K.key==="Enter"&&ae[A]&&(K.preventDefault(),te(ae[A]))};let ie=-1;return s.jsxs("section",{className:"agents-suggested-tasks",ref:R,"aria-label":"Suggested tasks",children:[s.jsxs("header",{className:"agents-suggested-header",children:[s.jsxs("div",{children:[s.jsxs("span",{className:"agents-suggested-title",children:[s.jsx(Ls,{size:15})," Suggested tasks"]}),s.jsxs("small",{children:[_," available · ",O.length," total. Choose a task, edit it, then run it."]})]}),s.jsx("button",{className:"agents-suggested-close",type:"button","aria-label":"Close suggested tasks",onClick:m,children:s.jsx(Ha,{size:16})})]}),s.jsxs("label",{className:"agents-suggested-search",children:[s.jsx(a0,{size:15,"aria-hidden":"true"}),s.jsx("input",{ref:q,value:p,onChange:K=>v(K.target.value),onKeyDown:ye,placeholder:"Search tasks...","aria-label":"Search suggested tasks"})]}),s.jsx("div",{className:"agents-suggested-filters","aria-label":"Task categories and availability filters",children:["all","recent","favorites","read-only","auto","approval","full-access","available","unavailable",...hy].map(K=>{const I=K==="recent"?Vy:K==="favorites"?Ah:K==="all"?Ls:K==="available"?Hn:K==="unavailable"?s0:K==="read-only"||K==="auto"||K==="approval"||K==="full-access"?Lt:PN[K];return s.jsxs("button",{className:g===K?"active":"",type:"button",title:mh(K),"aria-label":mh(K),"aria-pressed":g===K,onClick:()=>{w(K),N(0),T("")},children:[s.jsx(I,{size:12})," ",$N(K)]},K)})}),k&&s.jsx("div",{className:"agents-suggested-notice",role:"status",children:k}),s.jsxs("div",{className:"agents-suggested-list",role:"listbox","aria-label":"Suggested tasks",children:[G.map(K=>s.jsxs("div",{className:"agents-suggested-group",children:[s.jsx("strong",{children:K.category}),K.templates.map(I=>{ie+=1;const Q=ie===A,U=C.includes(I.id),W=Y.get(I.id),ue=W.availableDeviceIds.length+W.unsupportedDeviceIds.length||L,be=W.available?`Available on ${W.availableDeviceIds.length} of ${ue} target${ue===1?"":"s"}`:`Unavailable: ${W.reason||"not supported by the current targets"}`;return s.jsxs("div",{className:`agents-suggested-item ${Q?"active":""} ${W.available?"":"unavailable"}`,children:[s.jsxs("button",{className:"agents-suggested-prompt",type:"button",role:"option","aria-selected":Q,"aria-disabled":!W.available,onClick:()=>te(I),children:[s.jsx("span",{children:I.title}),s.jsx("small",{className:"agents-suggested-description",children:I.description}),s.jsxs("span",{className:"agents-suggested-meta",children:[s.jsx("em",{children:I.category}),s.jsx("em",{className:qN(W.state),children:W.label}),s.jsx("em",{className:`risk-${I.risk}`,children:GN(I.risk)}),s.jsx("em",{children:I.supportedPlatforms.map(VN).join(" · ")}),s.jsx("em",{className:W.available?"availability-ok":"availability-unavailable",children:be}),W.available&&W.unsupportedDeviceIds.length>0&&s.jsxs("em",{className:"availability-warning",children:["Unsupported on ",W.unsupportedDeviceIds.length]})]})]}),s.jsx("button",{className:`agents-suggested-favorite ${U?"favorite":""}`,type:"button","aria-label":U?`Remove ${I.title} from favorites`:`Add ${I.title} to favorites`,"aria-pressed":U,onClick:()=>P(I.id),children:s.jsx(Ah,{size:14,fill:U?"currentColor":"none"})})]},I.id)})]},K.category)),ae.length===0&&s.jsx("p",{className:"agents-suggested-empty",children:"No tasks match this search or current filter."})]})]})}function YN({devices:n,mode:a,selectedIds:r,onModeChange:l,onToggle:c,permissionMode:d,onPermissionModeChange:m}){const p=n.filter(lf),v=r.filter(g=>p.some(w=>w.deviceId===g)).length;return s.jsxs("section",{className:"agents-target-picker","aria-label":"Agent targets",children:[s.jsxs("div",{className:"agents-target-toolbar",children:[s.jsx("span",{className:"agents-section-label",children:"Targets"}),s.jsxs("div",{className:"agents-target-modes",children:[s.jsxs("button",{className:a==="all"?"active":"",onClick:()=>l("all"),type:"button",children:[s.jsx(Qc,{size:14})," All connected ",s.jsx("small",{children:p.length})]}),s.jsxs("button",{className:a==="selected"?"active":"",onClick:()=>l("selected"),type:"button",children:[s.jsx(ri,{size:14})," Selected ",v]}),s.jsxs("button",{className:a==="auto"?"active":"",onClick:()=>l("auto"),type:"button",children:[s.jsx(Ls,{size:14})," Auto"]}),s.jsxs("button",{type:"button",disabled:!0,title:"Saved workstation groups are coming next.",children:[s.jsx(Qc,{size:14})," Group ",s.jsx("small",{children:"Soon"})]})]}),s.jsxs("label",{className:`agents-permission-picker permission-${d}`,children:[s.jsx(uf,{size:14}),s.jsx("span",{children:"Permission"}),s.jsxs("select",{value:d,onChange:g=>m(g.target.value),"aria-label":"Agent permission mode",children:[s.jsx("option",{value:"ask",children:"Ask"}),s.jsx("option",{value:"safe-auto",children:"Safe Auto"}),s.jsx("option",{value:"full-access",children:"Full Access"}),s.jsx("option",{value:"custom",children:"Custom"})]}),s.jsx(Zy,{size:13,"aria-hidden":"true"})]})]}),s.jsx("div",{className:"agents-target-list",children:n.length===0?s.jsx("span",{className:"agents-target-empty",children:"No workstations discovered."}):n.map(g=>{const w=lf(g),y=a==="all"||a==="auto"?w:r.includes(g.deviceId);return s.jsxs("label",{className:`agents-target-option ${y?"selected":""} ${w?"":"offline"}`,children:[s.jsx("input",{type:"checkbox",checked:y,disabled:!w||a!=="selected",onChange:()=>c(g.deviceId)}),s.jsx("span",{className:"agents-target-icon",children:s.jsx(Yt,{size:15})}),s.jsxs("span",{children:[s.jsx("strong",{children:rf(g)}),s.jsx("small",{children:w?"Ready":g.connected?"Agent reconnecting":"Offline"})]}),y&&s.jsx(ri,{className:"agents-target-check",size:15,"aria-hidden":"true"})]},g.deviceId)})})]})}async function KN(n,a){return Ge("/api/settings/agent/plan",{method:"POST",body:JSON.stringify({instruction:a})},n)}async function QN(n,a){return Ge("/api/settings/agent/run",{method:"POST",body:JSON.stringify(a)},n)}async function XN(n,a){return Ge(`/api/settings/agent/runs/${encodeURIComponent(a)}`,void 0,n)}async function ZN(n,a){return Ge(`/api/settings/agent/runs/${encodeURIComponent(a)}/cancel`,{method:"POST",body:JSON.stringify({})},n)}async function JN(n){return Ge("/api/settings/agent/runs/cancel-all",{method:"POST",body:JSON.stringify({})},n)}async function eM(n,a,r,l){return Ge(`/api/settings/agent/runs/${encodeURIComponent(a)}/approvals/${encodeURIComponent(r)}/approve`,{method:"POST",body:JSON.stringify({scope:l})},n)}async function tM(n,a,r,l="User rejected this action."){return Ge(`/api/settings/agent/runs/${encodeURIComponent(a)}/approvals/${encodeURIComponent(r)}/reject`,{method:"POST",body:JSON.stringify({reason:l})},n)}async function nM(n,a,r){return Ge(`/api/settings/agent/policies/${encodeURIComponent(a)}`,{method:"PUT",body:JSON.stringify({categories:r})},n)}async function aM(n,a){return Ge("/api/settings/agent/summary",{method:"POST",body:JSON.stringify(a)},n)}async function sM(n,a){return Ge("/api/remote/tasks",{method:"POST",body:JSON.stringify({instruction:a.instruction,deviceIds:a.deviceIds,operation:a.operation,targetQuery:a.targetQuery,approvalLevel:"read-only"})},n)}async function iM(n,a){return Ge(`/api/remote/tasks/${encodeURIComponent(a)}`,void 0,n)}async function rM(n,a){return Ge(`/api/remote/tasks/${encodeURIComponent(a)}/cancel`,{method:"POST",body:JSON.stringify({})},n)}async function lM(n,a){return Ge(`/api/remote/tasks/${encodeURIComponent(a)}/retry`,{method:"POST",body:JSON.stringify({failedOnly:!0})},n)}function Tl(n){return`${n}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function zd(n,a){const r=new Map(a.map(l=>[l.deviceId,rf(l)]));return n.results.map(l=>({deviceId:l.deviceId,deviceName:l.deviceName||r.get(l.deviceId)||l.deviceId,status:wN(l.status),stage:l.stage||(l.status==="running"?"Checking processes":void 0),result:l.result,data:l.data,error:l.error,sequence:Number.isSafeInteger(l.sequence)?l.sequence:0}))}function oM(n,a){const r=new Map(a.map(l=>[l.deviceId,l]));return n.map(l=>{const c=r.get(l.deviceId);return!c||c.sequence<=l.sequence?l:c})}function cM(n,a){const r=a.filter(d=>d.status==="completed"),l=a.filter(d=>d.status==="failed");if(n.operation==="process.list"){const m=`${r.filter(p=>{const v=p.result||"";return!/not running|no process/i.test(v)&&/running|online|found/i.test(v)}).length}대에서 요청한 프로세스가 실행 중입니다.`;return l.length>0?`${m}
15
- ${l.map(p=>`${p.deviceName}는 ${p.error||"응답하지 않았습니다."}`).join(`
16
- `)}`:m}return l.length>0?`${r.length}대 완료, ${l.length}대 실패했습니다.`:`${r.length}대 작업이 완료되었습니다.`}const uM={read:"allow",processControl:"ask",serviceControl:"ask",applicationControl:"ask",fileRead:"ask",fileWrite:"ask",fileDelete:"ask",shell:"ask",script:"ask",softwareInstall:"ask",network:"ask",systemPower:"ask",systemConfiguration:"ask",userAccount:"deny"};function dM(n){return n==="safe-auto"?"Safe Auto":n==="full-access"?"Full Access":n==="custom"?"Custom":"Ask"}function fM(n){return n.replace(/([A-Z])/g," $1").replace(/^./,a=>a.toUpperCase())}function mM(n){const a=n instanceof Error?n.message:String(n);return/agent-ai-disabled/i.test(a)?"Enable AI Agent in Settings before running commands.":/agent-no-target-devices|agent-target-not-connected|device-not-connected/i.test(a)?"The selected workstation is reconnecting. Wait until its Agent status is Ready and try again.":/codex-auth-required/i.test(a)?"Codex sign-in is required on the Hub. Open Settings > Agent and test the Codex connection.":a}function vy({hubUrl:n,devices:a,launchRequest:r,variant:l="page",selectedDeviceIds:c=[]}){const d=l==="dock",[m,p]=u.useState(d?c.length>0?"selected":"auto":"all"),[v,g]=u.useState(c),[w,y]=u.useState("auto"),[b,C]=u.useState(""),[j,A]=u.useState([]),[N,k]=u.useState(""),[T,R]=u.useState(""),[q,O]=u.useState(""),[Y,_]=u.useState("safe-auto"),[L]=u.useState("custom-default"),[ae,G]=u.useState(uM),[te,P]=u.useState([]),[ye,ie]=u.useState(""),[K,I]=u.useState(!1),[Q,U]=u.useState(null),[W,ue]=u.useState(!1),[be,X]=u.useState(""),[$,de]=u.useState(!1),[me,ve]=u.useState(null),Se=u.useRef(null),Oe=u.useRef(new Set),le=u.useRef(new Set),Z=u.useRef(new Set),He=u.useMemo(()=>a.filter(lf).map(J=>J.deviceId),[a]),_e=u.useMemo(()=>FN(aw,a,m,v,Y,ae),[ae,a,Y,v,m]);u.useEffect(()=>{d&&g(c)},[d,c]),u.useEffect(()=>{r?.deviceId&&(p("selected"),g([r.deviceId]),C(r.instruction),de(!1),window.requestAnimationFrame(()=>{Se.current?.focus(),Se.current?.setSelectionRange(r.instruction.length,r.instruction.length)}))},[r]);const se=u.useCallback(J=>{const Re=zd(J,a);if(A(ze=>ze.map(je=>je.type==="task"&&je.batchId===J.batchId?{...je,states:oM(je.states,Re),status:J.status}:je)),!["running","queued"].includes(J.status)&&!Oe.current.has(J.batchId)){Oe.current.add(J.batchId);const ze=Tl("agent-summary");A(je=>[...je,{type:"agent",id:ze,text:cM(J,Re)}]),J.operation&&aM(n,{instruction:J.instructionPreview,operation:J.operation,total:Re.length,completed:Re.filter(je=>je.status==="completed").length,failed:Re.filter(je=>je.status==="failed").length,results:Re.map(je=>({deviceName:je.deviceName,status:je.status,result:je.result,error:je.error}))}).then(je=>{!je.ok||!je.summary||A(Xe=>Xe.map(gt=>gt.type==="agent"&&gt.id===ze?{...gt,text:je.summary}:gt))}).catch(()=>{}),k(je=>je===J.batchId?"":je)}},[a,n]),fe=u.useCallback(async J=>{const Re=await iM(n,J);return se(Re),Re},[n,se]),Ne=u.useCallback((J,Re)=>{Z.current.has(J.batchId)||(Z.current.add(J.batchId),A(ze=>[...ze,{type:"task",id:Tl("task"),batchId:J.batchId,agentRunId:Re,operation:J.operation||"diagnostics.collect",instruction:J.instructionPreview,states:zd(J,a),status:J.status}])),se(J)},[a,se]),Te=u.useCallback(async J=>{const Re=await XN(n,J);for(const je of Re.taskBatches||[])Ne(je,J);P(Re.approvals||[]);const ze=["running","queued","waiting-approval"].includes(Re.status);if(ve(ze?{runId:J,stage:Re.stage||Re.status,message:Re.progressMessage||(Re.status==="waiting-approval"?"Review the requested action to continue.":"Codex is preparing the answer.")}:je=>je?.runId===J?null:je),!ze&&!le.current.has(J)){le.current.add(J);const je=[Re.error,Re.errorMessage].filter(Boolean).join(" — "),Xe=Re.finalResponse?.trim()||(Re.status==="cancelled"?"Codex 작업을 취소했습니다.":je?`Codex 작업이 완료되지 않았습니다: ${je}`:"Codex 작업이 완료되었습니다.");A(gt=>[...gt,{type:Re.status==="failed"?"error":"agent",id:Tl("agent-run-result"),text:Xe}])}return Re},[Ne,n]);u.useEffect(()=>{if(!N)return;let J=!0;const Re=async()=>{try{const je=await fe(N);J&&!["running","queued"].includes(je.status)&&k("")}catch(je){J&&X(je instanceof Error?je.message:String(je))}};Re();const ze=window.setInterval(()=>{Re()},800);return()=>{J=!1,window.clearInterval(ze)}},[N,fe]),u.useEffect(()=>{if(!T)return;let J=!0;const Re=async()=>{try{const je=await Te(T);J&&!["running","queued","waiting-approval"].includes(je.status)&&(R(""),ue(!1))}catch(je){J&&X(je instanceof Error?je.message:String(je))}};Re();const ze=window.setInterval(()=>{Re()},800);return()=>{J=!1,window.clearInterval(ze)}},[T,Te]);const Be=async(J="",Re,ze=!1)=>{const je=(J||b).trim();if(!je||N||T)return;let Xe=null;const gt=Re||(m==="all"||m==="auto"?He:v.filter(tt=>He.includes(tt)));if(gt.length===0){X("Select at least one connected workstation.");return}if(Y==="full-access"&&!W&&!ze){U({instruction:je,targetIds:gt});return}if(A(tt=>[...tt,{type:"user",id:Tl("user"),text:je}]),C(""),de(!1),X(""),gt.length===0){A(tt=>[...tt,{type:"error",id:Tl("no-targets"),text:"연결된 대상 장비를 하나 이상 선택해 주세요."}]);return}const ua=w==="ask"?`Read-only request. Inspect and answer without changing workstation state.
17
-
18
- ${je}`:w==="plan"?`Plan only. Produce a safe execution plan, but do not change workstation state.
19
-
20
- ${je}`:w==="execute"?`Execute this request within the configured LiveDesk approval policy.
21
-
22
- ${je}`:je,Un=m==="auto"?`Auto target selection is enabled. Inspect the allowed workstations and use only the most suitable target or targets for this request.
23
-
24
- ${ua}`:ua;if(!Xe){try{if(Y==="custom"){const $t=await nM(n,L,ae);if(!$t.ok)throw new Error($t.error||"Custom Agent policy could not be saved.")}const tt=await QN(n,{instruction:Un,deviceIds:gt,permissionMode:Y,customPolicyId:L});if(!tt.ok||!tt.runId)throw new Error(tt.error||"Codex Agent run could not be started.");P(tt.approvals||[]),ve({runId:tt.runId,stage:tt.stage||tt.status||"queued",message:tt.progressMessage||"Codex request queued on the Hub."}),R(tt.runId);return}catch(tt){try{const $t=await KN(n,Un);$t.ok&&$t.plan&&(Xe={operation:$t.plan.operation,query:$t.plan.targetQuery})}catch{A($t=>[...$t,{type:"error",id:Tl("unsupported"),text:mM(tt)}])}}if(!Xe)return}try{const tt=await sM(n,{instruction:Un,deviceIds:gt,operation:Xe.operation,targetQuery:Xe.query});if(!tt.ok||!tt.batch||!tt.batchId)throw new Error(tt.error||"작업을 만들지 못했습니다.");const $t={type:"task",id:Tl("task"),batchId:tt.batchId,operation:Xe.operation,instruction:je,states:zd(tt.batch,a),status:tt.batch.status};Z.current.add(tt.batchId),A(an=>[...an,$t]),k(tt.batchId)}catch(tt){X(tt instanceof Error?tt.message:String(tt))}},$e=async(J,Re)=>{ie(J.approvalId);try{const ze=await eM(n,J.runId,J.approvalId,Re);if(!ze.ok)throw new Error(ze.error||"Agent approval could not be applied.");await Te(J.runId)}catch(ze){X(ze instanceof Error?ze.message:String(ze))}finally{ie("")}},et=async J=>{ie(J.approvalId);try{const Re=await tM(n,J.runId,J.approvalId);if(!Re.ok)throw new Error(Re.error||"Agent approval could not be rejected.");await Te(J.runId)}catch(Re){X(Re instanceof Error?Re.message:String(Re))}finally{ie("")}},Mt=async(J,Re)=>{O(J);try{if(Re){const je=await ZN(n,Re);for(const Xe of je.taskBatches||[])se(Xe);R(Xe=>Xe===Re?"":Xe),ve(Xe=>Xe?.runId===Re?null:Xe);return}const ze=await rM(n,J);se(ze),k(je=>je===J?"":je)}catch(ze){X(ze instanceof Error?ze.message:String(ze))}finally{O("")}},ke=async()=>{if(!(K||!N&&!T)){I(!0);try{const J=await JN(n);if(!J.ok)throw new Error(J.error||"모든 Agent 작업을 취소하지 못했습니다.");k(""),R(""),ve(null),P([]),A(Re=>Re.map(ze=>ze.type==="task"&&["queued","running"].includes(ze.status)?{...ze,status:"cancelled",states:ze.states.map(je=>["queued","running"].includes(je.status)?{...je,status:"cancelled",stage:"Cancelled",error:"Cancelled by user."}:je)}:ze))}catch(J){X(J instanceof Error?J.message:String(J))}finally{I(!1)}}},Ye=async J=>{O(J);try{const Re=await lM(n,J);if(!Re.ok||!Re.batch||!Re.batchId)throw new Error(Re.error||"재시도하지 못했습니다.");Oe.current.delete(Re.batchId),A(ze=>ze.map(je=>je.type==="task"&&je.batchId===J?{...je,batchId:Re.batchId,states:zd(Re.batch,a),status:Re.batch.status}:je)),k(Re.batchId)}catch(Re){X(Re instanceof Error?Re.message:String(Re))}finally{O("")}},rt=J=>{C(J),de(!1),window.requestAnimationFrame(()=>Se.current?.focus())},vt=u.useMemo(()=>a.filter(lf),[a]),vn=u.useMemo(()=>vt.filter(J=>v.includes(J.deviceId)),[vt,v]),It=m==="auto"?`Auto · ${vt.length} available`:m==="all"?`All ${vt.length} computers`:vn.length===1?rf(vn[0]):`${vn.length} selected`,Zt=m==="auto"?"LiveDesk chooses the best computer for each task.":m==="all"?"The Agent may coordinate every connected computer.":vn.length>0?vn.map(rf).join(" · "):"Select one or more computers on the Wall.",ht=m==="selected"&&vn.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"],$n=m==="selected"?vn.length>0?"What should this computer do?":"Choose a computer or use Auto.":m==="all"?"Use all your computers together.":"What should LiveDesk handle?",Gt=m==="auto"?"LiveDesk can inspect the available computers and choose the best target.":"Describe the outcome. LiveDesk will plan, request approval when needed, and show progress per computer.";return s.jsxs("section",{className:`agents-page ${d?"agents-dock-console":""}`,children:[d&&s.jsxs("header",{className:"agent-console-header",children:[s.jsxs("div",{className:"agent-console-title",children:[s.jsx("span",{className:"agent-console-mark",children:s.jsx(Ls,{size:16})}),s.jsxs("div",{children:[s.jsx("small",{children:"Live agent"}),s.jsx("strong",{children:"Agent Console"})]}),s.jsx("i",{children:"Ready"})]}),s.jsxs("section",{className:"agent-console-target","aria-label":"Agent target scope",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Target"}),s.jsx("strong",{children:It}),s.jsx("small",{children:Zt})]}),s.jsxs("div",{className:"agent-console-target-modes",children:[s.jsxs("button",{className:m==="selected"?"active":"",onClick:()=>p("selected"),type:"button",children:[s.jsx(ri,{size:12})," Selected"]}),s.jsxs("button",{className:m==="all"?"active":"",onClick:()=>p("all"),type:"button",children:[s.jsx(Qc,{size:12})," All"]}),s.jsxs("button",{type:"button",disabled:!0,title:"Saved workstation groups are coming next.",children:[s.jsx(Qc,{size:12})," Group"]}),s.jsxs("button",{className:m==="auto"?"active":"",onClick:()=>p("auto"),type:"button",children:[s.jsx(Ls,{size:12})," Auto"]})]})]}),s.jsx("div",{className:"agent-console-interaction-modes","aria-label":"Agent interaction mode",children:["auto","ask","plan","execute"].map(J=>s.jsxs("button",{className:w===J?"active":"",onClick:()=>y(J),type:"button",children:[J==="auto"?s.jsx(Ls,{size:12}):J==="execute"?s.jsx(Yt,{size:12}):null,J[0].toUpperCase()+J.slice(1)]},J))})]}),s.jsxs("div",{className:"agents-workspace",children:[(N||T)&&s.jsxs("div",{className:"agents-page-status",children:[s.jsxs("span",{children:[He.length," workstations · ",dM(Y)]}),s.jsx("button",{type:"button",className:"agents-stop-all",onClick:()=>{ke()},disabled:K,children:K?"Stopping…":"Stop all"})]}),Q&&s.jsx("div",{className:"agents-permission-modal-backdrop",role:"presentation",children:s.jsxs("section",{className:"agents-permission-modal",role:"dialog","aria-modal":"true","aria-labelledby":"full-access-title",children:[s.jsx("span",{className:"agents-permission-modal-icon",children:s.jsx(uf,{size:20})}),s.jsx("h3",{id:"full-access-title",children:"Confirm Full Access"}),s.jsx("p",{children:"Codex may change files, run commands, manage applications, and modify system state on the selected workstations. This run is still limited to the selected devices, the fixed policy, and the tool budget."}),s.jsxs("div",{className:"agents-permission-modal-actions",children:[s.jsx("button",{type:"button",onClick:()=>U(null),children:"Cancel"}),s.jsx("button",{type:"button",className:"danger",onClick:()=>{const J=Q;U(null),ue(!0),Be(J.instruction,J.targetIds,!0)},children:"Run with Full Access"})]})]})}),be&&s.jsx("div",{className:"agents-error",role:"alert",children:be}),s.jsx(RN,{items:j,onCancel:Mt,onRetry:Ye,busyBatchId:q,approvals:te,onApprove:$e,onReject:et,busyApprovalId:ye,progress:me,emptyTitle:d?$n:void 0,emptyBody:d?Gt:void 0}),d&&j.length===0&&!me&&s.jsx("div",{className:"agent-console-suggestions","aria-label":"Suggested Agent commands",children:ht.map(J=>s.jsx("button",{type:"button",onClick:()=>rt(J),children:J},J))}),s.jsxs("div",{className:"agents-composer-shell",children:[$&&s.jsx(WN,{devices:a,targetMode:m,selectedIds:v,permissionMode:Y,customCategories:ae,onSelectPrompt:rt,onClose:()=>de(!1)}),s.jsx(yN,{ref:Se,value:b,onChange:C,onSubmit:()=>{Be()},onOpenSuggestedTasks:()=>de(J=>!J),suggestedOpen:$,suggestedTaskCount:_e,disabled:!!N||!!T,placeholder:d?"Tell LiveDesk what outcome you want...":void 0,compact:d})]})]}),!d&&s.jsxs("aside",{className:"agents-target-sidebar","aria-label":"Agent targets and permissions",children:[s.jsx(YN,{devices:a,mode:m,selectedIds:v,onModeChange:p,onToggle:J=>g(Re=>Re.includes(J)?Re.filter(ze=>ze!==J):[...Re,J]),permissionMode:Y,onPermissionModeChange:J=>{_(J),J!=="full-access"&&ue(!1)}}),Y==="custom"&&s.jsxs("section",{className:"agents-custom-policy","aria-label":"Custom Agent permissions",children:[s.jsxs("div",{className:"agents-custom-policy-head",children:[s.jsxs("div",{children:[s.jsx("span",{className:"agents-section-label",children:"Custom policy"}),s.jsx("strong",{children:"Choose what Codex may do automatically."})]}),s.jsx("span",{children:"Denied actions never reach a device."})]}),s.jsx("div",{className:"agents-custom-policy-grid",children:bN.map(J=>s.jsxs("label",{children:[s.jsx("span",{children:fM(J)}),s.jsxs("select",{value:ae[J],onChange:Re=>G(ze=>({...ze,[J]:Re.target.value})),children:[s.jsx("option",{value:"allow",children:"Allow automatically"}),s.jsx("option",{value:"ask",children:"Ask every time"}),s.jsx("option",{value:"deny",children:"Deny"})]})]},J))})]})]})]})}function iw(n){return{type:n.type,deviceIds:n.deviceIds,monitorIndex:n.monitorIndex,label:n.label}}async function rw(n){try{return(await n.json()).error||`${n.status} ${n.statusText}`}catch{return`${n.status} ${n.statusText}`}}async function lw(n,a,r){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(`${Wr(r)}/api/captures?metadata=${l}`,{method:"POST",headers:{"Content-Type":n.type||"application/octet-stream"},body:n,cache:"no-store"});if(!c.ok)throw new Error(await rw(c));return await c.json()}async function hM(n,a){return await Ge("/api/capture-sessions",{method:"POST",body:JSON.stringify({...n,target:iw(n.target)})},a)}async function pM(n,a,r,l){const c=await fetch(`${Wr(l)}/api/capture-sessions/${encodeURIComponent(n)}/chunks/${a}`,{method:"PUT",headers:{"Content-Type":r.type||"application/octet-stream"},body:r,cache:"no-store"});if(!c.ok)throw new Error(await rw(c));return await c.json()}async function gM(n,a,r){return await Ge(`/api/capture-sessions/${encodeURIComponent(n)}/finalize`,{method:"POST",body:JSON.stringify({durationMs:a})},r)}async function xy(n,a){await Ge(`/api/capture-sessions/${encodeURIComponent(n)}`,{method:"DELETE"},a)}async function vM(n){return await Ge("/api/captures",void 0,n)}function yy(n,a){return`${Wr(a)}/api/captures/${encodeURIComponent(n)}/content`}async function xM(n,a){return await Ge(`/api/captures/${encodeURIComponent(n)}`,{method:"DELETE"},a)}function yM({hubUrl:n,onToast:a}){const[r,l]=u.useState([]),[c,d]=u.useState(!0),m=u.useCallback(async()=>{d(!0);try{l((await vM(n)).captures||[])}catch(v){a(v instanceof Error?v.message:String(v))}finally{d(!1)}},[n,a]);u.useEffect(()=>{m()},[m]);const p=async v=>{const g=yy(v.id,n);if(navigator.share)try{await navigator.share({title:v.fileName,url:g});return}catch{}window.open(g,"_blank","noopener,noreferrer")};return s.jsxs("section",{className:"capture-gallery",children:[s.jsxs("header",{children:[s.jsxs("div",{children:[s.jsx("span",{className:"settings-eyebrow",children:"Capture Gallery"}),s.jsx("h2",{children:"Saved captures"})]}),s.jsxs("button",{className:"text-button",onClick:()=>{m()},type:"button",children:[s.jsx(Ho,{size:15})," Refresh"]})]}),c?s.jsx("p",{className:"settings-help",children:"Loading captures..."}):r.length===0?s.jsx("p",{className:"settings-help",children:"No captures saved yet."}):s.jsx("div",{className:"capture-gallery-grid",children:r.map(v=>{const g=yy(v.id,n);return s.jsxs("article",{className:"capture-gallery-card",children:[v.mimeType.startsWith("image/")?s.jsx("img",{src:g,alt:v.target.label}):s.jsx("video",{src:g,controls:!0,preload:"metadata"}),s.jsxs("div",{className:"capture-gallery-card-body",children:[s.jsx("strong",{children:v.fileName}),s.jsxs("small",{children:[v.target.label," · ",new Date(v.createdAt).toLocaleString()," · ",Math.ceil(v.sizeBytes/1024)," KB"]}),s.jsxs("div",{children:[s.jsx("button",{className:"icon-button",title:"Open","aria-label":"Open",onClick:()=>window.open(g,"_blank","noopener,noreferrer"),type:"button",children:s.jsx(o0,{size:15})}),s.jsx("a",{className:"icon-button",title:"Download","aria-label":"Download",href:`${g}?download=1`,download:v.fileName,children:s.jsx(Qh,{size:15})}),s.jsx("button",{className:"icon-button",title:"Share","aria-label":"Share",onClick:()=>{p(v)},type:"button",children:s.jsx(c0,{size:15})}),s.jsx("button",{className:"icon-button danger",title:"Delete","aria-label":"Delete",onClick:()=>{window.confirm(`Delete ${v.fileName}?`)&&xM(v.id,n).then(()=>m()).catch(w=>a(w instanceof Error?w.message:String(w)))},type:"button",children:s.jsx(Xh,{size:15})})]})]})]},v.id)})})]})}function Id(n){if(!n)return"";const a=Math.max(0,Math.floor((Date.now()-n)/1e3)),r=Math.floor(a/3600),l=Math.floor(a%3600/60),c=a%60;return r>0?`${String(r).padStart(2,"0")}:${String(l).padStart(2,"0")}:${String(c).padStart(2,"0")}`:`${String(l).padStart(2,"0")}:${String(c).padStart(2,"0")}`}function by({controller:n,compact:a=!1,onFirstRollingUse:r,onError:l}){const{state:c,settings:d,videoSupported:m}=n,p=async y=>{try{await y()}catch(b){l?.(b instanceof Error?b.message:String(b))}},v=async()=>{if(d.rollingEnabled){n.setRollingEnabled(!1);return}(r?await r():window.confirm(`Keep the most recent 30 seconds in memory temporarily?
25
- Nothing is saved until you press Save Last 30s.`))&&n.setRollingEnabled(!0)},g=c.recording?`Stop recording · ${Id(c.recordingStartedAt)}`:`Start recording · ${c.targetLabel}`,w=c.timelapse?`Stop timelapse · ${Id(c.timelapseStartedAt)}`:`Start timelapse · ${d.timelapseIntervalSeconds}s interval`;return s.jsxs("div",{className:`capture-toolbar ${a?"compact":""} ${c.recording?"recording-active":""}`,"aria-label":"Capture actions",children:[s.jsx("button",{className:"capture-action","aria-label":`Take screenshot · ${c.targetLabel}`,title:`Take screenshot · ${c.targetLabel}`,disabled:c.busy,onClick:()=>{p(n.takeScreenshot)},type:"button",children:s.jsx(u0,{size:17})}),s.jsx("button",{className:`capture-action ${c.recording?"active":""}`,"aria-label":g,title:g,disabled:!m||c.busy||c.timelapse,onClick:()=>{p(c.recording?n.stopRecording:n.startRecording)},type:"button",children:c.recording?s.jsxs(s.Fragment,{children:[s.jsx(ix,{size:14,fill:"currentColor"}),s.jsx("span",{children:Id(c.recordingStartedAt)})]}):s.jsx(Xy,{size:18})}),s.jsxs("button",{className:"capture-action","aria-label":c.bufferEnabled?`Save last 30 seconds · ${c.bufferSeconds}s ready`:"Enable Last 30s memory buffer",title:c.bufferEnabled?`Save last 30 seconds · ${c.bufferSeconds}s ready`:"Enable Last 30s memory buffer",disabled:!m||c.recording||c.timelapse||c.busy||c.bufferEnabled&&c.bufferSeconds<1,onClick:()=>c.bufferEnabled?void p(n.saveLast30Seconds):void v(),type:"button",children:[s.jsx(d0,{size:17}),s.jsx("small",{children:"30s"})]}),s.jsx("button",{className:`capture-action ${c.timelapse?"timelapse-active":""}`,"aria-label":w,title:w,disabled:!m||c.busy||c.recording,onClick:()=>{p(c.timelapse?n.stopTimelapse:n.startTimelapse)},type:"button",children:c.timelapse?s.jsxs(s.Fragment,{children:[s.jsx(ix,{size:14,fill:"currentColor"}),s.jsx("span",{children:Id(c.timelapseStartedAt)})]}):s.jsx(f0,{size:17})})]})}async function bM(n,a={}){const r=n.filter(y=>y.canvas&&y.canvas.width>0&&y.canvas.height>0),l=Math.max(320,a.maxWidth||1920),c=Math.max(180,a.maxHeight||1080),d=r.length<=1?1:r.length<=4?2:r.length<=9?3:4,m=Math.max(1,Math.ceil(Math.max(1,r.length)/d)),p=Math.floor(l/d),v=Math.floor(c/m),g=document.createElement("canvas");g.width=Math.max(320,p*d),g.height=Math.max(180,v*m);const w=g.getContext("2d",{alpha:!1});if(!w)return g;w.fillStyle="#0b1220",w.fillRect(0,0,g.width,g.height),w.font="600 14px system-ui, sans-serif",w.textBaseline="bottom";for(let y=0;y<r.length;y+=1){const b=r[y],C=y%d,j=Math.floor(y/d),A=C*p,N=j*v,k=b.canvas,T=Math.min(p/k.width,v/k.height),R=Math.max(1,Math.floor(k.width*T)),q=Math.max(1,Math.floor(k.height*T)),O=A+Math.floor((p-R)/2),Y=N+Math.floor((v-q)/2);w.drawImage(k,O,Y,R,q),a.includeLabels!==!1&&(w.fillStyle="rgba(4, 10, 20, .74)",w.fillRect(A,N+v-28,p,28),w.fillStyle="#f8fafc",w.fillText(b.label,A+9,N+v-9))}return g}function wM(n){return n?.signature||"none"}function SM(n){return n?.label||"No capture target"}function wy(n){return{...n,deviceIds:[...n.deviceIds],sourceCanvas:n.sourceCanvas||null}}function CM(){const n=new Date,a=r=>String(r).padStart(2,"0");return`${n.getFullYear()}${a(n.getMonth()+1)}${a(n.getDate())}_${a(n.getHours())}${a(n.getMinutes())}${a(n.getSeconds())}`}function jM(n){return n.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"Wall"}function kM(n){return`LiveDesk_${n.type==="wall"||n.type==="selection"?"Wall":`${jM(n.label)}_Monitor-${Number(n.monitorIndex||0)+1}`}_${CM()}.png`}async function AM(n,a,r){const l=await new Promise((d,m)=>n.toBlob(p=>p?d(p):m(new Error("Screenshot could not be encoded.")),"image/png")),c=await lw(l,{kind:"screenshot",fileName:kM(a),target:a},r);try{await navigator.clipboard.write([new ClipboardItem({"image/png":l})])}catch{}return c.capture}function ow(){return["video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm"].find(a=>typeof MediaRecorder<"u"&&MediaRecorder.isTypeSupported(a))||""}function NM(n,a){const r=new Date().toISOString().replace(/[-:]/g,"").replace(/\.\d{3}Z$/,"").replace("T","_"),l=a.label.replace(/[^a-zA-Z0-9._-]+/g,"-").slice(0,70)||"Wall";return n==="timelapse"?`LiveDesk_Timelapse_${l}_${r}.webm`:`LiveDesk_Recording_${l}_${r}.webm`}async function cw(n){if(typeof MediaRecorder>"u"||typeof n.canvas.captureStream!="function")throw new Error("This browser does not support video recording.");const a=ow();if(!a)throw new Error("This browser does not support WebM recording.");const r=n.kind||"recording",l=await hM({kind:r,fileName:NM(r,n.target),mimeType:a,target:n.target},n.hubUrl),c=n.canvas.captureStream(n.frameRequests?0:n.fps),d=new MediaRecorder(c,{mimeType:a,videoBitsPerSecond:r==="timelapse"?2e6:4e6}),m=performance.now();let p=0,v=!1,g=null,w=Promise.resolve();return d.ondataavailable=y=>{if(!y.data||y.data.size===0)return;const b=p++;w=w.then(()=>pM(l.sessionId,b,y.data,n.hubUrl).then(()=>{})).catch(C=>{g=g||(C instanceof Error?C:new Error(String(C))),n.onError?.(g)})},d.onerror=()=>{g=new Error("Video recording stopped unexpectedly."),n.onError?.(g)},d.start(1e3),{requestFrame:()=>{c.getVideoTracks()[0]?.requestFrame?.()},stop:async()=>{if(!v){if(v=!0,await new Promise(y=>{d.addEventListener("stop",()=>y(),{once:!0}),d.stop()}),c.getTracks().forEach(y=>y.stop()),await w,g)throw await xy(l.sessionId,n.hubUrl).catch(()=>{}),g;await gM(l.sessionId,Math.max(0,performance.now()-m),n.hubUrl)}},cancel:async()=>{v||(v=!0,d.stop(),c.getTracks().forEach(y=>y.stop()),await xy(l.sessionId,n.hubUrl).catch(()=>{}))}}}class MM{recorder=null;stream=null;segments=[];totalBytes=0;targetSignature="";startedAt=0;maxDurationMs=3e4;maxBytes=128*1024*1024;get seconds(){return!this.startedAt||this.segments.length===0?0:Math.min(30,Math.max(0,(performance.now()-this.segments[0].at)/1e3))}get active(){return this.recorder!==null}async start(a,r){if(this.recorder&&this.targetSignature===r.signature)return;if(this.stop(),typeof MediaRecorder>"u"||typeof a.captureStream!="function")throw new Error("This browser does not support Last 30s.");const l=ow();if(!l)throw new Error("This browser does not support WebM recording.");this.targetSignature=r.signature,this.stream=a.captureStream(20),this.recorder=new MediaRecorder(this.stream,{mimeType:l,videoBitsPerSecond:3e6}),this.startedAt=performance.now(),this.recorder.ondataavailable=c=>{if(!c.data.size)return;const d=performance.now();for(this.segments.push({blob:c.data,at:d}),this.totalBytes+=c.data.size;this.segments.length>1&&(d-this.segments[0].at>this.maxDurationMs||this.totalBytes>this.maxBytes);){const m=this.segments.shift();this.totalBytes-=m.blob.size}},this.recorder.start(1e3)}stop(){const a=this.recorder;this.recorder=null,a&&a.state!=="inactive"&&(a.ondataavailable=null,a.stop()),this.stream?.getTracks().forEach(r=>r.stop()),this.stream=null,this.segments=[],this.totalBytes=0,this.startedAt=0}async save(a,r){if(this.segments.length===0)throw new Error("The Last 30s buffer is not ready yet.");const l=new Blob(this.segments.map(m=>m.blob),{type:this.segments[0].blob.type||"video/webm"}),d=`LiveDesk_Last30s_${a.label.replace(/[^a-zA-Z0-9._-]+/g,"-").slice(0,70)||"Wall"}_${new Date().toISOString().replace(/[-:]/g,"").replace(/\.\d{3}Z$/,"").replace("T","_")}.webm`;return await lw(l,{kind:"last-30s",fileName:d,target:a,durationMs:Math.min(3e4,this.segments.length*1e3)},r)}}async function TM(n,a,r,l,c){const d=await cw({canvas:n,target:a,kind:"timelapse",fps:30,frameRequests:!0,hubUrl:l,onError:c});d.requestFrame?.();const m=window.setInterval(()=>d.requestFrame?.(),Math.max(5,r)*1e3);return{stop:async()=>{window.clearInterval(m),await d.stop()},cancel:async()=>{window.clearInterval(m),await d.cancel()}}}const uw="livedesk.captureSettings";function EM(){const n={rollingEnabled:!1,recordingQuality:"standard",timelapseIntervalSeconds:10,includeRemoteCursor:!0};try{const a=JSON.parse(localStorage.getItem(uw)||"null");return{...n,...a&&typeof a=="object"?a:{}}}catch{return n}}function RM(n){const[a,r]=u.useState(EM),[l,c]=u.useState(0),[d,m]=u.useState(0),[p,v]=u.useState(0),[g,w]=u.useState(!1),y=u.useRef(void 0),b=u.useRef(!1),C=u.useRef(""),j=u.useRef(null),A=u.useRef(null),N=u.useRef(null),k=u.useRef(null),T=u.useRef(new MM),R=n.sourceRegistry.resolveCurrentTarget(),q=wM(R),O=SM(R),Y=typeof MediaRecorder<"u"&&typeof HTMLCanvasElement<"u"&&"captureStream"in HTMLCanvasElement.prototype;u.useEffect(()=>{if(localStorage.setItem(uw,JSON.stringify(a)),!b.current)return;const U=JSON.stringify(a);U!==C.current&&(C.current=U,Ge("/api/settings",{method:"PATCH",body:JSON.stringify({revision:y.current,filesAudio:{rollingBufferEnabled:a.rollingEnabled,recordingQuality:a.recordingQuality,timelapseIntervalSeconds:a.timelapseIntervalSeconds,includeRemoteCursor:a.includeRemoteCursor}})},n.hubUrl).then(W=>{y.current=Number(W.revision||y.current||0)}).catch(()=>{}))},[n.hubUrl,a]),u.useEffect(()=>{let U=!0;return Ge("/api/settings",void 0,n.hubUrl).then(W=>{if(!U)return;const ue=W.settings?.filesAudio||{},be=typeof ue.rollingBufferEnabled=="boolean"?ue.rollingBufferEnabled:a.rollingEnabled,X=ue.recordingQuality==="high"?"high":"standard",$=[5,10,30,60].includes(Number(ue.timelapseIntervalSeconds))?Number(ue.timelapseIntervalSeconds):a.timelapseIntervalSeconds,de=typeof ue.includeRemoteCursor=="boolean"?ue.includeRemoteCursor:a.includeRemoteCursor,me={rollingEnabled:be,recordingQuality:X,timelapseIntervalSeconds:$,includeRemoteCursor:de};y.current=Number(W.revision||0),C.current=JSON.stringify(me),b.current=!0,r(me)}).catch(()=>{b.current=!0}),()=>{U=!1}},[n.hubUrl]);const _=u.useCallback(async U=>{if(U.sourceCanvas&&U.sourceCanvas.width>0&&U.sourceCanvas.height>0)return{target:wy(U),canvas:U.sourceCanvas,cleanup:()=>{}};const W=await n.sourceRegistry.composeWall(U.deviceIds,{maxWidth:1920,maxHeight:1080,includeLabels:!0});let ue=!1;const be=window.setInterval(async()=>{if(ue)return;const X=await n.sourceRegistry.composeWall(U.deviceIds,{maxWidth:1920,maxHeight:1080,includeLabels:!0}).catch(()=>null);!X||ue||((W.width!==X.width||W.height!==X.height)&&(W.width=X.width,W.height=X.height),W.getContext("2d")?.drawImage(X,0,0))},100);return{target:wy(U),canvas:W,cleanup:()=>{ue=!0,window.clearInterval(be)}}},[n.sourceRegistry]);u.useEffect(()=>{const U=T.current;if(!a.rollingEnabled||!R||!Y){U.stop(),v(0);return}let W=!1,ue=null;return(async()=>{try{if(ue=await _(R),W)return;await U.start(ue.canvas,ue.target);const X=window.setInterval(()=>v(Math.round(U.seconds)),500),$=()=>{window.clearInterval(X),ue?.cleanup()};U.__cleanup=$}catch(X){W||n.onToast(X instanceof Error?X.message:String(X))}})(),()=>{W=!0,U.stop(),U.__cleanup?.(),U.__cleanup=void 0,v(0)}},[_,n.onToast,a.rollingEnabled,q,Y]);const L=u.useCallback(U=>r(W=>({...W,rollingEnabled:U})),[]),ae=u.useCallback(U=>r(W=>({...W,recordingQuality:U})),[]),G=u.useCallback(U=>r(W=>({...W,timelapseIntervalSeconds:U})),[]),te=u.useCallback(async()=>{const U=n.sourceRegistry.resolveCurrentTarget();if(!U)throw new Error("화면이 준비된 후 다시 시도하세요.");w(!0);let W=null;try{W=await _(U),await AM(W.canvas,W.target,n.hubUrl),n.onToast("Screenshot saved")}finally{W?.cleanup(),w(!1)}},[_,n.hubUrl,n.onToast,n.sourceRegistry]),P=u.useCallback(async()=>{if(N.current)throw new Error("Stop the timelapse before recording.");const U=n.sourceRegistry.resolveCurrentTarget();if(!U)throw new Error("화면이 준비된 후 다시 시도하세요.");const W=await _(U),ue=await cw({canvas:W.canvas,target:W.target,fps:U.type==="control"?30:15,hubUrl:n.hubUrl,onError:be=>n.onToast(be.message)});A.current=W.cleanup,j.current=ue,c(Date.now()),n.onToast("Recording started")},[_,n.hubUrl,n.onToast,n.sourceRegistry]),ye=u.useCallback(async()=>{const U=j.current;if(U){w(!0);try{await U.stop(),n.onToast("Recording saved")}finally{j.current=null,A.current?.(),A.current=null,c(0),w(!1)}}},[n.onToast]),ie=u.useCallback(async()=>{if(j.current||N.current)throw new Error("Last 30s is unavailable during a recording.");const U=n.sourceRegistry.resolveCurrentTarget();if(!U)throw new Error("화면이 준비된 후 다시 시도하세요.");w(!0);try{await T.current.save(U,n.hubUrl),n.onToast("Last 30 seconds saved")}finally{w(!1)}},[n.hubUrl,n.onToast,n.sourceRegistry]),K=u.useCallback(async()=>{if(j.current)throw new Error("Stop the recording before starting a timelapse.");const U=n.sourceRegistry.resolveCurrentTarget();if(!U)throw new Error("화면이 준비된 후 다시 시도하세요.");const W=await _(U),ue=await TM(W.canvas,W.target,a.timelapseIntervalSeconds,n.hubUrl,be=>n.onToast(be.message));k.current=W.cleanup,N.current=ue,m(Date.now()),n.onToast("Timelapse started")},[_,n.hubUrl,n.onToast,n.sourceRegistry,a.timelapseIntervalSeconds]),I=u.useCallback(async()=>{const U=N.current;if(U){w(!0);try{await U.stop(),n.onToast("Timelapse saved")}finally{N.current=null,k.current?.(),k.current=null,m(0),w(!1)}}},[n.onToast]);return u.useEffect(()=>{const U=W=>{!j.current&&!N.current||(W.preventDefault(),W.returnValue="")};return window.addEventListener("beforeunload",U),()=>window.removeEventListener("beforeunload",U)},[]),u.useEffect(()=>()=>{T.current.stop(),j.current?.cancel(),N.current?.cancel(),A.current?.(),k.current?.()},[]),{state:u.useMemo(()=>({recording:!!j.current,recordingStartedAt:l,timelapse:!!N.current,timelapseStartedAt:d,bufferSeconds:p,bufferEnabled:a.rollingEnabled,busy:g,targetLabel:O}),[p,g,l,a.rollingEnabled,O,d]),settings:a,videoSupported:Y,targetKey:q,setRollingEnabled:L,setRecordingQuality:ae,setTimelapseInterval:G,takeScreenshot:te,startRecording:P,stopRecording:ye,saveLast30Seconds:ie,startTimelapse:K,stopTimelapse:I}}const DM=120,LM=999,Hc=5,Bc=30,_M=Number.POSITIVE_INFINITY,dw="livedesk.remoteDirectory",$h="livedesk.localHubAccessEnabled",fw="livedesk.streamSettings",Uh=16,mw="livedesk.controlStreamSettings",qh=6,hw="livedesk.wallMonitorSelections",pw=1,hh=512*1024,Gh="".trim(),gw="".trim(),Sy="livedesk-adsense-script",ph=!!Gh&&!!gw,zM=1e3/60,gh=1500,IM=650,OM=1800,HM=650,BM=2500,Cy=1500,jy=15e3,FM=6e4,ky=240,PM=1024,$M=640,UM=360,Ay="Connected LiveDesk clients are updating in batches. Hub will restart after every target reconnects on the requested versions.",Od="LiveDesk is replacing the Hub and verifying the requested version.",Hd=5*6e4,qM=5e3;function Pr({label:n,tooltip:a,disabled:r=!1,active:l=!1,danger:c=!1,pressed:d,onClick:m,children:p}){return s.jsx("span",{className:`manual-action-tooltip ${r?"disabled":""}`.trim(),"data-tooltip":a,children:s.jsx("button",{className:`manual-action ${l?"active":""} ${c?"danger":""}`.trim(),onClick:m,disabled:r,"aria-label":n,"aria-pressed":d,type:"button",children:p})})}function GM(n,a){if(a.deviceId!==n.deviceId)return!1;const r=Number(a.browserReceivedEpochMs);if(!Number.isFinite(r)||r<n.startedAtEpochMs)return!1;const l=Number(a.monitorIndex);if(Number.isFinite(l)&&Math.floor(l)!==n.monitorIndex)return!1;const c=String(a.frameMode||a.mode||"").trim().toLowerCase();return!c||c===n.frameMode}const El={free:{name:"Free",price:"$0",limit:Hc,audience:"Personal trial",note:"5 devices with a standard ad banner."},ltd:{name:"Plus",price:"$79 LTD",ltd:"$79 LTD",limit:Bc,audience:"Creators and homelabs",note:"30 devices, no ads, personal use."},pro:{name:"Pro",price:"$199 LTD",ltd:"$199 LTD",limit:_M,audience:"Business and studios",note:"Commercial use and larger workstation walls."}},vw={"mode1-jpeg":5,"mode3-h264-hw":30,"mode4-h264-atlas":20};function Ny(n,a){const r=m=>{const v=String(m||"").trim().replace(/^v/i,"").match(/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/);if(!v)return null;const g=v[4]?v[4].split(".").map(w=>/^\d+$/.test(w)?w.length>1&&w.startsWith("0")?Number.NaN:Number(w):w):[];return g.some(w=>typeof w=="number"&&!Number.isFinite(w))?null:{core:[Number(v[1]),Number(v[2]),Number(v[3])],prerelease:g}},l=r(n),c=r(a);if(!l||!c)return!1;for(let m=0;m<3;m+=1){if(l.core[m]>c.core[m])return!0;if(l.core[m]<c.core[m])return!1}if(l.prerelease.length===0||c.prerelease.length===0)return l.prerelease.length===0;const d=Math.max(l.prerelease.length,c.prerelease.length);for(let m=0;m<d;m+=1){const p=l.prerelease[m],v=c.prerelease[m];if(p===void 0||v===void 0)return v===void 0;if(p!==v){if(typeof p=="number"&&typeof v=="number")return p>v;if(typeof p=="number")return!1;if(typeof v=="number"||p>v)return!0;if(p<v)return!1}}return!0}function Rs(n,a){return`${n}:${a}`}const xa={frameMode:"mode3-h264-hw",h264DecodeAcceleration:"prefer-hardware",fps:vw["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},Ia={frameMode:"mode3-h264-hw",h264DecodeAcceleration:"prefer-software",fps:30,maxWidth:1920,maxHeight:1080,quality:75,showScreenStatus:!1};function vh(n,a){if(n.length===0)return 0;const r=[...n].sort((c,d)=>c-d),l=Math.max(0,Math.min(r.length-1,Math.ceil(r.length*a)-1));return r[l]}function xw(n,a){n.push(a),n.length>ky&&n.splice(0,n.length-ky)}function My(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 Ty(n,a,r){if(n.lastAt!==void 0){const l=Math.max(0,a-n.lastAt);n.intervalCount+=1,n.intervalSumMs+=l,n.minIntervalMs=Math.min(n.minIntervalMs,l),n.maxIntervalMs=Math.max(n.maxIntervalMs,l),xw(n.intervalSamplesMs,l)}if(n.lastFrameSeq!==void 0){const l=r-n.lastFrameSeq;l!==1&&(n.seqGapCount+=1,n.maxSeqGap=Math.max(n.maxSeqGap,Math.abs(l)))}n.lastAt=a,n.lastFrameSeq=r}function Ey(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 Ry(n){return!n||n.seqGapCount<=0?"none":`${n.seqGapCount} gaps / max ${n.maxSeqGap}`}function VM(n){return Number.isFinite(n)?String(n):"30+"}const Wd=[{id:"mode4-h264-atlas",label:"Mode 4",detail:"Hub H.264 Atlas"},{id:"mode3-h264-hw",label:"Mode 3",detail:"H.264 hardware"}],Vh=[{id:"prefer-software",label:"Software low latency"},{id:"prefer-hardware",label:"Hardware decode"},{id:"no-preference",label:"Browser auto"}],WM=[{id:"mode3-h264-hw",label:"Mode 3 - H.264 hardware"}],Yd=[{id:"640x360",label:"Compact",width:640,height:360},{id:"960x540",label:"Standard",width:960,height:540},{id:"1280x720",label:"HD",width:1280,height:720},{id:"1920x1080",label:"Full HD",width:1920,height:1080},{id:"2560x1440",label:"QHD",width:2560,height:1440},{id:"3840x2160",label:"4K",width:3840,height:2160}],xh=Yd.filter(n=>n.width>=1280),yh=[{id:"auto",label:"Auto by wall size"},{id:"320x180",label:"Standard 320x180",width:320,height:180},{id:"480x270",label:"Sharp 480x270",width:480,height:270},{id:"640x360",label:"Crisp 640x360",width:640,height:360}],bp=[1,2,5,8,12,20,30],YM=[20,30,60],Dy=[45,60,75,90],Ly={large:{maxWidth:1280,maxHeight:720},medium:{maxWidth:960,maxHeight:540},list:{maxWidth:640,maxHeight:360}},ca={preserveConfiguredFpsDeviceCount:12,visibleRootMargin:"520px 0px 760px 0px",fallbackVisibleCounts:{large:12,medium:18,list:32},maxWallFramesPerSecond:li.maxDirectFramesPerSecond,maxWallBytesPerSecond:80*1024*1024,maxFrameGapMs:280,lowLoadFrameRatio:.58,lowLoadByteRatio:.52,downshiftCooldownMs:1800,recoveryCooldownMs:14e3,minFps:5},_y=2200,KM=8e3,QM=3500,XM=7e3,ZM=2,JM=2600,eT=4200,tT=750,nT=2,zy=4200;function Iy(n,a){return Math.min(3e4,n*2**Math.min(3,Math.max(0,a)))}function Wc(n,a){const r=n.capabilities?.[a];return typeof r=="boolean"?r:/^(1|true|yes|on)$/i.test(String(r||"").trim())}function Ka(n){return n.deviceName||n.hostname||n.deviceId}function aT(){return"npx -y --prefer-online livedesk@latest client"}function sT(){return"npx -y --prefer-online livedesk@latest"}function iT(){try{return localStorage.getItem(dw)||""}catch{return""}}function rT(){try{return localStorage.getItem($h)==="1"}catch{return!1}}function To(n){try{n?localStorage.setItem($h,"1"):localStorage.removeItem($h)}catch{}}function ds(n,a,r,l){const c=Number(n);return Number.isFinite(c)?Math.max(a,Math.min(r,Math.round(c))):l}function Wh(n){const a=String(n||"").trim();return Wd.some(r=>r.id===a)?a:xa.frameMode}function cf(n){const a=String(n||"").trim();return Vh.some(r=>r.id===a)?a:xa.h264DecodeAcceleration}function Yh(n){return n==="mode3-h264-hw"?n:Ia.frameMode}function yw(n){return vw[n]||12}function bw(n){return n==="mode3-h264-hw"?30:n==="mode4-h264-atlas"?20:30}function Kh(n,a){return ds(n,1,bw(a),yw(a))}function Pl(n){return n&&typeof n=="object"&&!Array.isArray(n)?n:{}}function va(n){const a=Pl(n.status),r=Pl(a.screens),l=Pl(n.capabilities),c=[a.monitorCount,a.screenCount,r.count,l.monitorCount,l.screenCount];for(const d of c){const m=Number(d);if(Number.isFinite(m)&&m>0)return Math.max(1,Math.min(64,Math.floor(m)))}return 1}function qr(n){const a=Number(n);return Number.isFinite(a)&&a>0?Math.floor(a):0}function lT(n){const a=Pl(n.status),l=[Pl(a.screens).displays,a.displays,a.monitors];for(const c of l)if(!(!Array.isArray(c)||c.length===0))return c.map(d=>Pl(d));return[]}function ww(n,a){const r=lT(n),l=r.find(v=>Number(v.index)===a)||r[a]||r[0]||{},c=qr(l.width),d=qr(l.height),m=[l.name,l.displayName,l.deviceName,l.id].find(v=>typeof v=="string"&&v.trim()),p=typeof m=="string"?m.trim():`Display ${a+1}`;return{index:a,name:p,width:c,height:d,primary:l.primary===!0||l.isPrimary===!0}}function oT(n){const a=va(n);return Array.from({length:a},(r,l)=>ww(n,l))}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 r=ww(n,a);if(r.width>0&&r.height>0)return{width:r.width,height:r.height};const l=Pl(n.status),c=qr(l.screenWidth||l.width),d=qr(l.screenHeight||l.height);return c>0&&d>0?{width:c,height:d}:null}function Cw(n){if(!n)return null;const a=qr(n.sourceWidth)||qr(n.width),r=qr(n.sourceHeight)||qr(n.height);return a>0&&r>0?{width:a,height:r}:null}function uT(n,a,r){const d=((typeof a?.monitorIndex=="number"?za(a.monitorIndex,Math.max(1,a.monitorCount||1)):r)===r?Cw(a):null)||Sw(n,r);return d?Math.max(.25,Math.min(4,d.width/d.height)):16/9}const Bd=16/9;function za(n,a){const r=Math.max(1,Math.min(64,Math.floor(Number(a)||1))),l=Math.floor(Number(n));return Number.isFinite(l)?Math.max(0,Math.min(r-1,l)):0}function dT(){try{const n=localStorage.getItem(hw);if(!n)return{};const a=JSON.parse(n),r=a&&typeof a=="object"&&!Array.isArray(a)?a.selections:void 0;if(Number(a?.version)!==pw||!r||typeof r!="object"||Array.isArray(r))return{};const l={};for(const[c,d]of Object.entries(r)){const m=c.trim(),p=Math.floor(Number(d));!m||!Number.isFinite(p)||(l[m]=Math.max(0,Math.min(63,p)))}return l}catch{return{}}}function fT(n){try{localStorage.setItem(hw,JSON.stringify({version:pw,selections:n}))}catch{}}function mT(){try{const n=JSON.parse(localStorage.getItem(fw)||"{}"),a=Number(n.version);if(![Uh,15,14,13,12,11].includes(a))return xa;const r=Wh(n.frameMode),l=ds(n.maxWidth,320,3840,xa.maxWidth),c=ds(n.maxHeight,180,2160,xa.maxHeight),d=Number(n.atlasTileWidth),m=Number(n.atlasTileHeight),p=d>=640||m>=360?{width:640,height:360}:d>=480||m>=270?{width:480,height:270}:{width:320,height:180};return{frameMode:r,h264DecodeAcceleration:cf(n.h264DecodeAcceleration),fps:a<Uh&&r==="mode3-h264-hw"?xa.fps:Kh(n.fps,r),maxWidth:l,maxHeight:c,atlasTileWidth:p.width,atlasTileHeight:p.height,atlasTileSizeMode:n.atlasTileSizeMode==="fixed"?"fixed":"auto",quality:ds(n.quality,20,95,xa.quality),autoStartLive:typeof n.autoStartLive=="boolean"?n.autoStartLive:xa.autoStartLive,showScreenStatus:typeof n.showScreenStatus=="boolean"?n.showScreenStatus:xa.showScreenStatus,visibleOnlyLive:typeof n.visibleOnlyLive=="boolean"?n.visibleOnlyLive:xa.visibleOnlyLive,adaptiveLoadShedding:typeof n.adaptiveLoadShedding=="boolean"?n.adaptiveLoadShedding:xa.adaptiveLoadShedding,adaptiveSizeByWall:typeof n.adaptiveSizeByWall=="boolean"?n.adaptiveSizeByWall:xa.adaptiveSizeByWall}}catch{return xa}}function hT(n){try{localStorage.setItem(fw,JSON.stringify({...n,version:Uh}))}catch{}}function pT(){try{const n=JSON.parse(localStorage.getItem(mw)||"{}"),a=Number(n.version);if(![qh,5,4,3,2,1].includes(a))return Ia;const r=ds(n.fps,20,60,Ia.fps),l=a<qh;return{frameMode:l?Ia.frameMode:Yh(n.frameMode),h264DecodeAcceleration:l?Ia.h264DecodeAcceleration:cf(n.h264DecodeAcceleration),fps:l?Ia.fps:r,maxWidth:ds(n.maxWidth,1280,3840,Ia.maxWidth),maxHeight:ds(n.maxHeight,720,2160,Ia.maxHeight),quality:ds(n.quality,20,95,Ia.quality),showScreenStatus:typeof n.showScreenStatus=="boolean"?n.showScreenStatus:Ia.showScreenStatus}}catch{return Ia}}function gT(n){try{localStorage.setItem(mw,JSON.stringify({...n,version:qh}))}catch{}}function bh(n,a){return n.length!==a.length?!1:n.every((r,l)=>r===a[l])}function wh(n){return[...new Set(n.filter(Boolean))].sort()}function vT(n){return ca.fallbackVisibleCounts[n]||ca.fallbackVisibleCounts.large}function xT(n,a,r){if(n.frameMode==="mode4-h264-atlas")return n.atlasTileSizeMode==="auto"?a==="large"?{maxWidth:640,maxHeight:360}:{maxWidth:320,maxHeight:180}:{maxWidth:n.atlasTileWidth,maxHeight:n.atlasTileHeight};if(!n.adaptiveSizeByWall)return{maxWidth:n.maxWidth,maxHeight:n.maxHeight};const l=Ly[a]||Ly.large;return{maxWidth:Math.min(n.maxWidth,l.maxWidth),maxHeight:Math.min(n.maxHeight,l.maxHeight)}}function yT(n,a=ca.minFps){const r=[...bp].sort((c,d)=>c-d),l=Math.max(a,Math.floor(n/2));return[...r].reverse().find(c=>c<n&&c>=a)||l}function bT(n,a){return[...bp].sort((l,c)=>l-c).find(l=>l>n&&l<=a)||a}function Fc(n){if(!Number.isFinite(n)||n<=0)return"0 B";const a=["B","KB","MB","GB","TB"];let r=n,l=0;for(;r>=1024&&l<a.length-1;)r/=1024,l+=1;const c=l===0||r>=100?0:1;return`${r.toFixed(c)} ${a[l]}`}function Oy(n){if(!Number.isFinite(n)||!n||n<=0)return"0GB";const a=1024**4,r=1024**3;return n>=a?`${Math.max(1,Math.round(n/a))}TB`:`${Math.max(1,Math.round(n/r))}GB`}function Sh(n,a){if(!Number.isFinite(n)||!n||n<=0)return"not reported";const r=Math.max(0,n-Math.max(0,Number(a||0)));return`${Oy(r)} / ${Oy(n)}`}function wT(n){const a=new Uint8Array(n),r=32768;let l="";for(let c=0;c<a.length;c+=r){const d=a.subarray(c,c+r);l+=String.fromCharCode(...d)}return btoa(l)}function Hy(n){return Array.from(n).filter(a=>a.size>=0).map(a=>{const r=a.webkitRelativePath||a.name;return{file:a,relativePath:r,fingerprint:`${a.size}:${a.lastModified}`}})}function ST(n){return n===1?"middle":n===2?"right":"left"}function By(n,...a){for(const r of a){const l=n?.[r];if(typeof l=="string"&&l.trim())return l.trim()}return""}function Fy(n){const a=Number(n);return Number.isInteger(a)&&a>=1&&a<=LM?a:0}const CT={cpu:"CPU",memory:"MEM",disk:"Disk",gpu:"GPU",vram:"VRAM",npu:"NPU",temp:"Temp",network:"Net"};function jT(n,a,r){if(n==="online")return"Online";if(n==="busy")return"Busy";if(n==="stale")return"Stale";if(n==="offline")return"Offline";if(r==="failed")return"Task failed";const l=n==="critical"?"critical":"warn",c=a.find(m=>m.state===l)||a.find(m=>m.state==="critical"||m.state==="warn");if(!c)return n==="critical"?"Issue":"Check";const d=CT[c.id]||c.label;return c.value&&c.value!=="-"?`${d} ${c.value}`:d}function yf(n,a){const r=a.split(".");let l=n;for(const c of r){if(l==null)return;if(Array.isArray(l)){const d=Number(c);l=Number.isInteger(d)?l[d]:void 0;continue}if(typeof l=="object"){l=l[c];continue}return}return l}function pn(n,...a){for(const r of a){const l=yf(n,r),c=Number(l);if(Number.isFinite(c))return c}}function Qa(n,...a){for(const r of a){const l=yf(n,r);if(typeof l=="string"&&l.trim())return l.trim();if(typeof l=="number"&&Number.isFinite(l))return String(l)}return""}function kT(n,...a){for(const r of a){const l=yf(n,r);if(typeof l=="boolean")return l;if(/^(1|true|yes|on|online|running|ready)$/i.test(String(l||"").trim()))return!0;if(/^(0|false|no|off|offline|stopped|missing)$/i.test(String(l||"").trim()))return!1}}function Ui(n){const a=Number(n);if(Number.isFinite(a))return Math.max(0,Math.min(1,a>1?a/100:a))}function Ch(n,a){if(!(typeof n!="number"||typeof a!="number"||!Number.isFinite(n)||!Number.isFinite(a)||n<=0))return Ui((n-Math.max(0,a))/n)}function Eo(n){return n===void 0?"-":`${Math.round(n*100)}%`}function jh(n){return n===void 0||!Number.isFinite(n)?"":n>=1e3?`${(n/1e3).toFixed(n>=1e4?0:1)}Gb/s`:`${Math.round(n)}Mb/s`}function Rl(n,a=.92,r=.78){return n===void 0?"unknown":n>=a?"critical":n>=r?"warn":"good"}function AT(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 Fd(n,a,r){const l=yf(n,`tools.${a}`),c=Qa(n,`tools.${a}.status`,`tooling.${a}.status`,`${a}.status`).toLowerCase(),d=kT(n,`tools.${a}.running`,`tooling.${a}.running`,`${a}.running`),m=Qa(n,`tools.${a}.version`,`tooling.${a}.version`,`${a}.version`),p=Qa(n,`tools.${a}.port`,`tooling.${a}.port`,`${a}.port`);let v="unknown";return c==="busy"?v="busy":["online","running","ready","active"].includes(c)||d===!0?v="online":(["offline","stopped","missing","not-found"].includes(c)||d===!1||l===!1)&&(v="offline"),{id:a,label:r,status:v,detail:v==="offline"?"offline":m||(p?`:${p}`:v==="unknown"?"not reported":v)}}function jw(n){const a=n.status||{},r=pn(a,"cpu.cores","cpuCores","processorCount"),l=pn(a,"loadavg.0","cpu.load1"),c=Ui(pn(a,"cpu.usedRatio","cpu.usageRatio","cpu.ratio","cpu.usedPct","cpu.usagePct","cpu.percent")??(r&&l!==void 0?l/Math.max(1,r):void 0)),d=pn(a,"memory.totalBytes","totalMem"),m=pn(a,"memory.freeBytes","freeMem"),p=Ui(pn(a,"memory.usedRatio","memory.usedPct","usedMemRatio"))??Ch(d,m),v=pn(a,"disk.totalBytes","rootDisk.totalBytes","storage.totalBytes"),g=pn(a,"disk.freeBytes","rootDisk.freeBytes","storage.freeBytes"),w=Ui(pn(a,"disk.usedRatio","disk.usedPct","rootDisk.usedRatio","storage.usedRatio"))??Ch(v,g),y=pn(a,"thermal.cpuC","temperatureC","cpu.temperatureC","gpu.temperatureC"),b=Ui(pn(a,"gpu.usedRatio","gpu.usageRatio","gpu.usedPct","gpu.usagePct","gpu.percent","accelerators.gpu.usageRatio")),C=Qa(a,"gpu.name","gpu.model","accelerators.gpu.name"),j=pn(a,"gpu.memory.totalBytes","gpu.totalMemoryBytes","gpu.vramTotalBytes"),A=pn(a,"gpu.memory.freeBytes","gpu.freeMemoryBytes","gpu.vramFreeBytes"),N=Ui(pn(a,"gpu.memory.usedRatio","gpu.vramUsedRatio"))??Ch(j,A),k=pn(a,"gpu.temperatureC","thermal.gpuC"),T=Ui(pn(a,"npu.usedRatio","npu.usageRatio","npu.usedPct","npu.usagePct","npu.percent","accelerators.npu.usageRatio")),R=Qa(a,"npu.name","npu.model","accelerators.npu.name"),q=pn(a,"npu.tops","npu.topsInt8","accelerators.npu.tops"),O=pn(a,"network.rxMbps","network.receiveMbps","network.downMbps"),Y=pn(a,"network.txMbps","network.transmitMbps","network.upMbps"),_=pn(a,"network.latencyMs","network.rttMs"),L=Ui(pn(a,"network.usedRatio","network.usageRatio","network.saturationRatio")),ae=Qa(a,"network.link","network.interface","network.name"),G=Math.max(y??Number.NEGATIVE_INFINITY,k??Number.NEGATIVE_INFINITY),te=Number.isFinite(G)?G:void 0,P=te===void 0?void 0:Ui((te-35)/60),ye=y!==void 0&&k!==void 0?`CPU ${Math.round(y)}° · GPU ${Math.round(k)}°`:y!==void 0?`CPU ${Math.round(y)}°`:k!==void 0?`GPU ${Math.round(k)}°`:"-",ie=Qa(a,"workload.role","role","lane")||(Wc(n,"aiAssist")?"Agent worker":Wc(n,"taskDispatch")?"Task worker":"Local machine"),K=Qa(n.latestTask,"status")||Qa(a,"workload.status")||"idle",I=Qa(n.latestTask,"title","instructionPreview")||Qa(a,"workload.title"),Q=Qa(n.latestTask,"resultSummary","error","instructionPreview")||Qa(a,"workload.summary"),U=[Fd(a,"ollama","Ollama"),Fd(a,"lmStudio","LM Studio"),Fd(a,"comfyui","ComfyUI"),Fd(a,"stableDiffusion","Stable Diffusion")],W=U.some(me=>me.status!=="unknown"),ue=Date.parse(n.lastSeenAt||n.connectedAt||""),be=Number.isFinite(ue)?Date.now()-ue:0;let X="online";n.connected?be>5*6e4?X="stale":(y??0)>=86||(k??0)>=88||(c??0)>=.94||(b??0)>=.96||(N??0)>=.96||(T??0)>=.96||(p??0)>=.94||(w??0)>=.94||(_??0)>=200||K==="failed"?X="critical":(y??0)>=78||(k??0)>=80||(c??0)>=.82||(b??0)>=.86||(N??0)>=.88||(T??0)>=.86||(p??0)>=.82||(w??0)>=.86||(_??0)>=80?X="warn":(["queued","running","targeted"].includes(K)||U.some(me=>me.status==="busy"))&&(X="busy"):X="offline";const $=U.filter(me=>me.status==="online"||me.status==="busy").length,de=[{id:"cpu",label:"CPU",value:Eo(c),detail:r?`${r} cores`:l!==void 0?`load ${l.toFixed(1)}`:"not reported",ratio:c,state:Rl(c,.92,.78)},{id:"memory",label:"RAM",value:Eo(p),detail:Sh(d,m),ratio:p,state:Rl(p,.92,.78)},{id:"disk",label:"DISK",value:Eo(w),detail:Sh(v,g),ratio:w,state:Rl(w,.92,.82)},{id:"gpu",label:"GPU",value:Eo(b),detail:C||(j&&A!==void 0?`${Fc(A)} VRAM free`:k!==void 0?`${Math.round(k)}C`:"not reported"),ratio:b,state:k!==void 0&&k>=88?"critical":k!==void 0&&k>=80?"warn":Rl(b,.96,.86)},{id:"vram",label:"VRAM",value:Eo(N),detail:Sh(j,A),ratio:N,state:Rl(N,.96,.88)},{id:"npu",label:"NPU",value:T!==void 0?Eo(T):q!==void 0?`${Math.round(q)} TOPS`:"-",detail:R||(q!==void 0?"neural engine":"not reported"),ratio:T,state:Rl(T,.96,.86)},{id:"temp",label:"TEMP",value:ye,detail:$>0?`${$} local tools`:`uptime ${AT(pn(a,"uptimeSec"))}`,ratio:P,state:te===void 0?"unknown":te>=86?"critical":te>=78?"warn":"good"},{id:"network",label:"NET",value:jh(O)||(_!==void 0?`${Math.round(_)}ms`:ae||"-"),detail:jh(Y)?`${jh(Y)} up`:ae||"not reported",ratio:L,state:_!==void 0&&_>=200?"critical":_!==void 0&&_>=80?"warn":Rl(L,.9,.75)}];return{state:X,label:jT(X,de,K),role:ie,taskLabel:I||(K==="idle"?"idle":K),taskStatus:K,taskSummary:Q,tools:W?U:U.map(me=>({...me,detail:"not reported"})),metrics:de}}const NT=[{id:"list",label:"List"},{id:"medium",label:"Small"},{id:"large",label:"Large"}],MT=[{id:"sync-server",label:"Hub",icon:Gi,accent:"blue",tooltip:"hub"},{id:"wall",label:"Wall",icon:Kc,accent:"blue",tooltip:"wall"},{id:"control",label:"Control",icon:$d,accent:"red",tooltip:"control"},{id:"share-files",label:"Share Files",icon:Pd,accent:"green",tooltip:"share-files"},{id:"agents",label:"Agents",icon:Ud,accent:"violet",tooltip:"agents"}],TT=[{id:"doc",label:"Doc",icon:Kd,accent:"amber"},{id:"support",label:"Support",icon:Pc,accent:"violet"},{id:"pricing",label:"Pricing",icon:Do,accent:"green"}];function ET(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 ln(n){return ET(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 Dl(n){return n.map(a=>ln(a))}function la(n){return{languageName:n.languageName,languageLabel:n.languageLabel,eyebrow:n.eyebrow,title:ln(n.title),intro:ln(n.intro),sections:[{title:ln(n.managerTitle),body:ln(n.managerBody),points:Dl(n.managerPoints)},{title:ln(n.clientTitle),body:ln(n.clientBody),points:Dl(n.clientPoints)},{title:ln(n.syncTitle),body:ln(n.syncBody),points:Dl(n.syncPoints)},...n.agentTitle&&n.agentBody&&n.agentPoints?[{title:ln(n.agentTitle),body:ln(n.agentBody),points:Dl(n.agentPoints)}]:[],{title:ln(n.platformTitle),body:ln(n.platformBody),points:Dl(n.platformPoints)}],sync:{title:ln(n.syncTitle),body:ln(n.syncBody),points:Dl(n.syncPoints)},firewall:{title:ln(n.firewallTitle),body:ln(n.firewallBody),points:Dl(n.firewallPoints)},commands:{title:ln(n.commandsTitle),body:ln(n.commandsBody),manager:ln(n.managerCommandLabel),primary:ln(n.clientCommandLabel),slot:ln(n.slotCommandLabel),manual:ln(n.manualCommandLabel)}}}const Oo={ko:la({languageName:"한국어",languageLabel:"문서 언어",eyebrow:"LiveDesk Manual",title:"한 줄로 여는 로컬 Screen Wall",intro:"LiveDesk는 매니저 PC 한 대에서 여러 작업 PC, AI 박스, 맥미니, 개발 장비를 한 화면에 모니터링하고 필요한 제어를 실행하는 npm-first 원격 작업 데크입니다.",managerTitle:"1. 매니저 실행",managerBody:"화면을 모아 볼 컴퓨터에서 LiveDesk 매니저를 실행합니다. 매니저는 UI와 로컬 서버를 같이 열고 브라우저를 http://127.0.0.1:5179 로 띄웁니다.",managerPoints:["명령은 npx -y livedesk 입니다.","매니저는 Screen Wall/API 포트 5179와 클라이언트 접속 포트 5197을 사용합니다.","기존 LiveDesk 포트가 남아 있으면 기본적으로 정리하고 새로 시작합니다. 필요하면 --no-clean 을 붙입니다."],clientTitle:"2. 워크스테이션 연결",clientBody:"모니터링할 PC에서는 Google 로그인 또는 Hub 화면의 6자리 PIN으로 연결합니다. Hub가 꺼져 있으면 실시간 온라인 알림을 기다리고 적응형 간격으로 다시 확인합니다.",clientPoints:["빈 자리에 자동 배치하려면 npx -y livedesk client 를 실행합니다.","자리 번호를 고정하려면 npx -y livedesk client 3 처럼 번호를 붙입니다.","브라우저 연결 페이지에서 Google 버튼 또는 6자리 PIN 입력 중 하나를 선택합니다."],syncTitle:"3. Sync Server와 자동 발견",syncBody:"Sync Server는 이 매니저를 현재 계정의 활성 Screen Wall로 Supabase에 등록합니다. 클라이언트는 같은 Google 계정으로 로그인한 뒤 그 기록을 읽고 접속 후보들을 순서대로 시도합니다.",syncPoints:["등록 정보에는 host instance, LAN/private 주소, public 후보 주소, pair token, 짧은 lease가 포함됩니다.","같은 LAN 후보를 먼저 쓰고, 필요하면 외부 주소 후보를 시도합니다.","매니저 위치, VPN, 방화벽, 공유기 설정이 바뀌었거나 개발 중 활성 매니저를 바꿀 때 Sync Server를 누릅니다.","이제 livedesk.pages.dev의 Chrome Local Network Access 허용은 기본 실행 경로가 아닙니다. npm 매니저 앱이 실제 서버입니다."],agentTitle:"4. Agent로 여러 장비 작업하기",agentBody:"Agents 화면은 Hub에서 실행되는 Codex 기반 Agent가 연결된 장비를 확인하고, 선택한 권한 범위 안에서 작업을 실행하는 공간입니다. 클라이언트 PC에 Codex 앱이나 Codex SDK를 설치할 필요는 없습니다.",agentPoints:["Suggested tasks에는 현재 72개의 읽기·운영 작업 템플릿이 있으며, 검색과 권한·플랫폼·capability 조건으로 실행 가능 항목을 안내합니다.","Ask, Safe Auto, Full Access, Custom 권한 모드를 선택할 수 있습니다. 위험한 변경 작업은 승인 카드와 장비 capability 검사를 거칩니다.","All connected 또는 Selected로 대상 장비를 제한하고, 결과는 장비별 상태 칩과 실제 RAM·디스크·GPU·프로세스 요약으로 확인합니다.","Agent 실행은 Hub의 격리된 runtime과 LiveDesk MCP 도구를 통해서만 장비에 전달되며, 모든 작업은 timeout·취소·tool limit·감사 로그 경계를 가집니다."],platformTitle:"5. 현재 플랫폼과 스트림 상태",platformBody:"Windows의 Wall, Control, 파일 전송, 원격 오디오와 RemoteFast 경로를 현재 기준으로 확인했습니다. macOS와 Linux는 같은 npm 명령 경로를 유지하면서 권한과 캡처 백엔드를 확장하고 있습니다.",platformPoints:["Wall은 Mode 3 H.264와 Mode 4 H.264 Atlas를 사용합니다. Mode 2는 Mode 4의 내부 Atlas 입력에만 한정되며 Wall/Control fallback으로 사용되지 않습니다.","원격 오디오는 선택한 장비가 capability를 광고할 때 사용할 수 있으며, 브라우저는 queue·drop·resync·automatic restart 상태를 진단합니다.","macOS: 화면 캡처와 제어에는 Screen Recording/Accessibility 권한이 필요합니다. RemoteFast 로그는 필요한 상태 중심으로 제한됩니다.","Linux: linux-x64 runtime, grim/gnome-screenshot/import/scrot 캡처, xdotool 입력 백엔드가 추가되었습니다. 오디오는 아직 비활성입니다."],firewallTitle:"방화벽과 외부 장소 연결",firewallBody:"같은 LAN 안에서는 보통 공유기 포트포워딩이 필요 없습니다. 다른 장소의 PC를 붙이려면 클라이언트가 매니저의 클라이언트 접속 포트에 도달할 수 있어야 합니다.",firewallPoints:["클라이언트 접속 포트는 TCP 5197입니다.","클라이언트 쪽은 나가는 연결이므로 보통 인바운드 포트 개방이 필요 없습니다.","다른 네트워크에서 붙일 때는 매니저 PC 방화벽에서 TCP 5197 인바운드를 허용하고, 공유기에서는 TCP 5197을 매니저 PC로 전달합니다.","Screen Wall/API 포트 5179는 매니저 UI용입니다. 외부 브라우저에서 Wall을 직접 열 필요가 있을 때만 별도로 노출을 검토합니다.","공개 인터넷에 바로 열기보다 VPN, Tailscale, ZeroTier, 고정 IP allowlist를 우선합니다."],commandsTitle:"현재 사용 명령",commandsBody:"웹사이트를 찾아가 설치 파일을 받는 방식보다 터미널 한 줄로 모든 운영체제에서 거의 같은 흐름을 쓰는 것이 LiveDesk의 기본 방향입니다.",managerCommandLabel:"매니저 시작",clientCommandLabel:"워크스테이션 연결",slotCommandLabel:"3번 슬롯에 고정",manualCommandLabel:"고급 수동 연결"}),en:la({languageName:"English",languageLabel:"Document language",eyebrow:"LiveDesk Manual",title:"Open a local Screen Wall with one command",intro:"LiveDesk is an npm-first remote work deck for monitoring many workstations, AI boxes, Mac minis, and dev machines from one manager PC.",managerTitle:"1. Run the manager",managerBody:"Run LiveDesk on the computer that will watch the screens. The manager starts the UI and local server together, then opens http://127.0.0.1:5179.",managerPoints:["The command is npx -y livedesk.","The manager uses port 5179 for the Screen Wall/API and port 5197 for client connections.","If an old LiveDesk process still owns those ports, startup cleans it by default. Add --no-clean when you want to keep it."],clientTitle:"2. Connect a workstation",clientBody:"On each monitored computer, connect with Google sign-in or the 6-digit PIN shown on the Hub screen. If no manager is online yet, the client waits for a live online signal and falls back to adaptive retries.",clientPoints:["Run npx -y livedesk client for first available placement.","Run npx -y livedesk client 3 to pin the machine to slot 3.","The browser connection page lets you choose Google or a 6-digit PIN."],syncTitle:"3. Sync Server and discovery",syncBody:"Sync Server publishes this manager as the active Screen Wall for the signed-in account. Clients read that Supabase record after Google sign-in and try the endpoint candidates in order.",syncPoints:["The record includes host instance, LAN/private addresses, public endpoint candidates, pair token, and a short lease.","LAN candidates are preferred first, then public candidates if needed.","Press Sync Server after manager moves, VPN/firewall/router changes, or when this development machine should take over as active manager.","Chrome Local Network Access on livedesk.pages.dev is no longer the default runtime path. The npm manager app is the real server."],agentTitle:"4. Run multi-workstation tasks with Agent",agentBody:"The Agents page runs a Codex-based Agent in the Hub to inspect connected workstations and perform actions within the selected permission scope. Client PCs do not need the Codex app or Codex SDK installed.",agentPoints:["Suggested tasks currently contains 72 read-only and operational templates with search plus permission, platform, and capability availability checks.","Choose Ask, Safe Auto, Full Access, or Custom. Risky changes go through approval cards and explicit client capability checks.","Limit targets with All connected or Selected. Results use compact per-device status chips and show real RAM, disk, GPU, and process summaries.","Runs stay inside the Hub-isolated runtime and LiveDesk MCP tools, with timeout, cancellation, tool-call limits, and audit-log boundaries."],platformTitle:"5. Current platform and stream state",platformBody:"Windows Wall, Control, file transfer, remote audio, and the RemoteFast path are verified against the current implementation. macOS and Linux keep the same npm command path while capture and permission backends expand.",platformPoints:["Wall uses Mode 3 H.264 and Mode 4 H.264 Atlas. Mode 2 is restricted to internal Mode 4 Atlas input and is never used as a Wall or Control fallback.","Remote audio is available when the selected workstation advertises the capability, with queue, drop, resync, and automatic-restart diagnostics in the browser.","macOS requires Screen Recording and Accessibility permissions for capture and control. RemoteFast logs focus on actionable state.","Linux includes the linux-x64 runtime, grim/gnome-screenshot/import/scrot capture, and xdotool input backend. Audio is still disabled."],firewallTitle:"Firewall and remote locations",firewallBody:"On the same LAN, router forwarding is usually unnecessary. For another office, building, or country, clients must be able to reach the manager client port.",firewallPoints:["Client connection port: TCP 5197.","Client machines normally only need outbound access.","For remote networks, allow inbound TCP 5197 on the manager firewall and forward TCP 5197 from the router to the manager PC.","Screen Wall/API port 5179 is for the manager UI. Expose it only if a remote browser must open the Wall directly.","Prefer VPN, Tailscale, ZeroTier, or fixed-IP allowlists over public internet exposure."],commandsTitle:"Current commands",commandsBody:"The product direction is one terminal command across operating systems instead of finding a website, downloading, and installing manually.",managerCommandLabel:"Start manager",clientCommandLabel:"Connect workstation",slotCommandLabel:"Pin to slot 3",manualCommandLabel:"Advanced manual connection"}),ja:la({languageName:"日本語",languageLabel:"ドキュメント言語",eyebrow:"LiveDesk Manual",title:"1行でローカル Screen Wall を開く",intro:"LiveDesk は、複数の作業 PC、AI マシン、Mac mini、開発機を1台の manager PC から監視する npm-first のリモート作業デッキです。",managerTitle:"1. manager を実行",managerBody:"画面を集めて見るコンピューターで LiveDesk manager を実行します。UI とローカルサーバーが同時に起動し、http://127.0.0.1:5179 が開きます。",managerPoints:["コマンドは npx -y livedesk です。","Screen Wall/API は 5179、client 接続は 5197 を使います。","古い LiveDesk プロセスがポートを使っている場合は、基本的に自動で整理して起動します。"],clientTitle:"2. workstation を接続",clientBody:"監視される PC で同じ Google アカウントにログインします。manager がまだ無い場合、client はオンライン通知を待ち、適応型の間隔で再確認します。",clientPoints:["空きスロットに入れるには npx -y livedesk client を実行します。","スロットを固定するには npx -y livedesk client 3 のように番号を付けます。","大量の PC でも再ログインなしで待ち続けます。"],syncTitle:"3. Sync Server と自動検出",syncBody:"Sync Server はこの manager を現在の Google アカウントの active Screen Wall として Supabase に登録します。",syncPoints:["host instance、LAN/private アドレス、public 候補、pair token、短い lease を登録します。","client は LAN 候補を優先し、必要なら public 候補も試します。","VPN、firewall、router、manager の場所が変わったら Sync Server を押します。","livedesk.pages.dev の Chrome Local Network Access は標準実行経路ではありません。npm manager アプリが実際のサーバーです。"],platformTitle:"4. 現在のプラットフォーム状態",platformBody:"Windows は live screen transfer まで確認済みです。macOS と Linux も同じ npm コマンド経路を目標に対応を広げています。",platformPoints:["Windows: 動作確認済み。","macOS: 画面取得と制御には Screen Recording/Accessibility 権限が必要です。","Linux: linux-x64 runtime、grim/gnome-screenshot/import/scrot capture、xdotool input backend を追加済み。audio は未対応です。"],firewallTitle:"Firewall と外部拠点",firewallBody:"同じ LAN なら通常 router forwarding は不要です。外部拠点では client が manager の接続ポートへ到達できる必要があります。",firewallPoints:["client 接続ポートは TCP 5197 です。","client 側は通常 outbound だけで足ります。","外部 network では manager PC の firewall で TCP 5197 inbound を許可し、router から manager PC へ forward します。","5179 は manager UI 用なので、外部ブラウザで Wall を開く必要がある時だけ公開を検討します。","公開 internet より VPN、Tailscale、ZeroTier、IP allowlist を優先してください。"],commandsTitle:"現在のコマンド",commandsBody:"Web サイトから installer を探すより、OS をまたいで terminal 1行で動かす方向です。",managerCommandLabel:"manager 起動",clientCommandLabel:"workstation 接続",slotCommandLabel:"slot 3 に固定",manualCommandLabel:"高度な手動接続"}),"zh-CN":la({languageName:"简体中文",languageLabel:"文档语言",eyebrow:"LiveDesk Manual",title:"用一条命令打开本地 Screen Wall",intro:"LiveDesk 是 npm-first 的远程工作台,用一台 manager PC 监控多台工作站、AI 主机、Mac mini 和开发机器。",managerTitle:"1. 运行 manager",managerBody:"在负责查看屏幕的电脑上运行 LiveDesk manager。它会同时启动 UI 和本地服务器,并打开 http://127.0.0.1:5179。",managerPoints:["命令是 npx -y livedesk。","Screen Wall/API 使用 5179,client 连接使用 5197。","如果旧的 LiveDesk 进程占用端口,默认会清理后重新启动。"],clientTitle:"2. 连接 workstation",clientBody:"在被监控的电脑上使用同一个 Google 账号登录。如果 manager 尚未在线,client 会等待上线通知,并以自适应间隔重新检查。",clientPoints:["自动放入空位: npx -y livedesk client。","固定到 3 号位置: npx -y livedesk client 3。","大量电脑也可以持续等待,不需要反复登录。"],syncTitle:"3. Sync Server 和自动发现",syncBody:"Sync Server 会把当前 manager 作为该账号的 active Screen Wall 写入 Supabase。client 登录后读取记录并依次尝试连接候选地址。",syncPoints:["记录包括 host instance、LAN/private 地址、public 候选、pair token 和短 lease。","优先尝试同一 LAN 地址,需要时再尝试外部地址。","manager 位置、VPN、防火墙或路由变化后请点击 Sync Server。","livedesk.pages.dev 的 Chrome Local Network Access 不再是默认运行方式。npm manager app 才是真正服务器。"],platformTitle:"4. 当前平台状态",platformBody:"Windows 已确认可传输实时画面。macOS 和 Linux 正按同一 npm 命令路径扩展支持。",platformPoints:["Windows: 已确认可用。","macOS: 画面捕获和控制需要 Screen Recording/Accessibility 权限。","Linux: 已加入 linux-x64 runtime、grim/gnome-screenshot/import/scrot 捕获、xdotool 输入后端。音频尚未启用。"],firewallTitle:"防火墙和外部地点",firewallBody:"同一 LAN 通常不需要路由端口转发。不同地点连接时,client 必须能访问 manager 的 client 连接端口。",firewallPoints:["client 连接端口是 TCP 5197。","client 机器通常只需要出站访问。","跨网络时,在 manager 防火墙放行 TCP 5197 入站,并在路由器转发到 manager PC。","5179 是 manager UI 端口,仅在需要远程浏览器直接打开 Wall 时考虑暴露。","优先使用 VPN、Tailscale、ZeroTier 或固定 IP allowlist。"],commandsTitle:"当前命令",commandsBody:"产品方向是跨操作系统使用一条终端命令,而不是先找网站、下载、安装。",managerCommandLabel:"启动 manager",clientCommandLabel:"连接 workstation",slotCommandLabel:"固定到 slot 3",manualCommandLabel:"高级手动连接"}),"zh-TW":la({languageName:"繁體中文",languageLabel:"文件語言",eyebrow:"LiveDesk Manual",title:"用一行指令開啟本機 Screen Wall",intro:"LiveDesk 是 npm-first 的遠端工作台,用一台 manager PC 監看多台工作站、AI 主機、Mac mini 與開發機。",managerTitle:"1. 執行 manager",managerBody:"在負責看畫面的電腦上執行 LiveDesk manager。它會同時啟動 UI 與本機伺服器,並開啟 http://127.0.0.1:5179。",managerPoints:["指令是 npx -y livedesk。","Screen Wall/API 使用 5179,client 連線使用 5197。","若舊的 LiveDesk 程序占用連接埠,預設會清理後重新啟動。"],clientTitle:"2. 連接 workstation",clientBody:"在被監看的電腦上使用同一個 Google 帳號登入。如果 manager 尚未上線,client 會等待上線通知,並以自適應間隔重新檢查。",clientPoints:["自動放入空位: npx -y livedesk client。","固定到 3 號位置: npx -y livedesk client 3。","大量電腦也能持續等待,不需要反覆登入。"],syncTitle:"3. Sync Server 與自動探索",syncBody:"Sync Server 會把目前 manager 登錄為此帳號的 active Screen Wall。client 登入後讀取 Supabase 記錄並依序嘗試連線候選地址。",syncPoints:["記錄包含 host instance、LAN/private 位址、public 候選、pair token 與短 lease。","優先嘗試 LAN 位址,需要時再嘗試外部位址。","manager 位置、VPN、防火牆或路由設定改變後請按 Sync Server。","livedesk.pages.dev 的 Chrome Local Network Access 不再是預設執行路徑。npm manager app 才是真正伺服器。"],platformTitle:"4. 目前平台狀態",platformBody:"Windows 已確認可傳輸即時畫面。macOS 與 Linux 也沿用相同 npm 指令路徑擴充支援。",platformPoints:["Windows: 已確認可用。","macOS: 畫面擷取與控制需要 Screen Recording/Accessibility 權限。","Linux: 已加入 linux-x64 runtime、grim/gnome-screenshot/import/scrot capture、xdotool input backend。音訊尚未啟用。"],firewallTitle:"防火牆與外部地點",firewallBody:"同一 LAN 通常不需要路由器轉發。不同地點連線時,client 必須能到達 manager 的 client 連線埠。",firewallPoints:["client 連線埠是 TCP 5197。","client 電腦通常只需要對外連線。","跨網路時,請在 manager 防火牆允許 TCP 5197 inbound,並從路由器轉發到 manager PC。","5179 是 manager UI 連接埠,只在需要遠端瀏覽器直接打開 Wall 時才考慮公開。","優先使用 VPN、Tailscale、ZeroTier 或固定 IP allowlist。"],commandsTitle:"目前指令",commandsBody:"產品方向是跨作業系統用一行 terminal 指令,而不是先找網站、下載、安裝。",managerCommandLabel:"啟動 manager",clientCommandLabel:"連接 workstation",slotCommandLabel:"固定到 slot 3",manualCommandLabel:"進階手動連線"}),es:la({languageName:"Español",languageLabel:"Idioma del documento",eyebrow:"LiveDesk Manual",title:"Abre un Screen Wall local con un comando",intro:"LiveDesk es una consola npm-first para vigilar muchas estaciones, cajas de IA, Mac mini y equipos de desarrollo desde un PC manager.",managerTitle:"1. Ejecuta el manager",managerBody:"Ejecuta LiveDesk en el equipo que verá las pantallas. El manager inicia la UI y el servidor local juntos y abre http://127.0.0.1:5179.",managerPoints:["El comando es npx -y livedesk.","El manager usa 5179 para Screen Wall/API y 5197 para conexiones client.","Si un proceso antiguo ocupa los puertos, el arranque lo limpia por defecto."],clientTitle:"2. Conecta una workstation",clientBody:"En cada equipo monitoreado, inicia sesión con la misma cuenta Google. Si el manager aún no está activo, el client espera una señal en tiempo real y vuelve a comprobar con intervalos adaptativos.",clientPoints:["Usa npx -y livedesk client para el primer slot libre.","Usa npx -y livedesk client 3 para fijar el equipo al slot 3.","Los clients siguen esperando para no repetir login en muchas máquinas."],syncTitle:"3. Sync Server y descubrimiento",syncBody:"Sync Server publica este manager como Screen Wall activo para la cuenta. Los clients leen el registro en Supabase y prueban los endpoints.",syncPoints:["Incluye host instance, direcciones LAN/private, candidatos public, pair token y lease corto.","Primero se prueban candidatos LAN, luego públicos si hace falta.","Pulsa Sync Server después de cambios de manager, VPN, firewall o router.","Chrome Local Network Access en livedesk.pages.dev ya no es el flujo principal. La app npm manager es el servidor real."],platformTitle:"4. Estado de plataformas",platformBody:"Windows ya fue verificado con transferencia de pantalla. macOS y Linux siguen el mismo camino npm.",platformPoints:["Windows: verificado.","macOS: captura y control requieren permisos Screen Recording/Accessibility.","Linux: agregado linux-x64 runtime, captura grim/gnome-screenshot/import/scrot y entrada xdotool. Audio aún desactivado."],firewallTitle:"Firewall y sedes remotas",firewallBody:"En la misma LAN normalmente no hace falta port forwarding. Para otra red, los clients deben llegar al puerto client del manager.",firewallPoints:["Puerto de conexión client: TCP 5197.","Los equipos client normalmente solo necesitan salida.","Para redes remotas, permite TCP 5197 inbound en el manager y reenvía TCP 5197 al PC manager.","El puerto 5179 es para la UI del manager; expónlo solo si un navegador remoto debe abrir el Wall.","Prefiere VPN, Tailscale, ZeroTier o allowlist de IP fijas."],commandsTitle:"Comandos actuales",commandsBody:"La dirección del producto es un comando de terminal común entre sistemas, no descargar e instalar desde una web.",managerCommandLabel:"Iniciar manager",clientCommandLabel:"Conectar workstation",slotCommandLabel:"Fijar al slot 3",manualCommandLabel:"Conexión manual avanzada"}),fr:la({languageName:"Français",languageLabel:"Langue du document",eyebrow:"LiveDesk Manual",title:"Ouvrir un Screen Wall local en une commande",intro:"LiveDesk est un deck npm-first pour surveiller plusieurs postes, machines IA, Mac mini et machines dev depuis un PC manager.",managerTitle:"1. Lancer le manager",managerBody:"Lancez LiveDesk sur l’ordinateur qui observe les écrans. Le manager démarre l’UI et le serveur local, puis ouvre http://127.0.0.1:5179.",managerPoints:["La commande est npx -y livedesk.","Le manager utilise 5179 pour Screen Wall/API et 5197 pour les connexions client.","Si un ancien processus utilise les ports, le démarrage le nettoie par défaut."],clientTitle:"2. Connecter une workstation",clientBody:"Sur chaque ordinateur surveillé, connectez-vous avec le même compte Google. Si le manager n’est pas encore actif, le client réessaie toutes les 5 secondes.",clientPoints:["Utilisez npx -y livedesk client pour le premier slot libre.","Utilisez npx -y livedesk client 3 pour fixer la machine au slot 3.","Les clients continuent d’attendre pour éviter les reconnexions répétées."],syncTitle:"3. Sync Server et découverte",syncBody:"Sync Server publie ce manager comme Screen Wall actif du compte. Les clients lisent l’enregistrement Supabase et testent les endpoints.",syncPoints:["Il contient host instance, adresses LAN/private, candidats public, pair token et lease court.","Les candidats LAN sont essayés en premier, puis les candidats publics si besoin.","Cliquez Sync Server après un changement de manager, VPN, firewall ou routeur.","Chrome Local Network Access sur livedesk.pages.dev n’est plus le chemin par défaut. L’app npm manager est le vrai serveur."],platformTitle:"4. État des plateformes",platformBody:"Windows est vérifié avec transfert d’écran live. macOS et Linux suivent le même chemin npm.",platformPoints:["Windows: vérifié.","macOS: capture et contrôle nécessitent Screen Recording/Accessibility.","Linux: runtime linux-x64, capture grim/gnome-screenshot/import/scrot et entrée xdotool ajoutés. Audio désactivé."],firewallTitle:"Firewall et sites distants",firewallBody:"Sur le même LAN, le port forwarding est rarement nécessaire. Depuis un autre réseau, les clients doivent atteindre le port client du manager.",firewallPoints:["Port de connexion client: TCP 5197.","Les machines client ont normalement seulement besoin de sortie réseau.","Pour un réseau distant, autorisez TCP 5197 entrant sur le manager et redirigez TCP 5197 vers le PC manager.","Le port 5179 sert à l’UI manager; exposez-le seulement si un navigateur distant doit ouvrir le Wall.","Préférez VPN, Tailscale, ZeroTier ou allowlist IP fixes."],commandsTitle:"Commandes actuelles",commandsBody:"La direction produit est une commande terminal commune aux OS, plutôt qu’un téléchargement manuel depuis un site.",managerCommandLabel:"Démarrer manager",clientCommandLabel:"Connecter workstation",slotCommandLabel:"Fixer au slot 3",manualCommandLabel:"Connexion manuelle avancée"}),de:la({languageName:"Deutsch",languageLabel:"Dokumentsprache",eyebrow:"LiveDesk Manual",title:"Lokale Screen Wall mit einem Befehl öffnen",intro:"LiveDesk ist ein npm-first Arbeitsdeck, um viele Workstations, AI-Boxen, Mac minis und Dev-Rechner von einem Manager-PC zu überwachen.",managerTitle:"1. Manager starten",managerBody:"Starte LiveDesk auf dem Computer, der die Screens sieht. Der Manager startet UI und lokalen Server zusammen und öffnet http://127.0.0.1:5179.",managerPoints:["Der Befehl ist npx -y livedesk.","Der Manager nutzt 5179 für Screen Wall/API und 5197 für Client-Verbindungen.","Wenn alte LiveDesk-Prozesse Ports belegen, werden sie beim Start standardmäßig bereinigt."],clientTitle:"2. Workstation verbinden",clientBody:"Melde dich auf jedem überwachten Computer mit demselben Google-Konto an. Wenn kein Manager online ist, wartet der Client auf ein Live-Signal und prüft mit adaptiven Intervallen erneut.",clientPoints:["npx -y livedesk client nutzt den ersten freien Slot.","npx -y livedesk client 3 fixiert den Rechner auf Slot 3.","Clients warten weiter, damit große Setups kein wiederholtes Login brauchen."],syncTitle:"3. Sync Server und Discovery",syncBody:"Sync Server veröffentlicht diesen Manager als aktive Screen Wall des Kontos. Clients lesen den Supabase-Eintrag und testen Endpoints der Reihe nach.",syncPoints:["Enthält host instance, LAN/private Adressen, public Kandidaten, pair token und kurze lease.","LAN-Kandidaten werden zuerst versucht, danach public Kandidaten.","Nach Änderungen an Manager, VPN, Firewall oder Router Sync Server drücken.","Chrome Local Network Access auf livedesk.pages.dev ist nicht mehr der Standardpfad. Die npm Manager App ist der echte Server."],platformTitle:"4. Plattformstatus",platformBody:"Windows wurde mit Live-Screen-Transfer geprüft. macOS und Linux folgen demselben npm-Pfad.",platformPoints:["Windows: verifiziert.","macOS: Capture und Control brauchen Screen Recording/Accessibility Rechte.","Linux: linux-x64 Runtime, grim/gnome-screenshot/import/scrot Capture und xdotool Input Backend sind ergänzt. Audio ist deaktiviert."],firewallTitle:"Firewall und entfernte Standorte",firewallBody:"Im gleichen LAN ist Router-Forwarding meist unnötig. Aus anderen Netzwerken müssen Clients den Client-Port des Managers erreichen.",firewallPoints:["Client-Verbindungsport: TCP 5197.","Client-Rechner brauchen normalerweise nur ausgehenden Zugriff.","Für entfernte Netzwerke TCP 5197 inbound am Manager erlauben und vom Router zum Manager-PC forwarden.","Port 5179 ist für die Manager-UI; nur öffnen, wenn ein Remote-Browser die Wall direkt öffnen muss.","VPN, Tailscale, ZeroTier oder feste IP-Allowlists bevorzugen."],commandsTitle:"Aktuelle Befehle",commandsBody:"Die Produktlinie ist ein Terminalbefehl über Betriebssysteme hinweg, statt Website suchen, herunterladen und installieren.",managerCommandLabel:"Manager starten",clientCommandLabel:"Workstation verbinden",slotCommandLabel:"An Slot 3 fixieren",manualCommandLabel:"Erweiterte manuelle Verbindung"}),"pt-BR":la({languageName:"Português",languageLabel:"Idioma do documento",eyebrow:"LiveDesk Manual",title:"Abra um Screen Wall local com um comando",intro:"LiveDesk é um deck npm-first para monitorar várias estações, caixas de IA, Mac minis e máquinas dev a partir de um PC manager.",managerTitle:"1. Execute o manager",managerBody:"Rode LiveDesk no computador que verá as telas. O manager inicia a UI e o servidor local juntos e abre http://127.0.0.1:5179.",managerPoints:["O comando é npx -y livedesk.","O manager usa 5179 para Screen Wall/API e 5197 para conexões client.","Se um processo antigo ocupa as portas, a inicialização limpa por padrão."],clientTitle:"2. Conecte uma workstation",clientBody:"Em cada computador monitorado, entre com a mesma conta Google. Se o manager ainda não estiver online, o client aguarda um sinal em tempo real e verifica novamente em intervalos adaptativos.",clientPoints:["Use npx -y livedesk client para o primeiro slot livre.","Use npx -y livedesk client 3 para fixar no slot 3.","Clients continuam tentando para evitar login repetido em muitos PCs."],syncTitle:"3. Sync Server e descoberta",syncBody:"Sync Server publica este manager como Screen Wall ativo da conta. Clients leem o registro no Supabase e testam endpoints.",syncPoints:["Inclui host instance, endereços LAN/private, candidatos public, pair token e lease curto.","Candidatos LAN vêm primeiro; public depois se necessário.","Clique Sync Server após mudanças de manager, VPN, firewall ou roteador.","Chrome Local Network Access em livedesk.pages.dev não é mais o caminho padrão. O app npm manager é o servidor real."],platformTitle:"4. Estado das plataformas",platformBody:"Windows foi verificado com transferência de tela. macOS e Linux seguem o mesmo caminho npm.",platformPoints:["Windows: verificado.","macOS: captura e controle precisam de permissões Screen Recording/Accessibility.","Linux: runtime linux-x64, captura grim/gnome-screenshot/import/scrot e entrada xdotool adicionados. Áudio ainda desativado."],firewallTitle:"Firewall e locais remotos",firewallBody:"Na mesma LAN normalmente não é preciso port forwarding. Em outra rede, clients precisam alcançar a porta client do manager.",firewallPoints:["Porta client: TCP 5197.","Máquinas client normalmente só precisam de saída.","Para redes remotas, permita TCP 5197 inbound no manager e encaminhe TCP 5197 para o PC manager.","A porta 5179 é para a UI do manager; exponha apenas se um navegador remoto precisar abrir o Wall.","Prefira VPN, Tailscale, ZeroTier ou allowlist de IP fixo."],commandsTitle:"Comandos atuais",commandsBody:"A direção do produto é um comando de terminal comum entre sistemas, não baixar e instalar manualmente.",managerCommandLabel:"Iniciar manager",clientCommandLabel:"Conectar workstation",slotCommandLabel:"Fixar no slot 3",manualCommandLabel:"Conexão manual avançada"}),it:la({languageName:"Italiano",languageLabel:"Lingua documento",eyebrow:"LiveDesk Manual",title:"Apri uno Screen Wall locale con un comando",intro:"LiveDesk è un deck npm-first per monitorare workstation, box AI, Mac mini e macchine dev da un solo PC manager.",managerTitle:"1. Avvia il manager",managerBody:"Esegui LiveDesk sul computer che guarderà gli schermi. Il manager avvia UI e server locale e apre http://127.0.0.1:5179.",managerPoints:["Il comando è npx -y livedesk.","Il manager usa 5179 per Screen Wall/API e 5197 per connessioni client.","Se vecchi processi occupano le porte, l’avvio le pulisce di default."],clientTitle:"2. Connetti una workstation",clientBody:"Su ogni computer monitorato, accedi con lo stesso account Google. Se il manager non è online, il client riprova ogni 5 secondi.",clientPoints:["npx -y livedesk client usa il primo slot libero.","npx -y livedesk client 3 fissa la macchina allo slot 3.","I client continuano a provare per evitare login ripetuti."],syncTitle:"3. Sync Server e discovery",syncBody:"Sync Server pubblica questo manager come Screen Wall attivo dell’account. I client leggono Supabase e provano gli endpoint.",syncPoints:["Include host instance, indirizzi LAN/private, candidati public, pair token e lease breve.","Prima LAN, poi public se necessario.","Premi Sync Server dopo cambi di manager, VPN, firewall o router.","Chrome Local Network Access su livedesk.pages.dev non è più il percorso principale. L’app npm manager è il server reale."],platformTitle:"4. Stato piattaforme",platformBody:"Windows è verificato con trasferimento schermo live. macOS e Linux seguono lo stesso percorso npm.",platformPoints:["Windows: verificato.","macOS: capture e control richiedono permessi Screen Recording/Accessibility.","Linux: aggiunti runtime linux-x64, capture grim/gnome-screenshot/import/scrot e input xdotool. Audio disattivato."],firewallTitle:"Firewall e sedi remote",firewallBody:"Nella stessa LAN di solito non serve port forwarding. Da altre reti, i client devono raggiungere la porta client del manager.",firewallPoints:["Porta client: TCP 5197.","I client normalmente richiedono solo uscita.","Per reti remote, abilita TCP 5197 inbound sul manager e inoltra TCP 5197 al PC manager.","La porta 5179 è per la UI manager; esponila solo se un browser remoto deve aprire il Wall.","Preferisci VPN, Tailscale, ZeroTier o IP allowlist."],commandsTitle:"Comandi attuali",commandsBody:"La direzione è un comando terminale comune tra sistemi operativi, invece di download e install manuale.",managerCommandLabel:"Avvia manager",clientCommandLabel:"Connetti workstation",slotCommandLabel:"Fissa allo slot 3",manualCommandLabel:"Connessione manuale avanzata"}),id:la({languageName:"Bahasa Indonesia",languageLabel:"Bahasa dokumen",eyebrow:"LiveDesk Manual",title:"Buka Screen Wall lokal dengan satu perintah",intro:"LiveDesk adalah deck npm-first untuk memantau banyak workstation, AI box, Mac mini, dan mesin dev dari satu PC manager.",managerTitle:"1. Jalankan manager",managerBody:"Jalankan LiveDesk di komputer yang melihat layar. Manager membuka UI dan server lokal bersama, lalu membuka http://127.0.0.1:5179.",managerPoints:["Perintahnya npx -y livedesk.","Manager memakai 5179 untuk Screen Wall/API dan 5197 untuk koneksi client.","Jika proses lama memakai port itu, startup membersihkannya secara default."],clientTitle:"2. Hubungkan workstation",clientBody:"Di komputer yang dipantau, masuk dengan akun Google yang sama. Jika manager belum online, client tetap mencoba tiap 5 detik.",clientPoints:["npx -y livedesk client memakai slot kosong pertama.","npx -y livedesk client 3 mengunci mesin ke slot 3.","Client terus mencoba agar banyak PC tidak perlu login berulang."],syncTitle:"3. Sync Server dan discovery",syncBody:"Sync Server menerbitkan manager ini sebagai Screen Wall aktif untuk akun. Client membaca Supabase dan mencoba endpoint.",syncPoints:["Berisi host instance, alamat LAN/private, kandidat public, pair token, dan lease pendek.","Kandidat LAN dicoba lebih dulu, lalu public jika perlu.","Tekan Sync Server setelah perubahan manager, VPN, firewall, atau router.","Chrome Local Network Access di livedesk.pages.dev bukan jalur utama lagi. App npm manager adalah server sebenarnya."],platformTitle:"4. Status platform",platformBody:"Windows sudah diverifikasi dengan live screen transfer. macOS dan Linux mengikuti jalur npm yang sama.",platformPoints:["Windows: terverifikasi.","macOS: capture dan control perlu izin Screen Recording/Accessibility.","Linux: runtime linux-x64, capture grim/gnome-screenshot/import/scrot, dan input xdotool sudah ditambahkan. Audio belum aktif."],firewallTitle:"Firewall dan lokasi luar",firewallBody:"Di LAN yang sama biasanya tidak perlu port forwarding. Dari jaringan lain, client harus mencapai port client manager.",firewallPoints:["Port client: TCP 5197.","Mesin client biasanya hanya perlu akses keluar.","Untuk jaringan luar, izinkan TCP 5197 inbound di manager dan forward TCP 5197 ke PC manager.","Port 5179 untuk UI manager; buka hanya jika browser luar harus membuka Wall.","Utamakan VPN, Tailscale, ZeroTier, atau IP allowlist."],commandsTitle:"Perintah saat ini",commandsBody:"Arah produk adalah satu perintah terminal lintas OS, bukan download dan instal manual.",managerCommandLabel:"Mulai manager",clientCommandLabel:"Hubungkan workstation",slotCommandLabel:"Kunci ke slot 3",manualCommandLabel:"Koneksi manual lanjutan"}),vi:la({languageName:"Tiếng Việt",languageLabel:"Ngôn ngữ tài liệu",eyebrow:"LiveDesk Manual",title:"Mở Screen Wall cục bộ bằng một lệnh",intro:"LiveDesk là deck npm-first để giám sát nhiều workstation, máy AI, Mac mini và máy dev từ một PC manager.",managerTitle:"1. Chạy manager",managerBody:"Chạy LiveDesk trên máy dùng để xem màn hình. Manager khởi động UI và server cục bộ cùng lúc, rồi mở http://127.0.0.1:5179.",managerPoints:["Lệnh là npx -y livedesk.","Manager dùng 5179 cho Screen Wall/API và 5197 cho kết nối client.","Nếu tiến trình cũ giữ port, startup mặc định sẽ dọn và khởi động lại."],clientTitle:"2. Kết nối workstation",clientBody:"Trên mỗi máy được giám sát, đăng nhập cùng tài khoản Google. Nếu manager chưa online, client tiếp tục thử mỗi 5 giây.",clientPoints:["npx -y livedesk client dùng slot trống đầu tiên.","npx -y livedesk client 3 ghim máy vào slot 3.","Client tiếp tục chờ để nhiều máy không cần đăng nhập lại."],syncTitle:"3. Sync Server và tự phát hiện",syncBody:"Sync Server đăng manager này là Screen Wall đang hoạt động của tài khoản. Client đọc Supabase và thử các endpoint.",syncPoints:["Bao gồm host instance, địa chỉ LAN/private, public candidate, pair token và lease ngắn.","Ưu tiên LAN trước, sau đó thử public nếu cần.","Bấm Sync Server sau thay đổi manager, VPN, firewall hoặc router.","Chrome Local Network Access trên livedesk.pages.dev không còn là đường chạy chính. App npm manager mới là server thật."],platformTitle:"4. Trạng thái nền tảng",platformBody:"Windows đã được kiểm chứng với truyền màn hình live. macOS và Linux đi theo cùng đường npm.",platformPoints:["Windows: đã kiểm chứng.","macOS: capture và control cần quyền Screen Recording/Accessibility.","Linux: đã thêm runtime linux-x64, capture grim/gnome-screenshot/import/scrot và input xdotool. Audio chưa bật."],firewallTitle:"Firewall và địa điểm ngoài",firewallBody:"Trong cùng LAN thường không cần port forwarding. Từ mạng khác, client phải truy cập được port client của manager.",firewallPoints:["Port client: TCP 5197.","Máy client thường chỉ cần kết nối outbound.","Với mạng ngoài, cho phép TCP 5197 inbound trên manager và forward TCP 5197 tới PC manager.","Port 5179 dành cho UI manager; chỉ mở nếu trình duyệt từ xa cần mở Wall trực tiếp.","Ưu tiên VPN, Tailscale, ZeroTier hoặc allowlist IP cố định."],commandsTitle:"Lệnh hiện tại",commandsBody:"Hướng sản phẩm là một lệnh terminal dùng chung giữa các OS, thay vì tải và cài thủ công.",managerCommandLabel:"Khởi động manager",clientCommandLabel:"Kết nối workstation",slotCommandLabel:"Ghim vào slot 3",manualCommandLabel:"Kết nối thủ công nâng cao"}),th:la({languageName:"ไทย",languageLabel:"ภาษาของเอกสาร",eyebrow:"LiveDesk Manual",title:"เปิด Screen Wall ภายในด้วยคำสั่งเดียว",intro:"LiveDesk คือ deck แบบ npm-first สำหรับดู workstation, กล่อง AI, Mac mini และเครื่อง dev หลายเครื่องจาก manager PC เครื่องเดียว",managerTitle:"1. รัน manager",managerBody:"รัน LiveDesk บนเครื่องที่ใช้ดูหน้าจอ Manager จะเปิด UI และ local server พร้อมกัน แล้วเปิด http://127.0.0.1:5179",managerPoints:["คำสั่งคือ npx -y livedesk","Manager ใช้ 5179 สำหรับ Screen Wall/API และ 5197 สำหรับ client connection","ถ้า process เก่ายังใช้ port อยู่ startup จะล้างให้โดย default"],clientTitle:"2. เชื่อม workstation",clientBody:"บนเครื่องที่ต้อง monitor ให้ login ด้วย Google account เดียวกัน ถ้า manager ยังไม่ออนไลน์ client จะลองใหม่ทุก 5 วินาที",clientPoints:["npx -y livedesk client จะใช้ slot ว่างแรก","npx -y livedesk client 3 จะตรึงเครื่องไว้ที่ slot 3","Client จะรอต่อเนื่องเพื่อไม่ต้อง login ซ้ำเมื่อมีหลายเครื่อง"],syncTitle:"3. Sync Server และ discovery",syncBody:"Sync Server จะ publish manager นี้เป็น active Screen Wall ของ account แล้ว client อ่านข้อมูลจาก Supabase และลอง endpoint ต่างๆ",syncPoints:["มี host instance, LAN/private address, public candidate, pair token และ short lease","ลอง LAN ก่อน แล้วค่อยลอง public ถ้าจำเป็น","กด Sync Server หลังเปลี่ยน manager, VPN, firewall หรือ router","Chrome Local Network Access บน livedesk.pages.dev ไม่ใช่ runtime หลักแล้ว app npm manager คือ server จริง"],platformTitle:"4. สถานะ platform",platformBody:"Windows ตรวจสอบแล้วว่าส่งภาพ live ได้ macOS และ Linux ใช้เส้นทาง npm เดียวกัน",platformPoints:["Windows: verified","macOS: capture/control ต้องใช้สิทธิ์ Screen Recording/Accessibility","Linux: เพิ่ม linux-x64 runtime, grim/gnome-screenshot/import/scrot capture และ xdotool input แล้ว audio ยังปิดอยู่"],firewallTitle:"Firewall และเครื่องต่างสถานที่",firewallBody:"ใน LAN เดียวกันปกติไม่ต้อง port forwarding ถ้าอยู่คนละ network client ต้องเข้าถึง client port ของ manager ได้",firewallPoints:["Client port คือ TCP 5197","เครื่อง client ปกติต้องการ outbound เท่านั้น","ถ้าอยู่นอก network ให้เปิด TCP 5197 inbound ที่ manager และ forward TCP 5197 ไปยัง manager PC","Port 5179 เป็น UI ของ manager เปิดเฉพาะเมื่อ browser ระยะไกลต้องเปิด Wall โดยตรง","ควรใช้ VPN, Tailscale, ZeroTier หรือ IP allowlist ก่อนเปิดสู่ public internet"],commandsTitle:"คำสั่งปัจจุบัน",commandsBody:"ทิศทาง product คือคำสั่ง terminal เดียวข้าม OS ไม่ใช่ download/install จากเว็บไซต์",managerCommandLabel:"เริ่ม manager",clientCommandLabel:"เชื่อม workstation",slotCommandLabel:"ตรึง slot 3",manualCommandLabel:"manual connection ขั้นสูง"}),hi:la({languageName:"हिन्दी",languageLabel:"दस्तावेज़ भाषा",eyebrow:"LiveDesk Manual",title:"एक कमांड से local Screen Wall खोलें",intro:"LiveDesk एक npm-first remote work deck है जिससे एक manager PC से कई workstation, AI box, Mac mini और dev machines देखे जा सकते हैं।",managerTitle:"1. manager चलाएं",managerBody:"जिस computer से screens देखनी हैं उस पर LiveDesk manager चलाएं। यह UI और local server साथ में शुरू करता है और http://127.0.0.1:5179 खोलता है।",managerPoints:["कमांड है npx -y livedesk।","Manager Screen Wall/API के लिए 5179 और client connections के लिए 5197 इस्तेमाल करता है।","अगर पुराने LiveDesk ports बचे हों तो startup default रूप से साफ करता है।"],clientTitle:"2. workstation जोड़ें",clientBody:"हर monitored computer पर उसी Google account से sign in करें। Manager online न हो तब भी client बंद नहीं होता और हर 5 सेकंड retry करता है।",clientPoints:["npx -y livedesk client पहला खाली slot लेता है।","npx -y livedesk client 3 machine को slot 3 पर pin करता है।","बहुत सी machines हों तब भी बार-बार login की जरूरत नहीं रहती।"],syncTitle:"3. Sync Server और discovery",syncBody:"Sync Server इस manager को account का active Screen Wall बनाकर Supabase में publish करता है। Clients record पढ़कर endpoints try करते हैं।",syncPoints:["इसमें host instance, LAN/private addresses, public candidates, pair token और short lease होता है।","LAN candidates पहले try होते हैं, जरूरत हो तो public candidates।","Manager, VPN, firewall या router बदलने के बाद Sync Server दबाएं।","livedesk.pages.dev का Chrome Local Network Access अब default runtime नहीं है। npm manager app ही real server है।"],platformTitle:"4. Platform status",platformBody:"Windows live screen transfer के साथ verified है। macOS और Linux भी इसी npm path पर आगे बढ़ रहे हैं।",platformPoints:["Windows: verified.","macOS: capture/control के लिए Screen Recording/Accessibility permissions चाहिए।","Linux: linux-x64 runtime, grim/gnome-screenshot/import/scrot capture और xdotool input backend जोड़े गए हैं। Audio अभी disabled है।"],firewallTitle:"Firewall और remote locations",firewallBody:"Same LAN में आम तौर पर router forwarding जरूरी नहीं। दूसरे network से clients को manager client port तक पहुंचना होगा।",firewallPoints:["Client connection port: TCP 5197.","Client machines को आम तौर पर सिर्फ outbound access चाहिए।","Remote network के लिए manager firewall में TCP 5197 inbound allow करें और router से TCP 5197 manager PC पर forward करें।","5179 manager UI port है; इसे तभी expose करें जब remote browser को Wall खोलना हो।","Public internet से पहले VPN, Tailscale, ZeroTier या fixed IP allowlist बेहतर है।"],commandsTitle:"Current commands",commandsBody:"Product direction है OS के बीच एक terminal command, website से download/install नहीं।",managerCommandLabel:"Start manager",clientCommandLabel:"Connect workstation",slotCommandLabel:"Pin to slot 3",manualCommandLabel:"Advanced manual connection"}),ar:la({languageName:"العربية",languageLabel:"لغة المستند",eyebrow:"LiveDesk Manual",title:"افتح Screen Wall محلي بأمر واحد",intro:"LiveDesk هو deck بنمط npm-first لمراقبة عدة workstations وأجهزة AI وMac mini وأجهزة تطوير من كمبيوتر manager واحد.",managerTitle:"1. شغل manager",managerBody:"شغل LiveDesk على الكمبيوتر الذي سيعرض الشاشات. يبدأ manager الواجهة والخادم المحلي معا ويفتح http://127.0.0.1:5179.",managerPoints:["الأمر هو npx -y livedesk.","يستخدم manager المنفذ 5179 للواجهة/API والمنفذ 5197 لاتصالات client.","إذا بقيت عملية LiveDesk قديمة على المنافذ، يتم تنظيفها افتراضيا عند التشغيل."],clientTitle:"2. وصل workstation",clientBody:"على كل كمبيوتر تتم مراقبته، سجل الدخول بنفس حساب Google. إذا لم يكن manager متاحا، يبقى client يعمل ويحاول كل 5 ثوان.",clientPoints:["npx -y livedesk client يختار أول slot فارغ.","npx -y livedesk client 3 يثبت الجهاز في slot 3.","clients تستمر بالمحاولة لتجنب تكرار تسجيل الدخول عند كثرة الأجهزة."],syncTitle:"3. Sync Server والاكتشاف",syncBody:"Sync Server ينشر هذا manager كـ active Screen Wall للحساب. يقرأ clients سجل Supabase ويجربون endpoints بالترتيب.",syncPoints:["السجل يتضمن host instance وعناوين LAN/private وpublic candidates وpair token وlease قصير.","يتم تفضيل LAN أولا، ثم public عند الحاجة.","اضغط Sync Server بعد تغيير manager أو VPN أو firewall أو router.","Chrome Local Network Access على livedesk.pages.dev لم يعد مسار التشغيل الافتراضي. تطبيق npm manager هو الخادم الحقيقي."],platformTitle:"4. حالة المنصات",platformBody:"Windows تم التحقق منه مع نقل شاشة live. macOS وLinux يتبعان نفس مسار npm.",platformPoints:["Windows: تم التحقق.","macOS: capture/control يحتاجان أذونات Screen Recording/Accessibility.","Linux: تمت إضافة linux-x64 runtime وgrim/gnome-screenshot/import/scrot capture وxdotool input. الصوت ما زال معطلا."],firewallTitle:"Firewall والمواقع البعيدة",firewallBody:"داخل نفس LAN غالبا لا تحتاج port forwarding. من شبكة أخرى يجب أن يصل client إلى منفذ manager client.",firewallPoints:["منفذ client: TCP 5197.","أجهزة client تحتاج عادة اتصال outbound فقط.","للشبكات البعيدة، اسمح TCP 5197 inbound على manager ووجه TCP 5197 من router إلى manager PC.","المنفذ 5179 مخصص لواجهة manager؛ اكشفه فقط إذا كان متصفح بعيد يحتاج فتح Wall مباشرة.","يفضل VPN أو Tailscale أو ZeroTier أو fixed IP allowlist بدل التعريض العام."],commandsTitle:"الأوامر الحالية",commandsBody:"اتجاه المنتج هو أمر terminal واحد عبر الأنظمة، وليس تحميل وتثبيت يدوي من موقع.",managerCommandLabel:"Start manager",clientCommandLabel:"Connect workstation",slotCommandLabel:"Pin to slot 3",manualCommandLabel:"Advanced manual connection"}),tr:la({languageName:"Türkçe",languageLabel:"Belge dili",eyebrow:"LiveDesk Manual",title:"Yerel Screen Wall tek komutla açılsın",intro:"LiveDesk, tek bir manager PC üzerinden birçok workstation, AI box, Mac mini ve dev machine izlemek için npm-first bir çalışma deckidir.",managerTitle:"1. Manager çalıştır",managerBody:"Ekranları izleyecek bilgisayarda LiveDesk manager çalıştır. Manager UI ve local server birlikte başlar ve http://127.0.0.1:5179 açılır.",managerPoints:["Komut: npx -y livedesk.","Manager Screen Wall/API için 5179, client bağlantıları için 5197 kullanır.","Eski LiveDesk process portları tutuyorsa başlangıç varsayılan olarak temizler."],clientTitle:"2. Workstation bağla",clientBody:"İzlenecek bilgisayarda aynı Google hesabıyla giriş yap. Manager henüz online değilse client kapanmaz ve her 5 saniyede tekrar dener.",clientPoints:["npx -y livedesk client ilk boş slota yerleşir.","npx -y livedesk client 3 makineyi slot 3’e sabitler.","Çok makinede tekrar tekrar login gerekmesin diye client beklemeye devam eder."],syncTitle:"3. Sync Server ve discovery",syncBody:"Sync Server bu managerı hesabın active Screen Wall kaydı olarak Supabase’e yazar. Clients bu kaydı okuyup endpoint adaylarını dener.",syncPoints:["Host instance, LAN/private adresler, public adaylar, pair token ve kısa lease içerir.","Önce LAN adayları, gerekirse public adaylar denenir.","Manager, VPN, firewall veya router değişince Sync Server’a bas.","livedesk.pages.dev üzerindeki Chrome Local Network Access artık default runtime yolu değil. Gerçek server npm manager app."],platformTitle:"4. Platform durumu",platformBody:"Windows live screen transfer ile doğrulandı. macOS ve Linux aynı npm yolunu takip ediyor.",platformPoints:["Windows: doğrulandı.","macOS: capture/control için Screen Recording/Accessibility izinleri gerekir.","Linux: linux-x64 runtime, grim/gnome-screenshot/import/scrot capture ve xdotool input backend eklendi. Audio kapalı."],firewallTitle:"Firewall ve uzak konumlar",firewallBody:"Aynı LAN içinde genelde router forwarding gerekmez. Başka ağdan clients manager client portuna ulaşabilmelidir.",firewallPoints:["Client port: TCP 5197.","Client makineler normalde sadece outbound erişim ister.","Uzak ağ için manager firewall üzerinde TCP 5197 inbound aç ve routerdan TCP 5197yi manager PCye forward et.","5179 manager UI portudur; sadece uzak browser Wall açacaksa expose et.","Public internet yerine VPN, Tailscale, ZeroTier veya sabit IP allowlist tercih et."],commandsTitle:"Güncel komutlar",commandsBody:"Ürün yönü, webden indirip kurmak yerine işletim sistemleri arasında ortak tek terminal komutu.",managerCommandLabel:"Manager başlat",clientCommandLabel:"Workstation bağla",slotCommandLabel:"Slot 3’e sabitle",manualCommandLabel:"Gelişmiş manuel bağlantı"})},RT=Object.entries(Oo).map(([n,a])=>({id:n,label:a.languageName}));function DT(){if(typeof navigator>"u")return"en";const n=navigator.languages?.length?navigator.languages:[navigator.language];for(const a of n){const r=a.toLowerCase();if(Oo[a])return a;if(r.startsWith("zh-tw")||r.startsWith("zh-hk"))return"zh-TW";if(r.startsWith("pt"))return"pt-BR";const l=r.split("-")[0];if(Oo[l])return l}return"en"}function Py({index:n}){const a=n+1;return s.jsx("article",{className:"device-tile placeholder-tile","aria-label":`Empty slot ${a}`,children:s.jsxs("div",{className:"tile-screen","aria-hidden":"true",children:[s.jsx("span",{className:"slot-grid","aria-hidden":"true"}),s.jsxs("span",{className:"empty-screen",children:[s.jsx(Yt,{size:24}),s.jsxs("strong",{children:["Slot ",String(a).padStart(3,"0")]})]})]})})}const LT=["cpu","gpu","memory","vram","network","disk","temp"];function _T({device:n,slotNumber:a,selected:r,updateIndicator:l,onSelect:c,onOpenControl:d}){const m=jw(n),p=new Map(m.metrics.map(g=>[g.id,g])),v=l?.label||m.label;return s.jsxs("div",{className:`wall-device-list-row state-${m.state} ${r?"selected":""}`,role:"row","aria-selected":r,tabIndex:0,onClick:c,onDoubleClick:g=>{g.preventDefault(),d()},onKeyDown:g=>{(g.key==="Enter"||g.key===" ")&&(g.preventDefault(),c())},children:[s.jsxs("span",{className:"wall-device-name",role:"gridcell",children:[s.jsx("span",{className:"wall-device-icon","aria-hidden":"true",children:s.jsx(Yt,{size:17})}),s.jsxs("span",{children:[s.jsx("strong",{children:Ka(n)}),s.jsxs("small",{children:["Slot ",String(a).padStart(3,"0"),n.platform?` · ${n.platform}`:"",n.arch?` · ${n.arch}`:""]})]}),r&&s.jsx(ri,{size:16,strokeWidth:3,"aria-label":"Selected"})]}),s.jsxs("span",{className:`wall-device-list-status state-${m.state} ${l?`update-${l.state}`:""}`,role:"gridcell",title:l?.error||v,children:[s.jsx("i",{"aria-hidden":"true"}),s.jsx("strong",{children:v})]}),LT.map(g=>{const w=p.get(g);return s.jsxs("span",{className:`wall-device-list-metric state-${w?.state||"unknown"}`,role:"gridcell",title:w?`${w.label}: ${w.value} · ${w.detail}`:"Not reported",children:[s.jsx("strong",{children:w?.value||"-"}),s.jsx("small",{children:w?.detail||"not reported"}),w?.ratio!==void 0&&s.jsx("i",{style:{width:`${Math.round(w.ratio*100)}%`},"aria-hidden":"true"})]},g)})]})}function zT(n){if(!n)return!1;const a=String(n.platform||"").trim().toLowerCase();return qi(a)&&n.capabilities?.screenRecordingPermission===!1}function qi(n){const a=String(n||"").trim().toLowerCase();return a==="macos"||a==="darwin"||a==="mac"||a==="macosx"}function $y(n){if(!n)return!1;const a=String(n.capabilities?.liveCaptureConcurrency||"").trim().toLowerCase();return a==="exclusive"?!0:a==="parallel"?!1:qi(n.platform)}function kh({device:n,frame:a,selected:r,controlEnabled:l,showStatus:c,monitorIndex:d,monitorCount:m,onSelect:p,onFocusDevice:v,onOpenControl:g,onCycleMonitor:w,onCanvasReady:y,sendInput:b,updateIndicator:C,presentationReady:j,showPresentationSpinner:A=!1}){const N=u.useRef(null),k=u.useRef(null),T=u.useRef(0),R=u.useRef(null),q=jw(n),O=["cpu","gpu","memory","vram"].map($=>q.metrics.find(de=>de.id===$)).filter($=>!!$),Y=za(d,m),_=m>1,L=j??!!a,ae=zT(n)&&!L,G=A&&n.connected&&!L&&!ae,te=uT(n,a,Y),P=te>=Bd?100:te/Bd*100,ye=te>=Bd?Bd/te*100:100,ie={"--screen-aspect":te.toFixed(5),"--screen-content-width":`${Math.max(1,Math.min(100,P)).toFixed(3)}%`,"--screen-content-height":`${Math.max(1,Math.min(100,ye)).toFixed(3)}%`},K=u.useCallback($=>{N.current=$,y(n.deviceId,$)},[n.deviceId,y]),I=$=>{const de=$.currentTarget.getBoundingClientRect();return Ej($.clientX,$.clientY,de)},Q=$=>({shiftKey:$.shiftKey,ctrlKey:$.ctrlKey,altKey:$.altKey,metaKey:$.metaKey}),U=u.useCallback(()=>{R.current!==null&&(window.cancelAnimationFrame(R.current),R.current=null)},[]),W=u.useCallback(()=>{const $=k.current;if(!$)return;k.current=null;const de=Number($.input.normalizedX),me=Number($.input.normalizedY);if(!Number.isFinite(de)||!Number.isFinite(me))return;b(n.deviceId,{...$.input,normalizedX:de,normalizedY:me})&&(T.current=performance.now())},[n.deviceId,b]),ue=u.useCallback(()=>{R.current===null&&(R.current=window.requestAnimationFrame(()=>{R.current=null,W()}))},[W]);u.useEffect(()=>()=>{U(),k.current=null},[U]);const be=($,de)=>{if(!l)return;const me={type:de,monitorIndex:Y,...I($),button:ST($.button),...Q($)};if(de==="pointermove"){const ve=performance.now();k.current={input:me},ve-T.current>=zM&&(U(),W()),ue();return}k.current&&(U(),W()),b(n.deviceId,me)},X=u.useCallback($=>{const de=document.activeElement;de instanceof HTMLElement&&$.contains(de)&&de.classList.contains("monitor-cycle-button")&&de.blur()},[]);return s.jsx("article",{className:`device-tile ${r?"selected":""} ${n.connected?"online":"offline"}`,"data-live-device-id":n.deviceId,style:ie,children:s.jsxs("div",{className:`tile-screen ${L?"has-frame":"is-empty"}`,role:"button",tabIndex:l?-1:0,"aria-pressed":r,onClick:$=>{$.target instanceof Element&&$.target.closest(".monitor-cycle")||l||p()},onKeyDown:$=>{$.target instanceof Element&&$.target.closest(".monitor-cycle")||l||($.key==="Enter"||$.key===" ")&&($.preventDefault(),p())},onDoubleClick:$=>{$.target instanceof Element&&$.target.closest(".monitor-cycle")||($.preventDefault(),g())},onPointerLeave:$=>X($.currentTarget),children:[s.jsx("span",{className:`screen-content ${L?"has-frame":"is-empty"}`,children:s.jsx("canvas",{ref:K,className:`remote-canvas ${L?"has-frame":"is-empty"}`,tabIndex:l?0:-1,onPointerDown:$=>{l&&($.preventDefault(),$.stopPropagation(),v(),$.currentTarget.focus(),$.currentTarget.setPointerCapture($.pointerId),be($,"pointerdown"))},onPointerMove:$=>{l&&$.preventDefault(),be($,"pointermove")},onPointerLeave:$=>{l&&(be($,"pointermove"),U(),W())},onPointerUp:$=>{l&&($.preventDefault(),$.stopPropagation(),be($,"pointerup"),$.currentTarget.hasPointerCapture($.pointerId)&&$.currentTarget.releasePointerCapture($.pointerId))},onPointerCancel:$=>{$.currentTarget.hasPointerCapture($.pointerId)&&$.currentTarget.releasePointerCapture($.pointerId)},onWheel:$=>{l&&($.preventDefault(),b(n.deviceId,{type:"wheel",monitorIndex:Y,...I($),deltaX:$.deltaX,deltaY:$.deltaY,...Q($)}))},onKeyDown:$=>{l&&($.preventDefault(),$.stopPropagation(),b(n.deviceId,{type:"keydown",monitorIndex:Y,key:$.key,code:$.code,keyCode:$.keyCode||$.which||0,location:$.location,text:$.key.length===1?$.key:"",repeat:$.repeat,...Q($)}))},onKeyUp:$=>{l&&($.preventDefault(),$.stopPropagation(),b(n.deviceId,{type:"keyup",monitorIndex:Y,key:$.key,code:$.code,keyCode:$.keyCode||$.which||0,location:$.location,text:$.key.length===1?$.key:"",repeat:!1,...Q($)}))},onContextMenu:$=>l&&$.preventDefault()})}),!L&&s.jsx("span",{className:"empty-screen",children:s.jsx(Yt,{size:26})}),G&&s.jsxs("span",{className:"wall-presentation-loading",role:"status","aria-live":"polite",children:[s.jsx("span",{className:"wall-presentation-spinner","aria-hidden":"true"}),s.jsx("strong",{children:"Preparing video"})]}),ae&&s.jsxs("span",{className:"wall-presentation-loading permission-required",role:"status","aria-live":"polite",children:[s.jsx(Lt,{size:24,"aria-hidden":"true"}),s.jsx("strong",{children:"Screen Recording permission required"}),s.jsx("small",{children:"Allow the terminal app on this Mac, then restart LiveDesk."})]}),C&&s.jsxs("span",{className:`wall-update-status state-${C.state}`,role:"status","aria-live":"polite",title:C.error||C.label,children:[C.state==="updated"?s.jsx(Hn,{size:20,"aria-hidden":"true"}):C.state==="failed"?s.jsx(Ha,{size:22,"aria-hidden":"true"}):C.state==="offline"?s.jsx(Hl,{size:22,"aria-hidden":"true"}):s.jsx("span",{className:"wall-update-spinner","aria-hidden":"true"}),s.jsx("strong",{children:C.label}),C.error?s.jsx("small",{children:C.error}):null]}),c&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:`tile-health-pill state-${q.state}`,children:q.label}),s.jsx("span",{className:"tile-metrics","aria-label":`${Ka(n)} status`,children:O.map($=>s.jsxs("span",{className:`tile-metric state-${$.state}`,children:[s.jsx("b",{children:$.label}),s.jsx("em",{children:$.value}),$.ratio!==void 0&&s.jsx("i",{style:{width:`${Math.round($.ratio*100)}%`}})]},$.id))})]}),_&&s.jsxs("span",{className:"monitor-cycle","aria-label":`${Ka(n)} display ${Y+1} of ${m}`,onPointerDown:$=>$.stopPropagation(),onClick:$=>$.stopPropagation(),onDoubleClick:$=>$.stopPropagation(),children:[s.jsx("button",{className:"monitor-cycle-button previous",onClick:$=>{$.preventDefault(),$.stopPropagation(),w(-1),$.currentTarget.blur()},title:"Previous display",type:"button",children:s.jsx(Jy,{size:18})}),s.jsxs("span",{className:"monitor-cycle-count",children:["Screen ",Y+1,"/",m]}),s.jsx("button",{className:"monitor-cycle-button next",onClick:$=>{$.preventDefault(),$.stopPropagation(),w(1),$.currentTarget.blur()},title:"Next display",type:"button",children:s.jsx(ep,{size:18})})]}),r&&s.jsx("span",{className:"device-selection-check","aria-hidden":"true",children:s.jsx(ri,{size:23,strokeWidth:3.5})})]})})}function IT({visible:n}){return u.useEffect(()=>{if(!n||!ph)return;if(!document.getElementById(Sy)){const r=document.createElement("script");r.id=Sy,r.async=!0,r.crossOrigin="anonymous",r.src=`https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=${encodeURIComponent(Gh)}`,document.head.appendChild(r)}const a=window.setTimeout(()=>{try{window.adsbygoogle=window.adsbygoogle||[],window.adsbygoogle.push({})}catch{}},120);return()=>window.clearTimeout(a)},[n]),n?s.jsxs("aside",{className:`free-ad-banner ${ph?"adsense-ready":"house-ad"}`,"aria-label":"Advertisement",children:[s.jsx("span",{className:"ad-label",children:"Advertisement"}),ph?s.jsx("ins",{className:"adsbygoogle livedesk-ad-unit",style:{display:"block"},"data-ad-client":Gh,"data-ad-slot":gw,"data-ad-format":"auto","data-full-width-responsive":"true"}):s.jsxs("div",{className:"house-ad-copy",children:[s.jsx("strong",{children:"Sponsored placement"}),s.jsx("span",{children:"Local AI gear, mini PCs, GPUs, NAS, and developer tools."})]})]}):null}function OT(){const{session:n,loading:a}=oj(),{target:r,error:l,refresh:c}=uj(n),d=u.useMemo(()=>{if(!r?.active)return null;const x=r.expires_at?Date.parse(r.expires_at):Number.POSITIVE_INFINITY;return Number.isFinite(x)&&x<=Date.now()?null:r},[r]),m=u.useMemo(()=>xx(d),[d]),p=u.useMemo(()=>m.length>0?[...new Set([...m,Cn])]:[Cn],[m]),[v,g]=u.useState(rT),w=u.useMemo(()=>p.some(x=>!!qc(x)),[p]),y=!w||v,{status:b,devices:C,error:j,refresh:A,hubBaseUrl:N}=cj(p,y),{entitlement:k,licensed:T,loading:R,error:q,refresh:O}=dj(n),[Y,_]=u.useState([]),[L,ae]=u.useState(""),[G,te]=u.useState(""),[P,ye]=u.useState(""),[ie,K]=u.useState(""),[I,Q]=u.useState(""),[U,W]=u.useState("idle"),[ue,be]=u.useState(!1),[X,$]=u.useState(null),[de,me]=u.useState(""),ve=u.useRef("");ve.current=ie;const[Se,Oe]=u.useState(!1),[le,Z]=u.useState(!1),He=u.useRef(""),_e=u.useRef(new Map),se=u.useRef(0),[fe,Ne]=u.useState(""),[Te,Be]=u.useState(""),[$e,et]=u.useState(!1),Mt=u.useRef(null),ke=u.useRef(null),[Ye,rt]=u.useState(null);u.useEffect(()=>{fe==="auth"&&n?.access_token&&Ne("")},[fe,n?.access_token]);const[vt,vn]=u.useState(""),[It,Zt]=u.useState(null),ht=u.useRef(null),$n=u.useRef(0),Gt=u.useCallback((x,M,D)=>{const B=String(x||"").trim();if(vn(B),ht.current!==null&&(window.clearTimeout(ht.current),ht.current=null),!B){Zt(null);return}const z=++$n.current;if(Zt({id:z,message:B,tone:M}),!D)return;const ge=window.setTimeout(()=>{Zt(pe=>pe?.id===z?null:pe),ht.current===ge&&(ht.current=null)},5e3);ht.current=ge},[]),J=u.useCallback((x,M="info")=>{Gt(x,M,!0)},[Gt]),Re=u.useCallback(x=>{Gt(x,"progress",!1)},[Gt]);u.useEffect(()=>()=>{ht.current!==null&&window.clearTimeout(ht.current)},[]);const[ze,je]=u.useState(()=>typeof window<"u"&&window.location.pathname.startsWith("/support")?"support":"wall");u.useEffect(()=>{const x=()=>{je(window.location.pathname.startsWith("/support")?"support":M=>M==="support"?"wall":M)};return window.addEventListener("popstate",x),()=>window.removeEventListener("popstate",x)},[]);const[Xe,gt]=u.useState("large"),[Ee,ua]=u.useState(DT),[Un,tt]=u.useState(!1),[$t,an]=u.useState(!1),[Za,Ja]=u.useState(!1),[Xn,Wi]=u.useState(iT),[Fe,Is]=u.useState(mT),[ut,ui]=u.useState(pT),[Kt,H]=u.useState(dT),[De,st]=u.useState(null),[on,es]=u.useState([]),[Tn,da]=u.useState(Fe.fps),[ne,Ae]=u.useState(""),[qe,ot]=u.useState(0),[Jt,Ut]=u.useState(0),[Ze,jt]=u.useState(()=>new Set),Ot=u.useRef(new Map),Vt=u.useRef(new Map),sn=u.useRef(new Map),wt=u.useRef(new Map),cn=u.useRef(new Map),Tt=u.useRef(new Set),ts=u.useRef(new Map),xn=u.useRef(""),un=u.useRef(""),dn=u.useRef(null),Os=u.useRef(null),ya=u.useRef(new Map),Hs=u.useRef(null),Po=u.useRef(0),Yi=u.useRef(new Map),[Ki,ms]=u.useState({}),Zn=u.useRef(new Map),[$l,bf]=u.useState({}),[Ul,ba]=u.useState(!1),Qi=u.useRef(null),ns=u.useRef(null),Qt=u.useRef(0),hs=u.useRef(""),Xi=u.useRef(new Map),di=u.useRef(new Map),ps=u.useRef(performance.now()),Zi=u.useRef(new Map),fi=u.useRef(new Map),Fa=u.useRef(new Map),$o=u.useRef(new Map),Ji=u.useRef(0),Yr=u.useRef(0),er=u.useRef(0),ql=u.useRef(0),Uo=u.useRef(0),Kr=u.useRef(new Map),Ln=u.useRef(new Map),[gs,as]=u.useState(null),[tr,Bs]=u.useState(!1),[wf,qo]=u.useState([]),[mi,Qr]=u.useState("all"),[Jn,Xr]=u.useState([]),[Gl,hi]=u.useState(!1),[au,Vl]=u.useState(!0),Go=u.useRef(null),Zr=u.useRef(null),Wl=u.useRef(null),su=u.useRef(null),ea=u.useRef(!1),vs=u.useRef(!1),nr=u.useRef(!1),xs=u.useRef(0),Fs=u.useRef(0),ar=ze==="settings",Yl=ze==="pricing",sr=ze==="doc",Jr=ze==="support",ir=ze==="share-files",Vo=ze==="agents",iu=!ar&&!Yl&&!sr&&!Jr&&!ir&&!Vo,it=ze==="control",ct=Fe.frameMode==="mode4-h264-atlas",wa=I||ut.frameMode,rr=wa!=="mode3-h264-hw"?Math.min(30,ut.fps):ut.fps,Ps=wa!=="mode3-h264-hw"?{maxWidth:Math.min(1920,ut.maxWidth),maxHeight:Math.min(1080,ut.maxHeight)}:{maxWidth:ut.maxWidth,maxHeight:ut.maxHeight};u.useEffect(()=>{if(b?.started){if(!n?.access_token){Ge("/api/remote/license",{method:"DELETE"},N).catch(()=>{});return}Ge("/api/remote/license/sync",{method:"POST",headers:{Authorization:`Bearer ${n.access_token}`}},N).catch(x=>{console.warn("[LiveDesk] Hub license sync failed",x)})}},[k?.updated_at,N,n?.access_token,b?.started]),u.useEffect(()=>{!n?.access_token||!b?.started||b.runtimeRole!=="hub"||!b.deviceId||(async()=>{try{const{data:x,error:M}=await mt.rpc("register_livedesk_device",{p_device_id:b.deviceId,p_device_name:b.deviceName||b.deviceId,p_role:"hub",p_assigned_hub_id:null,p_platform:navigator.platform||navigator.userAgent,p_os_version:navigator.userAgent,p_app_version:b.managerVersion||b.managerPackage||""}),D=Array.isArray(x)?x[0]:x;(M||D?.ok===!1)&&console.warn("[LiveDesk] Hub device role registration failed",M||D?.reason||"unknown-error")}catch(x){console.warn("[LiveDesk] Hub device role registration failed",x)}})()},[n?.access_token,b?.deviceId,b?.deviceName,b?.managerPackage,b?.managerVersion,b?.runtimeRole,b?.started]),u.useEffect(()=>{!n?.access_token||!n.refresh_token||!b?.started||b.runtimeRole!=="hub"||nr.current||(nr.current=!0,Ge("/api/auth/session",{method:"POST",body:JSON.stringify({accessToken:n.access_token,refreshToken:n.refresh_token,expiresAt:n.expires_at,user:{id:n.user.id,email:n.user.email}})},N||Cn).then(x=>{x.hostTarget?.ok===!1&&console.warn("[LiveDesk] Hub host target publish is waiting for a valid Hub role:",x.hostTarget.error||"unknown-error"),A()}).catch(x=>{console.warn("[LiveDesk] Hub session sync failed:",x)}).finally(()=>{nr.current=!1}))},[N,A,n?.access_token,n?.expires_at,n?.refresh_token,n?.user?.email,n?.user?.id,b?.runtimeRole,b?.started]);const at=u.useMemo(()=>C.filter(x=>x.connected),[C]),ru=mi==="all"?at.length:Jn.filter(x=>at.some(M=>M.deviceId===x)).length,lu=u.useMemo(()=>at.reduce((x,M)=>Math.max(x,Fy(M.slotNumber)),0),[at]),Kl=Math.max(DM,at.length,lu),pi=u.useMemo(()=>{const x=Array(Kl).fill(null),M=[];for(const D of at){const B=Fy(D.slotNumber);B>0&&B<=Kl&&!x[B-1]?x[B-1]=D:M.push(D)}for(const D of M){const B=x.findIndex(z=>!z);B<0?x.push(D):x[B]=D}return x},[at]),ou=u.useMemo(()=>pi.flatMap((x,M)=>x?[{device:x,slotNumber:M+1}]:[]),[pi]),Wo=u.useMemo(()=>at.map(x=>x.deviceId),[at]),ys=u.useMemo(()=>new Set(Y),[Y]),fa=u.useMemo(()=>at.filter(x=>ys.has(x.deviceId)),[at,ys]),lr=u.useMemo(()=>C.find(x=>x.deviceId===L)||fa[0]||null,[C,L,fa]),qn=u.useMemo(()=>C.find(x=>x.deviceId===G)||null,[G,C]),bs=qn?za(Kt[qn.deviceId],va(qn)):0,Le=it?qn:lr,cu=u.useMemo(()=>new Set(Jn),[Jn]),Sf=u.useMemo(()=>mi==="all"?at.map(x=>x.deviceId):at.filter(x=>cu.has(x.deviceId)).map(x=>x.deviceId),[at,cu,mi]),Cf=Le?Wc(Le,"control"):!1,Yo=qi(Le?.platform)&&(Le?.capabilities?.controlPermission===!1||Le?.capabilities?.accessibilityPermission===!1),el=Le?Wc(Le,"audio")||Wc(Le,"remoteAudio"):!1,uu=Array.isArray(Le?.capabilities?.agentTools)?Le.capabilities.agentTools.map(String):[],du=uu.includes("system.power"),fu=uu.includes("command.run"),Ht=T?k?.plan==="pro"?"pro":"ltd":"free",or=El[Ht],Ql=or.limit,gi=u.useMemo(()=>{if(!Number.isFinite(Ql))return new Set(at.map(M=>M.deviceId));const x=Le?[Le,...at.filter(M=>M.deviceId!==Le.deviceId)]:at;return new Set(x.slice(0,Ql).map(M=>M.deviceId))},[Ql,at,Le]),mu=!Le||gi.has(Le.deviceId),hu=Ht==="free",Wt=mu,cr=Ht==="ltd"?`Plus includes up to ${Bc} workstations. Upgrade to Pro for commercial use and larger walls.`:`Free includes up to ${Hc} workstations. Upgrade to Plus for ${Bc} devices and no ads.`,ur=Ht==="free",ws=Wt&&!!Le&&Cf,pu=Wt&&!!Le&&el,Xl=u.useMemo(()=>pi.filter(x=>!!x?.connected).slice(0,vT(Xe)).map(x=>x.deviceId),[pi,Xe]),tl=u.useMemo(()=>Xe==="list"?[]:ct?Wo:Fe.visibleOnlyLive?on.length>0?on:Xl:Wo,[Xl,ct,on,Fe.visibleOnlyLive,Wo,Xe]),Sa=u.useMemo(()=>wh(tl.filter(x=>gi.has(x))),[gi,tl]),Ca=u.useMemo(()=>Sa.filter(x=>x!==ne),[Sa,ne]),$s=u.useMemo(()=>new Map(at.map(x=>[x.deviceId,x.platform])),[at]),ss=Rj(ct,Sa.length),Gn=u.useMemo(()=>ct?Ca.filter(x=>zc({mode4Enabled:ct,directMode4WallEnabled:ss,isMac:qi($s.get(x))})==="atlas"):[],[ss,ct,$s,Ca]),ta=u.useMemo(()=>Ca.filter(x=>zc({mode4Enabled:ct,directMode4WallEnabled:ss,isMac:qi($s.get(x))})==="direct"),[ss,ct,$s,Ca]);u.useEffect(()=>{const x=new Set(Sa);jt(M=>{let D=!1;const B=new Set;for(const z of M)x.has(z)?B.add(z):D=!0;return D?B:M})},[Sa]);const gu=u.useMemo(()=>{const x=z=>at.find(ge=>ge.deviceId===z)||null,M=z=>za(Kt[z],x(z)?va(x(z)):0),D=(z,ge=M(z))=>z===P&&(U==="connecting"||U==="active"||U==="warm")?wt.current.get(z)||Vt.current.get(z)||null:ct?ya.current.get(z)||Ot.current.get(z)||null:Ot.current.get(z)||null,B=(z,ge=M(z))=>{const pe=x(z);return`${pe?Ka(pe):z} · Monitor ${ge+1}`};return{resolveCurrentTarget(){if(it&&qn){const Ue=bs;return{type:"control",deviceIds:[qn.deviceId],monitorIndex:Ue,label:`${Ka(qn)} · Monitor ${Ue+1}`,sourceCanvas:D(qn.deviceId,Ue),signature:`control:${qn.deviceId}:${Ue}:${ut.frameMode}`}}const z=fa.map(Ue=>Ue.deviceId).filter(Ue=>Ca.includes(Ue)),ge=lr&&Ca.includes(lr.deviceId)?lr.deviceId:"",pe=z.length>0?z:ge?[ge]:Ca,Ie=z.length===0&&!ge;if(pe.length===0)return null;if(pe.length===1){const Ue=pe[0],Ke=M(Ue);return{type:Ie?"wall":z.length>1?"selection":"device",deviceIds:pe,monitorIndex:Ke,label:Ie?"Wall":B(Ue,Ke),sourceCanvas:Ie?null:D(Ue,Ke),signature:`${Ie?"wall":"device"}:${Ue}:${Ke}:${ct?"atlas":"direct"}`}}return{type:z.length>1?"selection":"wall",deviceIds:pe,label:z.length>1?`${pe.length} selected workstations`:"Wall",sourceCanvas:null,signature:`${z.length>1?"selection":"wall"}:${pe.join(",")}:${Xe}`}},getDeviceCanvas:D,composeWall(z,ge={}){return bM(z.map(pe=>{const Ie=M(pe);return{deviceId:pe,label:B(pe,Ie),canvas:D(pe,Ie)}}),ge)}}},[at,qn,P,U,ut.frameMode,Ot,ct,Kt,bs,fa,it,Ca,lr,Xe]),Zl=RM({hubUrl:N,sourceRegistry:gu,onToast:J}),Us=u.useMemo(()=>Wt&&P&&gi.has(P)&&(U==="connecting"||U==="active"||U==="warm")?[P]:[],[P,U,Wt,gi]),vu=u.useMemo(()=>wh([...Sa,...Us]),[Us,Sa]),_n=u.useMemo(()=>xT(Fe,Xe),[Fe,Xe]),vi=Dj({mode4Enabled:ct,directMode4WallEnabled:ss,adaptiveFps:Tn,directDeviceCount:ta.length}),Ss=u.useCallback((x,M,D)=>{if(x.width<=0||x.height<=0)return!1;const B=D?Math.min(1,D.maxWidth/x.width,D.maxHeight/x.height):1,z=Math.max(1,Math.round(x.width*B)),ge=Math.max(1,Math.round(x.height*B));(M.width!==z||M.height!==ge)&&(M.width=z,M.height=ge);const pe=M.getContext("2d",{alpha:!1});return pe?(pe.imageSmoothingEnabled=!0,pe.imageSmoothingQuality="high",pe.drawImage(x,0,0,x.width,x.height,0,0,M.width,M.height),!0):!1},[]),dr=u.useCallback(x=>{x&&jt(M=>{if(M.has(x))return M;const D=new Set(M);return D.add(x),D})},[]),Jl=u.useCallback(x=>{x&&jt(M=>{if(!M.has(x))return M;const D=new Set(M);return D.delete(x),D})},[]),eo=u.useCallback((x,M)=>{if(!M||M.width<=0||M.height<=0)return!1;const D=document.createElement("canvas");return D.width=M.width,D.height=M.height,Ss(M,D)?(sn.current.set(x,D),dr(x),!0):!1},[dr,Ss]),Cs=u.useCallback((x,M=!1)=>{if(!Tt.current.has(x))return!1;const D=performance.now(),B=ts.current.get(x)||0,z=Math.max(1,Math.min(li.controlWallReuseMaxFps,rr)),ge=rr>z?Math.max(0,1e3/z-2):0;if(!M&&D-B<ge)return!1;const pe=wt.current.get(x)||Vt.current.get(x),Ie=Ot.current.get(x)||ya.current.get(x);return!pe||!Ie||!Ss(pe,Ie,_n)?!1:(ts.current.set(x,D),dr(x),!0)},[rr,_n,dr,Ss]);u.useEffect(()=>{xn.current=ne},[ne]);const na=u.useCallback((x,M)=>{const D=Ot.current.get(x);if(D&&D!==M&&(eo(x,D),_c(D)),M){Ot.current.set(x,M),sn.current.delete(x),Cs(x,!0);return}Ot.current.delete(x),sn.current.has(x)||Jl(x)},[Jl,Cs,eo]),nl=u.useCallback((x,M)=>{const D=Vt.current.get(x);if(D&&D!==M&&_c(D),M){Vt.current.set(x,M);const B=wt.current.get(x)||sn.current.get(x)||Ot.current.get(x)||ya.current.get(x);B&&Ss(B,M)&&x===G&&ba(!0);return}Vt.current.delete(x)},[G,Ss]),al=u.useCallback((x,M,D)=>{const B=performance.now(),z=Rs(x,D.deviceId);let ge=D;if(x==="control"&&D.visualChanged){const Ie=vj(D.deviceId),Ue=Kr.current.get(D.deviceId)||0,Ke=Ie?B-Ie.sentAt:Number.POSITIVE_INFINITY;Ie&&Ie.inputSeq>Ue&&Ke<=Cy&&(ge={...D,inputFeedbackSeq:Ie.inputSeq,inputFeedbackMs:Math.max(0,Ke),inputFeedbackAt:B},Kr.current.set(D.deviceId,Ie.inputSeq))}di.current.set(z,B);const pe=Yi.current.get(z)||{totalFrames:0,totalChangedFrames:0,sampleFrames:0,sampleChangedFrames:0,sampleStartedAt:B,intervalCount:0,intervalSumMs:0,minIntervalMs:Number.POSITIVE_INFINITY,maxIntervalMs:0,intervalSamplesMs:[],seqGapCount:0,maxSeqGap:0,sampleDecoderInputBase:0,sampleDecoderOutputBase:0};x==="control"&&ge.inputFeedbackMs===void 0&&pe.lastInfo?.inputFeedbackMs!==void 0&&pe.lastInfo.inputFeedbackAt!==void 0&&B-pe.lastInfo.inputFeedbackAt<=Cy&&(ge={...ge,inputFeedbackSeq:pe.lastInfo.inputFeedbackSeq,inputFeedbackMs:pe.lastInfo.inputFeedbackMs,inputFeedbackAt:pe.lastInfo.inputFeedbackAt}),pe.totalFrames+=1,pe.sampleFrames+=1,Ty(pe,B,ge.frameSeq),ge.visualChanged&&(pe.totalChangedFrames+=1,pe.sampleChangedFrames+=1),pe.lastInfo=ge,Yi.current.set(z,pe)},[]),sl=u.useCallback((x,M)=>{al("wall",x,M),x.kind==="live"&&dr(x.deviceId);const D=ue&&P===x.deviceId;xn.current!==x.deviceId&&!D&&(Tt.current.delete(x.deviceId),ts.current.delete(x.deviceId))},[P,ue,dr,al]),Ko=u.useCallback((x,M)=>{al("control",x,M),me(ge=>ge&&"");const D=wt.current.get(x.deviceId),B=Vt.current.get(x.deviceId);D&&D.width>0&&D.height>0&&(B&&Ss(D,B),cn.current.set(x.deviceId,{...x,payload:new Uint8Array(0),byteLength:0}),sn.current.delete(x.deviceId),Tt.current.add(x.deviceId),x.deviceId===P&&(be(!0),W(ge=>ge==="connecting"?"active":ge)),Cs(x.deviceId));const z=Qi.current;!z||!GM(z,x)||ba(!0)},[P,Ss,Cs,al]);u.useEffect(()=>{const x=window.setInterval(()=>{const M=performance.now(),D={};for(const[B,z]of Yi.current.entries()){const ge=Math.max(1,M-z.sampleStartedAt);D[B]={totalFrames:z.totalFrames,totalChangedFrames:z.totalChangedFrames,framesPerSecond:z.sampleFrames*1e3/ge,changedFramesPerSecond:z.sampleChangedFrames*1e3/ge,averageIntervalMs:z.intervalCount>0?z.intervalSumMs/z.intervalCount:0,minIntervalMs:Number.isFinite(z.minIntervalMs)?z.minIntervalMs:0,maxIntervalMs:z.maxIntervalMs,p95IntervalMs:vh(z.intervalSamplesMs,.95),intervalCount:z.intervalCount,seqGapCount:z.seqGapCount,maxSeqGap:z.maxSeqGap,decoderInputFps:Math.max(0,(Number(z.lastInfo?.decoderInputCount||0)-z.sampleDecoderInputBase)*1e3/ge),decoderOutputFps:Math.max(0,(Number(z.lastInfo?.decoderOutputCount||0)-z.sampleDecoderOutputBase)*1e3/ge),sampleMs:ge,lastInfo:z.lastInfo},z.sampleDecoderInputBase=Number(z.lastInfo?.decoderInputCount||0),z.sampleDecoderOutputBase=Number(z.lastInfo?.decoderOutputCount||0),z.sampleChangedFrames=0,My(z,M)}ms(D)},1e3);return()=>window.clearInterval(x)},[]);const xi=u.useCallback((x,M)=>{const D=performance.now(),B=Rs(x,M.deviceId);Xi.current.set(B,D),Ln.current.delete(B),x==="control"&&fi.current.delete(B);const z=Zn.current.get(B)||{totalFrames:0,sampleFrames:0,sampleStartedAt:D,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(z.totalFrames+=1,z.sampleFrames+=1,z.sampleBytes+=Math.max(0,Number(M.byteLength||0)),String(M.frameMode||M.mode||M.codec||M.mimeType||"").toLowerCase().includes("h264")){z.sampleH264Frames+=1,Number(M.byteLength||0)<=PM&&(z.sampleTinyFrames+=1);const Ue=String(M.contentHash||"");Ue&&z.lastContentHash===Ue&&(z.sampleRepeatedFrames+=1),z.lastContentHash=Ue}const Ie=Number(M.agentSendGapMs||0);Ie>0&&Ie<1e3&&xw(z.sourceSendIntervalsMs,Ie),z.lastFrame=M,Ty(z,D,M.frameSeq),Zn.current.set(B,z)},[]);u.useEffect(()=>{const x=window.setInterval(()=>{const M=performance.now(),D={};for(const[B,z]of Zn.current.entries()){const ge=Math.max(1,M-z.sampleStartedAt);D[B]={totalFrames:z.totalFrames,framesPerSecond:z.sampleFrames*1e3/ge,averageIntervalMs:z.intervalCount>0?z.intervalSumMs/z.intervalCount:0,minIntervalMs:Number.isFinite(z.minIntervalMs)?z.minIntervalMs:0,maxIntervalMs:z.maxIntervalMs,p95IntervalMs:vh(z.intervalSamplesMs,.95),intervalCount:z.intervalCount,seqGapCount:z.seqGapCount,maxSeqGap:z.maxSeqGap,averageFrameBytes:z.sampleFrames>0?z.sampleBytes/z.sampleFrames:0,tinyFrameRatio:z.sampleH264Frames>0?z.sampleTinyFrames/z.sampleH264Frames:0,repeatedFrameRatio:z.sampleH264Frames>0?z.sampleRepeatedFrames/z.sampleH264Frames:0,sourceSendAverageMs:z.sourceSendIntervalsMs.length>0?z.sourceSendIntervalsMs.reduce((pe,Ie)=>pe+Ie,0)/z.sourceSendIntervalsMs.length:0,sourceSendP95Ms:vh(z.sourceSendIntervalsMs,.95),sourceSendSampleCount:z.sourceSendIntervalsMs.length,sampleMs:ge,lastFrame:z.lastFrame},z.sampleBytes=0,z.sampleH264Frames=0,z.sampleTinyFrames=0,z.sampleRepeatedFrames=0,z.sourceSendIntervalsMs.length=0,My(z,M)}bf(D)},1e3);return()=>window.clearInterval(x)},[]);const to=u.useCallback(x=>{xi("wall",x);const M=Ot.current.get(x.deviceId);if(!M)return;const D=Lj(ct,Fe.h264DecodeAcceleration);nh(M,x,()=>Ot.current.get(x.deviceId)!==M,sl,D.acceleration,D.latencyMode).catch(()=>{})},[sl,ct,xi,Fe.h264DecodeAcceleration]),xu=u.useCallback(x=>{xi("control",x);let M=wt.current.get(x.deviceId);M||(M=document.createElement("canvas"),M.setAttribute("aria-hidden","true"),wt.current.set(x.deviceId,M));const D=M,B=ve.current;nh(D,x,()=>wt.current.get(x.deviceId)!==D,Ko,ut.h264DecodeAcceleration,"interactive").catch(z=>{ve.current!==B||wt.current.get(x.deviceId)!==D||P!==x.deviceId||me(z instanceof Error?z.message:String(z||"Control H.264 decode failed"))})},[P,ut.h264DecodeAcceleration,Ko,xi]),fr=u.useCallback(x=>{const M=Os.current;M&&M!==x&&_c(M),Os.current=x,Ji.current=0,Yr.current=0,er.current=0,ql.current=0,Uo.current=0,Po.current=0},[]),qs=u.useCallback(()=>{const x=Os.current,M=Hs.current;if(!(!x||!M||x.width<=0||x.height<=0||Po.current!==M.layoutVersion))for(const D of M.tiles){const B=ya.current.get(D.deviceId);if(!B||D.width<=0||D.height<=0)continue;const z=Math.max(1,Math.round(D.width)),ge=Math.max(1,Math.round(D.height)),pe=$M,Ie=UM;(B.width!==pe||B.height!==Ie)&&(B.width=pe,B.height=Ie);const Ue=B.getContext("2d",{alpha:!1});if(Ue){Ue.imageSmoothingEnabled=!0,Ue.imageSmoothingQuality="high";try{Ue.drawImage(x,Math.round(D.x),Math.round(D.y),z,ge,0,0,pe,Ie)}catch{}}}},[]),il=u.useCallback((x,M)=>{if(M){ya.current.set(x,M),sn.current.delete(x),window.requestAnimationFrame(qs),window.requestAnimationFrame(()=>Cs(x,!0));return}const D=ya.current.get(x);eo(x,D),ya.current.delete(x),sn.current.has(x)||Jl(x)},[Jl,qs,Cs,eo]),no=u.useCallback((x,M)=>{er.current=performance.now(),Po.current=Number(x.layoutVersion||0),qs();const D=Hs.current?.tiles||[],B=D.length>0?Math.round(x.byteLength/D.length):x.byteLength;for(const z of D){const ge={...x,deviceId:z.deviceId,width:z.width,height:z.height,sourceWidth:z.width,sourceHeight:z.height,byteLength:B};sl(ge,{...M,deviceId:z.deviceId,width:z.width,height:z.height,byteLength:B}),xn.current===z.deviceId&&Cs(z.deviceId,!0)}},[sl,qs,Cs]),yu=u.useCallback(x=>{const M=performance.now();Ji.current<=0&&(Ji.current=M),Yr.current=M;const D=Os.current;if(!D)return;const B=Hs.current?.tiles||[],z=B.length>0?Math.round(x.byteLength/B.length):x.byteLength;for(const ge of B)xi("wall",{...x,deviceId:ge.deviceId,width:ge.width,height:ge.height,sourceWidth:ge.width,sourceHeight:ge.height,byteLength:z});nh(D,x,()=>Os.current!==D,no).catch(()=>{})},[no,xi]),yi=u.useMemo(()=>({fps:vi,maxWidth:_n.maxWidth,maxHeight:_n.maxHeight,quality:Fe.quality,mode:ct?"mode3-h264-hw":Fe.frameMode,frameMode:ct?"mode3-h264-hw":Fe.frameMode,streamPurpose:"wall",monitorSelections:Kt,onFrame:to}),[vi,to,_n,ct,Kt,Fe]),bi=u.useCallback(x=>{if(x.deviceId!==P||x.streamPurpose!=="control"||x.monitorIndex!==bs)return;const M=at.find(D=>D.deviceId===x.deviceId);!M?.sessionId||M.sessionId!==x.sessionId||($(x),W(D=>D==="connecting"?"active":D))},[at,P,bs]);u.useEffect(()=>{$(null)},[P,ie,wa,bs]);const Qo=u.useMemo(()=>({fps:rr,maxWidth:Ps.maxWidth,maxHeight:Ps.maxHeight,quality:ut.quality,mode:wa,frameMode:wa,streamPurpose:"control",forceRestart:ie!=="",forceRestartToken:ie,restartReason:ie?"control-session-start":"",monitorSelections:Kt,onFrame:xu,onStreamReady:bi}),[ie,ut.quality,xu,rr,wa,Ps.maxHeight,Ps.maxWidth,bi,Kt]),{frames:Xo,state:Pa,error:Zo,stats:js,restartLive:rl}=Rx(ta,Fe.autoStartLive&&ta.length>0,N,yi),{frame:mr,layout:wi,state:Jo,stats:bu,refreshInputs:ec}=xj(Gn,ct&&Fe.autoStartLive&&Gn.length>0,N,{fps:li.atlasOutputFps,width:1920,height:1080,tileWidth:_n.maxWidth,tileHeight:_n.maxHeight,captureDeviceIds:Gn,monitorSelections:Kt,onFrame:yu});u.useEffect(()=>{Hs.current=wi,wi&&window.requestAnimationFrame(qs)},[wi,qs]),u.useEffect(()=>{if(!ct||Jo!=="open"){Ji.current=0,Yr.current=0,er.current=0;return}const x=window.setInterval(()=>{const M=Os.current,D=performance.now();if(!M||document.visibilityState!=="visible"||D-ps.current<gh)return;const B=Yr.current,z=Ji.current;if(B<=0||z<=0||D-B>500)return;const ge=er.current||z,pe=D-ge;if(pe>=OM&&D-Uo.current>=BM){eh(M)&&(Uo.current=D,ql.current=D);return}pe>=IM&&D-ql.current>=HM&&tj(M)&&(ql.current=D)},250);return()=>window.clearInterval(x)},[Jo,ct]);const{frames:ll,state:ma,error:Gs,stats:ja,restartLive:ks,reconnectLive:ao}=Rx(Us,Us.length>0,N,Qo),Si=u.useMemo(()=>{const x=new Map(Xo);if(ct&&mr&&Gn.length>0){const M=new Map((wi?.tiles||[]).map(B=>[B.deviceId,B])),D=Math.max(1,M.size);for(const B of Gn){const z=M.get(B);z&&x.set(B,{...mr,deviceId:B,width:z.width,height:z.height,sourceWidth:z.width,sourceHeight:z.height,byteLength:Math.round(mr.byteLength/D)})}}for(const[M,D]of ll.entries())x.set(M,D);for(const M of tl){if(!Tt.current.has(M)||x.has(M))continue;const D=cn.current.get(M);D&&x.set(M,D)}return x},[mr,wi,ll,Gn,ct,Xo,tl,Jt]),hr=it&&Us.length>0?ma:Gn.length>0?Jo:Pa,ol=it&&Us.length>0?ja:Gn.length>0?bu:js;u.useCallback((x,M="browser-stale")=>{const D=rl(x,M),B=ks(x,M);return D||B},[ks,rl]),u.useEffect(()=>{ct&&Gn.length>0&&!it&&ec()},[Gn.length,ct,ec,it]);const is=u.useCallback((x,M,D)=>{const B=M==="control"?wt.current.get(x)||null:Ot.current.get(x)||null;if(!B||!eh(B))return!1;const z=performance.now();return $o.current.set(Rs(M,x),z),!0},[]),cl=u.useCallback(x=>{if(wa!=="mode3-h264-hw"||!P||I)return!1;const M=at.find(Ie=>Ie.deviceId===P)||qn,D=String(M?.platform||"").toLowerCase();if(!["win32","windows","win32nt"].includes(D))return!1;const B="mode5-lzo-delta",z=Rs("control",P),ge=performance.now();Fa.current.set(z,ge),Xi.current.delete(z),di.current.delete(z),Zi.current.delete(z),fi.current.delete(z),Ln.current.delete(z),eh(wt.current.get(P)||null),ao([P],"control-decode-fallback"),Q(B),K(`control-${B}-fallback-${P}-${Date.now()}`),be(!1),ba(!1);const pe=x==="no first frame"||x==="control-first-frame-timeout";return me(Ie=>Ie||(pe?`Control frame transport timeout; retrying Control with Mode 5 (${x})`:`H.264 decode failed; retrying Control with Mode 5 (${x})`)),W("connecting"),!0},[at,qn,P,I,wa,ao]);u.useEffect(()=>{const x=it?qn:null;if(x){Qi.current={deviceId:x.deviceId,monitorIndex:bs,frameMode:wa,startedAtEpochMs:Date.now()},ba(P===x.deviceId&&ue||Ze.has(x.deviceId));return}Qi.current=null,ba(!1)},[qn?.sessionId,G,P,ue,wa,bs,it,Ze]);const Vs=u.useCallback(async x=>{const M=C.find(pe=>pe.deviceId===x),D=zc({mode4Enabled:ct,directMode4WallEnabled:ss,isMac:qi(M?.platform)})==="atlas",B=za(Kt[x],M?va(M):1),z=D?{fps:li.scalableAtlasInputFps,maxWidth:_n.maxWidth,maxHeight:_n.maxHeight,quality:60,mode:"mode2-lzo",frameMode:"mode2-lzo",streamPurpose:"atlas",monitorIndex:B}:{fps:ct&&!D?vi:Tn,maxWidth:_n.maxWidth,maxHeight:_n.maxHeight,quality:Fe.quality,mode:ct?"mode3-h264-hw":Fe.frameMode,frameMode:ct?"mode3-h264-hw":Fe.frameMode,streamPurpose:"wall",monitorIndex:B},ge=await Ge(`/api/remote/devices/${encodeURIComponent(x)}/live/start`,{method:"POST",body:JSON.stringify(z)},N);if(ge?.ok===!1)throw new Error(ge.error||"wall-stream-start-failed");return ge},[Tn,C,ss,vi,_n.maxHeight,_n.maxWidth,N,ct,Kt,Fe.frameMode,Fe.quality]),As=u.useCallback(async x=>{const M=C.find(z=>z.deviceId===x),D=zc({mode4Enabled:ct,directMode4WallEnabled:ss,isMac:qi(M?.platform)})==="atlas",B=await Ge(`/api/remote/devices/${encodeURIComponent(x)}/live/stop`,{method:"POST",body:JSON.stringify({streamPurpose:D?"atlas":"wall",reason:"control-active"})},N);if(B?.ok===!1)throw new Error(B.error||"wall-stream-stop-failed");return B},[C,ss,N,ct]),pr=u.useCallback(async(x,M="control-session-stop")=>{const D=await Ge(`/api/remote/devices/${encodeURIComponent(x)}/live/stop`,{method:"POST",body:JSON.stringify({streamPurpose:"control",reason:M})},N);if(D?.ok===!1)throw new Error(D.error||"control-stream-stop-failed");return D},[N]),jn=u.useCallback(x=>{const M=wt.current.get(x);M&&(_c(M),wt.current.delete(x));const D=Vt.current.get(x);D&&_c(D),cn.current.delete(x),Tt.current.delete(x),ts.current.delete(x)},[]);u.useEffect(()=>{const x=G&&at.find(z=>z.deviceId===G)||null;if(!it||!Wt||!x){hs.current&&(++Qt.current,hs.current="");return}if(P===x.deviceId&&(U==="active"||U==="warm"||U==="connecting")){W(z=>z==="warm"?"active":z);return}if(hs.current===x.deviceId)return;const M=++Qt.current,D=P;hs.current=x.deviceId,(async()=>{if(D){if(W("stopping"),await pr(D,"control-session-switch").catch(()=>{}),M!==Qt.current)return;const pe=xn.current;if(pe&&pe!==x.deviceId)try{await Vs(pe)}catch(Ie){J(Ie instanceof Error?Ie.message:String(Ie))}finally{xn.current===pe&&(xn.current="",Ae(""))}if(M!==Qt.current)return;jn(D)}if(M!==Qt.current)return;if($y(x)){try{await As(x.deviceId)}catch(pe){M===Qt.current&&(hs.current="",W("error"),J(pe instanceof Error?pe.message:String(pe)));return}if(M!==Qt.current){await Vs(x.deviceId).catch(()=>{});return}xn.current=x.deviceId,Ae(x.deviceId),Tt.current.add(x.deviceId)}const z=Rs("control",x.deviceId),ge=`control-session-${M}-${x.deviceId}`;Fa.current.set(z,performance.now()),Xi.current.delete(z),di.current.delete(z),Ln.current.delete(z),fi.current.delete(z),Q(""),me(""),K(ge),ye(x.deviceId),be(!1),W("connecting"),Qt.current===M&&hs.current===x.deviceId&&(hs.current="")})()},[at,G,P,U,Wt,jn,J,it,Vs,pr,As]),u.useEffect(()=>{if(!P||at.some(D=>D.deviceId===P))return;const x=P,M=++Qt.current;W("stopping"),pr(x,"control-device-disconnected").catch(()=>{}).finally(()=>{M===Qt.current&&(jn(x),be(!1),K(""),Q(""),me(""),ye(D=>D===x?"":D),W("idle"))})},[at,P,jn,pr]);const so=$y(at.find(x=>x.deviceId===P));u.useEffect(()=>{if(ns.current!==null&&(window.clearTimeout(ns.current),ns.current=null),!P||U==="idle"||U==="stopping"||U==="error"||it||ze==="wall"){P&&!it&&ze==="wall"&&W(D=>D==="warm"||D==="active"?"active":D);return}W(D=>D==="idle"||D==="stopping"?D:"warm");const x=P,M=++Qt.current;return ns.current=window.setTimeout(()=>{ns.current=null,W("stopping"),pr(x,"control-session-warm-timeout").catch(()=>{}).finally(()=>{M===Qt.current&&(jn(x),be(!1),K(""),Q(""),me(""),ye(D=>D===x?"":D),W("idle"))})},FM),()=>{ns.current!==null&&(window.clearTimeout(ns.current),ns.current=null)}},[ze,P,U,jn,it,pr]),u.useEffect(()=>()=>{ns.current!==null&&window.clearTimeout(ns.current)},[]),u.useEffect(()=>{const M=P&&(so&&(U==="connecting"||U==="active"||U==="warm"||U==="stopping")||ue&&(U==="active"||U==="warm"))?P:"";if(un.current=M,dn.current)return;const D=async()=>{for(;;){const z=un.current,ge=xn.current;if(ge===z)return;if(ge){try{await Vs(ge)}catch(pe){J(pe instanceof Error?pe.message:String(pe))}finally{xn.current===ge&&(xn.current="",Ae(""))}continue}if(!z)return;try{await As(z)}catch(pe){un.current=xn.current,J(pe instanceof Error?pe.message:String(pe));return}xn.current=z,Ae(z),Tt.current.add(z)}};let B;B=D().finally(()=>{dn.current===B&&(dn.current=null),xn.current!==un.current&&ot(z=>z+1)}),dn.current=B},[P,ue,U,so,ct,J,Vs,As,qe]);const Vn=P&&at.find(x=>x.deviceId===P)||null,ul=!!(it&&Se&&U==="active"&&Vn?.sessionId&&X?.deviceId===Vn.deviceId&&X.sessionId===Vn.sessionId&&X.streamPurpose==="control"&&X.commandId&&X.captureGeneration>0&&X.monitorIndex===bs),{state:gr,sendInput:Ws,stats:ka,error:tc}=yj(ws&&ul,N),Ci=u.useCallback((x,M)=>!ul||!Vn||!X||x!==Vn.deviceId?!1:Ws(x,{...M,controlSessionId:Vn.sessionId,controlCommandId:X.commandId,captureGeneration:X.captureGeneration}),[ul,Vn,X,Ws]),vr=ul&&gr==="open",{state:Aa,lastFrame:ji,stats:fn,error:dl}=Mj(Le?.deviceId||"",pu&&le,N),Ys=u.useRef(new Map);u.useEffect(()=>{const x=[["hub",j],["registry",l],["license",q],["wall-stream",Zo],["control-stream",Gs],["control-decode",de],["remote-input",tc],["remote-audio",dl]];for(const[M,D]of x){const B=String(D||"").trim();if(M==="hub"&&De?.requiresHubRestart&&De.stage==="updating"){Ys.current.delete(M);continue}if(!B){Ys.current.delete(M);continue}Ys.current.get(M)!==B&&(Ys.current.set(M,B),J(B))}},[dl,de,Gs,j,tc,q,l,J,Zo,De]),u.useEffect(()=>{if(!it||!Se||!ws||!vr||!Le)return;const x=(B,z)=>{const ge=B.target,pe=ge?.tagName?.toLowerCase();ge?.isContentEditable||pe==="input"||pe==="textarea"||pe==="select"||(B.preventDefault(),B.stopPropagation(),Ci(Le.deviceId,{type:z,monitorIndex:za(Kt[Le.deviceId],va(Le)),key:B.key,code:B.code,keyCode:B.keyCode||B.which||0,location:B.location,text:B.key.length===1?B.key:"",repeat:z==="keydown"?B.repeat:!1,shiftKey:B.shiftKey,ctrlKey:B.ctrlKey,altKey:B.altKey,metaKey:B.metaKey}))},M=B=>x(B,"keydown"),D=B=>x(B,"keyup");return window.addEventListener("keydown",M),window.addEventListener("keyup",D),()=>{window.removeEventListener("keydown",M),window.removeEventListener("keyup",D)}},[ws,vr,Se,Kt,Le,Ci,it]),u.useEffect(()=>{const x=()=>{document.visibilityState==="visible"&&(ps.current=performance.now())};return document.addEventListener("visibilitychange",x),window.addEventListener("pageshow",x),()=>{document.removeEventListener("visibilitychange",x),window.removeEventListener("pageshow",x)}},[]),u.useEffect(()=>{if(!P||U!=="connecting"&&U!=="active"&&U!=="warm"||ma!=="open")return;const x=P,M=Rs("control",x),D=window.setInterval(()=>{const B=performance.now();if(document.visibilityState!=="visible"||B-ps.current<gh)return;const z=Xi.current.get(M)||0,ge=di.current.get(M)||0,pe=Zi.current.get(M)||0,Ie=Fa.current.get(M)||B;Fa.current.has(M)||Fa.current.set(M,Ie);const Ue=z<=0,Ke=Ue?B-Ie>KM:B-z>_y,en=z>0&&(ge<=0||B-ge>_y);if(!Ke&&en){const Ar=$o.current.get(M)||0;B-Ar>=zy&&is(x,"control","decoder-paint-stale");return}if(!Ke)return;const Dt=fi.current.get(M)||0;if(Dt>0){if(B-Dt<XM)return;fi.current.delete(M)}const tn=Ln.current.get(M)||0;if(tn>=ZM){if(cl(Ue?"no first frame":"stale stream"))return;be(!1),ba(!1),W("error");return}if(B-pe<Iy(QM,tn))return;ks([x],Ue?"control-first-frame-timeout":"control-receive-stale")&&(Zi.current.set(M,B),fi.current.set(M,B),Fa.current.set(M,B),Ln.current.set(M,tn+1))},650);return()=>window.clearInterval(D)},[ma,P,U,cl,is,ks]),u.useEffect(()=>{!de||wa!=="mode3-h264-hw"||cl(de)||(be(!1),ba(!1),W("error"))},[de,wa,cl]),u.useEffect(()=>{!it||!P||!Gs||W(x=>x==="error"?x:"error")},[Gs,P,it]),u.useEffect(()=>{if(Pa!=="open"||!Fe.autoStartLive||ta.length===0)return;const x=window.setInterval(()=>{const M=performance.now();if(document.visibilityState!=="visible"||M-ps.current<gh)return;const D=1e3/Math.max(1,vi||Fe.fps||1),B=Math.max(JM,Math.ceil(D*4)),z=[];for(const ge of ta){if(z.length>=nT)break;const pe=Rs("wall",ge),Ie=Xi.current.get(pe)||0;if(Ie<=0)continue;const Ue=Zi.current.get(pe)||0,Ke=di.current.get(pe)||0,en=M-Ie>B,Dt=Ke<=0||M-Ke>B;if(!en&&Dt){const Ua=$o.current.get(pe)||0;M-Ua>=zy&&is(ge,"wall","decoder-paint-stale");continue}if(!en)continue;const tn=Ln.current.get(pe)||0;M-Ue>=Iy(eT,tn)&&z.push(ge)}if(z.length>0&&rl(z,"wall-frame-stale"))for(const ge of z){const pe=Rs("wall",ge);Zi.current.set(pe,M),Ln.current.set(pe,(Ln.current.get(pe)||0)+1)}},tT);return()=>window.clearInterval(x)},[vi,ta,is,rl,Fe.autoStartLive,Fe.fps,Pa]),u.useEffect(()=>{da(Fe.fps),xs.current=Date.now(),Fs.current=0},[Fe.fps,Fe.frameMode,Fe.adaptiveLoadShedding]),u.useEffect(()=>{WC({h264DecodeAcceleration:Fe.h264DecodeAcceleration})},[Fe.h264DecodeAcceleration]),u.useEffect(()=>{if(!Wt||it||Xe==="list"||!Fe.visibleOnlyLive){es([]);return}const x=Go.current;if(!x||typeof IntersectionObserver>"u"){es(Xl);return}const M=Array.from(x.querySelectorAll("[data-live-device-id]"));if(M.length===0){es([]);return}const D=new Map,B=()=>{const ge=wh(M.map(pe=>String(pe.dataset.liveDeviceId||"")).filter(pe=>(D.get(pe)||0)>0));es(pe=>bh(pe,ge)?pe:ge)},z=new IntersectionObserver(ge=>{for(const pe of ge){const Ie=String(pe.target.dataset.liveDeviceId||"");Ie&&D.set(Ie,pe.isIntersecting?pe.intersectionRatio||.01:0)}B()},{root:null,rootMargin:ca.visibleRootMargin,threshold:[0,.01,.2,.6,1]});return M.forEach(ge=>z.observe(ge)),B(),()=>z.disconnect()},[Xl,Wt,it,pi,Fe.visibleOnlyLive,Xe]),u.useEffect(()=>{if(!Fe.adaptiveLoadShedding||!Fe.autoStartLive||ta.length===0)return;const x=Fe.fps;if(ta.length<=ca.preserveConfiguredFpsDeviceCount){Tn!==x&&(da(x),xs.current=Date.now(),Fs.current=0);return}if(Pa!=="open"||js.sampleMs<500)return;const M=Date.now(),D=ta.length*Tn,B=js.framesPerSecond,z=js.bytesPerSecond,ge=Math.max(0,...ta.map(en=>$l[Rs("wall",en)]?.maxIntervalMs||0)),pe=Math.max(0,...ta.map(en=>Ki[Rs("wall",en)]?.maxIntervalMs||0)),Ie=D>8&&B>0&&B<D*.72;if(B>ca.maxWallFramesPerSecond||z>ca.maxWallBytesPerSecond||ge>ca.maxFrameGapMs||pe>ca.maxFrameGapMs||Ie){Fs.current=0;const en=ca.minFps;if(M-xs.current>=ca.downshiftCooldownMs&&Tn>en){const Dt=Math.max(en,yT(Tn,en));Dt<Tn&&(da(Dt),xs.current=M)}return}const Ke=B<ca.maxWallFramesPerSecond*ca.lowLoadFrameRatio&&z<ca.maxWallBytesPerSecond*ca.lowLoadByteRatio;if(!Ke||Tn>=x){Ke||(Fs.current=0);return}if(!Fs.current){Fs.current=M;return}if(M-Fs.current>=ca.recoveryCooldownMs){const en=Math.min(x,bT(Tn,x));en>Tn&&(da(en),xs.current=M,Fs.current=0)}},[Tn,ta.length,ta,Ki,$l,Pa,js.bytesPerSecond,js.framesPerSecond,js.lastUpdatedAt,js.sampleMs,Fe.adaptiveLoadShedding,Fe.autoStartLive,Fe.frameMode,Fe.fps]),u.useEffect(()=>{const x=new URLSearchParams(window.location.search).get("checkout");if(x==="success"){J("Checkout returned. Waiting for Dodo confirmation."),O();const M=window.setInterval(()=>{O()},4e3),D=window.setTimeout(()=>{window.clearInterval(M)},45e3);return()=>{window.clearInterval(M),window.clearTimeout(D)}}x==="cancelled"&&J("Checkout cancelled.")},[O]),u.useEffect(()=>{!Wt&&Se&&Oe(!1),!Wt&&le&&Z(!1)},[le,Se,Wt]),u.useEffect(()=>{const x=Le?.deviceId||"",M=He.current;if(He.current=x,!M||M===x)return;const D=++se.current,B=x?`audio-${Date.now()}-${Math.random().toString(36).slice(2,8)}`:"";x&&le&&_e.current.set(x,B);let z=!0;return(async()=>{try{const pe=_e.current.get(M);if(_e.current.delete(M),await Ge(`/api/remote/devices/${encodeURIComponent(M)}/audio/stop`,{method:"POST",body:JSON.stringify(pe?{streamId:pe}:{})},N),!z||D!==se.current||!le||!x||!Wt||!el)return;const Ie=await Ge(`/api/remote/devices/${encodeURIComponent(x)}/audio/start`,{method:"POST",body:JSON.stringify({streamId:B,mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},N);if(Ie.ok===!1)throw new Error(Ie.error||"Remote audio start failed.")}catch(pe){z&&(_e.current.delete(x),Z(!1),J(pe instanceof Error?pe.message:String(pe)))}})(),()=>{z=!1}},[le,Wt,N,el,Le?.deviceId]),u.useEffect(()=>{const x=at.map(B=>B.deviceId),M=new Set(x),D=new Map(at.map(B=>[B.deviceId,B]));_(B=>{const z=B.filter(ge=>M.has(ge));return bh(B,z)?B:z}),ae(B=>B&&M.has(B)?B:""),te(B=>B&&M.has(B)?B:""),H(B=>{let z=!1;const ge={};for(const[pe,Ie]of Object.entries(B)){const Ue=D.get(pe);if(!Ue){ge[pe]=Ie;continue}const Ke=za(Ie,Ue?va(Ue):1);ge[pe]=Ke,Ke!==Ie&&(z=!0)}return z?ge:B}),Xr(B=>{const z=B.filter(ge=>M.has(ge));return bh(B,z)?B:z})},[at,Kl]),u.useEffect(()=>{qo([]),Vl(!1)},[Cs]),u.useEffect(()=>{!ir||mi!=="selected"||Jn.length>0||fa.length===0||Xr(fa.map(x=>x.deviceId))},[fa,Jn.length,mi,ir]),u.useEffect(()=>{try{localStorage.setItem(dw,Xn)}catch{}},[Xn]),u.useEffect(()=>{hT(Fe)},[Fe]),u.useEffect(()=>{gT(ut)},[ut]),u.useEffect(()=>{fT(Kt)},[Kt]);const aa=u.useCallback(async()=>{const x=new Set(p);x.add(Cn);try{const ge=await Ge("/api/remote/status",void 0,Cn);xx({endpoint:ge.agentEndpoint,endpoint_candidates:[...ge.agentEndpointCandidates||[],...ge.hostTargetEndpointCandidates||[]]}).forEach(pe=>x.add(pe))}catch{}const M=[...x].sort((ge,pe)=>{const Ie=Ue=>{const Ke=qc(Ue);return Ke==="local"?0:Ke==="loopback"?1:2};return Ie(ge)-Ie(pe)||ge.localeCompare(pe)});let D=!1,B="",z=!1;try{for(const ge of M){const pe=qc(ge);try{if(await Ge("/api/health",void 0,ge),pe==="local")return g(!0),To(!0),ge;pe==="loopback"&&(D=!0,B=ge)}catch{pe==="local"&&(z=!0)}}return D?(z&&J("LiveDesk Hub is reachable on this PC, but not through the LAN address yet. Restart LiveDesk Hub to bind 5179 on the network."),g(!0),To(!0),B||Cn):(g(!1),To(!1),"")}catch{return g(!1),To(!1),""}},[p]),zn=async()=>{if(Ne("auth"),an(!1),await aa(),window.liveDesk?.auth?.signInWithGoogle){const D=await window.liveDesk.auth.signInWithGoogle();D?.ok===!1&&(J(D.error||"LiveDesk could not open the system browser for Google sign-in."),Ne(""));return}const{data:x,error:M}=await mt.auth.signInWithOAuth({provider:"google",options:{redirectTo:`${window.location.origin}/callback`}});M&&(J(M.message),Ne(""))},Ks=async()=>{Ne("auth"),an(!1),await mt.auth.signOut(),(await window.liveDesk?.auth?.persistSession?.(null))?.runtimeCleared===!1?J("Signed out locally. The LiveDesk runtime could not be reached to clear its session."):window.liveDesk?.auth?.persistSession||await Ge("/api/auth/session",{method:"DELETE"},Cn).catch(()=>{}),Ne("")};u.useEffect(()=>{if(!$t)return;const x=D=>{D.target instanceof Element&&(D.target.closest(".account-popover, .rail-account")||an(!1))},M=D=>{D.key==="Escape"&&an(!1)};return window.addEventListener("pointerdown",x),window.addEventListener("keydown",M),()=>{window.removeEventListener("pointerdown",x),window.removeEventListener("keydown",M)}},[$t]);const Na=u.useCallback(async(x={})=>{const M=x.silent===!0,D=x.takeover===!0,B=x.requestLocalAccess===!0;if(!n?.user){M||J("Sign in before publishing this host.","error");return}if(!vs.current){vs.current=!0,M||(Ne("host"),Re("Hub · 1/4 · Checking the local runtime…"));try{const ge=(B?await aa():"")||N||Cn;if(!(b||await Ge("/api/remote/status",void 0,ge)).started)throw new Error("Start LiveDesk on this computer before syncing the server.");M||Re("Hub · 2/4 · Sending the signed-in session to the Hub…");const Ie=await Ge("/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}})},ge);if(!Ie.ok||!Ie.authenticated)throw new Error(Ie.error||"hub-session-sync-failed");M||Re("Hub · 3/4 · Claiming the Hub role and publishing its endpoint…");const Ue=await Ge("/api/hub/sync",{method:"POST",body:JSON.stringify({takeover:D})},ge);if(!Ue.ok)throw new Error(Ue.error||"host-target-failed");if(!M){Re("Hub · 4/4 · Verifying the endpoint and lease renewal…");const Ke=await Ge("/api/hub/status",void 0,ge);if(!Ke.hostTargetActive)throw new Error(Ke.hostTargetLease?.lastError||"host-target-not-active-after-sync");const en=Ke.hostTargetEndpoint||Ke.agentEndpoint||"endpoint ready",Dt=Number(Ke.connectedDeviceCount||0),tn=Dt>0?`${Dt} client${Dt===1?"":"s"} connected.`:"No clients connected yet; reconnect the laptop Client.";J(`Hub ready · ${en} · lease auto-renewal active. ${tn}`,"success"),(B||w)&&(g(!0),To(!0)),A()}c()}catch(z){if(!M){const ge=z instanceof Error?z.message:String(z);ge.includes("local network access")&&(g(!1),To(!1)),J(`Hub setup failed · ${ge}`,"error")}}finally{vs.current=!1,M||Ne("")}}},[N,w,A,c,aa,n,J,Re,b]),sa=u.useCallback((x=!0)=>{fe!=="host"&&(et(!1),x&&window.requestAnimationFrame(()=>ke.current?.focus()))},[fe]),Ns=u.useCallback(()=>{fe!=="host"&&(ke.current=document.activeElement instanceof HTMLElement?document.activeElement:null,an(!1),et(!0))},[fe]),wu=u.useCallback(()=>{et(!1),Na({takeover:!0,requestLocalAccess:!0})},[Na]);u.useEffect(()=>{if(!$e)return;const x=window.requestAnimationFrame(()=>Mt.current?.focus()),M=B=>{B.target instanceof Element&&B.target.closest(".client-hub-switch-popover, .hub-sync-trigger")||sa(!1)},D=B=>{B.key==="Escape"&&sa()};return window.addEventListener("pointerdown",M),window.addEventListener("keydown",D),()=>{window.cancelAnimationFrame(x),window.removeEventListener("pointerdown",M),window.removeEventListener("keydown",D)}},[sa,$e]);const nc=u.useCallback(async()=>{if(!(!b?.update?.canApply||fe==="update")){Ne("update");try{const x=await Ge("/api/update/apply",{method:"POST",body:JSON.stringify({})},N||Cn);if(!x.ok)throw new Error(x.error||"LiveDesk update could not be started.");const M=[...new Set((x.targets||[]).map(z=>String(z.deviceId||"").trim()).filter(Boolean))],D=!!(x.managerUpdateAvailable||x.clientPackageUpdateAvailable),B=x.state==="hub-restart-requested"?Date.now():void 0;(M.length>0||D)&&st({operationId:String(x.operationId||`wall-update-${Date.now()}`),targetIds:M,stage:x.state==="clients-updated"?"updated":"updating",requiresHubRestart:D,initialHostInstanceId:String(b.hostInstanceId||""),targetManagerVersion:String(x.latestVersion||b.update?.latestVersion||""),targetClientVersion:String(x.latestClientVersion||b.update?.latestClientVersion||""),restartRequestedAt:B,restartDeadlineAt:B?B+Hd:void 0}),Re(x.state==="hub-restart-requested"?Od:Ay),A()}catch(x){J(x instanceof Error?x.message:String(x),"error")}finally{Ne("")}}},[fe,N,A,J,Re,b]);u.useEffect(()=>{const x=De,M=b?.update;if(!x||x.stage!=="updating"||!M)return;const D=M.restartResult?.operationId===x.operationId?M.restartResult:null;if(D?.outcome==="restored"){const Ue=D.error||`The requested Hub ${D.targetVersion||x.targetManagerVersion||"version"} failed verification.`;st(Ke=>Ke?.operationId===x.operationId?{...Ke,stage:"restored",error:Ue}:Ke),J(`LiveDesk update did not complete. Hub ${D.fallbackVersion||D.appVersion||"the previous version"} was restored. ${Ue}`,"error");return}if(D?.outcome==="failed"){const Ue=D.error||"No verified LiveDesk Hub replacement could be started.";st(Ke=>Ke?.operationId===x.operationId?{...Ke,stage:"failed",error:Ue}:Ke),J(`LiveDesk Hub update failed. ${Ue}`,"error");return}if(M.operationId===x.operationId&&M.state==="failed"){const Ue=M.error||"LiveDesk update failed before the Hub replacement completed.";st(Ke=>Ke?.operationId===x.operationId?{...Ke,stage:"failed",error:Ue}:Ke),J(Ue,"error");return}if(M.operationId===x.operationId){if(M.state==="hub-restart-requested"&&!x.restartDeadlineAt){const Ue=Date.now();st(Ke=>Ke?.operationId===x.operationId?{...Ke,restartRequestedAt:Ue,restartDeadlineAt:Ue+Hd}:Ke),Re(Od)}!x.requiresHubRestart&&M.state==="clients-updated"&&(st(Ue=>Ue?.operationId===x.operationId?{...Ue,stage:"updated"}:Ue),J("LiveDesk clients updated and reconnected successfully.","success"));return}if(!x.requiresHubRestart)return;const B=b.started===!0&&(!x.initialHostInstanceId||b.hostInstanceId&&b.hostInstanceId!==x.initialHostInstanceId),z=!!M.checkedAt,ge=Ny(M.currentVersion,x.targetManagerVersion),pe=!x.targetClientVersion||Ny(M.currentClientVersion,x.targetClientVersion),Ie=z&&M.state==="idle"&&M.updateAvailable===!1&&ge&&pe;B&&Ie&&(st(Ue=>Ue?.operationId===x.operationId?{...Ue,stage:"updated"}:Ue),J(`LiveDesk Hub ${M.currentVersion||D?.appVersion||x.targetManagerVersion} restarted and passed version verification.`,"success"))},[J,Re,b,De]),u.useEffect(()=>{const x=De;if(!x||x.stage!=="updating"||!x.requiresHubRestart||x.restartDeadlineAt)return;const M=()=>{const B=Date.now();st(z=>z?.operationId===x.operationId&&z.stage==="updating"&&!z.restartDeadlineAt?{...z,restartRequestedAt:B,restartDeadlineAt:B+Hd}:z),Re(Od)};if(b?.update?.state==="hub-restart-requested"){M();return}if(!j)return;const D=window.setTimeout(M,qM);return()=>window.clearTimeout(D)},[j,Re,b?.update?.state,De]),u.useEffect(()=>{const x=De;if(!x||x.stage!=="updating"||!x.requiresHubRestart||!x.restartDeadlineAt)return;const M=Math.max(0,x.restartDeadlineAt-Date.now()),D=x.operationId,B=window.setTimeout(()=>{const z=`LiveDesk Hub did not return and verify ${x.targetManagerVersion||"the requested version"} within ${Math.round(Hd/6e4)} minutes. Check the Hub terminal or restart log, then run livedesk@latest manually if the Hub is still offline.`;st(ge=>ge?.operationId===D&&ge.stage==="updating"?{...ge,stage:"failed",error:z}:ge),J(z,"error")},M);return()=>window.clearTimeout(B)},[J,De]),u.useEffect(()=>{if(!De||De.stage!=="updated")return;const x=De.operationId,M=window.setTimeout(()=>{st(D=>D?.operationId===x?null:D)},8e3);return()=>window.clearTimeout(M)},[De]),u.useEffect(()=>{if(vt!==Ay&&vt!==Od)return;const x=b?.update;if(String(x?.state||"")==="failed"){J(x?.error||"LiveDesk update failed.","error");return}De?.stage==="updated"&&J("")},[vt,J,b?.update?.error,b?.update?.state,De?.stage]);const ac=u.useCallback(async()=>{if(!fe){Ne("pin");try{const M=await Ge("/api/remote/pairing-pin",{method:"POST"},N||Cn);if(!M.ok)throw new Error(M.error||"pin-rotation-failed");await A(),J("New PIN published.")}catch(x){J(x instanceof Error?x.message:String(x))}finally{Ne("")}}},[fe,N,A]),io=u.useCallback(x=>{x&&(ae(x),_(M=>M.includes(x)?M:[...M,x]))},[]),yn=u.useCallback(x=>{if(!x)return;const M=ys.has(x);ae(D=>M?D===x?"":D:x),_(D=>M?D.filter(B=>B!==x):D.includes(x)?D:[...D,x])},[ys]),Et=u.useCallback(()=>{_([]),ae("")},[Ss]),xt=u.useCallback(()=>{_(at.map(x=>x.deviceId)),ae("")},[at]),rs=u.useCallback((x,M)=>{const D=at.find(z=>z.deviceId===x);if(!D)return;const B=va(D);B<=1||(H(z=>{const pe=(za(z[x],B)+M+B)%B;return{...z,[x]:pe}}),it&&(ba(!1),te(x)))},[at,it]);u.useEffect(()=>{const x=M=>{if(it&&Se&&ws)return;const D=M.target,B=D?.tagName?.toLowerCase();D?.isContentEditable||B==="input"||B==="textarea"||B==="select"||((M.ctrlKey||M.metaKey)&&M.key.toLowerCase()==="a"&&(M.preventDefault(),xt()),M.key==="Escape"&&Et())};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[ws,Et,Se,xt,it]);const Ma=(x,M)=>{const D=at.find(z=>z.deviceId===x),B=za(M,D?va(D):1);H(z=>({...z,[x]:B})),it?(ba(!1),te(x)):io(x)},ki=async x=>{if(ba(!1),te(x),je("control"),!gi.has(x)){Oe(!1),J(cr);return}const M=at.find(B=>B.deviceId===x);if(qi(M?.platform)&&(M?.capabilities?.controlPermission===!1||M?.capabilities?.accessibilityPermission===!1)){Oe(!1),J("Mac remote control needs Accessibility permission. Allow it for the terminal app that starts LiveDesk, then restart the Mac client.","error");return}Oe(!0),J(`Opening remote control${M?` for ${Ka(M)}`:""}.`,"success")},Qs=async()=>{if(!Le){J("Select a workstation before playing audio.");return}if(!Wt){J(cr);return}if(!el){J("Selected workstation does not report remote audio support yet.");return}if(Te)return;const x=!le,M=x?`audio-${Date.now()}-${Math.random().toString(36).slice(2,8)}`:_e.current.get(Le.deviceId);x&&M?_e.current.set(Le.deviceId,M):x||_e.current.delete(Le.deviceId),Be("audio"),Z(x);try{await Ge(`/api/remote/devices/${encodeURIComponent(Le.deviceId)}/audio/${x?"start":"stop"}`,{method:"POST",body:JSON.stringify({...M?{streamId:M}:{},mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},N),J(`${x?"Audio started":"Audio stopped"} for ${Ka(Le)}.`,"success")}catch(D){x&&_e.current.delete(Le.deviceId),Z(!1),J(D instanceof Error?D.message:String(D),"error")}finally{Be("")}},Su=x=>{const M=x instanceof Error?x.message:String(x);return/remote-actions-disabled|allowAgent-blocked-by-settings/i.test(M)?"Remote actions are off. Turn on Settings > Agent > Enable AI Agent first.":/power-actions-disabled/i.test(M)?"Power actions are off. Turn on Settings > Agent > Allow power actions first.":/agent-tool-capability-unavailable|unsupported-agent-operation/i.test(M)?"This workstation needs a newer LiveDesk Client for power actions.":/device-not-connected|404 device-not-found/i.test(M)?"The workstation disconnected before the action could be sent.":M},fl=async x=>{if(!Le||Te)return;const M=Le,B={lock:"Lock",sleep:"Sleep",restart:"Restart",shutdown:"Shut down"}[x];if(!(x!=="lock"&&!window.confirm(`${B} ${Ka(M)}? Unsaved work on that computer may be lost.`))){Be(x),J(`Sending ${B.toLowerCase()} request to ${Ka(M)}...`);try{const z=await Ge(`/api/remote/devices/${encodeURIComponent(M.deviceId)}/quick-actions`,{method:"POST",body:JSON.stringify({action:x})},N);if(!z.ok)throw new Error(z.error||"The remote action could not be sent.");J(`${B} request sent to ${Ka(M)}.`,"success"),A()}catch(z){J(Su(z),"error")}finally{Be("")}}},xr=()=>{Le&&(rt({id:Date.now(),deviceId:Le.deviceId,instruction:"Run command "}),Oe(!1),je("agents"),J(`Command runner opened for ${Ka(Le)}.`))},Xs=async(x,M,D="files")=>{const B=x.filter(Ie=>Ie.file.size>=0);if(B.length===0)return{files:0,bytes:0};if(!Wt)throw new Error(cr);if(M.length===0)throw new Error("Select at least one connected workstation.");const z=crypto.randomUUID(),ge=B.reduce((Ie,Ue)=>Ie+Ue.file.size,0);let pe=0;as({id:z,status:"reading",progress:1,message:`Preparing ${B.length} ${D}`});try{for(let Ie=0;Ie<B.length;Ie+=1){const Ue=B[Ie],Ke=Ue.file,en=Math.max(1,Math.ceil(Ke.size/hh));for(let Dt=0;Dt<en;Dt+=1){const tn=Dt*hh,Ua=Math.min(Ke.size,tn+hh),Ar=Ke.size===0?new ArrayBuffer(0):await Ke.slice(tn,Ua).arrayBuffer(),Tu=Dt===en-1;as({id:z,status:"sending",progress:Math.max(2,Math.min(98,Math.round(pe/Math.max(1,ge)*96))),message:`${Ie+1}/${B.length} ${Ue.relativePath}`});const qa=await Ge("/api/remote/files/chunk",{method:"POST",body:JSON.stringify({transferId:z,deviceIds:M,remoteDirectory:Xn.trim(),name:Ke.name,relativePath:Ue.relativePath,size:Ke.size,type:Ke.type,lastModified:Ke.lastModified,offset:tn,totalBytes:Ke.size,final:Tu,dataBase64:wT(Ar)})},N);if(!qa.ok||qa.queued!==M.length)throw new Error(qa.error||`file-chunk-not-queued-${qa.queued}/${M.length}`);pe+=Ar.byteLength,await new Promise(pa=>window.setTimeout(pa,0))}}return as({id:z,status:"queued",progress:100,message:`Sent ${B.length} file${B.length===1?"":"s"} to ${M.length} workstation${M.length===1?"":"s"}`}),window.setTimeout(()=>{as(Ie=>Ie?.id===z&&Ie.status==="queued"?null:Ie)},4500),{files:B.length,bytes:ge}}catch(Ie){throw as({id:z,status:"failed",progress:100,message:Ie instanceof Error?Ie.message:String(Ie)}),Ie}},ro=async x=>{const M=fa.length>0?fa.map(D=>D.deviceId):Le?[Le.deviceId]:[];try{await Xs(Hy(x),M)}catch(D){J(D instanceof Error?D.message:String(D))}},yr=async x=>{try{await Xs(Hy(x),Sf)}catch(M){J(M instanceof Error?M.message:String(M))}};u.useEffect(()=>{ea.current=!1},[]);const sc=x=>{x.preventDefault(),x.stopPropagation(),Bs(!1),ro(x.dataTransfer.files)},ls=async(x="ltd")=>{if(!n){J("Sign in with Google before checkout.");return}if(T&&x===Ht){J("LiveDesk license is already active.");return}if(T&&Ht==="pro"){J("LiveDesk Pro is already active.");return}Ne("checkout");try{const{data:M,error:D}=await mt.functions.invoke("dodo-checkout",{body:{plan:x}});if(D)throw D;if(!M?.checkout_url)throw new Error("Checkout function did not return a checkout URL.");window.location.assign(M.checkout_url)}catch(M){J(M instanceof Error?M.message:String(M)),Ne("")}},In=aT(),$a=sT(),Ms=at.length,ml=vu.filter(x=>Si.has(x)).length,hl=hr==="open"&&ol.sampleMs>0?`${ol.framesPerSecond.toFixed(1)} fps`:hr,Me=Le?it?ll.get(Le.deviceId):Si.get(Le.deviceId):void 0,Ai=Le?za(Kt[Le.deviceId],va(Le)):0,Zs=Le?oT(Le):[],En=typeof Me?.monitorIndex=="number"?za(Me.monitorIndex,Math.max(1,Me.monitorCount||1)):Ai,lo=(Me&&En===Ai?Cw(Me):null)||(Le?Sw(Le,Ai):null);lo&&`${lo.width}${lo.height}`;const oo=Le?Rs(it?"control":"wall",Le.deviceId):"",Rn=oo?$l[oo]:void 0,ha=oo?Ki[oo]:void 0,Qe=ha?.lastInfo,rc=Rn&&Rn.sampleMs>0?`${Rn.framesPerSecond.toFixed(1)} fps`:"waiting";Rn&&`${Rn.totalFrames}${rc}`,ha&&ha.sampleMs>0&&`${ha.framesPerSecond.toFixed(1)}`,ha&&ha.sampleMs>0&&`${ha.changedFramesPerSecond.toFixed(1)}`,Qe&&(`${Qe.frameSeq}${Qe.decoderLabel}${Qe.queueSize}${Qe.renderQueueSize}${Qe.droppedForLatency}${Qe.decoderFlushCount}${Qe.decoderTimestampFallbacks}${Qe.decoderInputCount}${Qe.decoderOutputCount}`,Qe.visualChanged),Qe&&`${Math.round(Qe.queuedForMs)}${Math.round(Qe.decodedForMs)}${Math.round(Qe.scheduledForMs)}${Qe.drawMs.toFixed(1)}`,Qe?.targetPaintIntervalMs&&`${Qe.targetPaintIntervalMs.toFixed(1)}${(1e3/Qe.targetPaintIntervalMs).toFixed(1)}`,ha&&`${ha.decoderInputFps.toFixed(1)}${ha.decoderOutputFps.toFixed(1)}`,Qe?.canvasPresentation,Qe&&`${Qe.interactiveBufferWaitCount}${Math.round(Qe.interactiveBufferWaitMs)}${Qe.interactiveQueueDrainCount}`,Rn&&(Me?.frameMode==="mode5-lzo-delta"?`${Fc(Rn.averageFrameBytes)}${Me.deltaVisualTileCount||0}${Me.deltaRefreshTileCount||0}${Me.deltaTotalTiles||0}`:`${Fc(Rn.averageFrameBytes)}${Math.round(Rn.tinyFrameRatio*100)}${Math.round(Rn.repeatedFrameRatio*100)}`),Rn&&Rn.sourceSendSampleCount>0&&`${Rn.sourceSendAverageMs.toFixed(1)}${Rn.sourceSendP95Ms.toFixed(1)}`,Ey(Rn),Ey(ha),Rn&&ha&&`${Ry(Rn)}${Ry(ha)}`,Me?Me.frameMode||Me.mode||Me.codec||Me.mimeType:it?ut.frameMode:Fe.frameMode,it?ut.frameMode:Fe.frameMode,Me?`${Me.width}${Me.height}${Fc(Me.byteLength)}`:it?`${Ps.maxWidth}${Ps.maxHeight}`:`${Fe.maxWidth}${Fe.maxHeight}`,Me&&`${Me.isKeyFrame?"key":String(Me.chunkType||"delta")}`,Me&&Me.monitorCount&&((Me.monitorIndex??0)+1,`${Me.monitorCount}`),Me&&[`src ${Math.round(Me.sourceGapMs||0)}ms`,`gap ${Math.round(Me.agentSendGapMs||0)}ms`,`tx ${Math.round(Me.agentSendDurationMs||0)}ms`,`pace ${Math.round(Me.agentPaceMs||0)}ms`,`queue ${Math.round(Me.agentQueueBeforePaceMs||0)}ms`,`age ${Math.round(Me.agentFrameAgeMs||0)}ms`,Me.browserReceivedEpochMs&&Me.receivedAt?`hub ${Math.max(0,Math.round(Me.browserReceivedEpochMs-Date.parse(Me.receivedAt)))}ms`:"",Me.browserReceivedEpochMs&&Me.hubPacketEpochMs?`sock ${Math.max(0,Math.round(Me.browserReceivedEpochMs-Me.hubPacketEpochMs))}ms`:"",Me.droppedByAgent?`drop ${Me.droppedByAgent}`:"",Me.hubIngressDropped?`ingress-drop ${Me.hubIngressDropped}`:"",Me.hubClientDropped?`ws-drop ${Me.hubClientDropped}`:"",Me.captureStageMs?`capture ${Math.round(Me.captureStageMs)}ms`:"",Me.requestedFps?`req ${Math.round(Me.requestedFps)}fps`:"",Me.effectiveFps?`eff ${Math.round(Me.effectiveFps)}fps`:"",Me.captureAverageMs?`avg ${Math.round(Me.captureAverageMs)}ms`:"",Me.captureP95Ms?`p95 ${Math.round(Me.captureP95Ms)}ms`:"",Me.slowFrameCount?`slow ${Math.round(Me.slowFrameCount)}`:"",Me.captureHelperRestarts?`helper ${Math.round(Me.captureHelperRestarts)}`:"",Me.convertMs?`rgb565 ${Math.round(Me.convertMs)}ms`:"",Me.compressMs?`lzo ${Math.round(Me.compressMs)}ms`:"",Me.captureSourceSerial?`cap #${Me.captureSourceSerial}`:"",Me.captureSourceSkipped?`cap skip ${Me.captureSourceSkipped}`:"",Me.frameMode==="mode5-lzo-delta"?`tiles ${Me.deltaVisualTileCount||0}+${Me.deltaRefreshTileCount||0}/${Me.deltaTotalTiles||0}@${Me.deltaTileSize||0}`:"",Me.platformProfile||Me.hardwareEncoder||"-",Me.atlasComposeMs?`atlas ${Me.atlasComposeMs.toFixed(1)}ms`:"",Me.atlasPoolStarved?`pool ${Me.atlasPoolStarved}`:"",Me.atlasTileCount?`tiles ${Me.atlasReadyTiles||0}/${Me.atlasTileCount}`:"",Me.atlasInputRevision?`input #${Me.atlasInputRevision}`:"",Me.atlasSourceMaxAgeMs!==void 0?`input-age ${Math.round(Me.atlasSourceMaxAgeMs)}ms`:"",Qe?.inputFeedbackMs!==void 0&&Qe.inputFeedbackAt!==void 0&&performance.now()-Qe.inputFeedbackAt<=jy?`feedback ${Math.round(Qe.inputFeedbackMs)}ms`:"",Me.contentHash?`enc ${Me.contentHash.slice(0,6)}`:"",Qe?.visualHash?`pix ${Qe.visualHash.slice(0,6)}`:""].filter(Boolean).join(" / "),gr==="open"&&[`${ka.sentPerSecond.toFixed(1)} hz`,ka.lastInputSeq>0?`rtt ${Math.round(ka.lastRoundTripMs)}ms`:"",ka.lastInputSeq>0?`apply ${ka.lastAgentApplyMs.toFixed(1)}ms`:"",ka.droppedPerSecond>0?`drop ${ka.droppedPerSecond.toFixed(1)}/s`:"",ka.bufferedAmount>0?`buf ${Fc(ka.bufferedAmount)}`:"",ka.lastInputType||"ready"].filter(Boolean).join(" / "),Qe?.inputFeedbackMs!==void 0&&Qe.inputFeedbackAt!==void 0&&performance.now()-Qe.inputFeedbackAt<=jy&&`${Math.round(Qe.inputFeedbackMs)}${Qe.inputFeedbackSeq||0}`,le&&[Aa,`context ${fn.audioContextState}`,`queue ${Math.round(fn.queuedMs)}ms`,`last ${Math.round(fn.lastPacketAgeMs)}ms`,`accepted ${Math.round(fn.lastAcceptedAgeMs)}ms`,`process ${Math.round(fn.localProcessingAgeMs)}ms`,`remote ${Math.round(fn.browserAgeMs)}/${Math.round(fn.captureAgeMs)}ms`,`heartbeat ${Math.round(fn.captureStatusAgeMs)}ms`,`capture ${fn.captureAlive&&fn.helperAlive?"alive":"down"}`,`drop ${fn.drops}`,`resync ${fn.resyncs}`,`restart ${fn.automaticRestarts}`,fn.pendingDecodes>0?`decode ${fn.pendingDecodes}`:"",ji?`#${ji.frameSeq}`:"waiting"].filter(Boolean).join(" / "),Me&&`${Me.frameSeq}${sb(Me.receivedAt||Me.capturedAt)}`;const os=Math.max(0,ol.bytesPerSecond*8/1e6),br=mr?.atlasReadyTiles??ml,pl=mr?.atlasTileCount??ml,wr=br===pl?`${pl} tiles`:`${br}/${pl} tiles`,Sr=Gn.length>0;it?`${hl}${os.toFixed(os>=10?0:1)}`:Sr?`${wr}${hl}${os.toFixed(os>=10?0:1)}`:`${ml}${hl}${os.toFixed(os>=10?0:1)}`;const Cu=j?"offline":b?.started?"online":"starting",co=fa.length,jf=it?Le?Ka(Le):"No workstation":co===0?"No workstation":co>1?`${co} selected`:Le?Ka(Le):"No workstation",ju=it?[Le?.deviceId].filter(x=>!!x):fa.map(x=>x.deviceId),rn=Oo[Ee]||Oo.en,Cr=rn.sync||Oo.en.sync,gl=a||R?"checking":T?Ht==="pro"?"Pro LTD active":`Plus LTD ${at.length}/${Bc}`:hu?`Free ${at.length}/${Hc}`:`Upgrade ${at.length}/${Hc}`,ku=Ht==="pro"?"Pro active":fe==="checkout"?"Opening":Ht==="ltd"?"Pro $199":"Plus $79",lc=T?Ht==="pro"?"Pro active":"Upgrade to Pro LTD":n?fe==="checkout"?"Opening checkout":Ht==="ltd"?"Buy Pro LTD":"Buy Plus LTD":fe==="auth"?"Opening Google":"Sign in to buy",uo=Ht==="pro"||fe==="checkout"||fe==="auth"||a||R,xl=n?.user?.user_metadata,yl=By(xl,"avatar_url","picture"),jr=By(xl,"full_name","name")||n?.user?.email||"Google",Js=jr.slice(0,1).toUpperCase(),Ni=b?.started?"Local app ready":"Start LiveDesk",Au=r?.active?"Published":n?"Not published":"Sign in required",Nu=/^\d{6}$/.test(b?.pairingPin||"")?b?.pairingPin:"------",kr=Yd.find(x=>x.width===Fe.maxWidth&&x.height===Fe.maxHeight)?.id||`${Fe.maxWidth}x${Fe.maxHeight}`,bl=Fe.atlasTileSizeMode==="auto"?"auto":yh.find(x=>x.width===Fe.atlasTileWidth&&x.height===Fe.atlasTileHeight)?.id||"320x180",fo=xh.find(x=>x.width===ut.maxWidth&&x.height===ut.maxHeight)?.id||`${ut.maxWidth}x${ut.maxHeight}`,wl=Wd.find(x=>x.id===Fe.frameMode)||Wd[0],Wn=x=>{Is(M=>{const D=x.frameMode?Wh(x.frameMode):M.frameMode,B=x.frameMode!==void 0&&D!==M.frameMode;return{...M,...x,frameMode:D,fps:Kh(x.fps??(B?yw(D):M.fps),D)}})},Mu=x=>{const M=Yd.find(D=>D.id===x);M&&Wn({maxWidth:M.width,maxHeight:M.height})},Mi=x=>{if(x==="auto"){Wn({atlasTileSizeMode:"auto"});return}const M=yh.find(D=>D.id===x);!M?.width||!M?.height||Wn({atlasTileSizeMode:"fixed",atlasTileWidth:M.width,atlasTileHeight:M.height})},Ti=x=>{x.frameMode!==void 0&&(Q(""),me("")),ui(M=>{const D=x.frameMode?Yh(x.frameMode):M.frameMode,B=x.frameMode!==void 0&&D!==M.frameMode,z=x.fps??(B?30:M.fps),ge=x.maxWidth??M.maxWidth,pe=x.maxHeight??M.maxHeight;return{...M,...x,frameMode:D,fps:ds(z,20,D==="mode3-h264-hw"?60:30,D==="mode3-h264-hw"?60:30),maxWidth:D==="mode3-h264-hw"?ge:Math.min(1920,ge),maxHeight:D==="mode3-h264-hw"?pe:Math.min(1080,pe)}})},ei=x=>{const M=xh.find(D=>D.id===x);M&&Ti({maxWidth:M.width,maxHeight:M.height})},Sl=x=>{if(typeof window<"u"&&(x==="support"?window.history.pushState({},"","/support"):ze==="support"&&window.history.pushState({},"","/")),x==="control"){const M=qn||lr;if(M&&(ba(!1),te(M.deviceId)),je(x),!Wt){Oe(!1),J(cr);return}Oe(!0);return}x==="agents"&&rt(null),x==="wall"&&Ut(M=>M+1),je(x),Oe(!1)},ti=fe==="update"||De?.stage==="updating"||["dispatching","waiting-for-clients","hub-restart-requested"].includes(b?.update?.state||""),ni=!!(b?.update?.updateAvailable&&b.update.canApply||ti||!b&&De),ia=hC(Ee),Ei=u.useCallback(x=>{if(!De?.targetIds.includes(x))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 M=b?.update?.operationId===De.operationId?b.update.targets?.find(D=>D.deviceId===x):void 0;switch(M?.state){case"completed":return{state:"updated",label:"Updated"};case"failed":return{state:"failed",label:"Update failed",error:M.error||b?.update?.error};case"pending-offline":return{state:"offline",label:"Waiting for reconnect"};case"queued":return{state:"queued",label:"Queued"};case"waiting":return M.candidateSince?{state:"updating",label:"Verifying restart..."}:{state:"updating",label:"Restarting..."};default:return{state:"updating",label:"Verifying..."}}},[b?.update,De]);return s.jsxs("main",{className:"app-shell",children:[s.jsxs("aside",{className:"tool-rail","aria-label":"LiveDesk tools",children:[s.jsx("div",{className:"rail-brand",title:"LiveDesk",children:s.jsx(ib,{size:25})}),s.jsx("nav",{className:"rail-tools",children:MT.map(x=>{const M=x.icon,D=Xd(x.tooltip,Ee);return s.jsxs("button",{className:`rail-tool ${x.id==="sync-server"?"sync-server hub-sync-trigger":""} ${ze===x.id?"active":""} accent-${x.accent}`,onClick:()=>x.id==="sync-server"?Ns():Sl(x.id),"data-tooltip":x.id==="sync-server"&&$e?void 0:Th(x.label,x.tooltip,Ee),"aria-label":`${x.label}. ${D}`,type:"button",disabled:x.id==="sync-server"&&fe==="host","aria-busy":x.id==="sync-server"&&fe==="host","aria-expanded":x.id==="sync-server"?$e:void 0,"aria-haspopup":x.id==="sync-server"?"dialog":void 0,"aria-controls":x.id==="sync-server"&&$e?"hub-sync-popover":void 0,children:[x.id==="sync-server"&&fe==="host"?s.jsx("span",{className:"sync-server-spinner","aria-hidden":"true"}):s.jsx(M,{size:19}),s.jsx("span",{children:x.id==="sync-server"&&fe==="host"?"Syncing…":x.label})]},x.id)})}),s.jsxs("div",{className:"rail-footer",children:[TT.map(x=>{const M=x.icon;return s.jsxs("button",{className:`rail-tool compact ${ze===x.id?"active":""} accent-${x.accent}`,onClick:()=>Sl(x.id),title:x.label,type:"button",children:[s.jsx(M,{size:18}),s.jsx("span",{children:x.label})]},x.id)}),s.jsxs("button",{className:`rail-tool compact local-settings ${ar?"active":""}`,onClick:()=>{je("settings"),typeof window<"u"&&window.history.pushState({},"","/"),an(!1),Oe(!1),tt(!1)},title:"Settings",type:"button",children:[s.jsx(qy,{size:18}),s.jsx("span",{children:"Settings"})]}),s.jsxs("button",{className:`rail-account ${n?"signed-in":""}`,onClick:()=>{an(x=>!x)},disabled:a||fe==="auth","aria-expanded":$t,title:n?`Account: ${n.user?.email||jr}`:"Sign in with Google",type:"button",children:[n?yl?s.jsx("img",{src:yl,alt:jr,referrerPolicy:"no-referrer"}):s.jsx("span",{className:"avatar-fallback",children:Js}):s.jsx(Ol,{size:18}),s.jsx("span",{children:n?"Account":"Google"})]}),$t&&s.jsxs("section",{className:"account-popover",role:"dialog","aria-label":"LiveDesk account",children:[s.jsxs("div",{className:"account-popover-head",children:[s.jsx("div",{className:"account-popover-avatar",children:n&&yl?s.jsx("img",{src:yl,alt:jr,referrerPolicy:"no-referrer"}):n?s.jsx("span",{children:Js}):s.jsx(Ol,{size:18})}),s.jsxs("div",{children:[s.jsx("strong",{children:n?jr:"Account"}),s.jsx("p",{children:n?.user?.email||"Not signed in"})]})]}),s.jsxs("dl",{className:"account-popover-facts",children:[s.jsx("dt",{children:"User"}),s.jsx("dd",{children:n?.user?.email||"Not signed in"}),s.jsx("dt",{children:"Network"}),s.jsx("dd",{children:Ni}),s.jsx("dt",{children:"Access"}),s.jsx("dd",{children:Au}),s.jsx("dt",{children:"Plan"}),s.jsx("dd",{children:gl}),s.jsx("dt",{children:"Ads"}),s.jsx("dd",{children:Ht==="free"?"Standard banner":"Removed"})]}),n?s.jsxs("button",{className:"account-popover-action",onClick:Ks,disabled:fe==="auth",type:"button",children:[s.jsx(Gy,{size:16}),"Logout"]}):s.jsxs("button",{className:"account-popover-action primary",onClick:zn,disabled:fe==="auth",type:"button",children:[s.jsx(Ol,{size:16}),"Sign in with Google"]})]})]})]}),$e&&s.jsxs("section",{id:"hub-sync-popover",className:"client-hub-switch-popover hub-sync-popover",role:"dialog","aria-modal":"false","aria-labelledby":"hub-sync-title","aria-describedby":"hub-sync-description hub-sync-notice",children:[s.jsxs("header",{className:"client-hub-switch-head",children:[s.jsx("span",{className:"client-hub-switch-mark","aria-hidden":"true",children:s.jsx(Gi,{size:19})}),s.jsx("span",{className:"client-hub-switch-eyebrow",children:ia.eyebrow}),s.jsx("button",{className:"client-hub-switch-close",type:"button",onClick:()=>sa(),"aria-label":ia.closeLabel,children:s.jsx(Ha,{size:17})})]}),s.jsx("h2",{id:"hub-sync-title",children:ia.title}),s.jsx("p",{id:"hub-sync-description",children:ia.description}),s.jsxs("p",{id:"hub-sync-notice",className:"client-hub-switch-notice",children:[s.jsx(Lt,{size:16,"aria-hidden":"true"}),s.jsx("span",{children:ia.restartNotice})]}),s.jsxs("div",{className:"client-hub-switch-actions",children:[s.jsx("button",{type:"button",onClick:()=>sa(),children:ia.cancel}),s.jsxs("button",{ref:Mt,className:"primary",type:"button",onClick:wu,disabled:fe==="host",children:[s.jsx(Gi,{size:16}),ia.confirm]})]})]}),s.jsxs("section",{className:`desk-stage ${iu&&!Un?"dock-open":""} ${it?"control-stage":""} ${Vo?"agents-stage":""}`,children:[s.jsxs("header",{className:"topbar",children:[s.jsxs("div",{className:"brand",children:[s.jsx("span",{className:"brand-mark",children:s.jsx(gn,{size:18})}),s.jsxs("div",{className:"brand-copy",children:[s.jsx("h1",{children:"LiveDesk"}),s.jsx("p",{children:"Control wall for local machines"})]}),ni?s.jsxs("button",{className:"topbar-update-button",onClick:()=>{nc()},title:De?.error||`Update LiveDesk to ${b?.update?.latestVersion||De?.targetManagerVersion||"latest"}`,"aria-label":ti?"LiveDesk update in progress":`Update LiveDesk to ${b?.update?.latestVersion||De?.targetManagerVersion||"latest"}`,type:"button",disabled:ti||!b?.update?.canApply,"aria-busy":ti,children:[ti?s.jsx("span",{className:"topbar-update-spinner","aria-hidden":"true"}):s.jsx(Qh,{size:19,"aria-hidden":"true"}),ti&&b?.update?.targetCount?s.jsxs("span",{className:"topbar-update-count","aria-hidden":"true",children:[b.update.completedCount||0,"/",b.update.targetCount]}):null]}):null]}),s.jsxs("div",{className:"topbar-tray",children:[ir&&!it&&s.jsxs("div",{className:"file-share-top-route","aria-label":"File distribution route",children:[s.jsxs("div",{children:[s.jsx(zl,{size:17}),s.jsxs("span",{children:[s.jsx("small",{children:"Source"}),s.jsx("strong",{children:"LiveDesk Hub"})]})]}),s.jsx(Jh,{size:15}),s.jsx(m0,{size:16}),s.jsxs("div",{children:[s.jsx("span",{className:"file-share-top-route-laptops",children:"▣ ▣ ▣"}),s.jsxs("span",{children:[s.jsx("small",{children:"Destination"}),s.jsxs("strong",{children:[ru," workstation",ru===1?"":"s"]}),s.jsx("em",{children:Xn.trim()||"Desktop/LiveDeskFiles"})]})]})]}),iu&&!it&&s.jsxs("div",{className:"top-actions",children:[s.jsx(by,{controller:Zl,onError:J}),s.jsx("span",{className:"top-actions-divider","aria-hidden":"true"}),s.jsx("div",{className:"segmented-control","aria-label":"Wall view",children:NT.map(x=>s.jsx("button",{className:Xe===x.id?"active":"",onClick:()=>gt(x.id),type:"button",children:x.label},x.id))})]}),it&&s.jsx("div",{className:"top-actions",children:s.jsx(by,{controller:Zl,onError:J})})]})]}),sr?s.jsxs("section",{className:"doc-page",lang:Ee,dir:Ee==="ar"?"rtl":"ltr",children:[s.jsxs("section",{className:"doc-hero",children:[s.jsxs("div",{className:"doc-hero-copy",children:[s.jsxs("span",{className:"pricing-eyebrow",children:[s.jsx(Kd,{size:16}),rn.eyebrow]}),s.jsx("h2",{children:rn.title}),s.jsx("p",{children:rn.intro})]}),s.jsxs("label",{className:"doc-language-picker",children:[s.jsxs("span",{children:[s.jsx(h0,{size:17}),rn.languageLabel]}),s.jsx("select",{value:Ee,onChange:x=>ua(x.target.value),children:RT.map(x=>s.jsx("option",{value:x.id,children:x.label},x.id))})]})]}),s.jsx("section",{className:"doc-grid",children:rn.sections.map((x,M)=>{const B=[Gi,Ud,Um,Lt,Hl][M]||Kd;return s.jsxs("article",{className:"doc-card",children:[s.jsx("div",{className:"doc-card-icon",children:s.jsx(B,{size:19})}),s.jsxs("div",{children:[s.jsx("h3",{children:x.title}),s.jsx("p",{children:x.body}),s.jsx("ul",{children:x.points.map(z=>s.jsx("li",{children:z},z))})]})]},x.title)})}),Cr&&s.jsxs("section",{className:"doc-sync",children:[s.jsxs("div",{className:"doc-sync-head",children:[s.jsx(Um,{size:20}),s.jsxs("div",{children:[s.jsx("h3",{children:Cr.title}),s.jsx("p",{children:Cr.body})]})]}),s.jsx("ul",{children:Cr.points.map(x=>s.jsx("li",{children:x},x))})]}),s.jsxs("section",{className:"doc-firewall",children:[s.jsxs("div",{className:"doc-firewall-head",children:[s.jsx(Lt,{size:20}),s.jsxs("div",{children:[s.jsx("h3",{children:rn.firewall.title}),s.jsx("p",{children:rn.firewall.body})]})]}),s.jsx("ul",{children:rn.firewall.points.map(x=>s.jsx("li",{children:x},x))})]}),s.jsxs("section",{className:"doc-command-panel",children:[s.jsxs("div",{className:"doc-command-head",children:[s.jsx(Ud,{size:20}),s.jsxs("div",{children:[s.jsx("h3",{children:rn.commands.title}),s.jsx("p",{children:rn.commands.body})]})]}),s.jsxs("div",{className:"doc-command-list",children:[rn.commands.manager&&s.jsxs("div",{className:"doc-command-row",children:[s.jsx("span",{children:rn.commands.manager}),s.jsx("code",{children:$a}),s.jsx("button",{className:"icon-button",onClick:()=>Ll($a),title:"Copy command",type:"button",children:s.jsx(Nl,{size:16})})]}),s.jsxs("div",{className:"doc-command-row",children:[s.jsx("span",{children:rn.commands.primary}),s.jsx("code",{children:In}),s.jsx("button",{className:"icon-button",onClick:()=>Ll(In),title:"Copy command",type:"button",children:s.jsx(Nl,{size:16})})]}),s.jsxs("div",{className:"doc-command-row",children:[s.jsx("span",{children:rn.commands.slot}),s.jsx("code",{children:`${In} 3`}),s.jsx("button",{className:"icon-button",onClick:()=>Ll(`${In} 3`),title:"Copy command",type:"button",children:s.jsx(Nl,{size:16})})]})]})]})]}):Vo?s.jsx(vy,{hubUrl:N,devices:C,launchRequest:Ye}):ir?s.jsx(xN,{hubUrl:N,devices:at,localFeatureAccess:Wt,upgradeNotice:cr,remoteDirectory:Xn,onRemoteDirectoryChange:Wi,targetMode:mi,selectedTargetIds:Jn,onTargetModeChange:Qr,onTargetToggle:x=>Xr(M=>M.includes(x)?M.filter(D=>D!==x):[...M,x]),filePickerRef:Wl,folderPickerRef:su,onBrowserFileImport:x=>{yr(x)},onBrowserFolderImport:x=>{yr(x)},onNotice:J,onTransferChange:x=>{if(!x){as(null);return}const M=x.state==="failed"||x.state==="partially-failed"||x.state==="cancelled"?"failed":x.state==="completed"?"queued":x.state==="sending"?"sending":"reading";as({id:x.id,status:M,progress:x.progress,message:x.message}),["completed","partially-failed","failed","cancelled"].includes(x.state)&&window.setTimeout(()=>as(D=>D?.id===x.id?null:D),4500)}}):Jr?s.jsx(tb,{session:n,currentProductKey:"livedesk",appVersion:"",onSignIn:zn}):ar?s.jsx(zj,{hubUrl:N,runtimeRole:b?.runtimeRole||"hub",runtimeDeviceId:b?.deviceId||"",sessionAccessToken:n?.access_token||"",pin:s.jsxs(Ij,{children:[s.jsxs("div",{className:"settings-section-grid",children:[s.jsxs("section",{className:"settings-section-card settings-pairing-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Pair a workstation"}),s.jsx("h3",{children:"Connect another local PC"})]}),s.jsx(Yt,{size:20})]}),s.jsxs("div",{className:"settings-pin-display",children:[s.jsx("span",{children:"Hub PIN"}),s.jsx("strong",{children:Nu}),s.jsxs("button",{className:"text-button ghost compact",onClick:ac,disabled:!b?.started||fe==="pin",type:"button",children:[s.jsx(Ds,{size:15}),fe==="pin"?"Creating":"New PIN"]})]})]}),s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Hub status"}),s.jsx("h3",{children:Cu})]}),s.jsx("span",{className:`settings-status-dot state-${Cu}`})]}),s.jsxs("dl",{className:"settings-facts",children:[s.jsx("dt",{children:"Address"}),s.jsx("dd",{children:N||"-"}),s.jsx("dt",{children:"Connected workstations"}),s.jsxs("dd",{children:[Ms,"/",Kl]}),s.jsx("dt",{children:"Sync access"}),s.jsx("dd",{children:b?.started?"Local app ready":"Start Hub first"}),s.jsx("dt",{children:"Plan"}),s.jsx("dd",{children:gl})]}),s.jsxs("div",{className:"settings-action-row",children:[s.jsxs("button",{className:"text-button primary",onClick:()=>Na({takeover:!0,requestLocalAccess:!0}),disabled:!n||fe==="host",type:"button",children:[fe==="host"?s.jsx("span",{className:"sync-server-spinner","aria-hidden":"true"}):s.jsx(Um,{size:16}),fe==="host"?"Syncing…":"Sync access"]}),s.jsxs("button",{className:"text-button buy",onClick:()=>ls(Ht==="ltd"?"pro":"ltd"),disabled:fe==="checkout"||Ht==="pro",type:"button",children:[s.jsx(Do,{size:16}),ku]})]})]})]}),s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"File transfer"}),s.jsx("h3",{children:"Client destination folder"})]}),s.jsx(Lo,{size:20})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"Remote folder"}),s.jsx("input",{value:Xn,onChange:x=>Wi(x.target.value),placeholder:"Desktop/LiveDeskFiles"})]}),s.jsx("p",{className:"settings-help",children:"Blank uses Desktop/LiveDeskFiles on each workstation."})]})]}),wall:s.jsx(Oj,{children:s.jsxs("div",{className:"settings-section-grid",children:[s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Wall stream"}),s.jsx("h3",{children:"Frame delivery"})]}),s.jsx(Kc,{size:20})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"Frame mode"}),s.jsx("select",{value:Fe.frameMode,onChange:x=>Wn({frameMode:Wh(x.target.value)}),children:Wd.map(x=>s.jsxs("option",{value:x.id,children:[x.label," - ",x.detail]},x.id))})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"H.264 decode"}),s.jsx("select",{value:Fe.h264DecodeAcceleration,onChange:x=>Wn({h264DecodeAcceleration:cf(x.target.value)}),children:Vh.map(x=>s.jsx("option",{value:x.id,children:x.label},x.id))})]}),s.jsxs("div",{className:"settings-field-grid",children:[s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"FPS"}),s.jsx("select",{value:Fe.fps,onChange:x=>Wn({fps:Kh(x.target.value,Fe.frameMode)}),children:bp.filter(x=>x<=bw(Fe.frameMode)).map(x=>s.jsx("option",{value:x,children:x},x))})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:ct?"Atlas tile":"Resolution"}),s.jsx("select",{value:ct?bl:kr,onChange:x=>ct?Mi(x.target.value):Mu(x.target.value),children:(ct?yh:Yd).map(x=>s.jsx("option",{value:x.id,children:x.label},x.id))})]})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"Quality"}),s.jsx("select",{value:Fe.quality,onChange:x=>Wn({quality:ds(x.target.value,20,95,xa.quality)}),children:Dy.map(x=>s.jsx("option",{value:x,children:x},x))})]})]}),s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Wall behavior"}),s.jsx("h3",{children:"Visibility and load"})]}),s.jsx(gn,{size:20})]}),s.jsxs("label",{className:"settings-toggle",children:[s.jsx("input",{type:"checkbox",checked:Fe.autoStartLive,onChange:x=>Wn({autoStartLive:x.target.checked})}),s.jsx("span",{children:"Auto live on connected screens"})]}),s.jsxs("label",{className:"settings-toggle",children:[s.jsx("input",{type:"checkbox",checked:Fe.visibleOnlyLive,onChange:x=>Wn({visibleOnlyLive:x.target.checked})}),s.jsx("span",{children:"Stream visible tiles first"})]}),!ct&&s.jsxs("label",{className:"settings-toggle",children:[s.jsx("input",{type:"checkbox",checked:Fe.adaptiveSizeByWall,onChange:x=>Wn({adaptiveSizeByWall:x.target.checked})}),s.jsx("span",{children:"Fit stream size to Wall"})]}),s.jsxs("label",{className:"settings-toggle",children:[s.jsx("input",{type:"checkbox",checked:Fe.adaptiveLoadShedding,onChange:x=>Wn({adaptiveLoadShedding:x.target.checked})}),s.jsx("span",{children:"Reduce FPS under load"})]}),s.jsxs("label",{className:"settings-toggle",children:[s.jsx("input",{type:"checkbox",checked:Fe.showScreenStatus,onChange:x=>Wn({showScreenStatus:x.target.checked})}),s.jsx("span",{children:"Screen status overlay"})]}),s.jsxs("div",{className:"settings-summary",children:[s.jsx("span",{children:wl.label}),s.jsxs("strong",{children:[_n.maxWidth,"x",_n.maxHeight," / ",Tn,"fps"]})]}),s.jsxs("button",{className:"settings-reset",onClick:()=>Is(xa),type:"button",children:[s.jsx($c,{size:15})," Reset Wall settings"]})]})]})}),control:s.jsx(Hj,{children:s.jsxs("div",{className:"settings-section-grid",children:[s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Control stream"}),s.jsx("h3",{children:"Low-latency delivery"})]}),s.jsx($d,{size:20})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"Frame mode"}),s.jsx("select",{value:ut.frameMode,onChange:x=>Ti({frameMode:Yh(x.target.value)}),children:WM.map(x=>s.jsx("option",{value:x.id,children:x.label},x.id))})]}),ut.frameMode==="mode3-h264-hw"&&s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"H.264 decode"}),s.jsx("select",{value:ut.h264DecodeAcceleration,onChange:x=>Ti({h264DecodeAcceleration:cf(x.target.value)}),children:Vh.map(x=>s.jsx("option",{value:x.id,children:x.label},x.id))})]}),s.jsxs("div",{className:"settings-field-grid",children:[s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"FPS"}),s.jsx("select",{value:ut.fps,onChange:x=>Ti({fps:ds(x.target.value,20,60,Ia.fps)}),children:YM.filter(x=>ut.frameMode==="mode3-h264-hw"||x<=30).map(x=>s.jsx("option",{value:x,children:x},x))})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"Resolution"}),s.jsx("select",{value:fo,onChange:x=>ei(x.target.value),children:xh.filter(x=>ut.frameMode==="mode3-h264-hw"||x.width<=1920).map(x=>s.jsx("option",{value:x.id,children:x.label},x.id))})]})]}),ut.frameMode==="mode3-h264-hw"&&s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"Quality"}),s.jsx("select",{value:ut.quality,onChange:x=>Ti({quality:ds(x.target.value,20,95,Ia.quality)}),children:Dy.map(x=>s.jsx("option",{value:x,children:x},x))})]})]}),s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Control behavior"}),s.jsx("h3",{children:"Session display"})]}),s.jsx(Yt,{size:20})]}),s.jsxs("label",{className:"settings-toggle",children:[s.jsx("input",{type:"checkbox",checked:ut.showScreenStatus,onChange:x=>Ti({showScreenStatus:x.target.checked})}),s.jsx("span",{children:"Screen status overlay"})]}),s.jsxs("div",{className:"settings-summary control",children:[s.jsx("span",{children:ut.frameMode==="mode5-lzo-delta"?"Mode 5 tile delta":"Mode 3 H.264"}),s.jsxs("strong",{children:[Ps.maxWidth,"x",Ps.maxHeight," / ",rr,"fps"]})]}),s.jsxs("button",{className:"settings-reset",onClick:()=>ui(Ia),type:"button",children:[s.jsx($c,{size:15})," Reset Control settings"]})]})]})}),agent:s.jsx(Bj,{hubUrl:N}),captureGallery:s.jsx(yM,{hubUrl:N,onToast:J}),advancedExtras:s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Connection commands"}),s.jsx("h3",{children:"Developer setup"})]}),s.jsx(Nl,{size:20})]}),s.jsxs("div",{className:"settings-command-list",children:[s.jsxs("div",{className:"settings-command-row",children:[s.jsx("span",{children:"Client"}),s.jsx("code",{children:In}),s.jsx("button",{className:"icon-button",onClick:()=>Ll(In),title:"Copy client command",type:"button",children:s.jsx(Nl,{size:16})})]}),s.jsxs("div",{className:"settings-command-row",children:[s.jsx("span",{children:"Slot example"}),s.jsx("code",{children:`${In} 3`}),s.jsx("button",{className:"icon-button",onClick:()=>Ll(`${In} 3`),title:"Copy slot command",type:"button",children:s.jsx(Nl,{size:16})})]}),s.jsxs("div",{className:"settings-command-row",children:[s.jsx("span",{children:"Hub"}),s.jsx("code",{children:$a}),s.jsx("button",{className:"icon-button",onClick:()=>Ll($a),title:"Copy Hub command",type:"button",children:s.jsx(Nl,{size:16})})]})]})]})}):Yl?s.jsxs("section",{className:"pricing-page",children:[s.jsxs("header",{className:"pricing-header",children:[s.jsxs("div",{children:[s.jsxs("span",{className:"pricing-eyebrow",children:[s.jsx(Ah,{size:15})," LiveDesk plans"]}),s.jsx("h2",{children:"Choose the plan that fits your wall"}),s.jsx("p",{children:"Start free with a local screen wall. Upgrade when you need ad-free monitoring, more workstations, or commercial controls."})]}),s.jsx("button",{className:"pricing-close",onClick:()=>Sl("wall"),title:"Close pricing",type:"button",children:s.jsx(Ha,{size:18})})]}),s.jsxs("div",{className:"pricing-status","aria-live":"polite",children:[s.jsx("span",{children:"Current plan"}),s.jsx("strong",{children:or.name}),s.jsxs("small",{children:[at.length,"/",VM(Ql)," connected devices"]})]}),s.jsxs("div",{className:"pricing-cards","aria-label":"LiveDesk plans",children:[s.jsxs("article",{className:`pricing-plan-card ${Ht==="free"?"current":""}`,children:[s.jsxs("div",{className:"pricing-plan-topline",children:[s.jsx("span",{className:"pricing-plan-badge free",children:"Free"}),s.jsx("strong",{children:"$0"})]}),s.jsx("p",{className:"pricing-plan-audience",children:El.free.audience}),s.jsx("h3",{children:"Monitor your local wall"}),s.jsx("p",{children:El.free.note}),s.jsxs("ul",{children:[s.jsxs("li",{children:[s.jsx(Hn,{size:16})," Up to ",Hc," devices"]}),s.jsxs("li",{children:[s.jsx(Hn,{size:16})," Live view and local control"]}),s.jsxs("li",{children:[s.jsx(Hn,{size:16})," Standard ad-supported banner"]})]}),s.jsx("span",{className:"pricing-current-label",children:Ht==="free"?"Current plan":"Included for everyone"})]}),s.jsxs("article",{className:`pricing-plan-card featured ${Ht==="ltd"?"current":""}`,children:[s.jsxs("div",{className:"pricing-plan-topline",children:[s.jsxs("span",{className:"pricing-plan-badge plus",children:[s.jsx(p0,{size:14})," Plus"]}),s.jsx("strong",{children:"$5"})]}),s.jsx("p",{className:"pricing-plan-audience",children:El.ltd.audience}),s.jsx("h3",{children:"Ad-free monitoring"}),s.jsx("p",{children:"More room for personal AI workstations without the standard banner."}),s.jsxs("ul",{children:[s.jsxs("li",{children:[s.jsx(Hn,{size:16})," Up to ",Bc," devices"]}),s.jsxs("li",{children:[s.jsx(Hn,{size:16})," No standard ad banner"]}),s.jsxs("li",{children:[s.jsx(Hn,{size:16})," ",El.ltd.ltd]})]}),s.jsxs("button",{className:"pricing-plan-button",onClick:n?()=>ls("ltd"):zn,disabled:Ht!=="free"||fe==="checkout"||fe==="auth"||a||R,type:"button",children:[s.jsx(Do,{size:16}),Ht==="free"?n?"Choose Plus":"Sign in for Plus":"Plus active"]})]}),s.jsxs("article",{className:`pricing-plan-card pro ${Ht==="pro"?"current":""}`,children:[s.jsxs("div",{className:"pricing-plan-topline",children:[s.jsxs("span",{className:"pricing-plan-badge pro",children:[s.jsx(Lt,{size:14})," Pro"]}),s.jsx("strong",{children:"$15"})]}),s.jsx("p",{className:"pricing-plan-audience",children:El.pro.audience}),s.jsx("h3",{children:"For serious operations"}),s.jsx("p",{children:"Commercial-ready monitoring for larger AI labs, studios, and teams."}),s.jsxs("ul",{children:[s.jsxs("li",{children:[s.jsx(Hn,{size:16})," 30+ workstation walls"]}),s.jsxs("li",{children:[s.jsx(Hn,{size:16})," Commercial use included"]}),s.jsxs("li",{children:[s.jsx(Hn,{size:16})," ",El.pro.ltd]})]}),s.jsxs("button",{className:"pricing-plan-button",onClick:n?()=>ls("pro"):zn,disabled:Ht==="pro"||fe==="checkout"||fe==="auth"||a||R,type:"button",children:[s.jsx(Do,{size:16}),Ht==="pro"?"Pro active":n?"Choose Pro":"Sign in for Pro"]})]})]}),s.jsxs("section",{className:"pricing-includes",children:[s.jsxs("div",{children:[s.jsx(Yt,{size:17}),s.jsx("span",{children:"Screen wall"}),s.jsx("strong",{children:"120+ slots"})]}),s.jsxs("div",{children:[s.jsx($d,{size:17}),s.jsx("span",{children:"Focused control"}),s.jsx("strong",{children:"Local-first"})]}),s.jsxs("div",{children:[s.jsx(rx,{size:17}),s.jsx("span",{children:"Remote audio"}),s.jsx("strong",{children:"Available"})]}),s.jsxs("div",{children:[s.jsx(Lo,{size:17}),s.jsx("span",{children:"File transfer"}),s.jsx("strong",{children:"Included"})]})]}),s.jsxs("p",{className:"pricing-note",children:[s.jsx(Hn,{size:15})," Commercial use requires Pro. Plus LTD is for personal, creator, and homelab use."]}),s.jsxs("button",{className:"pricing-primary-cta",onClick:n?()=>ls(Ht==="ltd"?"pro":"ltd"):zn,disabled:uo,type:"button",children:[s.jsx(Do,{size:18}),lc]})]}):s.jsx(s.Fragment,{children:s.jsxs("section",{className:`monitor-layout ${Un?"dock-collapsed":""}`,children:[s.jsxs("section",{ref:Go,className:`screen-wall-panel ${tr?"drop-active":""}`,onClick:x=>{x.currentTarget===x.target&&Et()},onDragEnter:x=>{x.preventDefault(),Bs(!0)},onDragOver:x=>{x.preventDefault(),x.dataTransfer.dropEffect="copy"},onDragLeave:x=>{x.currentTarget===x.target&&Bs(!1)},onDrop:sc,children:[Gn.length>0&&s.jsx("canvas",{ref:fr,className:"atlas-source-canvas",width:wi?.width||1920,height:wi?.height||1080,"aria-hidden":"true"}),it?s.jsx("section",{className:"control-focus",children:s.jsxs("div",{className:"control-wall",children:[Le&&Zs.length>1&&s.jsx("div",{className:"control-monitor-tabs","aria-label":"Select monitor",children:Zs.map(x=>s.jsxs("button",{className:x.index===Ai?"active":"",onClick:()=>Ma(Le.deviceId,x.index),title:cT(x),type:"button",children:[s.jsx("span",{children:x.name||`Display ${x.index+1}`}),x.width>0&&x.height>0&&s.jsxs("small",{children:[x.width,"x",x.height]})]},x.index))}),Le?s.jsx(kh,{device:Le,frame:Me,selected:!1,controlEnabled:ws&&Se&&vr,showStatus:ut.showScreenStatus,monitorIndex:za(Kt[Le.deviceId],va(Le)),monitorCount:va(Le),onSelect:()=>{},onFocusDevice:()=>te(Le.deviceId),onOpenControl:()=>ki(Le.deviceId),onCycleMonitor:x=>rs(Le.deviceId,x),onCanvasReady:nl,sendInput:Ci,presentationReady:Ul},Le.deviceId):s.jsxs("div",{className:"control-empty",children:[s.jsx(Yt,{size:30}),s.jsx("strong",{children:"No workstation"}),s.jsx("span",{children:"Open a workstation from the Wall."})]}),Le&&Yo&&s.jsxs("div",{className:"control-connection-overlay",role:"alert",children:[s.jsx(Lt,{size:22,"aria-hidden":"true"}),s.jsx("strong",{children:"Accessibility permission required"}),s.jsx("small",{children:"On the Mac, allow Accessibility for the terminal app that starts LiveDesk, then restart the Mac client."})]}),Le&&!Yo&&!Ul&&s.jsxs("div",{className:"control-connection-overlay",role:"status","aria-live":"polite",children:[U!=="error"&&s.jsx("span",{className:"control-connection-spinner","aria-hidden":"true"}),s.jsx("strong",{children:U==="error"?"Connection failed":"Connecting"}),s.jsx("small",{children:U==="error"?"See the notification for details. Reopen Control to retry.":Gs||de?"Control stream is recovering. See the notification for details.":hr==="open"?"Preparing the first control frame":"Opening the Control stream"})]})]})}):Xe==="list"?s.jsxs("div",{className:"wall-device-list",role:"grid","aria-label":"Computer status list",children:[s.jsxs("div",{className:"wall-device-list-head",role:"row",children:[s.jsx("span",{role:"columnheader",children:"Computer"}),s.jsx("span",{role:"columnheader",children:"Status"}),s.jsx("span",{role:"columnheader",children:"CPU"}),s.jsx("span",{role:"columnheader",children:"GPU"}),s.jsx("span",{role:"columnheader",children:"RAM"}),s.jsx("span",{role:"columnheader",children:"VRAM"}),s.jsx("span",{role:"columnheader",children:"Network"}),s.jsx("span",{role:"columnheader",children:"HDD"}),s.jsx("span",{role:"columnheader",children:"Temp"})]}),ou.length>0?ou.map(({device:x,slotNumber:M})=>s.jsx(_T,{device:x,slotNumber:M,selected:ys.has(x.deviceId),updateIndicator:Ei(x.deviceId),onSelect:()=>yn(x.deviceId),onOpenControl:()=>ki(x.deviceId)},x.deviceId)):s.jsxs("div",{className:"wall-device-list-empty",children:[s.jsx(Yt,{size:24,"aria-hidden":"true"}),s.jsx("strong",{children:"No connected computers"})]})]}):ct?s.jsx("div",{className:`screen-wall atlas-slot-wall size-${Xe}`,onClick:x=>{x.currentTarget===x.target&&Et()},children:pi.map((x,M)=>x?s.jsx(kh,{device:x,frame:Si.get(x.deviceId),selected:ys.has(x.deviceId),controlEnabled:!1,showStatus:Fe.showScreenStatus,monitorIndex:za(Kt[x.deviceId],va(x)),monitorCount:va(x),onSelect:()=>yn(x.deviceId),onFocusDevice:()=>io(x.deviceId),onOpenControl:()=>ki(x.deviceId),onCycleMonitor:D=>rs(x.deviceId,D),onCanvasReady:zc({mode4Enabled:ct,directMode4WallEnabled:ss,isMac:qi(x.platform)})==="direct"?na:il,sendInput:Ci,updateIndicator:Ei(x.deviceId),presentationReady:Fe.autoStartLive&&Sa.includes(x.deviceId)?Ze.has(x.deviceId):void 0,showPresentationSpinner:Fe.autoStartLive&&Sa.includes(x.deviceId)},x.deviceId):s.jsx(Py,{index:M},`slot-${M}`))}):s.jsx("div",{className:`screen-wall size-${Xe}`,onClick:x=>{x.currentTarget===x.target&&Et()},children:pi.map((x,M)=>x?s.jsx(kh,{device:x,frame:Si.get(x.deviceId),selected:ys.has(x.deviceId),controlEnabled:ws&&Se&&vr&&Le?.deviceId===x.deviceId,showStatus:Fe.showScreenStatus,monitorIndex:za(Kt[x.deviceId],va(x)),monitorCount:va(x),onSelect:()=>yn(x.deviceId),onFocusDevice:()=>io(x.deviceId),onOpenControl:()=>ki(x.deviceId),onCycleMonitor:D=>rs(x.deviceId,D),onCanvasReady:na,sendInput:Ci,updateIndicator:Ei(x.deviceId),presentationReady:Fe.autoStartLive&&Sa.includes(x.deviceId)?Ze.has(x.deviceId):void 0,showPresentationSpinner:Fe.autoStartLive&&Sa.includes(x.deviceId)},x.deviceId):s.jsx(Py,{index:M},`slot-${M}`))}),s.jsx(IT,{visible:ur&&!it})]}),!ar&&s.jsxs("aside",{className:`right-dock actions-mode ${Un?"collapsed":""}`,"aria-label":"LiveDesk tools",children:[s.jsx("button",{className:"dock-toggle",onClick:()=>tt(x=>!x),"aria-label":Un?"Show control panel":"Hide control panel",title:Un?"Show control panel":"Hide control panel",type:"button",children:Un?s.jsx(Jy,{size:18}):s.jsx(ep,{size:18})}),!Un&&s.jsxs(s.Fragment,{children:[s.jsxs("section",{className:"action-dock",children:[s.jsx("input",{ref:Zr,className:"hidden-file-input",type:"file",multiple:!0,onChange:x=>{x.currentTarget.files&&ro(x.currentTarget.files),x.currentTarget.value=""}}),s.jsxs("div",{className:"manual-action-bar",role:"toolbar","aria-label":"Manual workstation controls",children:[s.jsx(Pr,{label:"Control",tooltip:Le?Yo?"Allow Accessibility for the terminal app that starts LiveDesk, then restart the Mac client.":ws?vr?"Keyboard and mouse control is ready":"Waiting for the current Control capture session":"Remote control is not available on this workstation":"Select a workstation to use Control",onClick:()=>{if(Le){if(it&&Se){Oe(!1),J("Remote control paused. Screen viewing stays on.");return}ki(Le.deviceId)}},disabled:!ws||!!Te,active:Se,pressed:it&&Se,children:s.jsx($d,{size:17})}),s.jsx(Pr,{label:"Audio",tooltip:Le?el?le?"Stop hearing this workstation":"Hear this workstation":"Audio is not available on this workstation":"Select a workstation to use Audio",onClick:()=>{Qs()},disabled:!pu||!!Te,active:le,pressed:le,children:Te==="audio"?s.jsx(ii,{className:"spin",size:17}):s.jsx(rx,{size:17})}),s.jsx(Pr,{label:"Send files",tooltip:fa.length===0&&!it?"Select one or more workstations to send files":Le?"Choose files and send them to the selected workstation":"Select a workstation to send files",onClick:()=>{J(`Choose files to send to ${jf}.`),Zr.current?.click()},disabled:!!Te||!Wt||(it?!Le:fa.length===0),children:s.jsx(Lo,{size:17})}),s.jsx(Pr,{label:"Run command",tooltip:Le?fu?"Run command":"Command runner is not available on this workstation":"Select a workstation to run a command",onClick:xr,disabled:!Le||!Wt||!!Te||!fu,children:s.jsx(Ud,{size:17})}),s.jsx(Pr,{label:"Restart",tooltip:Le?du?"Restart workstation":"Restart is not available on this workstation":"Select a workstation to restart",onClick:()=>{fl("restart")},disabled:!Le||!Wt||!!Te||!du,children:Te==="restart"?s.jsx(ii,{className:"spin",size:17}):s.jsx($c,{size:17})}),s.jsx(Pr,{label:"Lock",tooltip:Le?"Lock workstation":"Select a workstation to lock",onClick:()=>{fl("lock")},disabled:!Le||!Wt||!!Te,children:Te==="lock"?s.jsx(ii,{className:"spin",size:17}):s.jsx(Ds,{size:17})}),s.jsx(Pr,{label:"Sleep",tooltip:Le?"Put workstation to sleep":"Select a workstation to put to sleep",onClick:()=>{fl("sleep")},disabled:!Le||!Wt||!!Te,children:Te==="sleep"?s.jsx(ii,{className:"spin",size:17}):s.jsx(g0,{size:17})}),s.jsx(Pr,{label:"Shut down",tooltip:Le?"Shut down workstation":"Select a workstation to shut down",onClick:()=>{fl("shutdown")},disabled:!Le||!Wt||!!Te,danger:!0,children:Te==="shutdown"?s.jsx(ii,{className:"spin",size:17}):s.jsx(v0,{size:17})})]})]}),s.jsx(vy,{hubUrl:N,devices:C,variant:"dock",selectedDeviceIds:ju})]})]})]})})]}),gs&&s.jsxs("aside",{className:`transfer-bar state-${gs.status}`,"aria-live":"polite",children:[s.jsx("span",{className:"transfer-bar-icon","aria-hidden":"true",children:gs.status==="queued"?s.jsx(Hn,{size:18}):gs.status==="failed"?s.jsx(Ha,{size:18}):s.jsx(Qy,{size:18})}),s.jsxs("div",{className:"transfer-bar-copy",children:[s.jsx("p",{children:gs.message}),s.jsx("div",{className:"transfer-bar-track",children:s.jsx("span",{style:{width:`${Math.max(0,Math.min(100,gs.progress))}%`}})})]}),s.jsxs("strong",{children:[Math.max(0,Math.min(100,gs.progress)),"%"]})]}),It&&s.jsxs("aside",{className:`livedesk-toast tone-${It.tone}`,role:It.tone==="error"?"alert":"status","aria-live":It.tone==="error"?"assertive":"polite","aria-busy":It.tone==="progress",children:[It.tone==="progress"&&s.jsx("span",{className:"livedesk-toast-spinner","aria-hidden":"true"}),s.jsx("span",{children:It.message}),s.jsx("button",{className:"livedesk-toast-close",onClick:()=>J(""),type:"button","aria-label":"Dismiss notification",title:"Dismiss notification",children:s.jsx(Ha,{size:15})})]})]})}function HT(){if(typeof window>"u")return[];const n=window.location.origin;return window.location.port==="5179"?[n]:["http://127.0.0.1:5179"]}function BT(){const[a,r]=u.useState(null);return u.useEffect(()=>{let l=!1,c=!1;const d=async()=>{for(const v of HT())try{const g=await fetch(`${v}/api/runtime`,{cache:"no-store"});if(!g.ok)continue;const y=(await g.json()).role==="hub"?"hub":"client";c=!0,l||r(y);return}catch{}};d();const m=window.setInterval(()=>{d()},1e3),p=window.setTimeout(()=>{!l&&!c&&r("client")},2500);return()=>{l=!0,window.clearInterval(m),window.clearTimeout(p)}},[null]),a?a==="client"?s.jsx(jC,{}):s.jsx(OT,{}):s.jsxs("main",{className:"runtime-role-boot","aria-busy":"true","aria-label":"Starting LiveDesk",children:[s.jsx("span",{className:"runtime-role-boot-mark","aria-hidden":"true"}),s.jsx("strong",{children:"Starting LiveDesk"}),s.jsx("p",{children:"Loading this computer's assigned role..."})]})}k0.createRoot(document.getElementById("root")).render(s.jsx(u.StrictMode,{children:s.jsx(BT,{})}));