livedesk 0.1.486 → 0.1.488

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,186 @@
1
+ import{r as OC,a as d,M as qf,S as Na,R as bd,B as HC,P as tg,X as hr,b as Yf,C as fo,F as mb,L as Ci,A as jx,c as BC,d as pb,E as hb,T as zC,D as Sv,e as Ba,f as $C,g as Ex,h as UC,i as qC,j as mo,k as Ta,l as Pp,m as Wf,n as Cv,o as lu,p as Dx,q as Zl,s as Ix,t as Lx,u as gb,v as WC,w as GC,H as su,W as wd,x as VC,y as KC,z as pd,K as QC,G as _x,I as zg,J as Fp,N as nc,O as YC,Q as XC,U as ZC,V as kv,Y as JC,Z as Mv,_ as Px,$ as ek,a0 as Si,a1 as vb,a2 as Av,a3 as Qp,a4 as Xf,a5 as Np,a6 as Fx,a7 as tk,a8 as Ox,a9 as nk,aa as Hx,ab as ak,ac as $g,ad as rk,ae as Ug,af as Bx,ag as sk,ah as ik,ai as ok,aj as lk,ak as ck,al as uk,am as yb,an as dk,ao as fk,ap as mk,aq as pk,ar as qg,as as Wg,at as hk,au as gk,av as bb,aw as ng,ax as vk,ay as wb,az as zx,aA as yk,aB as bk,aC as wk}from"./icons-BtzQBJR4.js";import{r as $x}from"./react-BDGiddLC.js";import{c as xk}from"./supabase-C7qjtLN3.js";(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const l of document.querySelectorAll('link[rel="modulepreload"]'))i(l);new MutationObserver(l=>{for(const u of l)if(u.type==="childList")for(const f of u.addedNodes)f.tagName==="LINK"&&f.rel==="modulepreload"&&i(f)}).observe(document,{childList:!0,subtree:!0});function r(l){const u={};return l.integrity&&(u.integrity=l.integrity),l.referrerPolicy&&(u.referrerPolicy=l.referrerPolicy),l.crossOrigin==="use-credentials"?u.credentials="include":l.crossOrigin==="anonymous"?u.credentials="omit":u.credentials="same-origin",u}function i(l){if(l.ep)return;l.ep=!0;const u=r(l);fetch(l.href,u)}})();var ag={exports:{}},Df={};var xb;function Sk(){if(xb)return Df;xb=1;var t=Symbol.for("react.transitional.element"),n=Symbol.for("react.fragment");function r(i,l,u){var f=null;if(u!==void 0&&(f=""+u),l.key!==void 0&&(f=""+l.key),"key"in l){u={};for(var h in l)h!=="key"&&(u[h]=l[h])}else u=l;return l=u.ref,{$$typeof:t,type:i,key:f,ref:l!==void 0?l:null,props:u}}return Df.Fragment=n,Df.jsx=r,Df.jsxs=r,Df}var Sb;function Ck(){return Sb||(Sb=1,ag.exports=Sk()),ag.exports}var o=Ck(),rg={exports:{}},If={},sg={exports:{}},ig={};var Cb;function kk(){return Cb||(Cb=1,(function(t){function n(B,L){var oe=B.length;B.push(L);e:for(;0<oe;){var be=oe-1>>>1,H=B[be];if(0<l(H,L))B[be]=L,B[oe]=H,oe=be;else break e}}function r(B){return B.length===0?null:B[0]}function i(B){if(B.length===0)return null;var L=B[0],oe=B.pop();if(oe!==L){B[0]=oe;e:for(var be=0,H=B.length,me=H>>>1;be<me;){var ue=2*(be+1)-1,Ce=B[ue],Me=ue+1,Ne=B[Me];if(0>l(Ce,oe))Me<H&&0>l(Ne,Ce)?(B[be]=Ne,B[Me]=oe,be=Me):(B[be]=Ce,B[ue]=oe,be=ue);else if(Me<H&&0>l(Ne,oe))B[be]=Ne,B[Me]=oe,be=Me;else break e}}return L}function l(B,L){var oe=B.sortIndex-L.sortIndex;return oe!==0?oe:B.id-L.id}if(t.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var u=performance;t.unstable_now=function(){return u.now()}}else{var f=Date,h=f.now();t.unstable_now=function(){return f.now()-h}}var g=[],y=[],w=1,b=null,x=3,M=!1,k=!1,N=!1,E=!1,I=typeof setTimeout=="function"?setTimeout:null,T=typeof clearTimeout=="function"?clearTimeout:null,P=typeof setImmediate<"u"?setImmediate:null;function U(B){for(var L=r(y);L!==null;){if(L.callback===null)i(y);else if(L.startTime<=B)i(y),L.sortIndex=L.expirationTime,n(g,L);else break;L=r(y)}}function F(B){if(N=!1,U(B),!k)if(r(g)!==null)k=!0,Y||(Y=!0,W());else{var L=r(y);L!==null&&ee(F,L.startTime-B)}}var Y=!1,D=-1,K=5,ne=-1;function q(){return E?!0:!(t.unstable_now()-ne<K)}function O(){if(E=!1,Y){var B=t.unstable_now();ne=B;var L=!0;try{e:{k=!1,N&&(N=!1,T(D),D=-1),M=!0;var oe=x;try{t:{for(U(B),b=r(g);b!==null&&!(b.expirationTime>B&&q());){var be=b.callback;if(typeof be=="function"){b.callback=null,x=b.priorityLevel;var H=be(b.expirationTime<=B);if(B=t.unstable_now(),typeof H=="function"){b.callback=H,U(B),L=!0;break t}b===r(g)&&i(g),U(B)}else i(g);b=r(g)}if(b!==null)L=!0;else{var me=r(y);me!==null&&ee(F,me.startTime-B),L=!1}}break e}finally{b=null,x=oe,M=!1}L=void 0}}finally{L?W():Y=!1}}}var W;if(typeof P=="function")W=function(){P(O)};else if(typeof MessageChannel<"u"){var ce=new MessageChannel,$=ce.port2;ce.port1.onmessage=O,W=function(){$.postMessage(null)}}else W=function(){I(O,0)};function ee(B,L){D=I(function(){B(t.unstable_now())},L)}t.unstable_IdlePriority=5,t.unstable_ImmediatePriority=1,t.unstable_LowPriority=4,t.unstable_NormalPriority=3,t.unstable_Profiling=null,t.unstable_UserBlockingPriority=2,t.unstable_cancelCallback=function(B){B.callback=null},t.unstable_forceFrameRate=function(B){0>B||125<B?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):K=0<B?Math.floor(1e3/B):5},t.unstable_getCurrentPriorityLevel=function(){return x},t.unstable_next=function(B){switch(x){case 1:case 2:case 3:var L=3;break;default:L=x}var oe=x;x=L;try{return B()}finally{x=oe}},t.unstable_requestPaint=function(){E=!0},t.unstable_runWithPriority=function(B,L){switch(B){case 1:case 2:case 3:case 4:case 5:break;default:B=3}var oe=x;x=B;try{return L()}finally{x=oe}},t.unstable_scheduleCallback=function(B,L,oe){var be=t.unstable_now();switch(typeof oe=="object"&&oe!==null?(oe=oe.delay,oe=typeof oe=="number"&&0<oe?be+oe:be):oe=be,B){case 1:var H=-1;break;case 2:H=250;break;case 5:H=1073741823;break;case 4:H=1e4;break;default:H=5e3}return H=oe+H,B={id:w++,callback:L,priorityLevel:B,startTime:oe,expirationTime:H,sortIndex:-1},oe>be?(B.sortIndex=oe,n(y,B),r(g)===null&&B===r(y)&&(N?(T(D),D=-1):N=!0,ee(F,oe-be))):(B.sortIndex=H,n(g,B),k||M||(k=!0,Y||(Y=!0,W()))),B},t.unstable_shouldYield=q,t.unstable_wrapCallback=function(B){var L=x;return function(){var oe=x;x=L;try{return B.apply(this,arguments)}finally{x=oe}}}})(ig)),ig}var kb;function Mk(){return kb||(kb=1,sg.exports=kk()),sg.exports}var Mb;function Ak(){if(Mb)return If;Mb=1;var t=Mk(),n=OC(),r=$x();function i(e){var a="https://react.dev/errors/"+e;if(1<arguments.length){a+="?args[]="+encodeURIComponent(arguments[1]);for(var s=2;s<arguments.length;s++)a+="&args[]="+encodeURIComponent(arguments[s])}return"Minified React error #"+e+"; visit "+a+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function l(e){return!(!e||e.nodeType!==1&&e.nodeType!==9&&e.nodeType!==11)}function u(e){var a=e,s=e;if(e.alternate)for(;a.return;)a=a.return;else{e=a;do a=e,(a.flags&4098)!==0&&(s=a.return),e=a.return;while(e)}return a.tag===3?s:null}function f(e){if(e.tag===13){var a=e.memoizedState;if(a===null&&(e=e.alternate,e!==null&&(a=e.memoizedState)),a!==null)return a.dehydrated}return null}function h(e){if(e.tag===31){var a=e.memoizedState;if(a===null&&(e=e.alternate,e!==null&&(a=e.memoizedState)),a!==null)return a.dehydrated}return null}function g(e){if(u(e)!==e)throw Error(i(188))}function y(e){var a=e.alternate;if(!a){if(a=u(e),a===null)throw Error(i(188));return a!==e?null:e}for(var s=e,c=a;;){var m=s.return;if(m===null)break;var v=m.alternate;if(v===null){if(c=m.return,c!==null){s=c;continue}break}if(m.child===v.child){for(v=m.child;v;){if(v===s)return g(m),e;if(v===c)return g(m),a;v=v.sibling}throw Error(i(188))}if(s.return!==c.return)s=m,c=v;else{for(var A=!1,_=m.child;_;){if(_===s){A=!0,s=m,c=v;break}if(_===c){A=!0,c=m,s=v;break}_=_.sibling}if(!A){for(_=v.child;_;){if(_===s){A=!0,s=v,c=m;break}if(_===c){A=!0,c=v,s=m;break}_=_.sibling}if(!A)throw Error(i(189))}}if(s.alternate!==c)throw Error(i(190))}if(s.tag!==3)throw Error(i(188));return s.stateNode.current===s?e:a}function w(e){var a=e.tag;if(a===5||a===26||a===27||a===6)return e;for(e=e.child;e!==null;){if(a=w(e),a!==null)return a;e=e.sibling}return null}var b=Object.assign,x=Symbol.for("react.element"),M=Symbol.for("react.transitional.element"),k=Symbol.for("react.portal"),N=Symbol.for("react.fragment"),E=Symbol.for("react.strict_mode"),I=Symbol.for("react.profiler"),T=Symbol.for("react.consumer"),P=Symbol.for("react.context"),U=Symbol.for("react.forward_ref"),F=Symbol.for("react.suspense"),Y=Symbol.for("react.suspense_list"),D=Symbol.for("react.memo"),K=Symbol.for("react.lazy"),ne=Symbol.for("react.activity"),q=Symbol.for("react.memo_cache_sentinel"),O=Symbol.iterator;function W(e){return e===null||typeof e!="object"?null:(e=O&&e[O]||e["@@iterator"],typeof e=="function"?e:null)}var ce=Symbol.for("react.client.reference");function $(e){if(e==null)return null;if(typeof e=="function")return e.$$typeof===ce?null:e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case N:return"Fragment";case I:return"Profiler";case E:return"StrictMode";case F:return"Suspense";case Y:return"SuspenseList";case ne:return"Activity"}if(typeof e=="object")switch(e.$$typeof){case k:return"Portal";case P:return e.displayName||"Context";case T:return(e._context.displayName||"Context")+".Consumer";case U:var a=e.render;return e=e.displayName,e||(e=a.displayName||a.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case D:return a=e.displayName||null,a!==null?a:$(e.type)||"Memo";case K:a=e._payload,e=e._init;try{return $(e(a))}catch{}}return null}var ee=Array.isArray,B=n.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,L=r.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,oe={pending:!1,data:null,method:null,action:null},be=[],H=-1;function me(e){return{current:e}}function ue(e){0>H||(e.current=be[H],be[H]=null,H--)}function Ce(e,a){H++,be[H]=e.current,e.current=a}var Me=me(null),Ne=me(null),He=me(null),Ve=me(null);function ie(e,a){switch(Ce(He,a),Ce(Ne,e),Ce(Me,null),a.nodeType){case 9:case 11:e=(e=a.documentElement)&&(e=e.namespaceURI)?Py(e):0;break;default:if(e=a.tagName,a=a.namespaceURI)a=Py(a),e=Fy(a,e);else switch(e){case"svg":e=1;break;case"math":e=2;break;default:e=0}}ue(Me),Ce(Me,e)}function Oe(){ue(Me),ue(Ne),ue(He)}function $e(e){e.memoizedState!==null&&Ce(Ve,e);var a=Me.current,s=Fy(a,e.type);a!==s&&(Ce(Ne,e),Ce(Me,s))}function qe(e){Ne.current===e&&(ue(Me),ue(Ne)),Ve.current===e&&(ue(Ve),Tf._currentValue=oe)}var vt,xe;function he(e){if(vt===void 0)try{throw Error()}catch(s){var a=s.stack.trim().match(/\n( *(at )?)/);vt=a&&a[1]||"",xe=-1<s.stack.indexOf(`
2
+ at`)?" (<anonymous>)":-1<s.stack.indexOf("@")?"@unknown:0:0":""}return`
3
+ `+vt+e+xe}var pe=!1;function Ae(e,a){if(!e||pe)return"";pe=!0;var s=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var c={DetermineComponentFrameRoot:function(){try{if(a){var Ie=function(){throw Error()};if(Object.defineProperty(Ie.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(Ie,[])}catch(ke){var we=ke}Reflect.construct(e,[],Ie)}else{try{Ie.call()}catch(ke){we=ke}e.call(Ie.prototype)}}else{try{throw Error()}catch(ke){we=ke}(Ie=e())&&typeof Ie.catch=="function"&&Ie.catch(function(){})}}catch(ke){if(ke&&we&&typeof ke.stack=="string")return[ke.stack,we.stack]}return[null,null]}};c.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var m=Object.getOwnPropertyDescriptor(c.DetermineComponentFrameRoot,"name");m&&m.configurable&&Object.defineProperty(c.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var v=c.DetermineComponentFrameRoot(),A=v[0],_=v[1];if(A&&_){var J=A.split(`
4
+ `),ye=_.split(`
5
+ `);for(m=c=0;c<J.length&&!J[c].includes("DetermineComponentFrameRoot");)c++;for(;m<ye.length&&!ye[m].includes("DetermineComponentFrameRoot");)m++;if(c===J.length||m===ye.length)for(c=J.length-1,m=ye.length-1;1<=c&&0<=m&&J[c]!==ye[m];)m--;for(;1<=c&&0<=m;c--,m--)if(J[c]!==ye[m]){if(c!==1||m!==1)do if(c--,m--,0>m||J[c]!==ye[m]){var Re=`
6
+ `+J[c].replace(" at new "," at ");return e.displayName&&Re.includes("<anonymous>")&&(Re=Re.replace("<anonymous>",e.displayName)),Re}while(1<=c&&0<=m);break}}}finally{pe=!1,Error.prepareStackTrace=s}return(s=e?e.displayName||e.name:"")?he(s):""}function Se(e,a){switch(e.tag){case 26:case 27:case 5:return he(e.type);case 16:return he("Lazy");case 13:return e.child!==a&&a!==null?he("Suspense Fallback"):he("Suspense");case 19:return he("SuspenseList");case 0:case 15:return Ae(e.type,!1);case 11:return Ae(e.type.render,!1);case 1:return Ae(e.type,!0);case 31:return he("Activity");default:return""}}function Pe(e){try{var a="",s=null;do a+=Se(e,s),s=e,e=e.return;while(e);return a}catch(c){return`
7
+ Error generating stack: `+c.message+`
8
+ `+c.stack}}var Qe=Object.prototype.hasOwnProperty,Z=t.unstable_scheduleCallback,$t=t.unstable_cancelCallback,Ee=t.unstable_shouldYield,Ge=t.unstable_requestPaint,ze=t.unstable_now,Ft=t.unstable_getCurrentPriorityLevel,Ze=t.unstable_ImmediatePriority,nt=t.unstable_UserBlockingPriority,lt=t.unstable_NormalPriority,Tt=t.unstable_LowPriority,Mt=t.unstable_IdlePriority,rt=t.log,dt=t.unstable_setDisableYieldValue,G=null,ge=null;function De(e){if(typeof rt=="function"&&dt(e),ge&&typeof ge.setStrictMode=="function")try{ge.setStrictMode(G,e)}catch{}}var z=Math.clz32?Math.clz32:Ue,ae=Math.log,Te=Math.LN2;function Ue(e){return e>>>=0,e===0?32:31-(ae(e)/Te|0)|0}var Xe=256,at=262144,kt=4194304;function At(e){var a=e&42;if(a!==0)return a;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 Ut(e,a,s){var c=e.pendingLanes;if(c===0)return 0;var m=0,v=e.suspendedLanes,A=e.pingedLanes;e=e.warmLanes;var _=c&134217727;return _!==0?(c=_&~v,c!==0?m=At(c):(A&=_,A!==0?m=At(A):s||(s=_&~e,s!==0&&(m=At(s))))):(_=c&~v,_!==0?m=At(_):A!==0?m=At(A):s||(s=c&~e,s!==0&&(m=At(s)))),m===0?0:a!==0&&a!==m&&(a&v)===0&&(v=m&-m,s=a&-a,v>=s||v===32&&(s&4194048)!==0)?a:m}function Qt(e,a){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&a)===0}function sa(e,a){switch(e){case 1:case 2:case 4:case 8:case 64:return a+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 a+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 Ra(){var e=kt;return kt<<=1,(kt&62914560)===0&&(kt=4194304),e}function Pn(e){for(var a=[],s=0;31>s;s++)a.push(e);return a}function $n(e,a){e.pendingLanes|=a,a!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function ia(e,a,s,c,m,v){var A=e.pendingLanes;e.pendingLanes=s,e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0,e.expiredLanes&=s,e.entangledLanes&=s,e.errorRecoveryDisabledLanes&=s,e.shellSuspendCounter=0;var _=e.entanglements,J=e.expirationTimes,ye=e.hiddenUpdates;for(s=A&~s;0<s;){var Re=31-z(s),Ie=1<<Re;_[Re]=0,J[Re]=-1;var we=ye[Re];if(we!==null)for(ye[Re]=null,Re=0;Re<we.length;Re++){var ke=we[Re];ke!==null&&(ke.lane&=-536870913)}s&=~Ie}c!==0&&Fe(e,c,0),v!==0&&m===0&&e.tag!==0&&(e.suspendedLanes|=v&~(A&~a))}function Fe(e,a,s){e.pendingLanes|=a,e.suspendedLanes&=~a;var c=31-z(a);e.entangledLanes|=a,e.entanglements[c]=e.entanglements[c]|1073741824|s&261930}function V(e,a){var s=e.entangledLanes|=a;for(e=e.entanglements;s;){var c=31-z(s),m=1<<c;m&a|e[c]&a&&(e[c]|=a),s&=~m}}function Je(e,a){var s=a&-a;return s=(s&42)!==0?1:gt(s),(s&(e.suspendedLanes|a))!==0?0:s}function gt(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 nn(e){return e&=-e,2<e?8<e?(e&134217727)!==0?32:268435456:8:2}function Sn(){var e=L.p;return e!==0?e:(e=window.event,e===void 0?32:ib(e.type))}function Ms(e,a){var s=L.p;try{return L.p=e,a()}finally{L.p=s}}var qa=Math.random().toString(36).slice(2),fe="__reactFiber$"+qa,_e="__reactProps$"+qa,et="__reactContainer$"+qa,Rt="__reactEvents$"+qa,An="__reactListeners$"+qa,Et="__reactHandles$"+qa,ct="__reactResources$"+qa,jt="__reactMarker$"+qa;function mt(e){delete e[fe],delete e[_e],delete e[Rt],delete e[An],delete e[Et]}function Yt(e){var a=e[fe];if(a)return a;for(var s=e.parentNode;s;){if(a=s[et]||s[fe]){if(s=a.alternate,a.child!==null||s!==null&&s.child!==null)for(e=qy(e);e!==null;){if(s=e[fe])return s;e=qy(e)}return a}e=s,s=e.parentNode}return null}function fn(e){if(e=e[fe]||e[et]){var a=e.tag;if(a===5||a===6||a===13||a===31||a===26||a===27||a===3)return e}return null}function Xt(e){var a=e.tag;if(a===5||a===26||a===27||a===6)return e.stateNode;throw Error(i(33))}function Rn(e){var a=e[ct];return a||(a=e[ct]={hoistableStyles:new Map,hoistableScripts:new Map}),a}function Wt(e){e[jt]=!0}var jr=new Set,Ks={};function Nn(e,a){Un(e,a),Un(e+"Capture",a)}function Un(e,a){for(Ks[e]=a,e=0;e<a.length;e++)jr.add(a[e])}var Ni=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]*$"),Ja={},Er={};function jn(e){return Qe.call(Er,e)?!0:Qe.call(Ja,e)?!1:Ni.test(e)?Er[e]=!0:(Ja[e]=!0,!1)}function Dr(e,a,s){if(jn(a))if(s===null)e.removeAttribute(a);else{switch(typeof s){case"undefined":case"function":case"symbol":e.removeAttribute(a);return;case"boolean":var c=a.toLowerCase().slice(0,5);if(c!=="data-"&&c!=="aria-"){e.removeAttribute(a);return}}e.setAttribute(a,""+s)}}function In(e,a,s){if(s===null)e.removeAttribute(a);else{switch(typeof s){case"undefined":case"function":case"symbol":case"boolean":e.removeAttribute(a);return}e.setAttribute(a,""+s)}}function ea(e,a,s,c){if(c===null)e.removeAttribute(s);else{switch(typeof c){case"undefined":case"function":case"symbol":case"boolean":e.removeAttribute(s);return}e.setAttributeNS(a,s,""+c)}}function en(e){switch(typeof e){case"bigint":case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function Qs(e){var a=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(a==="checkbox"||a==="radio")}function Ys(e,a,s){var c=Object.getOwnPropertyDescriptor(e.constructor.prototype,a);if(!e.hasOwnProperty(a)&&typeof c<"u"&&typeof c.get=="function"&&typeof c.set=="function"){var m=c.get,v=c.set;return Object.defineProperty(e,a,{configurable:!0,get:function(){return m.call(this)},set:function(A){s=""+A,v.call(this,A)}}),Object.defineProperty(e,a,{enumerable:c.enumerable}),{getValue:function(){return s},setValue:function(A){s=""+A},stopTracking:function(){e._valueTracker=null,delete e[a]}}}}function As(e){if(!e._valueTracker){var a=Qs(e)?"checked":"value";e._valueTracker=Ys(e,a,""+e[a])}}function lc(e){if(!e)return!1;var a=e._valueTracker;if(!a)return!0;var s=a.getValue(),c="";return e&&(c=Qs(e)?e.checked?"true":"false":e.value),e=c,e!==s?(a.setValue(e),!0):!1}function Xr(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 Ir=/[\n"\\]/g;function Ln(e){return e.replace(Ir,function(a){return"\\"+a.charCodeAt(0).toString(16)+" "})}function vo(e,a,s,c,m,v,A,_){e.name="",A!=null&&typeof A!="function"&&typeof A!="symbol"&&typeof A!="boolean"?e.type=A:e.removeAttribute("type"),a!=null?A==="number"?(a===0&&e.value===""||e.value!=a)&&(e.value=""+en(a)):e.value!==""+en(a)&&(e.value=""+en(a)):A!=="submit"&&A!=="reset"||e.removeAttribute("value"),a!=null?Ti(e,A,en(a)):s!=null?Ti(e,A,en(s)):c!=null&&e.removeAttribute("value"),m==null&&v!=null&&(e.defaultChecked=!!v),m!=null&&(e.checked=m&&typeof m!="function"&&typeof m!="symbol"),_!=null&&typeof _!="function"&&typeof _!="symbol"&&typeof _!="boolean"?e.name=""+en(_):e.removeAttribute("name")}function Zr(e,a,s,c,m,v,A,_){if(v!=null&&typeof v!="function"&&typeof v!="symbol"&&typeof v!="boolean"&&(e.type=v),a!=null||s!=null){if(!(v!=="submit"&&v!=="reset"||a!=null)){As(e);return}s=s!=null?""+en(s):"",a=a!=null?""+en(a):s,_||a===e.value||(e.value=a),e.defaultValue=a}c=c??m,c=typeof c!="function"&&typeof c!="symbol"&&!!c,e.checked=_?e.checked:!!c,e.defaultChecked=!!c,A!=null&&typeof A!="function"&&typeof A!="symbol"&&typeof A!="boolean"&&(e.name=A),As(e)}function Ti(e,a,s){a==="number"&&Xr(e.ownerDocument)===e||e.defaultValue===""+s||(e.defaultValue=""+s)}function Jr(e,a,s,c){if(e=e.options,a){a={};for(var m=0;m<s.length;m++)a["$"+s[m]]=!0;for(s=0;s<e.length;s++)m=a.hasOwnProperty("$"+e[s].value),e[s].selected!==m&&(e[s].selected=m),m&&c&&(e[s].defaultSelected=!0)}else{for(s=""+en(s),a=null,m=0;m<e.length;m++){if(e[m].value===s){e[m].selected=!0,c&&(e[m].defaultSelected=!0);return}a!==null||e[m].disabled||(a=e[m])}a!==null&&(a.selected=!0)}}function es(e,a,s){if(a!=null&&(a=""+en(a),a!==e.value&&(e.value=a),s==null)){e.defaultValue!==a&&(e.defaultValue=a);return}e.defaultValue=s!=null?""+en(s):""}function mu(e,a,s,c){if(a==null){if(c!=null){if(s!=null)throw Error(i(92));if(ee(c)){if(1<c.length)throw Error(i(93));c=c[0]}s=c}s==null&&(s=""),a=s}s=en(a),e.defaultValue=s,c=e.textContent,c===s&&c!==""&&c!==null&&(e.value=c),As(e)}function Ri(e,a){if(a){var s=e.firstChild;if(s&&s===e.lastChild&&s.nodeType===3){s.nodeValue=a;return}}e.textContent=a}var Xs=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 sl(e,a,s){var c=a.indexOf("--")===0;s==null||typeof s=="boolean"||s===""?c?e.setProperty(a,""):a==="float"?e.cssFloat="":e[a]="":c?e.setProperty(a,s):typeof s!="number"||s===0||Xs.has(a)?a==="float"?e.cssFloat=s:e[a]=(""+s).trim():e[a]=s+"px"}function St(e,a,s){if(a!=null&&typeof a!="object")throw Error(i(62));if(e=e.style,s!=null){for(var c in s)!s.hasOwnProperty(c)||a!=null&&a.hasOwnProperty(c)||(c.indexOf("--")===0?e.setProperty(c,""):c==="float"?e.cssFloat="":e[c]="");for(var m in a)c=a[m],a.hasOwnProperty(m)&&s[m]!==c&&sl(e,m,c)}else for(var v in a)a.hasOwnProperty(v)&&sl(e,v,a[v])}function qn(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 il=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"]]),rn=/^[\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 Zs(e){return rn.test(""+e)?"javascript:throw new Error('React has blocked a javascript: URL as a security precaution.')":e}function vr(){}var Ns=null;function yo(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var Ot=null,Wn=null;function bo(e){var a=fn(e);if(a&&(e=a.stateNode)){var s=e[_e]||null;e:switch(e=a.stateNode,a.type){case"input":if(vo(e,s.value,s.defaultValue,s.defaultValue,s.checked,s.defaultChecked,s.type,s.name),a=s.name,s.type==="radio"&&a!=null){for(s=e;s.parentNode;)s=s.parentNode;for(s=s.querySelectorAll('input[name="'+Ln(""+a)+'"][type="radio"]'),a=0;a<s.length;a++){var c=s[a];if(c!==e&&c.form===e.form){var m=c[_e]||null;if(!m)throw Error(i(90));vo(c,m.value,m.defaultValue,m.defaultValue,m.checked,m.defaultChecked,m.type,m.name)}}for(a=0;a<s.length;a++)c=s[a],c.form===e.form&&lc(c)}break e;case"textarea":es(e,s.value,s.defaultValue);break e;case"select":a=s.value,a!=null&&Jr(e,!!s.multiple,a,!1)}}}var Js=!1;function ta(e,a,s){if(Js)return e(a,s);Js=!0;try{var c=e(a);return c}finally{if(Js=!1,(Ot!==null||Wn!==null)&&(Lm(),Ot&&(a=Ot,e=Wn,Wn=Ot=null,bo(a),e)))for(a=0;a<e.length;a++)bo(e[a])}}function Ts(e,a){var s=e.stateNode;if(s===null)return null;var c=s[_e]||null;if(c===null)return null;s=c[a];e:switch(a){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(c=!c.disabled)||(e=e.type,c=!(e==="button"||e==="input"||e==="select"||e==="textarea")),e=!c;break e;default:e=!1}if(e)return null;if(s&&typeof s!="function")throw Error(i(231,a,typeof s));return s}var ja=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),ts=!1;if(ja)try{var wo={};Object.defineProperty(wo,"passive",{get:function(){ts=!0}}),window.addEventListener("test",wo,wo),window.removeEventListener("test",wo,wo)}catch{ts=!1}var Rs=null,cc=null,Lr=null;function pu(){if(Lr)return Lr;var e,a=cc,s=a.length,c,m="value"in Rs?Rs.value:Rs.textContent,v=m.length;for(e=0;e<s&&a[e]===m[e];e++);var A=s-e;for(c=1;c<=A&&a[s-c]===m[v-c];c++);return Lr=m.slice(e,1<c?1-c:void 0)}function ol(e){var a=e.keyCode;return"charCode"in e?(e=e.charCode,e===0&&a===13&&(e=13)):e=a,e===10&&(e=13),32<=e||e===13?e:0}function ji(){return!0}function ei(){return!1}function Ht(e){function a(s,c,m,v,A){this._reactName=s,this._targetInst=m,this.type=c,this.nativeEvent=v,this.target=A,this.currentTarget=null;for(var _ in e)e.hasOwnProperty(_)&&(s=e[_],this[_]=s?s(v):v[_]);return this.isDefaultPrevented=(v.defaultPrevented!=null?v.defaultPrevented:v.returnValue===!1)?ji:ei,this.isPropagationStopped=ei,this}return b(a.prototype,{preventDefault:function(){this.defaultPrevented=!0;var s=this.nativeEvent;s&&(s.preventDefault?s.preventDefault():typeof s.returnValue!="unknown"&&(s.returnValue=!1),this.isDefaultPrevented=ji)},stopPropagation:function(){var s=this.nativeEvent;s&&(s.stopPropagation?s.stopPropagation():typeof s.cancelBubble!="unknown"&&(s.cancelBubble=!0),this.isPropagationStopped=ji)},persist:function(){},isPersistent:ji}),a}var Fn={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},er=Ht(Fn),pn=b({},Fn,{view:0,detail:0}),js=Ht(pn),oa,Ei,tr,xo=b({},pn,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:gu,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!==tr&&(tr&&e.type==="mousemove"?(oa=e.screenX-tr.screenX,Ei=e.screenY-tr.screenY):Ei=oa=0,tr=e),oa)},movementY:function(e){return"movementY"in e?e.movementY:Ei}}),uc=Ht(xo),So=b({},xo,{dataTransfer:0}),nr=Ht(So),im=b({},pn,{relatedTarget:0}),ll=Ht(im),cl=b({},Fn,{animationName:0,elapsedTime:0,pseudoElement:0}),yr=Ht(cl),dc=b({},Fn,{clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}}),br=Ht(dc),ul=b({},Fn,{data:0}),dl=Ht(ul),ti={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},kd={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"},hu={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function Md(e){var a=this.nativeEvent;return a.getModifierState?a.getModifierState(e):(e=hu[e])?!!a[e]:!1}function gu(){return Md}var vu=b({},pn,{key:function(e){if(e.key){var a=ti[e.key]||e.key;if(a!=="Unidentified")return a}return e.type==="keypress"?(e=ol(e),e===13?"Enter":String.fromCharCode(e)):e.type==="keydown"||e.type==="keyup"?kd[e.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:gu,charCode:function(e){return e.type==="keypress"?ol(e):0},keyCode:function(e){return e.type==="keydown"||e.type==="keyup"?e.keyCode:0},which:function(e){return e.type==="keypress"?ol(e):e.type==="keydown"||e.type==="keyup"?e.keyCode:0}}),Ad=Ht(vu),Di=b({},xo,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),fc=Ht(Di),yu=b({},pn,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:gu}),bu=Ht(yu),Nd=b({},Fn,{propertyName:0,elapsedTime:0,pseudoElement:0}),Wa=Ht(Nd),wu=b({},xo,{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}),ch=Ht(wu),ni=b({},Fn,{newState:0,oldState:0}),om=Ht(ni),ns=[9,13,27,32],ar=ja&&"CompositionEvent"in window,va=null;ja&&"documentMode"in document&&(va=document.documentMode);var mc=ja&&"TextEvent"in window&&!va,Td=ja&&(!ar||va&&8<va&&11>=va),On=" ",ya=!1;function Rd(e,a){switch(e){case"keyup":return ns.indexOf(a.keyCode)!==-1;case"keydown":return a.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Co(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var pt=!1;function _r(e,a){switch(e){case"compositionend":return Co(a);case"keypress":return a.which!==32?null:(ya=!0,On);case"textInput":return e=a.data,e===On&&ya?null:e;default:return null}}function ko(e,a){if(pt)return e==="compositionend"||!ar&&Rd(e,a)?(e=pu(),Lr=cc=Rs=null,pt=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(a.ctrlKey||a.altKey||a.metaKey)||a.ctrlKey&&a.altKey){if(a.char&&1<a.char.length)return a.char;if(a.which)return String.fromCharCode(a.which)}return null;case"compositionend":return Td&&a.locale!=="ko"?null:a.data;default:return null}}var fl={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 ml(e){var a=e&&e.nodeName&&e.nodeName.toLowerCase();return a==="input"?!!fl[e.type]:a==="textarea"}function ai(e,a,s,c){Ot?Wn?Wn.push(c):Wn=[c]:Ot=c,a=zm(a,"onChange"),0<a.length&&(s=new er("onChange","change",null,s,c),e.push({event:s,listeners:a}))}var as=null,Ii=null;function pl(e){jy(e,0)}function Es(e){var a=Xt(e);if(lc(a))return e}function Li(e,a){if(e==="change")return a}var Mo=!1;if(ja){var hl;if(ja){var rr="oninput"in document;if(!rr){var _i=document.createElement("div");_i.setAttribute("oninput","return;"),rr=typeof _i.oninput=="function"}hl=rr}else hl=!1;Mo=hl&&(!document.documentMode||9<document.documentMode)}function xu(){as&&(as.detachEvent("onpropertychange",Ea),Ii=as=null)}function Ea(e){if(e.propertyName==="value"&&Es(Ii)){var a=[];ai(a,Ii,e,yo(e)),ta(pl,a)}}function uh(e,a,s){e==="focusin"?(xu(),as=a,Ii=s,as.attachEvent("onpropertychange",Ea)):e==="focusout"&&xu()}function dh(e){if(e==="selectionchange"||e==="keyup"||e==="keydown")return Es(Ii)}function fh(e,a){if(e==="click")return Es(a)}function pc(e,a){if(e==="input"||e==="change")return Es(a)}function Su(e,a){return e===a&&(e!==0||1/e===1/a)||e!==e&&a!==a}var Da=typeof Object.is=="function"?Object.is:Su;function Pi(e,a){if(Da(e,a))return!0;if(typeof e!="object"||e===null||typeof a!="object"||a===null)return!1;var s=Object.keys(e),c=Object.keys(a);if(s.length!==c.length)return!1;for(c=0;c<s.length;c++){var m=s[c];if(!Qe.call(a,m)||!Da(e[m],a[m]))return!1}return!0}function Cu(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function ku(e,a){var s=Cu(e);e=0;for(var c;s;){if(s.nodeType===3){if(c=e+s.textContent.length,e<=a&&c>=a)return{node:s,offset:a-e};e=c}e:{for(;s;){if(s.nextSibling){s=s.nextSibling;break e}s=s.parentNode}s=void 0}s=Cu(s)}}function hc(e,a){return e&&a?e===a?!0:e&&e.nodeType===3?!1:a&&a.nodeType===3?hc(e,a.parentNode):"contains"in e?e.contains(a):e.compareDocumentPosition?!!(e.compareDocumentPosition(a)&16):!1:!1}function jd(e){e=e!=null&&e.ownerDocument!=null&&e.ownerDocument.defaultView!=null?e.ownerDocument.defaultView:window;for(var a=Xr(e.document);a instanceof e.HTMLIFrameElement;){try{var s=typeof a.contentWindow.location.href=="string"}catch{s=!1}if(s)e=a.contentWindow;else break;a=Xr(e.document)}return a}function Mu(e){var a=e&&e.nodeName&&e.nodeName.toLowerCase();return a&&(a==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||a==="textarea"||e.contentEditable==="true")}var ri=ja&&"documentMode"in document&&11>=document.documentMode,si=null,Fi=null,Ds=null,ii=!1;function Gn(e,a,s){var c=s.window===s?s.document:s.nodeType===9?s:s.ownerDocument;ii||si==null||si!==Xr(c)||(c=si,"selectionStart"in c&&Mu(c)?c={start:c.selectionStart,end:c.selectionEnd}:(c=(c.ownerDocument&&c.ownerDocument.defaultView||window).getSelection(),c={anchorNode:c.anchorNode,anchorOffset:c.anchorOffset,focusNode:c.focusNode,focusOffset:c.focusOffset}),Ds&&Pi(Ds,c)||(Ds=c,c=zm(Fi,"onSelect"),0<c.length&&(a=new er("onSelect","select",null,a,s),e.push({event:a,listeners:c}),a.target=si)))}function Pr(e,a){var s={};return s[e.toLowerCase()]=a.toLowerCase(),s["Webkit"+e]="webkit"+a,s["Moz"+e]="moz"+a,s}var Ao={animationend:Pr("Animation","AnimationEnd"),animationiteration:Pr("Animation","AnimationIteration"),animationstart:Pr("Animation","AnimationStart"),transitionrun:Pr("Transition","TransitionRun"),transitionstart:Pr("Transition","TransitionStart"),transitioncancel:Pr("Transition","TransitionCancel"),transitionend:Pr("Transition","TransitionEnd")},la={},wr={};ja&&(wr=document.createElement("div").style,"AnimationEvent"in window||(delete Ao.animationend.animation,delete Ao.animationiteration.animation,delete Ao.animationstart.animation),"TransitionEvent"in window||delete Ao.transitionend.transition);function Oi(e){if(la[e])return la[e];if(!Ao[e])return e;var a=Ao[e],s;for(s in a)if(a.hasOwnProperty(s)&&s in wr)return la[e]=a[s];return e}var ca=Oi("animationend"),Hi=Oi("animationiteration"),oi=Oi("animationstart"),mh=Oi("transitionrun"),Ed=Oi("transitionstart"),Jv=Oi("transitioncancel"),lm=Oi("transitionend"),No=new Map,Dd="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(" ");Dd.push("scrollEnd");function Ia(e,a){No.set(e,a),Nn(a,[e])}var gl=typeof reportError=="function"?reportError:function(e){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var a=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(a))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",e);return}console.error(e)},rs=[],gc=0,cm=0;function Au(){for(var e=gc,a=cm=gc=0;a<e;){var s=rs[a];rs[a++]=null;var c=rs[a];rs[a++]=null;var m=rs[a];rs[a++]=null;var v=rs[a];if(rs[a++]=null,c!==null&&m!==null){var A=c.pending;A===null?m.next=m:(m.next=A.next,A.next=m),c.pending=m}v!==0&&um(s,m,v)}}function vc(e,a,s,c){rs[gc++]=e,rs[gc++]=a,rs[gc++]=s,rs[gc++]=c,cm|=c,e.lanes|=c,e=e.alternate,e!==null&&(e.lanes|=c)}function Nu(e,a,s,c){return vc(e,a,s,c),Tu(e)}function To(e,a){return vc(e,null,null,a),Tu(e)}function um(e,a,s){e.lanes|=s;var c=e.alternate;c!==null&&(c.lanes|=s);for(var m=!1,v=e.return;v!==null;)v.childLanes|=s,c=v.alternate,c!==null&&(c.childLanes|=s),v.tag===22&&(e=v.stateNode,e===null||e._visibility&1||(m=!0)),e=v,v=v.return;return e.tag===3?(v=e.stateNode,m&&a!==null&&(m=31-z(s),e=v.hiddenUpdates,c=e[m],c===null?e[m]=[a]:c.push(a),a.lane=s|536870912),v):null}function Tu(e){if(50<xf)throw xf=0,Mh=null,Error(i(185));for(var a=e.return;a!==null;)e=a,a=e.return;return e.tag===3?e.stateNode:null}var Bi={};function Id(e,a,s,c){this.tag=e,this.key=s,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.refCleanup=this.ref=null,this.pendingProps=a,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=c,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function La(e,a,s,c){return new Id(e,a,s,c)}function ss(e){return e=e.prototype,!(!e||!e.isReactComponent)}function ba(e,a){var s=e.alternate;return s===null?(s=La(e.tag,a,e.key,e.mode),s.elementType=e.elementType,s.type=e.type,s.stateNode=e.stateNode,s.alternate=e,e.alternate=s):(s.pendingProps=a,s.type=e.type,s.flags=0,s.subtreeFlags=0,s.deletions=null),s.flags=e.flags&65011712,s.childLanes=e.childLanes,s.lanes=e.lanes,s.child=e.child,s.memoizedProps=e.memoizedProps,s.memoizedState=e.memoizedState,s.updateQueue=e.updateQueue,a=e.dependencies,s.dependencies=a===null?null:{lanes:a.lanes,firstContext:a.firstContext},s.sibling=e.sibling,s.index=e.index,s.ref=e.ref,s.refCleanup=e.refCleanup,s}function is(e,a){e.flags&=65011714;var s=e.alternate;return s===null?(e.childLanes=0,e.lanes=a,e.child=null,e.subtreeFlags=0,e.memoizedProps=null,e.memoizedState=null,e.updateQueue=null,e.dependencies=null,e.stateNode=null):(e.childLanes=s.childLanes,e.lanes=s.lanes,e.child=s.child,e.subtreeFlags=0,e.deletions=null,e.memoizedProps=s.memoizedProps,e.memoizedState=s.memoizedState,e.updateQueue=s.updateQueue,e.type=s.type,a=s.dependencies,e.dependencies=a===null?null:{lanes:a.lanes,firstContext:a.firstContext}),e}function Ro(e,a,s,c,m,v){var A=0;if(c=e,typeof e=="function")ss(e)&&(A=1);else if(typeof e=="string")A=AC(e,s,Me.current)?26:e==="html"||e==="head"||e==="body"?27:5;else e:switch(e){case ne:return e=La(31,s,a,m),e.elementType=ne,e.lanes=v,e;case N:return Is(s.children,m,v,a);case E:A=8,m|=24;break;case I:return e=La(12,s,a,m|2),e.elementType=I,e.lanes=v,e;case F:return e=La(13,s,a,m),e.elementType=F,e.lanes=v,e;case Y:return e=La(19,s,a,m),e.elementType=Y,e.lanes=v,e;default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case P:A=10;break e;case T:A=9;break e;case U:A=11;break e;case D:A=14;break e;case K:A=16,c=null;break e}A=29,s=Error(i(130,e===null?"null":typeof e,"")),c=null}return a=La(A,s,a,m),a.elementType=e,a.type=c,a.lanes=v,a}function Is(e,a,s,c){return e=La(7,e,c,a),e.lanes=s,e}function vl(e,a,s){return e=La(6,e,null,a),e.lanes=s,e}function Ld(e){var a=La(18,null,null,0);return a.stateNode=e,a}function Ru(e,a,s){return a=La(4,e.children!==null?e.children:[],e.key,a),a.lanes=s,a.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},a}var _d=new WeakMap;function _a(e,a){if(typeof e=="object"&&e!==null){var s=_d.get(e);return s!==void 0?s:(a={value:e,source:a,stack:Pe(a)},_d.set(e,a),a)}return{value:e,source:a,stack:Pe(a)}}var zi=[],Ls=0,wt=null,xr=0,Sr=[],ua=0,Fr=null,wa=1,Cr="";function Dt(e,a){zi[Ls++]=xr,zi[Ls++]=wt,wt=e,xr=a}function kr(e,a,s){Sr[ua++]=wa,Sr[ua++]=Cr,Sr[ua++]=Fr,Fr=e;var c=wa;e=Cr;var m=32-z(c)-1;c&=~(1<<m),s+=1;var v=32-z(a)+m;if(30<v){var A=m-m%5;v=(c&(1<<A)-1).toString(32),c>>=A,m-=A,wa=1<<32-z(a)+m|s<<m|c,Cr=v+e}else wa=1<<v|s<<m|c,Cr=e}function jo(e){e.return!==null&&(Dt(e,1),kr(e,1,0))}function $i(e){for(;e===wt;)wt=zi[--Ls],zi[Ls]=null,xr=zi[--Ls],zi[Ls]=null;for(;e===Fr;)Fr=Sr[--ua],Sr[ua]=null,Cr=Sr[--ua],Sr[ua]=null,wa=Sr[--ua],Sr[ua]=null}function dm(e,a){Sr[ua++]=wa,Sr[ua++]=Cr,Sr[ua++]=Fr,wa=a.id,Cr=a.overflow,Fr=e}var xa=null,mn=null,Gt=!1,li=null,Ga=!1,Ui=Error(i(519));function ut(e){var a=Error(i(418,1<arguments.length&&arguments[1]!==void 0&&arguments[1]?"text":"HTML",""));throw _s(_a(a,e)),Ui}function Pd(e){var a=e.stateNode,s=e.type,c=e.memoizedProps;switch(a[fe]=e,a[_e]=c,s){case"dialog":Kt("cancel",a),Kt("close",a);break;case"iframe":case"object":case"embed":Kt("load",a);break;case"video":case"audio":for(s=0;s<Cf.length;s++)Kt(Cf[s],a);break;case"source":Kt("error",a);break;case"img":case"image":case"link":Kt("error",a),Kt("load",a);break;case"details":Kt("toggle",a);break;case"input":Kt("invalid",a),Zr(a,c.value,c.defaultValue,c.checked,c.defaultChecked,c.type,c.name,!0);break;case"select":Kt("invalid",a);break;case"textarea":Kt("invalid",a),mu(a,c.value,c.defaultValue,c.children)}s=c.children,typeof s!="string"&&typeof s!="number"&&typeof s!="bigint"||a.textContent===""+s||c.suppressHydrationWarning===!0||Ly(a.textContent,s)?(c.popover!=null&&(Kt("beforetoggle",a),Kt("toggle",a)),c.onScroll!=null&&Kt("scroll",a),c.onScrollEnd!=null&&Kt("scrollend",a),c.onClick!=null&&(a.onclick=vr),a=!0):a=!1,a||ut(e,!0)}function fm(e){for(xa=e.return;xa;)switch(xa.tag){case 5:case 31:case 13:Ga=!1;return;case 27:case 3:Ga=!0;return;default:xa=xa.return}}function os(e){if(e!==xa)return!1;if(!Gt)return fm(e),Gt=!0,!1;var a=e.tag,s;if((s=a!==3&&a!==27)&&((s=a===5)&&(s=e.type,s=!(s!=="form"&&s!=="button")||Bh(e.type,e.memoizedProps)),s=!s),s&&mn&&ut(e),fm(e),a===13){if(e=e.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(i(317));mn=Uy(e)}else if(a===31){if(e=e.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(i(317));mn=Uy(e)}else a===27?(a=mn,$l(e.type)?(e=Wh,Wh=null,mn=e):mn=a):mn=xa?$s(e.stateNode.nextSibling):null;return!0}function qi(){mn=xa=null,Gt=!1}function Or(){var e=li;return e!==null&&(Vr===null?Vr=e:Vr.push.apply(Vr,e),li=null),e}function _s(e){li===null?li=[e]:li.push(e)}var yc=me(null),ci=null,Ps=null;function Wi(e,a,s){Ce(yc,a._currentValue),a._currentValue=s}function ui(e){e._currentValue=yc.current,ue(yc)}function Fd(e,a,s){for(;e!==null;){var c=e.alternate;if((e.childLanes&a)!==a?(e.childLanes|=a,c!==null&&(c.childLanes|=a)):c!==null&&(c.childLanes&a)!==a&&(c.childLanes|=a),e===s)break;e=e.return}}function yl(e,a,s,c){var m=e.child;for(m!==null&&(m.return=e);m!==null;){var v=m.dependencies;if(v!==null){var A=m.child;v=v.firstContext;e:for(;v!==null;){var _=v;v=m;for(var J=0;J<a.length;J++)if(_.context===a[J]){v.lanes|=s,_=v.alternate,_!==null&&(_.lanes|=s),Fd(v.return,s,e),c||(A=null);break e}v=_.next}}else if(m.tag===18){if(A=m.return,A===null)throw Error(i(341));A.lanes|=s,v=A.alternate,v!==null&&(v.lanes|=s),Fd(A,s,e),A=null}else A=m.child;if(A!==null)A.return=m;else for(A=m;A!==null;){if(A===e){A=null;break}if(m=A.sibling,m!==null){m.return=A.return,A=m;break}A=A.return}m=A}}function bl(e,a,s,c){e=null;for(var m=a,v=!1;m!==null;){if(!v){if((m.flags&524288)!==0)v=!0;else if((m.flags&262144)!==0)break}if(m.tag===10){var A=m.alternate;if(A===null)throw Error(i(387));if(A=A.memoizedProps,A!==null){var _=m.type;Da(m.pendingProps.value,A.value)||(e!==null?e.push(_):e=[_])}}else if(m===Ve.current){if(A=m.alternate,A===null)throw Error(i(387));A.memoizedState.memoizedState!==m.memoizedState.memoizedState&&(e!==null?e.push(Tf):e=[Tf])}m=m.return}e!==null&&yl(a,e,s,c),a.flags|=262144}function Eo(e){for(e=e.firstContext;e!==null;){if(!Da(e.context._currentValue,e.memoizedValue))return!0;e=e.next}return!1}function Hr(e){ci=e,Ps=null,e=e.dependencies,e!==null&&(e.firstContext=null)}function tn(e){return Pa(ci,e)}function di(e,a){return ci===null&&Hr(e),Pa(e,a)}function Pa(e,a){var s=a._currentValue;if(a={context:a,memoizedValue:s,next:null},Ps===null){if(e===null)throw Error(i(308));Ps=a,e.dependencies={lanes:0,firstContext:a},e.flags|=524288}else Ps=Ps.next=a;return s}var Br=typeof AbortController<"u"?AbortController:function(){var e=[],a=this.signal={aborted:!1,addEventListener:function(s,c){e.push(c)}};this.abort=function(){a.aborted=!0,e.forEach(function(s){return s()})}},Be=t.unstable_scheduleCallback,mm=t.unstable_NormalPriority,Vn={$$typeof:P,Consumer:null,Provider:null,_currentValue:null,_currentValue2:null,_threadCount:0};function Od(){return{controller:new Br,data:new Map,refCount:0}}function Do(e){e.refCount--,e.refCount===0&&Be(mm,function(){e.controller.abort()})}var Va=null,pm=0,ls=0,Cn=null;function hm(e,a){if(Va===null){var s=Va=[];pm=0,ls=Eh(),Cn={status:"pending",value:void 0,then:function(c){s.push(c)}}}return pm++,a.then(ju,ju),a}function ju(){if(--pm===0&&Va!==null){Cn!==null&&(Cn.status="fulfilled");var e=Va;Va=null,ls=0,Cn=null;for(var a=0;a<e.length;a++)(0,e[a])()}}function Fs(e,a){var s=[],c={status:"pending",value:null,reason:null,then:function(m){s.push(m)}};return e.then(function(){c.status="fulfilled",c.value=a;for(var m=0;m<s.length;m++)(0,s[m])(a)},function(m){for(c.status="rejected",c.reason=m,m=0;m<s.length;m++)(0,s[m])(void 0)}),c}var gm=B.S;B.S=function(e,a){ry=ze(),typeof a=="object"&&a!==null&&typeof a.then=="function"&&hm(e,a),gm!==null&&gm(e,a)};var Io=me(null);function an(){var e=Io.current;return e!==null?e:Mn.pooledCache}function fi(e,a){a===null?Ce(Io,Io.current):Ce(Io,a.pool)}function vm(){var e=an();return e===null?null:{parent:Vn._currentValue,pool:e}}var sr=Error(i(460)),Eu=Error(i(474)),Gi=Error(i(542)),Fa={then:function(){}};function bc(e){return e=e.status,e==="fulfilled"||e==="rejected"}function ph(e,a,s){switch(s=e[s],s===void 0?e.push(a):s!==a&&(a.then(vr,vr),a=s),a.status){case"fulfilled":return a.value;case"rejected":throw e=a.reason,us(e),e;default:if(typeof a.status=="string")a.then(vr,vr);else{if(e=Mn,e!==null&&100<e.shellSuspendCounter)throw Error(i(482));e=a,e.status="pending",e.then(function(c){if(a.status==="pending"){var m=a;m.status="fulfilled",m.value=c}},function(c){if(a.status==="pending"){var m=a;m.status="rejected",m.reason=c}})}switch(a.status){case"fulfilled":return a.value;case"rejected":throw e=a.reason,us(e),e}throw Os=a,sr}}function cs(e){try{var a=e._init;return a(e._payload)}catch(s){throw s!==null&&typeof s=="object"&&typeof s.then=="function"?(Os=s,sr):s}}var Os=null;function wc(){if(Os===null)throw Error(i(459));var e=Os;return Os=null,e}function us(e){if(e===sr||e===Gi)throw Error(i(483))}var Ka=null,Vi=0;function Ki(e){var a=Vi;return Vi+=1,Ka===null&&(Ka=[]),ph(Ka,e,a)}function ir(e,a){a=a.props.ref,e.ref=a!==void 0?a:null}function Sa(e,a){throw a.$$typeof===x?Error(i(525)):(e=Object.prototype.toString.call(a),Error(i(31,e==="[object Object]"?"object with keys {"+Object.keys(a).join(", ")+"}":e)))}function or(e){function a(de,se){if(e){var ve=de.deletions;ve===null?(de.deletions=[se],de.flags|=16):ve.push(se)}}function s(de,se){if(!e)return null;for(;se!==null;)a(de,se),se=se.sibling;return null}function c(de){for(var se=new Map;de!==null;)de.key!==null?se.set(de.key,de):se.set(de.index,de),de=de.sibling;return se}function m(de,se){return de=ba(de,se),de.index=0,de.sibling=null,de}function v(de,se,ve){return de.index=ve,e?(ve=de.alternate,ve!==null?(ve=ve.index,ve<se?(de.flags|=67108866,se):ve):(de.flags|=67108866,se)):(de.flags|=1048576,se)}function A(de){return e&&de.alternate===null&&(de.flags|=67108866),de}function _(de,se,ve,je){return se===null||se.tag!==6?(se=vl(ve,de.mode,je),se.return=de,se):(se=m(se,ve),se.return=de,se)}function J(de,se,ve,je){var bt=ve.type;return bt===N?Re(de,se,ve.props.children,je,ve.key):se!==null&&(se.elementType===bt||typeof bt=="object"&&bt!==null&&bt.$$typeof===K&&cs(bt)===se.type)?(se=m(se,ve.props),ir(se,ve),se.return=de,se):(se=Ro(ve.type,ve.key,ve.props,null,de.mode,je),ir(se,ve),se.return=de,se)}function ye(de,se,ve,je){return se===null||se.tag!==4||se.stateNode.containerInfo!==ve.containerInfo||se.stateNode.implementation!==ve.implementation?(se=Ru(ve,de.mode,je),se.return=de,se):(se=m(se,ve.children||[]),se.return=de,se)}function Re(de,se,ve,je,bt){return se===null||se.tag!==7?(se=Is(ve,de.mode,je,bt),se.return=de,se):(se=m(se,ve),se.return=de,se)}function Ie(de,se,ve){if(typeof se=="string"&&se!==""||typeof se=="number"||typeof se=="bigint")return se=vl(""+se,de.mode,ve),se.return=de,se;if(typeof se=="object"&&se!==null){switch(se.$$typeof){case M:return ve=Ro(se.type,se.key,se.props,null,de.mode,ve),ir(ve,se),ve.return=de,ve;case k:return se=Ru(se,de.mode,ve),se.return=de,se;case K:return se=cs(se),Ie(de,se,ve)}if(ee(se)||W(se))return se=Is(se,de.mode,ve,null),se.return=de,se;if(typeof se.then=="function")return Ie(de,Ki(se),ve);if(se.$$typeof===P)return Ie(de,di(de,se),ve);Sa(de,se)}return null}function we(de,se,ve,je){var bt=se!==null?se.key:null;if(typeof ve=="string"&&ve!==""||typeof ve=="number"||typeof ve=="bigint")return bt!==null?null:_(de,se,""+ve,je);if(typeof ve=="object"&&ve!==null){switch(ve.$$typeof){case M:return ve.key===bt?J(de,se,ve,je):null;case k:return ve.key===bt?ye(de,se,ve,je):null;case K:return ve=cs(ve),we(de,se,ve,je)}if(ee(ve)||W(ve))return bt!==null?null:Re(de,se,ve,je,null);if(typeof ve.then=="function")return we(de,se,Ki(ve),je);if(ve.$$typeof===P)return we(de,se,di(de,ve),je);Sa(de,ve)}return null}function ke(de,se,ve,je,bt){if(typeof je=="string"&&je!==""||typeof je=="number"||typeof je=="bigint")return de=de.get(ve)||null,_(se,de,""+je,bt);if(typeof je=="object"&&je!==null){switch(je.$$typeof){case M:return de=de.get(je.key===null?ve:je.key)||null,J(se,de,je,bt);case k:return de=de.get(je.key===null?ve:je.key)||null,ye(se,de,je,bt);case K:return je=cs(je),ke(de,se,ve,je,bt)}if(ee(je)||W(je))return de=de.get(ve)||null,Re(se,de,je,bt,null);if(typeof je.then=="function")return ke(de,se,ve,Ki(je),bt);if(je.$$typeof===P)return ke(de,se,ve,di(se,je),bt);Sa(se,je)}return null}function it(de,se,ve,je){for(var bt=null,on=null,ft=se,zt=se=0,Jt=null;ft!==null&&zt<ve.length;zt++){ft.index>zt?(Jt=ft,ft=null):Jt=ft.sibling;var ln=we(de,ft,ve[zt],je);if(ln===null){ft===null&&(ft=Jt);break}e&&ft&&ln.alternate===null&&a(de,ft),se=v(ln,se,zt),on===null?bt=ln:on.sibling=ln,on=ln,ft=Jt}if(zt===ve.length)return s(de,ft),Gt&&Dt(de,zt),bt;if(ft===null){for(;zt<ve.length;zt++)ft=Ie(de,ve[zt],je),ft!==null&&(se=v(ft,se,zt),on===null?bt=ft:on.sibling=ft,on=ft);return Gt&&Dt(de,zt),bt}for(ft=c(ft);zt<ve.length;zt++)Jt=ke(ft,de,zt,ve[zt],je),Jt!==null&&(e&&Jt.alternate!==null&&ft.delete(Jt.key===null?zt:Jt.key),se=v(Jt,se,zt),on===null?bt=Jt:on.sibling=Jt,on=Jt);return e&&ft.forEach(function(Vl){return a(de,Vl)}),Gt&&Dt(de,zt),bt}function Ct(de,se,ve,je){if(ve==null)throw Error(i(151));for(var bt=null,on=null,ft=se,zt=se=0,Jt=null,ln=ve.next();ft!==null&&!ln.done;zt++,ln=ve.next()){ft.index>zt?(Jt=ft,ft=null):Jt=ft.sibling;var Vl=we(de,ft,ln.value,je);if(Vl===null){ft===null&&(ft=Jt);break}e&&ft&&Vl.alternate===null&&a(de,ft),se=v(Vl,se,zt),on===null?bt=Vl:on.sibling=Vl,on=Vl,ft=Jt}if(ln.done)return s(de,ft),Gt&&Dt(de,zt),bt;if(ft===null){for(;!ln.done;zt++,ln=ve.next())ln=Ie(de,ln.value,je),ln!==null&&(se=v(ln,se,zt),on===null?bt=ln:on.sibling=ln,on=ln);return Gt&&Dt(de,zt),bt}for(ft=c(ft);!ln.done;zt++,ln=ve.next())ln=ke(ft,de,zt,ln.value,je),ln!==null&&(e&&ln.alternate!==null&&ft.delete(ln.key===null?zt:ln.key),se=v(ln,se,zt),on===null?bt=ln:on.sibling=ln,on=ln);return e&&ft.forEach(function(FC){return a(de,FC)}),Gt&&Dt(de,zt),bt}function wn(de,se,ve,je){if(typeof ve=="object"&&ve!==null&&ve.type===N&&ve.key===null&&(ve=ve.props.children),typeof ve=="object"&&ve!==null){switch(ve.$$typeof){case M:e:{for(var bt=ve.key;se!==null;){if(se.key===bt){if(bt=ve.type,bt===N){if(se.tag===7){s(de,se.sibling),je=m(se,ve.props.children),je.return=de,de=je;break e}}else if(se.elementType===bt||typeof bt=="object"&&bt!==null&&bt.$$typeof===K&&cs(bt)===se.type){s(de,se.sibling),je=m(se,ve.props),ir(je,ve),je.return=de,de=je;break e}s(de,se);break}else a(de,se);se=se.sibling}ve.type===N?(je=Is(ve.props.children,de.mode,je,ve.key),je.return=de,de=je):(je=Ro(ve.type,ve.key,ve.props,null,de.mode,je),ir(je,ve),je.return=de,de=je)}return A(de);case k:e:{for(bt=ve.key;se!==null;){if(se.key===bt)if(se.tag===4&&se.stateNode.containerInfo===ve.containerInfo&&se.stateNode.implementation===ve.implementation){s(de,se.sibling),je=m(se,ve.children||[]),je.return=de,de=je;break e}else{s(de,se);break}else a(de,se);se=se.sibling}je=Ru(ve,de.mode,je),je.return=de,de=je}return A(de);case K:return ve=cs(ve),wn(de,se,ve,je)}if(ee(ve))return it(de,se,ve,je);if(W(ve)){if(bt=W(ve),typeof bt!="function")throw Error(i(150));return ve=bt.call(ve),Ct(de,se,ve,je)}if(typeof ve.then=="function")return wn(de,se,Ki(ve),je);if(ve.$$typeof===P)return wn(de,se,di(de,ve),je);Sa(de,ve)}return typeof ve=="string"&&ve!==""||typeof ve=="number"||typeof ve=="bigint"?(ve=""+ve,se!==null&&se.tag===6?(s(de,se.sibling),je=m(se,ve),je.return=de,de=je):(s(de,se),je=vl(ve,de.mode,je),je.return=de,de=je),A(de)):s(de,se)}return function(de,se,ve,je){try{Vi=0;var bt=wn(de,se,ve,je);return Ka=null,bt}catch(ft){if(ft===sr||ft===Gi)throw ft;var on=La(29,ft,null,de.mode);return on.lanes=je,on.return=de,on}}}var Qi=or(!0),ym=or(!1),mi=!1;function Yi(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function xc(e,a){e=e.updateQueue,a.updateQueue===e&&(a.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,callbacks:null})}function ds(e){return{lane:e,tag:0,payload:null,callback:null,next:null}}function Oa(e,a,s){var c=e.updateQueue;if(c===null)return null;if(c=c.shared,(dn&2)!==0){var m=c.pending;return m===null?a.next=a:(a.next=m.next,m.next=a),c.pending=a,a=Tu(e),um(e,null,s),a}return vc(e,c,a,s),Tu(e)}function fs(e,a,s){if(a=a.updateQueue,a!==null&&(a=a.shared,(s&4194048)!==0)){var c=a.lanes;c&=e.pendingLanes,s|=c,a.lanes=s,V(e,s)}}function Sc(e,a){var s=e.updateQueue,c=e.alternate;if(c!==null&&(c=c.updateQueue,s===c)){var m=null,v=null;if(s=s.firstBaseUpdate,s!==null){do{var A={lane:s.lane,tag:s.tag,payload:s.payload,callback:null,next:null};v===null?m=v=A:v=v.next=A,s=s.next}while(s!==null);v===null?m=v=a:v=v.next=a}else m=v=a;s={baseState:c.baseState,firstBaseUpdate:m,lastBaseUpdate:v,shared:c.shared,callbacks:c.callbacks},e.updateQueue=s;return}e=s.lastBaseUpdate,e===null?s.firstBaseUpdate=a:e.next=a,s.lastBaseUpdate=a}var ms=!1;function Xi(){if(ms){var e=Cn;if(e!==null)throw e}}function Zi(e,a,s,c){ms=!1;var m=e.updateQueue;mi=!1;var v=m.firstBaseUpdate,A=m.lastBaseUpdate,_=m.shared.pending;if(_!==null){m.shared.pending=null;var J=_,ye=J.next;J.next=null,A===null?v=ye:A.next=ye,A=J;var Re=e.alternate;Re!==null&&(Re=Re.updateQueue,_=Re.lastBaseUpdate,_!==A&&(_===null?Re.firstBaseUpdate=ye:_.next=ye,Re.lastBaseUpdate=J))}if(v!==null){var Ie=m.baseState;A=0,Re=ye=J=null,_=v;do{var we=_.lane&-536870913,ke=we!==_.lane;if(ke?(Zt&we)===we:(c&we)===we){we!==0&&we===ls&&(ms=!0),Re!==null&&(Re=Re.next={lane:0,tag:_.tag,payload:_.payload,callback:null,next:null});e:{var it=e,Ct=_;we=a;var wn=s;switch(Ct.tag){case 1:if(it=Ct.payload,typeof it=="function"){Ie=it.call(wn,Ie,we);break e}Ie=it;break e;case 3:it.flags=it.flags&-65537|128;case 0:if(it=Ct.payload,we=typeof it=="function"?it.call(wn,Ie,we):it,we==null)break e;Ie=b({},Ie,we);break e;case 2:mi=!0}}we=_.callback,we!==null&&(e.flags|=64,ke&&(e.flags|=8192),ke=m.callbacks,ke===null?m.callbacks=[we]:ke.push(we))}else ke={lane:we,tag:_.tag,payload:_.payload,callback:_.callback,next:null},Re===null?(ye=Re=ke,J=Ie):Re=Re.next=ke,A|=we;if(_=_.next,_===null){if(_=m.shared.pending,_===null)break;ke=_,_=ke.next,ke.next=null,m.lastBaseUpdate=ke,m.shared.pending=null}}while(!0);Re===null&&(J=Ie),m.baseState=J,m.firstBaseUpdate=ye,m.lastBaseUpdate=Re,v===null&&(m.shared.lanes=0),Fl|=A,e.lanes=A,e.memoizedState=Ie}}function ps(e,a){if(typeof e!="function")throw Error(i(191,e));e.call(a)}function hs(e,a){var s=e.callbacks;if(s!==null)for(e.callbacks=null,e=0;e<s.length;e++)ps(s[e],a)}var zr=me(null),Hn=me(0);function Cc(e,a){e=Xo,Ce(Hn,e),Ce(zr,a),Xo=e|a.baseLanes}function gs(){Ce(Hn,Xo),Ce(zr,zr.current)}function wl(){Xo=Hn.current,ue(zr),ue(Hn)}var Mr=me(null),$r=null;function vs(e){var a=e.alternate;Ce(_n,_n.current&1),Ce(Mr,e),$r===null&&(a===null||zr.current!==null||a.memoizedState!==null)&&($r=e)}function xl(e){Ce(_n,_n.current),Ce(Mr,e),$r===null&&($r=e)}function Hd(e){e.tag===22?(Ce(_n,_n.current),Ce(Mr,e),$r===null&&($r=e)):Ar()}function Ar(){Ce(_n,_n.current),Ce(Mr,Mr.current)}function lr(e){ue(Mr),$r===e&&($r=null),ue(_n)}var _n=me(0);function Du(e){for(var a=e;a!==null;){if(a.tag===13){var s=a.memoizedState;if(s!==null&&(s=s.dehydrated,s===null||Uh(s)||qh(s)))return a}else if(a.tag===19&&(a.memoizedProps.revealOrder==="forwards"||a.memoizedProps.revealOrder==="backwards"||a.memoizedProps.revealOrder==="unstable_legacy-backwards"||a.memoizedProps.revealOrder==="together")){if((a.flags&128)!==0)return a}else if(a.child!==null){a.child.return=a,a=a.child;continue}if(a===e)break;for(;a.sibling===null;){if(a.return===null||a.return===e)return null;a=a.return}a.sibling.return=a.return,a=a.sibling}return null}var cr=0,_t=null,un=null,Kn=null,kc=!1,Sl=!1,Ji=!1,Lo=0,Mc=0,_o=null,Ac=0;function En(){throw Error(i(321))}function pi(e,a){if(a===null)return!1;for(var s=0;s<a.length&&s<e.length;s++)if(!Da(e[s],a[s]))return!1;return!0}function Cl(e,a,s,c,m,v){return cr=v,_t=a,a.memoizedState=null,a.updateQueue=null,a.lanes=0,B.H=e===null||e.memoizedState===null?wm:$u,Ji=!1,v=s(c,m),Ji=!1,Sl&&(v=eo(a,s,c,m)),Po(e),v}function Po(e){B.H=vi;var a=un!==null&&un.next!==null;if(cr=0,Kn=un=_t=null,kc=!1,Mc=0,_o=null,a)throw Error(i(300));e===null||Qn||(e=e.dependencies,e!==null&&Eo(e)&&(Qn=!0))}function eo(e,a,s,c){_t=e;var m=0;do{if(Sl&&(_o=null),Mc=0,Sl=!1,25<=m)throw Error(i(301));if(m+=1,Kn=un=null,e.updateQueue!=null){var v=e.updateQueue;v.lastEffect=null,v.events=null,v.stores=null,v.memoCache!=null&&(v.memoCache.index=0)}B.H=jl,v=a(s,c)}while(Sl);return v}function Bd(){var e=B.H,a=e.useState()[0];return a=typeof a.then=="function"?to(a):a,e=e.useState()[0],(un!==null?un.memoizedState:null)!==e&&(_t.flags|=1024),a}function zd(){var e=Lo!==0;return Lo=0,e}function Iu(e,a,s){a.updateQueue=e.updateQueue,a.flags&=-2053,e.lanes&=~s}function Fo(e){if(kc){for(e=e.memoizedState;e!==null;){var a=e.queue;a!==null&&(a.pending=null),e=e.next}kc=!1}cr=0,Kn=un=_t=null,Sl=!1,Mc=Lo=0,_o=null}function Ca(){var e={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return Kn===null?_t.memoizedState=Kn=e:Kn=Kn.next=e,Kn}function kn(){if(un===null){var e=_t.alternate;e=e!==null?e.memoizedState:null}else e=un.next;var a=Kn===null?_t.memoizedState:Kn.next;if(a!==null)Kn=a,un=e;else{if(e===null)throw _t.alternate===null?Error(i(467)):Error(i(310));un=e,e={memoizedState:un.memoizedState,baseState:un.baseState,baseQueue:un.baseQueue,queue:un.queue,next:null},Kn===null?_t.memoizedState=Kn=e:Kn=Kn.next=e}return Kn}function Lu(){return{lastEffect:null,events:null,stores:null,memoCache:null}}function to(e){var a=Mc;return Mc+=1,_o===null&&(_o=[]),e=ph(_o,e,a),a=_t,(Kn===null?a.memoizedState:Kn.next)===null&&(a=a.alternate,B.H=a===null||a.memoizedState===null?wm:$u),e}function Nc(e){if(e!==null&&typeof e=="object"){if(typeof e.then=="function")return to(e);if(e.$$typeof===P)return tn(e)}throw Error(i(438,String(e)))}function Oo(e){var a=null,s=_t.updateQueue;if(s!==null&&(a=s.memoCache),a==null){var c=_t.alternate;c!==null&&(c=c.updateQueue,c!==null&&(c=c.memoCache,c!=null&&(a={data:c.data.map(function(m){return m.slice()}),index:0})))}if(a==null&&(a={data:[],index:0}),s===null&&(s=Lu(),_t.updateQueue=s),s.memoCache=a,s=a.data[a.index],s===void 0)for(s=a.data[a.index]=Array(e),c=0;c<e;c++)s[c]=q;return a.index++,s}function ys(e,a){return typeof a=="function"?a(e):a}function Ho(e){var a=kn();return kl(a,un,e)}function kl(e,a,s){var c=e.queue;if(c===null)throw Error(i(311));c.lastRenderedReducer=s;var m=e.baseQueue,v=c.pending;if(v!==null){if(m!==null){var A=m.next;m.next=v.next,v.next=A}a.baseQueue=m=v,c.pending=null}if(v=e.baseState,m===null)e.memoizedState=v;else{a=m.next;var _=A=null,J=null,ye=a,Re=!1;do{var Ie=ye.lane&-536870913;if(Ie!==ye.lane?(Zt&Ie)===Ie:(cr&Ie)===Ie){var we=ye.revertLane;if(we===0)J!==null&&(J=J.next={lane:0,revertLane:0,gesture:null,action:ye.action,hasEagerState:ye.hasEagerState,eagerState:ye.eagerState,next:null}),Ie===ls&&(Re=!0);else if((cr&we)===we){ye=ye.next,we===ls&&(Re=!0);continue}else Ie={lane:0,revertLane:ye.revertLane,gesture:null,action:ye.action,hasEagerState:ye.hasEagerState,eagerState:ye.eagerState,next:null},J===null?(_=J=Ie,A=v):J=J.next=Ie,_t.lanes|=we,Fl|=we;Ie=ye.action,Ji&&s(v,Ie),v=ye.hasEagerState?ye.eagerState:s(v,Ie)}else we={lane:Ie,revertLane:ye.revertLane,gesture:ye.gesture,action:ye.action,hasEagerState:ye.hasEagerState,eagerState:ye.eagerState,next:null},J===null?(_=J=we,A=v):J=J.next=we,_t.lanes|=Ie,Fl|=Ie;ye=ye.next}while(ye!==null&&ye!==a);if(J===null?A=v:J.next=_,!Da(v,e.memoizedState)&&(Qn=!0,Re&&(s=Cn,s!==null)))throw s;e.memoizedState=v,e.baseState=A,e.baseQueue=J,c.lastRenderedState=v}return m===null&&(c.lanes=0),[e.memoizedState,c.dispatch]}function Ml(e){var a=kn(),s=a.queue;if(s===null)throw Error(i(311));s.lastRenderedReducer=e;var c=s.dispatch,m=s.pending,v=a.memoizedState;if(m!==null){s.pending=null;var A=m=m.next;do v=e(v,A.action),A=A.next;while(A!==m);Da(v,a.memoizedState)||(Qn=!0),a.memoizedState=v,a.baseQueue===null&&(a.baseState=v),s.lastRenderedState=v}return[v,c]}function $d(e,a,s){var c=_t,m=kn(),v=Gt;if(v){if(s===void 0)throw Error(i(407));s=s()}else s=a();var A=!Da((un||m).memoizedState,s);if(A&&(m.memoizedState=s,Qn=!0),m=m.queue,Vd(qd.bind(null,c,m,e),[e]),m.getSnapshot!==a||A||Kn!==null&&Kn.memoizedState.tag&1){if(c.flags|=2048,hi(9,{destroy:void 0},Ud.bind(null,c,m,s,a),null),Mn===null)throw Error(i(349));v||(cr&127)!==0||no(c,a,s)}return s}function no(e,a,s){e.flags|=16384,e={getSnapshot:a,value:s},a=_t.updateQueue,a===null?(a=Lu(),_t.updateQueue=a,a.stores=[e]):(s=a.stores,s===null?a.stores=[e]:s.push(e))}function Ud(e,a,s,c){a.value=s,a.getSnapshot=c,Qa(a)&&Tc(e)}function qd(e,a,s){return s(function(){Qa(a)&&Tc(e)})}function Qa(e){var a=e.getSnapshot;e=e.value;try{var s=a();return!Da(e,s)}catch{return!0}}function Tc(e){var a=To(e,2);a!==null&&Kr(a,e,2)}function Rc(e){var a=Ca();if(typeof e=="function"){var s=e;if(e=s(),Ji){De(!0);try{s()}finally{De(!1)}}}return a.memoizedState=a.baseState=e,a.queue={pending:null,lanes:0,dispatch:null,lastRenderedReducer:ys,lastRenderedState:e},a}function Bo(e,a,s,c){return e.baseState=s,kl(e,un,typeof c=="function"?c:ys)}function Ur(e,a,s,c,m){if(_c(e))throw Error(i(485));if(e=a.action,e!==null){var v={payload:m,action:e,next:null,isTransition:!0,status:"pending",value:null,reason:null,listeners:[],then:function(A){v.listeners.push(A)}};B.T!==null?s(!0):v.isTransition=!1,c(v),s=a.pending,s===null?(v.next=a.pending=v,Nr(a,v)):(v.next=s.next,a.pending=s.next=v)}}function Nr(e,a){var s=a.action,c=a.payload,m=e.state;if(a.isTransition){var v=B.T,A={};B.T=A;try{var _=s(m,c),J=B.S;J!==null&&J(A,_),zo(e,a,_)}catch(ye){Al(e,a,ye)}finally{v!==null&&A.types!==null&&(v.types=A.types),B.T=v}}else try{v=s(m,c),zo(e,a,v)}catch(ye){Al(e,a,ye)}}function zo(e,a,s){s!==null&&typeof s=="object"&&typeof s.then=="function"?s.then(function(c){Wd(e,a,c)},function(c){return Al(e,a,c)}):Wd(e,a,s)}function Wd(e,a,s){a.status="fulfilled",a.value=s,Tr(a),e.state=s,a=e.pending,a!==null&&(s=a.next,s===a?e.pending=null:(s=s.next,a.next=s,Nr(e,s)))}function Al(e,a,s){var c=e.pending;if(e.pending=null,c!==null){c=c.next;do a.status="rejected",a.reason=s,Tr(a),a=a.next;while(a!==c)}e.action=null}function Tr(e){e=e.listeners;for(var a=0;a<e.length;a++)(0,e[a])()}function hh(e,a){return a}function Gd(e,a){if(Gt){var s=Mn.formState;if(s!==null){e:{var c=_t;if(Gt){if(mn){t:{for(var m=mn,v=Ga;m.nodeType!==8;){if(!v){m=null;break t}if(m=$s(m.nextSibling),m===null){m=null;break t}}v=m.data,m=v==="F!"||v==="F"?m:null}if(m){mn=$s(m.nextSibling),c=m.data==="F!";break e}}ut(c)}c=!1}c&&(a=s[0])}}return s=Ca(),s.memoizedState=s.baseState=a,c={pending:null,lanes:0,dispatch:null,lastRenderedReducer:hh,lastRenderedState:a},s.queue=c,s=Lc.bind(null,_t,c),c.dispatch=s,c=Rc(!1),v=zu.bind(null,_t,!1,c.queue),c=Ca(),m={state:a,dispatch:null,action:e,pending:null},c.queue=m,s=Ur.bind(null,_t,m,v,s),m.dispatch=s,c.memoizedState=e,[a,s,!1]}function jc(e){var a=kn();return _u(a,un,e)}function _u(e,a,s){if(a=kl(e,a,hh)[0],e=Ho(ys)[0],typeof a=="object"&&a!==null&&typeof a.then=="function")try{var c=to(a)}catch(A){throw A===sr?Gi:A}else c=a;a=kn();var m=a.queue,v=m.dispatch;return s!==a.memoizedState&&(_t.flags|=2048,hi(9,{destroy:void 0},Ec.bind(null,m,s),null)),[c,v,e]}function Ec(e,a){e.action=a}function Nl(e){var a=kn(),s=un;if(s!==null)return _u(a,s,e);kn(),a=a.memoizedState,s=kn();var c=s.queue.dispatch;return s.memoizedState=e,[a,c,!1]}function hi(e,a,s,c){return e={tag:e,create:s,deps:c,inst:a,next:null},a=_t.updateQueue,a===null&&(a=Lu(),_t.updateQueue=a),s=a.lastEffect,s===null?a.lastEffect=e.next=e:(c=s.next,s.next=e,e.next=c,a.lastEffect=e),e}function Tl(){return kn().memoizedState}function $o(e,a,s,c){var m=Ca();_t.flags|=e,m.memoizedState=hi(1|a,{destroy:void 0},s,c===void 0?null:c)}function Uo(e,a,s,c){var m=kn();c=c===void 0?null:c;var v=m.memoizedState.inst;un!==null&&c!==null&&pi(c,un.memoizedState.deps)?m.memoizedState=hi(a,v,s,c):(_t.flags|=e,m.memoizedState=hi(1|a,v,s,c))}function Pu(e,a){$o(8390656,8,e,a)}function Vd(e,a){Uo(2048,8,e,a)}function Fu(e){_t.flags|=4;var a=_t.updateQueue;if(a===null)a=Lu(),_t.updateQueue=a,a.events=[e];else{var s=a.events;s===null?a.events=[e]:s.push(e)}}function Kd(e){var a=kn().memoizedState;return Fu({ref:a,nextImpl:e}),function(){if((dn&2)!==0)throw Error(i(440));return a.impl.apply(void 0,arguments)}}function bs(e,a){return Uo(4,2,e,a)}function Qd(e,a){return Uo(4,4,e,a)}function Dc(e,a){if(typeof a=="function"){e=e();var s=a(e);return function(){typeof s=="function"?s():a(null)}}if(a!=null)return e=e(),a.current=e,function(){a.current=null}}function Ou(e,a,s){s=s!=null?s.concat([e]):null,Uo(4,4,Dc.bind(null,a,e),s)}function Hs(){}function Yd(e,a){var s=kn();a=a===void 0?null:a;var c=s.memoizedState;return a!==null&&pi(a,c[1])?c[0]:(s.memoizedState=[e,a],e)}function qr(e,a){var s=kn();a=a===void 0?null:a;var c=s.memoizedState;if(a!==null&&pi(a,c[1]))return c[0];if(c=e(),Ji){De(!0);try{e()}finally{De(!1)}}return s.memoizedState=[c,a],c}function gi(e,a,s){return s===void 0||(cr&1073741824)!==0&&(Zt&261930)===0?e.memoizedState=a:(e.memoizedState=s,e=iy(),_t.lanes|=e,Fl|=e,s)}function ka(e,a,s,c){return Da(s,a)?s:zr.current!==null?(e=gi(e,s,c),Da(e,a)||(Qn=!0),e):(cr&42)===0||(cr&1073741824)!==0&&(Zt&261930)===0?(Qn=!0,e.memoizedState=s):(e=iy(),_t.lanes|=e,Fl|=e,a)}function Wr(e,a,s,c,m){var v=L.p;L.p=v!==0&&8>v?v:8;var A=B.T,_={};B.T=_,zu(e,!1,a,s);try{var J=m(),ye=B.S;if(ye!==null&&ye(_,J),J!==null&&typeof J=="object"&&typeof J.then=="function"){var Re=Fs(J,c);ao(e,a,Re,Ss(e))}else ao(e,a,c,Ss(e))}catch(Ie){ao(e,a,{then:function(){},status:"rejected",reason:Ie},Ss())}finally{L.p=v,A!==null&&_.types!==null&&(A.types=_.types),B.T=A}}function Gr(){}function Ic(e,a,s,c){if(e.tag!==5)throw Error(i(476));var m=bm(e).queue;Wr(e,m,a,oe,s===null?Gr:function(){return Xd(e),s(c)})}function bm(e){var a=e.memoizedState;if(a!==null)return a;a={memoizedState:oe,baseState:oe,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:ys,lastRenderedState:oe},next:null};var s={};return a.next={memoizedState:s,baseState:s,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:ys,lastRenderedState:s},next:null},e.memoizedState=a,e=e.alternate,e!==null&&(e.memoizedState=a),a}function Xd(e){var a=bm(e);a.next===null&&(a=e.alternate.memoizedState),ao(e,a.next.queue,{},Ss())}function Zd(){return tn(Tf)}function Hu(){return kn().memoizedState}function Bu(){return kn().memoizedState}function Tn(e){for(var a=e.return;a!==null;){switch(a.tag){case 24:case 3:var s=Ss();e=ds(s);var c=Oa(a,e,s);c!==null&&(Kr(c,a,s),fs(c,a,s)),a={cache:Od()},e.payload=a;return}a=a.return}}function Jd(e,a,s){var c=Ss();s={lane:c,revertLane:0,gesture:null,action:s,hasEagerState:!1,eagerState:null,next:null},_c(e)?Rl(a,s):(s=Nu(e,a,s,c),s!==null&&(Kr(s,e,c),Pc(s,a,c)))}function Lc(e,a,s){var c=Ss();ao(e,a,s,c)}function ao(e,a,s,c){var m={lane:c,revertLane:0,gesture:null,action:s,hasEagerState:!1,eagerState:null,next:null};if(_c(e))Rl(a,m);else{var v=e.alternate;if(e.lanes===0&&(v===null||v.lanes===0)&&(v=a.lastRenderedReducer,v!==null))try{var A=a.lastRenderedState,_=v(A,s);if(m.hasEagerState=!0,m.eagerState=_,Da(_,A))return vc(e,a,m,0),Mn===null&&Au(),!1}catch{}if(s=Nu(e,a,m,c),s!==null)return Kr(s,e,c),Pc(s,a,c),!0}return!1}function zu(e,a,s,c){if(c={lane:2,revertLane:Eh(),gesture:null,action:c,hasEagerState:!1,eagerState:null,next:null},_c(e)){if(a)throw Error(i(479))}else a=Nu(e,s,c,2),a!==null&&Kr(a,e,2)}function _c(e){var a=e.alternate;return e===_t||a!==null&&a===_t}function Rl(e,a){Sl=kc=!0;var s=e.pending;s===null?a.next=a:(a.next=s.next,s.next=a),e.pending=a}function Pc(e,a,s){if((s&4194048)!==0){var c=a.lanes;c&=e.pendingLanes,s|=c,a.lanes=s,V(e,s)}}var vi={readContext:tn,use:Nc,useCallback:En,useContext:En,useEffect:En,useImperativeHandle:En,useLayoutEffect:En,useInsertionEffect:En,useMemo:En,useReducer:En,useRef:En,useState:En,useDebugValue:En,useDeferredValue:En,useTransition:En,useSyncExternalStore:En,useId:En,useHostTransitionStatus:En,useFormState:En,useActionState:En,useOptimistic:En,useMemoCache:En,useCacheRefresh:En};vi.useEffectEvent=En;var wm={readContext:tn,use:Nc,useCallback:function(e,a){return Ca().memoizedState=[e,a===void 0?null:a],e},useContext:tn,useEffect:Pu,useImperativeHandle:function(e,a,s){s=s!=null?s.concat([e]):null,$o(4194308,4,Dc.bind(null,a,e),s)},useLayoutEffect:function(e,a){return $o(4194308,4,e,a)},useInsertionEffect:function(e,a){$o(4,2,e,a)},useMemo:function(e,a){var s=Ca();a=a===void 0?null:a;var c=e();if(Ji){De(!0);try{e()}finally{De(!1)}}return s.memoizedState=[c,a],c},useReducer:function(e,a,s){var c=Ca();if(s!==void 0){var m=s(a);if(Ji){De(!0);try{s(a)}finally{De(!1)}}}else m=a;return c.memoizedState=c.baseState=m,e={pending:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:m},c.queue=e,e=e.dispatch=Jd.bind(null,_t,e),[c.memoizedState,e]},useRef:function(e){var a=Ca();return e={current:e},a.memoizedState=e},useState:function(e){e=Rc(e);var a=e.queue,s=Lc.bind(null,_t,a);return a.dispatch=s,[e.memoizedState,s]},useDebugValue:Hs,useDeferredValue:function(e,a){var s=Ca();return gi(s,e,a)},useTransition:function(){var e=Rc(!1);return e=Wr.bind(null,_t,e.queue,!0,!1),Ca().memoizedState=e,[!1,e]},useSyncExternalStore:function(e,a,s){var c=_t,m=Ca();if(Gt){if(s===void 0)throw Error(i(407));s=s()}else{if(s=a(),Mn===null)throw Error(i(349));(Zt&127)!==0||no(c,a,s)}m.memoizedState=s;var v={value:s,getSnapshot:a};return m.queue=v,Pu(qd.bind(null,c,v,e),[e]),c.flags|=2048,hi(9,{destroy:void 0},Ud.bind(null,c,v,s,a),null),s},useId:function(){var e=Ca(),a=Mn.identifierPrefix;if(Gt){var s=Cr,c=wa;s=(c&~(1<<32-z(c)-1)).toString(32)+s,a="_"+a+"R_"+s,s=Lo++,0<s&&(a+="H"+s.toString(32)),a+="_"}else s=Ac++,a="_"+a+"r_"+s.toString(32)+"_";return e.memoizedState=a},useHostTransitionStatus:Zd,useFormState:Gd,useActionState:Gd,useOptimistic:function(e){var a=Ca();a.memoizedState=a.baseState=e;var s={pending:null,lanes:0,dispatch:null,lastRenderedReducer:null,lastRenderedState:null};return a.queue=s,a=zu.bind(null,_t,!0,s),s.dispatch=a,[e,a]},useMemoCache:Oo,useCacheRefresh:function(){return Ca().memoizedState=Tn.bind(null,_t)},useEffectEvent:function(e){var a=Ca(),s={impl:e};return a.memoizedState=s,function(){if((dn&2)!==0)throw Error(i(440));return s.impl.apply(void 0,arguments)}}},$u={readContext:tn,use:Nc,useCallback:Yd,useContext:tn,useEffect:Vd,useImperativeHandle:Ou,useInsertionEffect:bs,useLayoutEffect:Qd,useMemo:qr,useReducer:Ho,useRef:Tl,useState:function(){return Ho(ys)},useDebugValue:Hs,useDeferredValue:function(e,a){var s=kn();return ka(s,un.memoizedState,e,a)},useTransition:function(){var e=Ho(ys)[0],a=kn().memoizedState;return[typeof e=="boolean"?e:to(e),a]},useSyncExternalStore:$d,useId:Hu,useHostTransitionStatus:Zd,useFormState:jc,useActionState:jc,useOptimistic:function(e,a){var s=kn();return Bo(s,un,e,a)},useMemoCache:Oo,useCacheRefresh:Bu};$u.useEffectEvent=Kd;var jl={readContext:tn,use:Nc,useCallback:Yd,useContext:tn,useEffect:Vd,useImperativeHandle:Ou,useInsertionEffect:bs,useLayoutEffect:Qd,useMemo:qr,useReducer:Ml,useRef:Tl,useState:function(){return Ml(ys)},useDebugValue:Hs,useDeferredValue:function(e,a){var s=kn();return un===null?gi(s,e,a):ka(s,un.memoizedState,e,a)},useTransition:function(){var e=Ml(ys)[0],a=kn().memoizedState;return[typeof e=="boolean"?e:to(e),a]},useSyncExternalStore:$d,useId:Hu,useHostTransitionStatus:Zd,useFormState:Nl,useActionState:Nl,useOptimistic:function(e,a){var s=kn();return un!==null?Bo(s,un,e,a):(s.baseState=e,[e,s.queue.dispatch])},useMemoCache:Oo,useCacheRefresh:Bu};jl.useEffectEvent=Kd;function ef(e,a,s,c){a=e.memoizedState,s=s(c,a),s=s==null?a:b({},a,s),e.memoizedState=s,e.lanes===0&&(e.updateQueue.baseState=s)}var tf={enqueueSetState:function(e,a,s){e=e._reactInternals;var c=Ss(),m=ds(c);m.payload=a,s!=null&&(m.callback=s),a=Oa(e,m,c),a!==null&&(Kr(a,e,c),fs(a,e,c))},enqueueReplaceState:function(e,a,s){e=e._reactInternals;var c=Ss(),m=ds(c);m.tag=1,m.payload=a,s!=null&&(m.callback=s),a=Oa(e,m,c),a!==null&&(Kr(a,e,c),fs(a,e,c))},enqueueForceUpdate:function(e,a){e=e._reactInternals;var s=Ss(),c=ds(s);c.tag=2,a!=null&&(c.callback=a),a=Oa(e,c,s),a!==null&&(Kr(a,e,s),fs(a,e,s))}};function xm(e,a,s,c,m,v,A){return e=e.stateNode,typeof e.shouldComponentUpdate=="function"?e.shouldComponentUpdate(c,v,A):a.prototype&&a.prototype.isPureReactComponent?!Pi(s,c)||!Pi(m,v):!0}function Sm(e,a,s,c){e=a.state,typeof a.componentWillReceiveProps=="function"&&a.componentWillReceiveProps(s,c),typeof a.UNSAFE_componentWillReceiveProps=="function"&&a.UNSAFE_componentWillReceiveProps(s,c),a.state!==e&&tf.enqueueReplaceState(a,a.state,null)}function ro(e,a){var s=a;if("ref"in a){s={};for(var c in a)c!=="ref"&&(s[c]=a[c])}if(e=e.defaultProps){s===a&&(s=b({},s));for(var m in e)s[m]===void 0&&(s[m]=e[m])}return s}function nf(e){gl(e)}function El(e){console.error(e)}function af(e){gl(e)}function Fc(e,a){try{var s=e.onUncaughtError;s(a.value,{componentStack:a.stack})}catch(c){setTimeout(function(){throw c})}}function Cm(e,a,s){try{var c=e.onCaughtError;c(s.value,{componentStack:s.stack,errorBoundary:a.tag===1?a.stateNode:null})}catch(m){setTimeout(function(){throw m})}}function rf(e,a,s){return s=ds(s),s.tag=3,s.payload={element:null},s.callback=function(){Fc(e,a)},s}function Oc(e){return e=ds(e),e.tag=3,e}function km(e,a,s,c){var m=s.type.getDerivedStateFromError;if(typeof m=="function"){var v=c.value;e.payload=function(){return m(v)},e.callback=function(){Cm(a,s,c)}}var A=s.stateNode;A!==null&&typeof A.componentDidCatch=="function"&&(e.callback=function(){Cm(a,s,c),typeof m!="function"&&(Ol===null?Ol=new Set([this]):Ol.add(this));var _=c.stack;this.componentDidCatch(c.value,{componentStack:_!==null?_:""})})}function gh(e,a,s,c,m){if(s.flags|=32768,c!==null&&typeof c=="object"&&typeof c.then=="function"){if(a=s.alternate,a!==null&&bl(a,s,m,!0),s=Mr.current,s!==null){switch(s.tag){case 31:case 13:return $r===null?_m():s.alternate===null&&Xn===0&&(Xn=3),s.flags&=-257,s.flags|=65536,s.lanes=m,c===Fa?s.flags|=16384:(a=s.updateQueue,a===null?s.updateQueue=new Set([c]):a.add(c),Th(e,c,m)),!1;case 22:return s.flags|=65536,c===Fa?s.flags|=16384:(a=s.updateQueue,a===null?(a={transitions:null,markerInstances:null,retryQueue:new Set([c])},s.updateQueue=a):(s=a.retryQueue,s===null?a.retryQueue=new Set([c]):s.add(c)),Th(e,c,m)),!1}throw Error(i(435,s.tag))}return Th(e,c,m),_m(),!1}if(Gt)return a=Mr.current,a!==null?((a.flags&65536)===0&&(a.flags|=256),a.flags|=65536,a.lanes=m,c!==Ui&&(e=Error(i(422),{cause:c}),_s(_a(e,s)))):(c!==Ui&&(a=Error(i(423),{cause:c}),_s(_a(a,s))),e=e.current.alternate,e.flags|=65536,m&=-m,e.lanes|=m,c=_a(c,s),m=rf(e.stateNode,c,m),Sc(e,m),Xn!==4&&(Xn=2)),!1;var v=Error(i(520),{cause:c});if(v=_a(v,s),wf===null?wf=[v]:wf.push(v),Xn!==4&&(Xn=2),a===null)return!0;c=_a(c,s),s=a;do{switch(s.tag){case 3:return s.flags|=65536,e=m&-m,s.lanes|=e,e=rf(s.stateNode,c,e),Sc(s,e),!1;case 1:if(a=s.type,v=s.stateNode,(s.flags&128)===0&&(typeof a.getDerivedStateFromError=="function"||v!==null&&typeof v.componentDidCatch=="function"&&(Ol===null||!Ol.has(v))))return s.flags|=65536,m&=-m,s.lanes|=m,m=Oc(m),km(m,e,s,c),Sc(s,m),!1}s=s.return}while(s!==null);return!1}var sf=Error(i(461)),Qn=!1;function na(e,a,s,c){a.child=e===null?ym(a,null,s,c):Qi(a,e.child,s,c)}function of(e,a,s,c,m){s=s.render;var v=a.ref;if("ref"in c){var A={};for(var _ in c)_!=="ref"&&(A[_]=c[_])}else A=c;return Hr(a),c=Cl(e,a,s,A,v,m),_=zd(),e!==null&&!Qn?(Iu(e,a,m),Bs(e,a,m)):(Gt&&_&&jo(a),a.flags|=1,na(e,a,c,m),a.child)}function lf(e,a,s,c,m){if(e===null){var v=s.type;return typeof v=="function"&&!ss(v)&&v.defaultProps===void 0&&s.compare===null?(a.tag=15,a.type=v,cf(e,a,v,c,m)):(e=Ro(s.type,null,c,a,a.mode,m),e.ref=a.ref,e.return=a,a.child=e)}if(v=e.child,!Gu(e,m)){var A=v.memoizedProps;if(s=s.compare,s=s!==null?s:Pi,s(A,c)&&e.ref===a.ref)return Bs(e,a,m)}return a.flags|=1,e=ba(v,c),e.ref=a.ref,e.return=a,a.child=e}function cf(e,a,s,c,m){if(e!==null){var v=e.memoizedProps;if(Pi(v,c)&&e.ref===a.ref)if(Qn=!1,a.pendingProps=c=v,Gu(e,m))(e.flags&131072)!==0&&(Qn=!0);else return a.lanes=e.lanes,Bs(e,a,m)}return Dl(e,a,s,c,m)}function Mm(e,a,s,c){var m=c.children,v=e!==null?e.memoizedState:null;if(e===null&&a.stateNode===null&&(a.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),c.mode==="hidden"){if((a.flags&128)!==0){if(v=v!==null?v.baseLanes|s:s,e!==null){for(c=a.child=e.child,m=0;c!==null;)m=m|c.lanes|c.childLanes,c=c.sibling;c=m&~v}else c=0,a.child=null;return Hc(e,a,v,s,c)}if((s&536870912)!==0)a.memoizedState={baseLanes:0,cachePool:null},e!==null&&fi(a,v!==null?v.cachePool:null),v!==null?Cc(a,v):gs(),Hd(a);else return c=a.lanes=536870912,Hc(e,a,v!==null?v.baseLanes|s:s,s,c)}else v!==null?(fi(a,v.cachePool),Cc(a,v),Ar(),a.memoizedState=null):(e!==null&&fi(a,null),gs(),Ar());return na(e,a,m,s),a.child}function qo(e,a){return e!==null&&e.tag===22||a.stateNode!==null||(a.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),a.sibling}function Hc(e,a,s,c,m){var v=an();return v=v===null?null:{parent:Vn._currentValue,pool:v},a.memoizedState={baseLanes:s,cachePool:v},e!==null&&fi(a,null),gs(),Hd(a),e!==null&&bl(e,a,c,!0),a.childLanes=m,null}function Bc(e,a){return a=qu({mode:a.mode,children:a.children},e.mode),a.ref=e.ref,e.child=a,a.return=e,a}function Uu(e,a,s){return Qi(a,e.child,null,s),e=Bc(a,a.pendingProps),e.flags|=2,lr(a),a.memoizedState=null,e}function uf(e,a,s){var c=a.pendingProps,m=(a.flags&128)!==0;if(a.flags&=-129,e===null){if(Gt){if(c.mode==="hidden")return e=Bc(a,c),a.lanes=536870912,qo(null,e);if(xl(a),(e=mn)?(e=$y(e,Ga),e=e!==null&&e.data==="&"?e:null,e!==null&&(a.memoizedState={dehydrated:e,treeContext:Fr!==null?{id:wa,overflow:Cr}:null,retryLane:536870912,hydrationErrors:null},s=Ld(e),s.return=a,a.child=s,xa=a,mn=null)):e=null,e===null)throw ut(a);return a.lanes=536870912,null}return Bc(a,c)}var v=e.memoizedState;if(v!==null){var A=v.dehydrated;if(xl(a),m)if(a.flags&256)a.flags&=-257,a=Uu(e,a,s);else if(a.memoizedState!==null)a.child=e.child,a.flags|=128,a=null;else throw Error(i(558));else if(Qn||bl(e,a,s,!1),m=(s&e.childLanes)!==0,Qn||m){if(c=Mn,c!==null&&(A=Je(c,s),A!==0&&A!==v.retryLane))throw v.retryLane=A,To(e,A),Kr(c,e,A),sf;_m(),a=Uu(e,a,s)}else e=v.treeContext,mn=$s(A.nextSibling),xa=a,Gt=!0,li=null,Ga=!1,e!==null&&dm(a,e),a=Bc(a,c),a.flags|=4096;return a}return e=ba(e.child,{mode:c.mode,children:c.children}),e.ref=a.ref,a.child=e,e.return=a,e}function We(e,a){var s=a.ref;if(s===null)e!==null&&e.ref!==null&&(a.flags|=4194816);else{if(typeof s!="function"&&typeof s!="object")throw Error(i(284));(e===null||e.ref!==s)&&(a.flags|=4194816)}}function Dl(e,a,s,c,m){return Hr(a),s=Cl(e,a,s,c,void 0,m),c=zd(),e!==null&&!Qn?(Iu(e,a,m),Bs(e,a,m)):(Gt&&c&&jo(a),a.flags|=1,na(e,a,s,m),a.child)}function df(e,a,s,c,m,v){return Hr(a),a.updateQueue=null,s=eo(a,c,s,m),Po(e),c=zd(),e!==null&&!Qn?(Iu(e,a,v),Bs(e,a,v)):(Gt&&c&&jo(a),a.flags|=1,na(e,a,s,v),a.child)}function Am(e,a,s,c,m){if(Hr(a),a.stateNode===null){var v=Bi,A=s.contextType;typeof A=="object"&&A!==null&&(v=tn(A)),v=new s(c,v),a.memoizedState=v.state!==null&&v.state!==void 0?v.state:null,v.updater=tf,a.stateNode=v,v._reactInternals=a,v=a.stateNode,v.props=c,v.state=a.memoizedState,v.refs={},Yi(a),A=s.contextType,v.context=typeof A=="object"&&A!==null?tn(A):Bi,v.state=a.memoizedState,A=s.getDerivedStateFromProps,typeof A=="function"&&(ef(a,s,A,c),v.state=a.memoizedState),typeof s.getDerivedStateFromProps=="function"||typeof v.getSnapshotBeforeUpdate=="function"||typeof v.UNSAFE_componentWillMount!="function"&&typeof v.componentWillMount!="function"||(A=v.state,typeof v.componentWillMount=="function"&&v.componentWillMount(),typeof v.UNSAFE_componentWillMount=="function"&&v.UNSAFE_componentWillMount(),A!==v.state&&tf.enqueueReplaceState(v,v.state,null),Zi(a,c,v,m),Xi(),v.state=a.memoizedState),typeof v.componentDidMount=="function"&&(a.flags|=4194308),c=!0}else if(e===null){v=a.stateNode;var _=a.memoizedProps,J=ro(s,_);v.props=J;var ye=v.context,Re=s.contextType;A=Bi,typeof Re=="object"&&Re!==null&&(A=tn(Re));var Ie=s.getDerivedStateFromProps;Re=typeof Ie=="function"||typeof v.getSnapshotBeforeUpdate=="function",_=a.pendingProps!==_,Re||typeof v.UNSAFE_componentWillReceiveProps!="function"&&typeof v.componentWillReceiveProps!="function"||(_||ye!==A)&&Sm(a,v,c,A),mi=!1;var we=a.memoizedState;v.state=we,Zi(a,c,v,m),Xi(),ye=a.memoizedState,_||we!==ye||mi?(typeof Ie=="function"&&(ef(a,s,Ie,c),ye=a.memoizedState),(J=mi||xm(a,s,J,c,we,ye,A))?(Re||typeof v.UNSAFE_componentWillMount!="function"&&typeof v.componentWillMount!="function"||(typeof v.componentWillMount=="function"&&v.componentWillMount(),typeof v.UNSAFE_componentWillMount=="function"&&v.UNSAFE_componentWillMount()),typeof v.componentDidMount=="function"&&(a.flags|=4194308)):(typeof v.componentDidMount=="function"&&(a.flags|=4194308),a.memoizedProps=c,a.memoizedState=ye),v.props=c,v.state=ye,v.context=A,c=J):(typeof v.componentDidMount=="function"&&(a.flags|=4194308),c=!1)}else{v=a.stateNode,xc(e,a),A=a.memoizedProps,Re=ro(s,A),v.props=Re,Ie=a.pendingProps,we=v.context,ye=s.contextType,J=Bi,typeof ye=="object"&&ye!==null&&(J=tn(ye)),_=s.getDerivedStateFromProps,(ye=typeof _=="function"||typeof v.getSnapshotBeforeUpdate=="function")||typeof v.UNSAFE_componentWillReceiveProps!="function"&&typeof v.componentWillReceiveProps!="function"||(A!==Ie||we!==J)&&Sm(a,v,c,J),mi=!1,we=a.memoizedState,v.state=we,Zi(a,c,v,m),Xi();var ke=a.memoizedState;A!==Ie||we!==ke||mi||e!==null&&e.dependencies!==null&&Eo(e.dependencies)?(typeof _=="function"&&(ef(a,s,_,c),ke=a.memoizedState),(Re=mi||xm(a,s,Re,c,we,ke,J)||e!==null&&e.dependencies!==null&&Eo(e.dependencies))?(ye||typeof v.UNSAFE_componentWillUpdate!="function"&&typeof v.componentWillUpdate!="function"||(typeof v.componentWillUpdate=="function"&&v.componentWillUpdate(c,ke,J),typeof v.UNSAFE_componentWillUpdate=="function"&&v.UNSAFE_componentWillUpdate(c,ke,J)),typeof v.componentDidUpdate=="function"&&(a.flags|=4),typeof v.getSnapshotBeforeUpdate=="function"&&(a.flags|=1024)):(typeof v.componentDidUpdate!="function"||A===e.memoizedProps&&we===e.memoizedState||(a.flags|=4),typeof v.getSnapshotBeforeUpdate!="function"||A===e.memoizedProps&&we===e.memoizedState||(a.flags|=1024),a.memoizedProps=c,a.memoizedState=ke),v.props=c,v.state=ke,v.context=J,c=Re):(typeof v.componentDidUpdate!="function"||A===e.memoizedProps&&we===e.memoizedState||(a.flags|=4),typeof v.getSnapshotBeforeUpdate!="function"||A===e.memoizedProps&&we===e.memoizedState||(a.flags|=1024),c=!1)}return v=c,We(e,a),c=(a.flags&128)!==0,v||c?(v=a.stateNode,s=c&&typeof s.getDerivedStateFromError!="function"?null:v.render(),a.flags|=1,e!==null&&c?(a.child=Qi(a,e.child,null,m),a.child=Qi(a,null,s,m)):na(e,a,s,m),a.memoizedState=v.state,e=a.child):e=Bs(e,a,m),e}function vh(e,a,s,c){return qi(),a.flags|=256,na(e,a,s,c),a.child}var zc={dehydrated:null,treeContext:null,retryLane:0,hydrationErrors:null};function Il(e){return{baseLanes:e,cachePool:vm()}}function aa(e,a,s){return e=e!==null?e.childLanes&~s:0,a&&(e|=xs),e}function ur(e,a,s){var c=a.pendingProps,m=!1,v=(a.flags&128)!==0,A;if((A=v)||(A=e!==null&&e.memoizedState===null?!1:(_n.current&2)!==0),A&&(m=!0,a.flags&=-129),A=(a.flags&32)!==0,a.flags&=-33,e===null){if(Gt){if(m?vs(a):Ar(),(e=mn)?(e=$y(e,Ga),e=e!==null&&e.data!=="&"?e:null,e!==null&&(a.memoizedState={dehydrated:e,treeContext:Fr!==null?{id:wa,overflow:Cr}:null,retryLane:536870912,hydrationErrors:null},s=Ld(e),s.return=a,a.child=s,xa=a,mn=null)):e=null,e===null)throw ut(a);return qh(e)?a.lanes=32:a.lanes=536870912,null}var _=c.children;return c=c.fallback,m?(Ar(),m=a.mode,_=qu({mode:"hidden",children:_},m),c=Is(c,m,s,null),_.return=a,c.return=a,_.sibling=c,a.child=_,c=a.child,c.memoizedState=Il(s),c.childLanes=aa(e,A,s),a.memoizedState=zc,qo(null,c)):(vs(a),yt(a,_))}var J=e.memoizedState;if(J!==null&&(_=J.dehydrated,_!==null)){if(v)a.flags&256?(vs(a),a.flags&=-257,a=so(e,a,s)):a.memoizedState!==null?(Ar(),a.child=e.child,a.flags|=128,a=null):(Ar(),_=c.fallback,m=a.mode,c=qu({mode:"visible",children:c.children},m),_=Is(_,m,s,null),_.flags|=2,c.return=a,_.return=a,c.sibling=_,a.child=c,Qi(a,e.child,null,s),c=a.child,c.memoizedState=Il(s),c.childLanes=aa(e,A,s),a.memoizedState=zc,a=qo(null,c));else if(vs(a),qh(_)){if(A=_.nextSibling&&_.nextSibling.dataset,A)var ye=A.dgst;A=ye,c=Error(i(419)),c.stack="",c.digest=A,_s({value:c,source:null,stack:null}),a=so(e,a,s)}else if(Qn||bl(e,a,s,!1),A=(s&e.childLanes)!==0,Qn||A){if(A=Mn,A!==null&&(c=Je(A,s),c!==0&&c!==J.retryLane))throw J.retryLane=c,To(e,c),Kr(A,e,c),sf;Uh(_)||_m(),a=so(e,a,s)}else Uh(_)?(a.flags|=192,a.child=e.child,a=null):(e=J.treeContext,mn=$s(_.nextSibling),xa=a,Gt=!0,li=null,Ga=!1,e!==null&&dm(a,e),a=yt(a,c.children),a.flags|=4096);return a}return m?(Ar(),_=c.fallback,m=a.mode,J=e.child,ye=J.sibling,c=ba(J,{mode:"hidden",children:c.children}),c.subtreeFlags=J.subtreeFlags&65011712,ye!==null?_=ba(ye,_):(_=Is(_,m,s,null),_.flags|=2),_.return=a,c.return=a,c.sibling=_,a.child=c,qo(null,c),c=a.child,_=e.child.memoizedState,_===null?_=Il(s):(m=_.cachePool,m!==null?(J=Vn._currentValue,m=m.parent!==J?{parent:J,pool:J}:m):m=vm(),_={baseLanes:_.baseLanes|s,cachePool:m}),c.memoizedState=_,c.childLanes=aa(e,A,s),a.memoizedState=zc,qo(e.child,c)):(vs(a),s=e.child,e=s.sibling,s=ba(s,{mode:"visible",children:c.children}),s.return=a,s.sibling=null,e!==null&&(A=a.deletions,A===null?(a.deletions=[e],a.flags|=16):A.push(e)),a.child=s,a.memoizedState=null,s)}function yt(e,a){return a=qu({mode:"visible",children:a},e.mode),a.return=e,e.child=a}function qu(e,a){return e=La(22,e,null,a),e.lanes=0,e}function so(e,a,s){return Qi(a,e.child,null,s),e=yt(a,a.pendingProps.children),e.flags|=2,a.memoizedState=null,e}function ff(e,a,s){e.lanes|=a;var c=e.alternate;c!==null&&(c.lanes|=a),Fd(e.return,a,s)}function Wu(e,a,s,c,m,v){var A=e.memoizedState;A===null?e.memoizedState={isBackwards:a,rendering:null,renderingStartTime:0,last:c,tail:s,tailMode:m,treeForkCount:v}:(A.isBackwards=a,A.rendering=null,A.renderingStartTime=0,A.last=c,A.tail=s,A.tailMode=m,A.treeForkCount=v)}function Wo(e,a,s){var c=a.pendingProps,m=c.revealOrder,v=c.tail;c=c.children;var A=_n.current,_=(A&2)!==0;if(_?(A=A&1|2,a.flags|=128):A&=1,Ce(_n,A),na(e,a,c,s),c=Gt?xr:0,!_&&e!==null&&(e.flags&128)!==0)e:for(e=a.child;e!==null;){if(e.tag===13)e.memoizedState!==null&&ff(e,s,a);else if(e.tag===19)ff(e,s,a);else if(e.child!==null){e.child.return=e,e=e.child;continue}if(e===a)break e;for(;e.sibling===null;){if(e.return===null||e.return===a)break e;e=e.return}e.sibling.return=e.return,e=e.sibling}switch(m){case"forwards":for(s=a.child,m=null;s!==null;)e=s.alternate,e!==null&&Du(e)===null&&(m=s),s=s.sibling;s=m,s===null?(m=a.child,a.child=null):(m=s.sibling,s.sibling=null),Wu(a,!1,m,s,v,c);break;case"backwards":case"unstable_legacy-backwards":for(s=null,m=a.child,a.child=null;m!==null;){if(e=m.alternate,e!==null&&Du(e)===null){a.child=m;break}e=m.sibling,m.sibling=s,s=m,m=e}Wu(a,!0,s,null,v,c);break;case"together":Wu(a,!1,null,null,void 0,c);break;default:a.memoizedState=null}return a.child}function Bs(e,a,s){if(e!==null&&(a.dependencies=e.dependencies),Fl|=a.lanes,(s&a.childLanes)===0)if(e!==null){if(bl(e,a,s,!1),(s&a.childLanes)===0)return null}else return null;if(e!==null&&a.child!==e.child)throw Error(i(153));if(a.child!==null){for(e=a.child,s=ba(e,e.pendingProps),a.child=s,s.return=a;e.sibling!==null;)e=e.sibling,s=s.sibling=ba(e,e.pendingProps),s.return=a;s.sibling=null}return a.child}function Gu(e,a){return(e.lanes&a)!==0?!0:(e=e.dependencies,!!(e!==null&&Eo(e)))}function Nm(e,a,s){switch(a.tag){case 3:ie(a,a.stateNode.containerInfo),Wi(a,Vn,e.memoizedState.cache),qi();break;case 27:case 5:$e(a);break;case 4:ie(a,a.stateNode.containerInfo);break;case 10:Wi(a,a.type,a.memoizedProps.value);break;case 31:if(a.memoizedState!==null)return a.flags|=128,xl(a),null;break;case 13:var c=a.memoizedState;if(c!==null)return c.dehydrated!==null?(vs(a),a.flags|=128,null):(s&a.child.childLanes)!==0?ur(e,a,s):(vs(a),e=Bs(e,a,s),e!==null?e.sibling:null);vs(a);break;case 19:var m=(e.flags&128)!==0;if(c=(s&a.childLanes)!==0,c||(bl(e,a,s,!1),c=(s&a.childLanes)!==0),m){if(c)return Wo(e,a,s);a.flags|=128}if(m=a.memoizedState,m!==null&&(m.rendering=null,m.tail=null,m.lastEffect=null),Ce(_n,_n.current),c)break;return null;case 22:return a.lanes=0,Mm(e,a,s,a.pendingProps);case 24:Wi(a,Vn,e.memoizedState.cache)}return Bs(e,a,s)}function mf(e,a,s){if(e!==null)if(e.memoizedProps!==a.pendingProps)Qn=!0;else{if(!Gu(e,s)&&(a.flags&128)===0)return Qn=!1,Nm(e,a,s);Qn=(e.flags&131072)!==0}else Qn=!1,Gt&&(a.flags&1048576)!==0&&kr(a,xr,a.index);switch(a.lanes=0,a.tag){case 16:e:{var c=a.pendingProps;if(e=cs(a.elementType),a.type=e,typeof e=="function")ss(e)?(c=ro(e,c),a.tag=1,a=Am(null,a,e,c,s)):(a.tag=0,a=Dl(null,a,e,c,s));else{if(e!=null){var m=e.$$typeof;if(m===U){a.tag=11,a=of(null,a,e,c,s);break e}else if(m===D){a.tag=14,a=lf(null,a,e,c,s);break e}}throw a=$(e)||e,Error(i(306,a,""))}}return a;case 0:return Dl(e,a,a.type,a.pendingProps,s);case 1:return c=a.type,m=ro(c,a.pendingProps),Am(e,a,c,m,s);case 3:e:{if(ie(a,a.stateNode.containerInfo),e===null)throw Error(i(387));c=a.pendingProps;var v=a.memoizedState;m=v.element,xc(e,a),Zi(a,c,null,s);var A=a.memoizedState;if(c=A.cache,Wi(a,Vn,c),c!==v.cache&&yl(a,[Vn],s,!0),Xi(),c=A.element,v.isDehydrated)if(v={element:c,isDehydrated:!1,cache:A.cache},a.updateQueue.baseState=v,a.memoizedState=v,a.flags&256){a=vh(e,a,c,s);break e}else if(c!==m){m=_a(Error(i(424)),a),_s(m),a=vh(e,a,c,s);break e}else for(e=a.stateNode.containerInfo,e.nodeType===9?e=e.body:e=e.nodeName==="HTML"?e.ownerDocument.body:e,mn=$s(e.firstChild),xa=a,Gt=!0,li=null,Ga=!0,s=ym(a,null,c,s),a.child=s;s;)s.flags=s.flags&-3|4096,s=s.sibling;else{if(qi(),c===m){a=Bs(e,a,s);break e}na(e,a,c,s)}a=a.child}return a;case 26:return We(e,a),e===null?(s=Ky(a.type,null,a.pendingProps,null))?a.memoizedState=s:Gt||(s=a.type,e=a.pendingProps,c=$m(He.current).createElement(s),c[fe]=a,c[_e]=e,Xa(c,s,e),Wt(c),a.stateNode=c):a.memoizedState=Ky(a.type,e.memoizedProps,a.pendingProps,e.memoizedState),null;case 27:return $e(a),e===null&&Gt&&(c=a.stateNode=Wy(a.type,a.pendingProps,He.current),xa=a,Ga=!0,m=mn,$l(a.type)?(Wh=m,mn=$s(c.firstChild)):mn=m),na(e,a,a.pendingProps.children,s),We(e,a),e===null&&(a.flags|=4194304),a.child;case 5:return e===null&&Gt&&((m=c=mn)&&(c=mC(c,a.type,a.pendingProps,Ga),c!==null?(a.stateNode=c,xa=a,mn=$s(c.firstChild),Ga=!1,m=!0):m=!1),m||ut(a)),$e(a),m=a.type,v=a.pendingProps,A=e!==null?e.memoizedProps:null,c=v.children,Bh(m,v)?c=null:A!==null&&Bh(m,A)&&(a.flags|=32),a.memoizedState!==null&&(m=Cl(e,a,Bd,null,null,s),Tf._currentValue=m),We(e,a),na(e,a,c,s),a.child;case 6:return e===null&&Gt&&((e=s=mn)&&(s=pC(s,a.pendingProps,Ga),s!==null?(a.stateNode=s,xa=a,mn=null,e=!0):e=!1),e||ut(a)),null;case 13:return ur(e,a,s);case 4:return ie(a,a.stateNode.containerInfo),c=a.pendingProps,e===null?a.child=Qi(a,null,c,s):na(e,a,c,s),a.child;case 11:return of(e,a,a.type,a.pendingProps,s);case 7:return na(e,a,a.pendingProps,s),a.child;case 8:return na(e,a,a.pendingProps.children,s),a.child;case 12:return na(e,a,a.pendingProps.children,s),a.child;case 10:return c=a.pendingProps,Wi(a,a.type,c.value),na(e,a,c.children,s),a.child;case 9:return m=a.type._context,c=a.pendingProps.children,Hr(a),m=tn(m),c=c(m),a.flags|=1,na(e,a,c,s),a.child;case 14:return lf(e,a,a.type,a.pendingProps,s);case 15:return cf(e,a,a.type,a.pendingProps,s);case 19:return Wo(e,a,s);case 31:return uf(e,a,s);case 22:return Mm(e,a,s,a.pendingProps);case 24:return Hr(a),c=tn(Vn),e===null?(m=an(),m===null&&(m=Mn,v=Od(),m.pooledCache=v,v.refCount++,v!==null&&(m.pooledCacheLanes|=s),m=v),a.memoizedState={parent:c,cache:m},Yi(a),Wi(a,Vn,m)):((e.lanes&s)!==0&&(xc(e,a),Zi(a,null,null,s),Xi()),m=e.memoizedState,v=a.memoizedState,m.parent!==c?(m={parent:c,cache:c},a.memoizedState=m,a.lanes===0&&(a.memoizedState=a.updateQueue.baseState=m),Wi(a,Vn,c)):(c=v.cache,Wi(a,Vn,c),c!==m.cache&&yl(a,[Vn],s,!0))),na(e,a,a.pendingProps.children,s),a.child;case 29:throw a.pendingProps}throw Error(i(156,a.tag))}function zs(e){e.flags|=4}function Go(e,a,s,c,m){if((a=(e.mode&32)!==0)&&(a=!1),a){if(e.flags|=16777216,(m&335544128)===m)if(e.stateNode.complete)e.flags|=8192;else if(uy())e.flags|=8192;else throw Os=Fa,Eu}else e.flags&=-16777217}function $c(e,a){if(a.type!=="stylesheet"||(a.state.loading&4)!==0)e.flags&=-16777217;else if(e.flags|=16777216,!Jy(a))if(uy())e.flags|=8192;else throw Os=Fa,Eu}function Vu(e,a){a!==null&&(e.flags|=4),e.flags&16384&&(a=e.tag!==22?Ra():536870912,e.lanes|=a,Xu|=a)}function Ll(e,a){if(!Gt)switch(e.tailMode){case"hidden":a=e.tail;for(var s=null;a!==null;)a.alternate!==null&&(s=a),a=a.sibling;s===null?e.tail=null:s.sibling=null;break;case"collapsed":s=e.tail;for(var c=null;s!==null;)s.alternate!==null&&(c=s),s=s.sibling;c===null?a||e.tail===null?e.tail=null:e.tail.sibling=null:c.sibling=null}}function hn(e){var a=e.alternate!==null&&e.alternate.child===e.child,s=0,c=0;if(a)for(var m=e.child;m!==null;)s|=m.lanes|m.childLanes,c|=m.subtreeFlags&65011712,c|=m.flags&65011712,m.return=e,m=m.sibling;else for(m=e.child;m!==null;)s|=m.lanes|m.childLanes,c|=m.subtreeFlags,c|=m.flags,m.return=e,m=m.sibling;return e.subtreeFlags|=c,e.childLanes=s,a}function yh(e,a,s){var c=a.pendingProps;switch($i(a),a.tag){case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return hn(a),null;case 1:return hn(a),null;case 3:return s=a.stateNode,c=null,e!==null&&(c=e.memoizedState.cache),a.memoizedState.cache!==c&&(a.flags|=2048),ui(Vn),Oe(),s.pendingContext&&(s.context=s.pendingContext,s.pendingContext=null),(e===null||e.child===null)&&(os(a)?zs(a):e===null||e.memoizedState.isDehydrated&&(a.flags&256)===0||(a.flags|=1024,Or())),hn(a),null;case 26:var m=a.type,v=a.memoizedState;return e===null?(zs(a),v!==null?(hn(a),$c(a,v)):(hn(a),Go(a,m,null,c,s))):v?v!==e.memoizedState?(zs(a),hn(a),$c(a,v)):(hn(a),a.flags&=-16777217):(e=e.memoizedProps,e!==c&&zs(a),hn(a),Go(a,m,e,c,s)),null;case 27:if(qe(a),s=He.current,m=a.type,e!==null&&a.stateNode!=null)e.memoizedProps!==c&&zs(a);else{if(!c){if(a.stateNode===null)throw Error(i(166));return hn(a),null}e=Me.current,os(a)?Pd(a):(e=Wy(m,c,s),a.stateNode=e,zs(a))}return hn(a),null;case 5:if(qe(a),m=a.type,e!==null&&a.stateNode!=null)e.memoizedProps!==c&&zs(a);else{if(!c){if(a.stateNode===null)throw Error(i(166));return hn(a),null}if(v=Me.current,os(a))Pd(a);else{var A=$m(He.current);switch(v){case 1:v=A.createElementNS("http://www.w3.org/2000/svg",m);break;case 2:v=A.createElementNS("http://www.w3.org/1998/Math/MathML",m);break;default:switch(m){case"svg":v=A.createElementNS("http://www.w3.org/2000/svg",m);break;case"math":v=A.createElementNS("http://www.w3.org/1998/Math/MathML",m);break;case"script":v=A.createElement("div"),v.innerHTML="<script><\/script>",v=v.removeChild(v.firstChild);break;case"select":v=typeof c.is=="string"?A.createElement("select",{is:c.is}):A.createElement("select"),c.multiple?v.multiple=!0:c.size&&(v.size=c.size);break;default:v=typeof c.is=="string"?A.createElement(m,{is:c.is}):A.createElement(m)}}v[fe]=a,v[_e]=c;e:for(A=a.child;A!==null;){if(A.tag===5||A.tag===6)v.appendChild(A.stateNode);else if(A.tag!==4&&A.tag!==27&&A.child!==null){A.child.return=A,A=A.child;continue}if(A===a)break e;for(;A.sibling===null;){if(A.return===null||A.return===a)break e;A=A.return}A.sibling.return=A.return,A=A.sibling}a.stateNode=v;e:switch(Xa(v,m,c),m){case"button":case"input":case"select":case"textarea":c=!!c.autoFocus;break e;case"img":c=!0;break e;default:c=!1}c&&zs(a)}}return hn(a),Go(a,a.type,e===null?null:e.memoizedProps,a.pendingProps,s),null;case 6:if(e&&a.stateNode!=null)e.memoizedProps!==c&&zs(a);else{if(typeof c!="string"&&a.stateNode===null)throw Error(i(166));if(e=He.current,os(a)){if(e=a.stateNode,s=a.memoizedProps,c=null,m=xa,m!==null)switch(m.tag){case 27:case 5:c=m.memoizedProps}e[fe]=a,e=!!(e.nodeValue===s||c!==null&&c.suppressHydrationWarning===!0||Ly(e.nodeValue,s)),e||ut(a,!0)}else e=$m(e).createTextNode(c),e[fe]=a,a.stateNode=e}return hn(a),null;case 31:if(s=a.memoizedState,e===null||e.memoizedState!==null){if(c=os(a),s!==null){if(e===null){if(!c)throw Error(i(318));if(e=a.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(i(557));e[fe]=a}else qi(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;hn(a),e=!1}else s=Or(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=s),e=!0;if(!e)return a.flags&256?(lr(a),a):(lr(a),null);if((a.flags&128)!==0)throw Error(i(558))}return hn(a),null;case 13:if(c=a.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(m=os(a),c!==null&&c.dehydrated!==null){if(e===null){if(!m)throw Error(i(318));if(m=a.memoizedState,m=m!==null?m.dehydrated:null,!m)throw Error(i(317));m[fe]=a}else qi(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;hn(a),m=!1}else m=Or(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=m),m=!0;if(!m)return a.flags&256?(lr(a),a):(lr(a),null)}return lr(a),(a.flags&128)!==0?(a.lanes=s,a):(s=c!==null,e=e!==null&&e.memoizedState!==null,s&&(c=a.child,m=null,c.alternate!==null&&c.alternate.memoizedState!==null&&c.alternate.memoizedState.cachePool!==null&&(m=c.alternate.memoizedState.cachePool.pool),v=null,c.memoizedState!==null&&c.memoizedState.cachePool!==null&&(v=c.memoizedState.cachePool.pool),v!==m&&(c.flags|=2048)),s!==e&&s&&(a.child.flags|=8192),Vu(a,a.updateQueue),hn(a),null);case 4:return Oe(),e===null&&_h(a.stateNode.containerInfo),hn(a),null;case 10:return ui(a.type),hn(a),null;case 19:if(ue(_n),c=a.memoizedState,c===null)return hn(a),null;if(m=(a.flags&128)!==0,v=c.rendering,v===null)if(m)Ll(c,!1);else{if(Xn!==0||e!==null&&(e.flags&128)!==0)for(e=a.child;e!==null;){if(v=Du(e),v!==null){for(a.flags|=128,Ll(c,!1),e=v.updateQueue,a.updateQueue=e,Vu(a,e),a.subtreeFlags=0,e=s,s=a.child;s!==null;)is(s,e),s=s.sibling;return Ce(_n,_n.current&1|2),Gt&&Dt(a,c.treeForkCount),a.child}e=e.sibling}c.tail!==null&&ze()>Dm&&(a.flags|=128,m=!0,Ll(c,!1),a.lanes=4194304)}else{if(!m)if(e=Du(v),e!==null){if(a.flags|=128,m=!0,e=e.updateQueue,a.updateQueue=e,Vu(a,e),Ll(c,!0),c.tail===null&&c.tailMode==="hidden"&&!v.alternate&&!Gt)return hn(a),null}else 2*ze()-c.renderingStartTime>Dm&&s!==536870912&&(a.flags|=128,m=!0,Ll(c,!1),a.lanes=4194304);c.isBackwards?(v.sibling=a.child,a.child=v):(e=c.last,e!==null?e.sibling=v:a.child=v,c.last=v)}return c.tail!==null?(e=c.tail,c.rendering=e,c.tail=e.sibling,c.renderingStartTime=ze(),e.sibling=null,s=_n.current,Ce(_n,m?s&1|2:s&1),Gt&&Dt(a,c.treeForkCount),e):(hn(a),null);case 22:case 23:return lr(a),wl(),c=a.memoizedState!==null,e!==null?e.memoizedState!==null!==c&&(a.flags|=8192):c&&(a.flags|=8192),c?(s&536870912)!==0&&(a.flags&128)===0&&(hn(a),a.subtreeFlags&6&&(a.flags|=8192)):hn(a),s=a.updateQueue,s!==null&&Vu(a,s.retryQueue),s=null,e!==null&&e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(s=e.memoizedState.cachePool.pool),c=null,a.memoizedState!==null&&a.memoizedState.cachePool!==null&&(c=a.memoizedState.cachePool.pool),c!==s&&(a.flags|=2048),e!==null&&ue(Io),null;case 24:return s=null,e!==null&&(s=e.memoizedState.cache),a.memoizedState.cache!==s&&(a.flags|=2048),ui(Vn),hn(a),null;case 25:return null;case 30:return null}throw Error(i(156,a.tag))}function bh(e,a){switch($i(a),a.tag){case 1:return e=a.flags,e&65536?(a.flags=e&-65537|128,a):null;case 3:return ui(Vn),Oe(),e=a.flags,(e&65536)!==0&&(e&128)===0?(a.flags=e&-65537|128,a):null;case 26:case 27:case 5:return qe(a),null;case 31:if(a.memoizedState!==null){if(lr(a),a.alternate===null)throw Error(i(340));qi()}return e=a.flags,e&65536?(a.flags=e&-65537|128,a):null;case 13:if(lr(a),e=a.memoizedState,e!==null&&e.dehydrated!==null){if(a.alternate===null)throw Error(i(340));qi()}return e=a.flags,e&65536?(a.flags=e&-65537|128,a):null;case 19:return ue(_n),null;case 4:return Oe(),null;case 10:return ui(a.type),null;case 22:case 23:return lr(a),wl(),e!==null&&ue(Io),e=a.flags,e&65536?(a.flags=e&-65537|128,a):null;case 24:return ui(Vn),null;case 25:return null;default:return null}}function Ku(e,a){switch($i(a),a.tag){case 3:ui(Vn),Oe();break;case 26:case 27:case 5:qe(a);break;case 4:Oe();break;case 31:a.memoizedState!==null&&lr(a);break;case 13:lr(a);break;case 19:ue(_n);break;case 10:ui(a.type);break;case 22:case 23:lr(a),wl(),e!==null&&ue(Io);break;case 24:ui(Vn)}}function Uc(e,a){try{var s=a.updateQueue,c=s!==null?s.lastEffect:null;if(c!==null){var m=c.next;s=m;do{if((s.tag&e)===e){c=void 0;var v=s.create,A=s.inst;c=v(),A.destroy=c}s=s.next}while(s!==m)}}catch(_){yn(a,a.return,_)}}function io(e,a,s){try{var c=a.updateQueue,m=c!==null?c.lastEffect:null;if(m!==null){var v=m.next;c=v;do{if((c.tag&e)===e){var A=c.inst,_=A.destroy;if(_!==void 0){A.destroy=void 0,m=a;var J=s,ye=_;try{ye()}catch(Re){yn(m,J,Re)}}}c=c.next}while(c!==v)}}catch(Re){yn(a,a.return,Re)}}function Ha(e){var a=e.updateQueue;if(a!==null){var s=e.stateNode;try{hs(a,s)}catch(c){yn(e,e.return,c)}}}function qc(e,a,s){s.props=ro(e.type,e.memoizedProps),s.state=e.memoizedState;try{s.componentWillUnmount()}catch(c){yn(e,a,c)}}function Wc(e,a){try{var s=e.ref;if(s!==null){switch(e.tag){case 26:case 27:case 5:var c=e.stateNode;break;case 30:c=e.stateNode;break;default:c=e.stateNode}typeof s=="function"?e.refCleanup=s(c):s.current=c}}catch(m){yn(e,a,m)}}function yi(e,a){var s=e.ref,c=e.refCleanup;if(s!==null)if(typeof c=="function")try{c()}catch(m){yn(e,a,m)}finally{e.refCleanup=null,e=e.alternate,e!=null&&(e.refCleanup=null)}else if(typeof s=="function")try{s(null)}catch(m){yn(e,a,m)}else s.current=null}function Tm(e){var a=e.type,s=e.memoizedProps,c=e.stateNode;try{e:switch(a){case"button":case"input":case"select":case"textarea":s.autoFocus&&c.focus();break e;case"img":s.src?c.src=s.src:s.srcSet&&(c.srcset=s.srcSet)}}catch(m){yn(e,e.return,m)}}function pf(e,a,s){try{var c=e.stateNode;oC(c,e.type,s,a),c[_e]=a}catch(m){yn(e,e.return,m)}}function hf(e){return e.tag===5||e.tag===3||e.tag===26||e.tag===27&&$l(e.type)||e.tag===4}function _l(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||hf(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&&$l(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 Vo(e,a,s){var c=e.tag;if(c===5||c===6)e=e.stateNode,a?(s.nodeType===9?s.body:s.nodeName==="HTML"?s.ownerDocument.body:s).insertBefore(e,a):(a=s.nodeType===9?s.body:s.nodeName==="HTML"?s.ownerDocument.body:s,a.appendChild(e),s=s._reactRootContainer,s!=null||a.onclick!==null||(a.onclick=vr));else if(c!==4&&(c===27&&$l(e.type)&&(s=e.stateNode,a=null),e=e.child,e!==null))for(Vo(e,a,s),e=e.sibling;e!==null;)Vo(e,a,s),e=e.sibling}function Gc(e,a,s){var c=e.tag;if(c===5||c===6)e=e.stateNode,a?s.insertBefore(e,a):s.appendChild(e);else if(c!==4&&(c===27&&$l(e.type)&&(s=e.stateNode),e=e.child,e!==null))for(Gc(e,a,s),e=e.sibling;e!==null;)Gc(e,a,s),e=e.sibling}function Rm(e){var a=e.stateNode,s=e.memoizedProps;try{for(var c=e.type,m=a.attributes;m.length;)a.removeAttributeNode(m[0]);Xa(a,c,s),a[fe]=e,a[_e]=s}catch(v){yn(e,e.return,v)}}var bi=!1,Yn=!1,Vc=!1,Ko=typeof WeakSet=="function"?WeakSet:Set,da=null;function Qo(e,a){if(e=e.containerInfo,Oh=Qm,e=jd(e),Mu(e)){if("selectionStart"in e)var s={start:e.selectionStart,end:e.selectionEnd};else e:{s=(s=e.ownerDocument)&&s.defaultView||window;var c=s.getSelection&&s.getSelection();if(c&&c.rangeCount!==0){s=c.anchorNode;var m=c.anchorOffset,v=c.focusNode;c=c.focusOffset;try{s.nodeType,v.nodeType}catch{s=null;break e}var A=0,_=-1,J=-1,ye=0,Re=0,Ie=e,we=null;t:for(;;){for(var ke;Ie!==s||m!==0&&Ie.nodeType!==3||(_=A+m),Ie!==v||c!==0&&Ie.nodeType!==3||(J=A+c),Ie.nodeType===3&&(A+=Ie.nodeValue.length),(ke=Ie.firstChild)!==null;)we=Ie,Ie=ke;for(;;){if(Ie===e)break t;if(we===s&&++ye===m&&(_=A),we===v&&++Re===c&&(J=A),(ke=Ie.nextSibling)!==null)break;Ie=we,we=Ie.parentNode}Ie=ke}s=_===-1||J===-1?null:{start:_,end:J}}else s=null}s=s||{start:0,end:0}}else s=null;for(Hh={focusedElem:e,selectionRange:s},Qm=!1,da=a;da!==null;)if(a=da,e=a.child,(a.subtreeFlags&1028)!==0&&e!==null)e.return=a,da=e;else for(;da!==null;){switch(a=da,v=a.alternate,e=a.flags,a.tag){case 0:if((e&4)!==0&&(e=a.updateQueue,e=e!==null?e.events:null,e!==null))for(s=0;s<e.length;s++)m=e[s],m.ref.impl=m.nextImpl;break;case 11:case 15:break;case 1:if((e&1024)!==0&&v!==null){e=void 0,s=a,m=v.memoizedProps,v=v.memoizedState,c=s.stateNode;try{var it=ro(s.type,m);e=c.getSnapshotBeforeUpdate(it,v),c.__reactInternalSnapshotBeforeUpdate=e}catch(Ct){yn(s,s.return,Ct)}}break;case 3:if((e&1024)!==0){if(e=a.stateNode.containerInfo,s=e.nodeType,s===9)$h(e);else if(s===1)switch(e.nodeName){case"HEAD":case"HTML":case"BODY":$h(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(i(163))}if(e=a.sibling,e!==null){e.return=a.return,da=e;break}da=a.return}}function gf(e,a,s){var c=s.flags;switch(s.tag){case 0:case 11:case 15:qt(e,s),c&4&&Uc(5,s);break;case 1:if(qt(e,s),c&4)if(e=s.stateNode,a===null)try{e.componentDidMount()}catch(A){yn(s,s.return,A)}else{var m=ro(s.type,a.memoizedProps);a=a.memoizedState;try{e.componentDidUpdate(m,a,e.__reactInternalSnapshotBeforeUpdate)}catch(A){yn(s,s.return,A)}}c&64&&Ha(s),c&512&&Wc(s,s.return);break;case 3:if(qt(e,s),c&64&&(e=s.updateQueue,e!==null)){if(a=null,s.child!==null)switch(s.child.tag){case 27:case 5:a=s.child.stateNode;break;case 1:a=s.child.stateNode}try{hs(e,a)}catch(A){yn(s,s.return,A)}}break;case 27:a===null&&c&4&&Rm(s);case 26:case 5:qt(e,s),a===null&&c&4&&Tm(s),c&512&&Wc(s,s.return);break;case 12:qt(e,s);break;case 31:qt(e,s),c&4&&j(e,s);break;case 13:qt(e,s),c&4&&Q(e,s),c&64&&(e=s.memoizedState,e!==null&&(e=e.dehydrated,e!==null&&(s=Q0.bind(null,s),hC(e,s))));break;case 22:if(c=s.memoizedState!==null||bi,!c){a=a!==null&&a.memoizedState!==null||Yn,m=bi;var v=Yn;bi=c,(Yn=a)&&!v?It(e,s,(s.subtreeFlags&8772)!==0):qt(e,s),bi=m,Yn=v}break;case 30:break;default:qt(e,s)}}function vf(e){var a=e.alternate;a!==null&&(e.alternate=null,vf(a)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(a=e.stateNode,a!==null&&mt(a)),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 p=null,S=!1;function C(e,a,s){for(s=s.child;s!==null;)R(e,a,s),s=s.sibling}function R(e,a,s){if(ge&&typeof ge.onCommitFiberUnmount=="function")try{ge.onCommitFiberUnmount(G,s)}catch{}switch(s.tag){case 26:Yn||yi(s,a),C(e,a,s),s.memoizedState?s.memoizedState.count--:s.stateNode&&(s=s.stateNode,s.parentNode.removeChild(s));break;case 27:Yn||yi(s,a);var c=p,m=S;$l(s.type)&&(p=s.stateNode,S=!1),C(e,a,s),Mf(s.stateNode),p=c,S=m;break;case 5:Yn||yi(s,a);case 6:if(c=p,m=S,p=null,C(e,a,s),p=c,S=m,p!==null)if(S)try{(p.nodeType===9?p.body:p.nodeName==="HTML"?p.ownerDocument.body:p).removeChild(s.stateNode)}catch(v){yn(s,a,v)}else try{p.removeChild(s.stateNode)}catch(v){yn(s,a,v)}break;case 18:p!==null&&(S?(e=p,By(e.nodeType===9?e.body:e.nodeName==="HTML"?e.ownerDocument.body:e,s.stateNode),sd(e)):By(p,s.stateNode));break;case 4:c=p,m=S,p=s.stateNode.containerInfo,S=!0,C(e,a,s),p=c,S=m;break;case 0:case 11:case 14:case 15:io(2,s,a),Yn||io(4,s,a),C(e,a,s);break;case 1:Yn||(yi(s,a),c=s.stateNode,typeof c.componentWillUnmount=="function"&&qc(s,a,c)),C(e,a,s);break;case 21:C(e,a,s);break;case 22:Yn=(c=Yn)||s.memoizedState!==null,C(e,a,s),Yn=c;break;default:C(e,a,s)}}function j(e,a){if(a.memoizedState===null&&(e=a.alternate,e!==null&&(e=e.memoizedState,e!==null))){e=e.dehydrated;try{sd(e)}catch(s){yn(a,a.return,s)}}}function Q(e,a){if(a.memoizedState===null&&(e=a.alternate,e!==null&&(e=e.memoizedState,e!==null&&(e=e.dehydrated,e!==null))))try{sd(e)}catch(s){yn(a,a.return,s)}}function X(e){switch(e.tag){case 31:case 13:case 19:var a=e.stateNode;return a===null&&(a=e.stateNode=new Ko),a;case 22:return e=e.stateNode,a=e._retryCache,a===null&&(a=e._retryCache=new Ko),a;default:throw Error(i(435,e.tag))}}function le(e,a){var s=X(e);a.forEach(function(c){if(!s.has(c)){s.add(c);var m=Y0.bind(null,e,c);c.then(m,m)}})}function te(e,a){var s=a.deletions;if(s!==null)for(var c=0;c<s.length;c++){var m=s[c],v=e,A=a,_=A;e:for(;_!==null;){switch(_.tag){case 27:if($l(_.type)){p=_.stateNode,S=!1;break e}break;case 5:p=_.stateNode,S=!1;break e;case 3:case 4:p=_.stateNode.containerInfo,S=!0;break e}_=_.return}if(p===null)throw Error(i(160));R(v,A,m),p=null,S=!1,v=m.alternate,v!==null&&(v.return=null),m.return=null}if(a.subtreeFlags&13886)for(a=a.child;a!==null;)Ye(a,e),a=a.sibling}var re=null;function Ye(e,a){var s=e.alternate,c=e.flags;switch(e.tag){case 0:case 11:case 14:case 15:te(a,e),Le(e),c&4&&(io(3,e,e.return),Uc(3,e),io(5,e,e.return));break;case 1:te(a,e),Le(e),c&512&&(Yn||s===null||yi(s,s.return)),c&64&&bi&&(e=e.updateQueue,e!==null&&(c=e.callbacks,c!==null&&(s=e.shared.hiddenCallbacks,e.shared.hiddenCallbacks=s===null?c:s.concat(c))));break;case 26:var m=re;if(te(a,e),Le(e),c&512&&(Yn||s===null||yi(s,s.return)),c&4){var v=s!==null?s.memoizedState:null;if(c=e.memoizedState,s===null)if(c===null)if(e.stateNode===null){e:{c=e.type,s=e.memoizedProps,m=m.ownerDocument||m;t:switch(c){case"title":v=m.getElementsByTagName("title")[0],(!v||v[jt]||v[fe]||v.namespaceURI==="http://www.w3.org/2000/svg"||v.hasAttribute("itemprop"))&&(v=m.createElement(c),m.head.insertBefore(v,m.querySelector("head > title"))),Xa(v,c,s),v[fe]=e,Wt(v),c=v;break e;case"link":var A=Xy("link","href",m).get(c+(s.href||""));if(A){for(var _=0;_<A.length;_++)if(v=A[_],v.getAttribute("href")===(s.href==null||s.href===""?null:s.href)&&v.getAttribute("rel")===(s.rel==null?null:s.rel)&&v.getAttribute("title")===(s.title==null?null:s.title)&&v.getAttribute("crossorigin")===(s.crossOrigin==null?null:s.crossOrigin)){A.splice(_,1);break t}}v=m.createElement(c),Xa(v,c,s),m.head.appendChild(v);break;case"meta":if(A=Xy("meta","content",m).get(c+(s.content||""))){for(_=0;_<A.length;_++)if(v=A[_],v.getAttribute("content")===(s.content==null?null:""+s.content)&&v.getAttribute("name")===(s.name==null?null:s.name)&&v.getAttribute("property")===(s.property==null?null:s.property)&&v.getAttribute("http-equiv")===(s.httpEquiv==null?null:s.httpEquiv)&&v.getAttribute("charset")===(s.charSet==null?null:s.charSet)){A.splice(_,1);break t}}v=m.createElement(c),Xa(v,c,s),m.head.appendChild(v);break;default:throw Error(i(468,c))}v[fe]=e,Wt(v),c=v}e.stateNode=c}else Zy(m,e.type,e.stateNode);else e.stateNode=Yy(m,c,e.memoizedProps);else v!==c?(v===null?s.stateNode!==null&&(s=s.stateNode,s.parentNode.removeChild(s)):v.count--,c===null?Zy(m,e.type,e.stateNode):Yy(m,c,e.memoizedProps)):c===null&&e.stateNode!==null&&pf(e,e.memoizedProps,s.memoizedProps)}break;case 27:te(a,e),Le(e),c&512&&(Yn||s===null||yi(s,s.return)),s!==null&&c&4&&pf(e,e.memoizedProps,s.memoizedProps);break;case 5:if(te(a,e),Le(e),c&512&&(Yn||s===null||yi(s,s.return)),e.flags&32){m=e.stateNode;try{Ri(m,"")}catch(it){yn(e,e.return,it)}}c&4&&e.stateNode!=null&&(m=e.memoizedProps,pf(e,m,s!==null?s.memoizedProps:m)),c&1024&&(Vc=!0);break;case 6:if(te(a,e),Le(e),c&4){if(e.stateNode===null)throw Error(i(162));c=e.memoizedProps,s=e.stateNode;try{s.nodeValue=c}catch(it){yn(e,e.return,it)}}break;case 3:if(Wm=null,m=re,re=Um(a.containerInfo),te(a,e),re=m,Le(e),c&4&&s!==null&&s.memoizedState.isDehydrated)try{sd(a.containerInfo)}catch(it){yn(e,e.return,it)}Vc&&(Vc=!1,st(e));break;case 4:c=re,re=Um(e.stateNode.containerInfo),te(a,e),Le(e),re=c;break;case 12:te(a,e),Le(e);break;case 31:te(a,e),Le(e),c&4&&(c=e.updateQueue,c!==null&&(e.updateQueue=null,le(e,c)));break;case 13:te(a,e),Le(e),e.child.flags&8192&&e.memoizedState!==null!=(s!==null&&s.memoizedState!==null)&&(Em=ze()),c&4&&(c=e.updateQueue,c!==null&&(e.updateQueue=null,le(e,c)));break;case 22:m=e.memoizedState!==null;var J=s!==null&&s.memoizedState!==null,ye=bi,Re=Yn;if(bi=ye||m,Yn=Re||J,te(a,e),Yn=Re,bi=ye,Le(e),c&8192)e:for(a=e.stateNode,a._visibility=m?a._visibility&-2:a._visibility|1,m&&(s===null||J||bi||Yn||sn(e)),s=null,a=e;;){if(a.tag===5||a.tag===26){if(s===null){J=s=a;try{if(v=J.stateNode,m)A=v.style,typeof A.setProperty=="function"?A.setProperty("display","none","important"):A.display="none";else{_=J.stateNode;var Ie=J.memoizedProps.style,we=Ie!=null&&Ie.hasOwnProperty("display")?Ie.display:null;_.style.display=we==null||typeof we=="boolean"?"":(""+we).trim()}}catch(it){yn(J,J.return,it)}}}else if(a.tag===6){if(s===null){J=a;try{J.stateNode.nodeValue=m?"":J.memoizedProps}catch(it){yn(J,J.return,it)}}}else if(a.tag===18){if(s===null){J=a;try{var ke=J.stateNode;m?zy(ke,!0):zy(J.stateNode,!1)}catch(it){yn(J,J.return,it)}}}else if((a.tag!==22&&a.tag!==23||a.memoizedState===null||a===e)&&a.child!==null){a.child.return=a,a=a.child;continue}if(a===e)break e;for(;a.sibling===null;){if(a.return===null||a.return===e)break e;s===a&&(s=null),a=a.return}s===a&&(s=null),a.sibling.return=a.return,a=a.sibling}c&4&&(c=e.updateQueue,c!==null&&(s=c.retryQueue,s!==null&&(c.retryQueue=null,le(e,s))));break;case 19:te(a,e),Le(e),c&4&&(c=e.updateQueue,c!==null&&(e.updateQueue=null,le(e,c)));break;case 30:break;case 21:break;default:te(a,e),Le(e)}}function Le(e){var a=e.flags;if(a&2){try{for(var s,c=e.return;c!==null;){if(hf(c)){s=c;break}c=c.return}if(s==null)throw Error(i(160));switch(s.tag){case 27:var m=s.stateNode,v=_l(e);Gc(e,v,m);break;case 5:var A=s.stateNode;s.flags&32&&(Ri(A,""),s.flags&=-33);var _=_l(e);Gc(e,_,A);break;case 3:case 4:var J=s.stateNode.containerInfo,ye=_l(e);Vo(e,ye,J);break;default:throw Error(i(161))}}catch(Re){yn(e,e.return,Re)}e.flags&=-3}a&4096&&(e.flags&=-4097)}function st(e){if(e.subtreeFlags&1024)for(e=e.child;e!==null;){var a=e;st(a),a.tag===5&&a.flags&1024&&a.stateNode.reset(),e=e.sibling}}function qt(e,a){if(a.subtreeFlags&8772)for(a=a.child;a!==null;)gf(e,a.alternate,a),a=a.sibling}function sn(e){for(e=e.child;e!==null;){var a=e;switch(a.tag){case 0:case 11:case 14:case 15:io(4,a,a.return),sn(a);break;case 1:yi(a,a.return);var s=a.stateNode;typeof s.componentWillUnmount=="function"&&qc(a,a.return,s),sn(a);break;case 27:Mf(a.stateNode);case 26:case 5:yi(a,a.return),sn(a);break;case 22:a.memoizedState===null&&sn(a);break;case 30:sn(a);break;default:sn(a)}e=e.sibling}}function It(e,a,s){for(s=s&&(a.subtreeFlags&8772)!==0,a=a.child;a!==null;){var c=a.alternate,m=e,v=a,A=v.flags;switch(v.tag){case 0:case 11:case 15:It(m,v,s),Uc(4,v);break;case 1:if(It(m,v,s),c=v,m=c.stateNode,typeof m.componentDidMount=="function")try{m.componentDidMount()}catch(ye){yn(c,c.return,ye)}if(c=v,m=c.updateQueue,m!==null){var _=c.stateNode;try{var J=m.shared.hiddenCallbacks;if(J!==null)for(m.shared.hiddenCallbacks=null,m=0;m<J.length;m++)ps(J[m],_)}catch(ye){yn(c,c.return,ye)}}s&&A&64&&Ha(v),Wc(v,v.return);break;case 27:Rm(v);case 26:case 5:It(m,v,s),s&&c===null&&A&4&&Tm(v),Wc(v,v.return);break;case 12:It(m,v,s);break;case 31:It(m,v,s),s&&A&4&&j(m,v);break;case 13:It(m,v,s),s&&A&4&&Q(m,v);break;case 22:v.memoizedState===null&&It(m,v,s),Wc(v,v.return);break;case 30:break;default:It(m,v,s)}a=a.sibling}}function gn(e,a){var s=null;e!==null&&e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(s=e.memoizedState.cachePool.pool),e=null,a.memoizedState!==null&&a.memoizedState.cachePool!==null&&(e=a.memoizedState.cachePool.pool),e!==s&&(e!=null&&e.refCount++,s!=null&&Do(s))}function Ya(e,a){e=null,a.alternate!==null&&(e=a.alternate.memoizedState.cache),a=a.memoizedState.cache,a!==e&&(a.refCount++,e!=null&&Do(e))}function fa(e,a,s,c){if(a.subtreeFlags&10256)for(a=a.child;a!==null;)Kc(e,a,s,c),a=a.sibling}function Kc(e,a,s,c){var m=a.flags;switch(a.tag){case 0:case 11:case 15:fa(e,a,s,c),m&2048&&Uc(9,a);break;case 1:fa(e,a,s,c);break;case 3:fa(e,a,s,c),m&2048&&(e=null,a.alternate!==null&&(e=a.alternate.memoizedState.cache),a=a.memoizedState.cache,a!==e&&(a.refCount++,e!=null&&Do(e)));break;case 12:if(m&2048){fa(e,a,s,c),e=a.stateNode;try{var v=a.memoizedProps,A=v.id,_=v.onPostCommit;typeof _=="function"&&_(A,a.alternate===null?"mount":"update",e.passiveEffectDuration,-0)}catch(J){yn(a,a.return,J)}}else fa(e,a,s,c);break;case 31:fa(e,a,s,c);break;case 13:fa(e,a,s,c);break;case 23:break;case 22:v=a.stateNode,A=a.alternate,a.memoizedState!==null?v._visibility&2?fa(e,a,s,c):Yo(e,a):v._visibility&2?fa(e,a,s,c):(v._visibility|=2,Ma(e,a,s,c,(a.subtreeFlags&10256)!==0||!1)),m&2048&&gn(A,a);break;case 24:fa(e,a,s,c),m&2048&&Ya(a.alternate,a);break;default:fa(e,a,s,c)}}function Ma(e,a,s,c,m){for(m=m&&((a.subtreeFlags&10256)!==0||!1),a=a.child;a!==null;){var v=e,A=a,_=s,J=c,ye=A.flags;switch(A.tag){case 0:case 11:case 15:Ma(v,A,_,J,m),Uc(8,A);break;case 23:break;case 22:var Re=A.stateNode;A.memoizedState!==null?Re._visibility&2?Ma(v,A,_,J,m):Yo(v,A):(Re._visibility|=2,Ma(v,A,_,J,m)),m&&ye&2048&&gn(A.alternate,A);break;case 24:Ma(v,A,_,J,m),m&&ye&2048&&Ya(A.alternate,A);break;default:Ma(v,A,_,J,m)}a=a.sibling}}function Yo(e,a){if(a.subtreeFlags&10256)for(a=a.child;a!==null;){var s=e,c=a,m=c.flags;switch(c.tag){case 22:Yo(s,c),m&2048&&gn(c.alternate,c);break;case 24:Yo(s,c),m&2048&&Ya(c.alternate,c);break;default:Yo(s,c)}a=a.sibling}}var yf=8192;function Qu(e,a,s){if(e.subtreeFlags&yf)for(e=e.child;e!==null;)ey(e,a,s),e=e.sibling}function ey(e,a,s){switch(e.tag){case 26:Qu(e,a,s),e.flags&yf&&e.memoizedState!==null&&NC(s,re,e.memoizedState,e.memoizedProps);break;case 5:Qu(e,a,s);break;case 3:case 4:var c=re;re=Um(e.stateNode.containerInfo),Qu(e,a,s),re=c;break;case 22:e.memoizedState===null&&(c=e.alternate,c!==null&&c.memoizedState!==null?(c=yf,yf=16777216,Qu(e,a,s),yf=c):Qu(e,a,s));break;default:Qu(e,a,s)}}function ty(e){var a=e.alternate;if(a!==null&&(e=a.child,e!==null)){a.child=null;do a=e.sibling,e.sibling=null,e=a;while(e!==null)}}function bf(e){var a=e.deletions;if((e.flags&16)!==0){if(a!==null)for(var s=0;s<a.length;s++){var c=a[s];da=c,ay(c,e)}ty(e)}if(e.subtreeFlags&10256)for(e=e.child;e!==null;)ny(e),e=e.sibling}function ny(e){switch(e.tag){case 0:case 11:case 15:bf(e),e.flags&2048&&io(9,e,e.return);break;case 3:bf(e);break;case 12:bf(e);break;case 22:var a=e.stateNode;e.memoizedState!==null&&a._visibility&2&&(e.return===null||e.return.tag!==13)?(a._visibility&=-3,jm(e)):bf(e);break;default:bf(e)}}function jm(e){var a=e.deletions;if((e.flags&16)!==0){if(a!==null)for(var s=0;s<a.length;s++){var c=a[s];da=c,ay(c,e)}ty(e)}for(e=e.child;e!==null;){switch(a=e,a.tag){case 0:case 11:case 15:io(8,a,a.return),jm(a);break;case 22:s=a.stateNode,s._visibility&2&&(s._visibility&=-3,jm(a));break;default:jm(a)}e=e.sibling}}function ay(e,a){for(;da!==null;){var s=da;switch(s.tag){case 0:case 11:case 15:io(8,s,a);break;case 23:case 22:if(s.memoizedState!==null&&s.memoizedState.cachePool!==null){var c=s.memoizedState.cachePool.pool;c!=null&&c.refCount++}break;case 24:Do(s.memoizedState.cache)}if(c=s.child,c!==null)c.return=s,da=c;else e:for(s=e;da!==null;){c=da;var m=c.sibling,v=c.return;if(vf(c),c===s){da=null;break e}if(m!==null){m.return=v,da=m;break e}da=v}}}var $0={getCacheForType:function(e){var a=tn(Vn),s=a.data.get(e);return s===void 0&&(s=e(),a.data.set(e,s)),s},cacheSignal:function(){return tn(Vn).controller.signal}},U0=typeof WeakMap=="function"?WeakMap:Map,dn=0,Mn=null,Vt=null,Zt=0,vn=0,ws=null,Pl=!1,Yu=!1,wh=!1,Xo=0,Xn=0,Fl=0,Qc=0,xh=0,xs=0,Xu=0,wf=null,Vr=null,Sh=!1,Em=0,ry=0,Dm=1/0,Im=null,Ol=null,Aa=0,Hl=null,Zu=null,Zo=0,Ch=0,kh=null,sy=null,xf=0,Mh=null;function Ss(){return(dn&2)!==0&&Zt!==0?Zt&-Zt:B.T!==null?Eh():Sn()}function iy(){if(xs===0)if((Zt&536870912)===0||Gt){var e=at;at<<=1,(at&3932160)===0&&(at=262144),xs=e}else xs=536870912;return e=Mr.current,e!==null&&(e.flags|=32),xs}function Kr(e,a,s){(e===Mn&&(vn===2||vn===9)||e.cancelPendingCommit!==null)&&(Ju(e,0),Bl(e,Zt,xs,!1)),$n(e,s),((dn&2)===0||e!==Mn)&&(e===Mn&&((dn&2)===0&&(Qc|=s),Xn===4&&Bl(e,Zt,xs,!1)),oo(e))}function oy(e,a,s){if((dn&6)!==0)throw Error(i(327));var c=!s&&(a&127)===0&&(a&e.expiredLanes)===0||Qt(e,a),m=c?G0(e,a):Nh(e,a,!0),v=c;do{if(m===0){Yu&&!c&&Bl(e,a,0,!1);break}else{if(s=e.current.alternate,v&&!q0(s)){m=Nh(e,a,!1),v=!1;continue}if(m===2){if(v=a,e.errorRecoveryDisabledLanes&v)var A=0;else A=e.pendingLanes&-536870913,A=A!==0?A:A&536870912?536870912:0;if(A!==0){a=A;e:{var _=e;m=wf;var J=_.current.memoizedState.isDehydrated;if(J&&(Ju(_,A).flags|=256),A=Nh(_,A,!1),A!==2){if(wh&&!J){_.errorRecoveryDisabledLanes|=v,Qc|=v,m=4;break e}v=Vr,Vr=m,v!==null&&(Vr===null?Vr=v:Vr.push.apply(Vr,v))}m=A}if(v=!1,m!==2)continue}}if(m===1){Ju(e,0),Bl(e,a,0,!0);break}e:{switch(c=e,v=m,v){case 0:case 1:throw Error(i(345));case 4:if((a&4194048)!==a)break;case 6:Bl(c,a,xs,!Pl);break e;case 2:Vr=null;break;case 3:case 5:break;default:throw Error(i(329))}if((a&62914560)===a&&(m=Em+300-ze(),10<m)){if(Bl(c,a,xs,!Pl),Ut(c,0,!0)!==0)break e;Zo=a,c.timeoutHandle=Oy(ly.bind(null,c,s,Vr,Im,Sh,a,xs,Qc,Xu,Pl,v,"Throttled",-0,0),m);break e}ly(c,s,Vr,Im,Sh,a,xs,Qc,Xu,Pl,v,null,-0,0)}}break}while(!0);oo(e)}function ly(e,a,s,c,m,v,A,_,J,ye,Re,Ie,we,ke){if(e.timeoutHandle=-1,Ie=a.subtreeFlags,Ie&8192||(Ie&16785408)===16785408){Ie={stylesheets:null,count:0,imgCount:0,imgBytes:0,suspenseyImages:[],waitingForImages:!0,waitingForViewTransition:!1,unsuspend:vr},ey(a,v,Ie);var it=(v&62914560)===v?Em-ze():(v&4194048)===v?ry-ze():0;if(it=TC(Ie,it),it!==null){Zo=v,e.cancelPendingCommit=it(gy.bind(null,e,a,v,s,c,m,A,_,J,Re,Ie,null,we,ke)),Bl(e,v,A,!ye);return}}gy(e,a,v,s,c,m,A,_,J)}function q0(e){for(var a=e;;){var s=a.tag;if((s===0||s===11||s===15)&&a.flags&16384&&(s=a.updateQueue,s!==null&&(s=s.stores,s!==null)))for(var c=0;c<s.length;c++){var m=s[c],v=m.getSnapshot;m=m.value;try{if(!Da(v(),m))return!1}catch{return!1}}if(s=a.child,a.subtreeFlags&16384&&s!==null)s.return=a,a=s;else{if(a===e)break;for(;a.sibling===null;){if(a.return===null||a.return===e)return!0;a=a.return}a.sibling.return=a.return,a=a.sibling}}return!0}function Bl(e,a,s,c){a&=~xh,a&=~Qc,e.suspendedLanes|=a,e.pingedLanes&=~a,c&&(e.warmLanes|=a),c=e.expirationTimes;for(var m=a;0<m;){var v=31-z(m),A=1<<v;c[v]=-1,m&=~A}s!==0&&Fe(e,s,a)}function Lm(){return(dn&6)===0?(Sf(0),!1):!0}function Ah(){if(Vt!==null){if(vn===0)var e=Vt.return;else e=Vt,Ps=ci=null,Fo(e),Ka=null,Vi=0,e=Vt;for(;e!==null;)Ku(e.alternate,e),e=e.return;Vt=null}}function Ju(e,a){var s=e.timeoutHandle;s!==-1&&(e.timeoutHandle=-1,uC(s)),s=e.cancelPendingCommit,s!==null&&(e.cancelPendingCommit=null,s()),Zo=0,Ah(),Mn=e,Vt=s=ba(e.current,null),Zt=a,vn=0,ws=null,Pl=!1,Yu=Qt(e,a),wh=!1,Xu=xs=xh=Qc=Fl=Xn=0,Vr=wf=null,Sh=!1,(a&8)!==0&&(a|=a&32);var c=e.entangledLanes;if(c!==0)for(e=e.entanglements,c&=a;0<c;){var m=31-z(c),v=1<<m;a|=e[m],c&=~v}return Xo=a,Au(),s}function cy(e,a){_t=null,B.H=vi,a===sr||a===Gi?(a=wc(),vn=3):a===Eu?(a=wc(),vn=4):vn=a===sf?8:a!==null&&typeof a=="object"&&typeof a.then=="function"?6:1,ws=a,Vt===null&&(Xn=1,Fc(e,_a(a,e.current)))}function uy(){var e=Mr.current;return e===null?!0:(Zt&4194048)===Zt?$r===null:(Zt&62914560)===Zt||(Zt&536870912)!==0?e===$r:!1}function dy(){var e=B.H;return B.H=vi,e===null?vi:e}function fy(){var e=B.A;return B.A=$0,e}function _m(){Xn=4,Pl||(Zt&4194048)!==Zt&&Mr.current!==null||(Yu=!0),(Fl&134217727)===0&&(Qc&134217727)===0||Mn===null||Bl(Mn,Zt,xs,!1)}function Nh(e,a,s){var c=dn;dn|=2;var m=dy(),v=fy();(Mn!==e||Zt!==a)&&(Im=null,Ju(e,a)),a=!1;var A=Xn;e:do try{if(vn!==0&&Vt!==null){var _=Vt,J=ws;switch(vn){case 8:Ah(),A=6;break e;case 3:case 2:case 9:case 6:Mr.current===null&&(a=!0);var ye=vn;if(vn=0,ws=null,ed(e,_,J,ye),s&&Yu){A=0;break e}break;default:ye=vn,vn=0,ws=null,ed(e,_,J,ye)}}W0(),A=Xn;break}catch(Re){cy(e,Re)}while(!0);return a&&e.shellSuspendCounter++,Ps=ci=null,dn=c,B.H=m,B.A=v,Vt===null&&(Mn=null,Zt=0,Au()),A}function W0(){for(;Vt!==null;)my(Vt)}function G0(e,a){var s=dn;dn|=2;var c=dy(),m=fy();Mn!==e||Zt!==a?(Im=null,Dm=ze()+500,Ju(e,a)):Yu=Qt(e,a);e:do try{if(vn!==0&&Vt!==null){a=Vt;var v=ws;t:switch(vn){case 1:vn=0,ws=null,ed(e,a,v,1);break;case 2:case 9:if(bc(v)){vn=0,ws=null,py(a);break}a=function(){vn!==2&&vn!==9||Mn!==e||(vn=7),oo(e)},v.then(a,a);break e;case 3:vn=7;break e;case 4:vn=5;break e;case 7:bc(v)?(vn=0,ws=null,py(a)):(vn=0,ws=null,ed(e,a,v,7));break;case 5:var A=null;switch(Vt.tag){case 26:A=Vt.memoizedState;case 5:case 27:var _=Vt;if(A?Jy(A):_.stateNode.complete){vn=0,ws=null;var J=_.sibling;if(J!==null)Vt=J;else{var ye=_.return;ye!==null?(Vt=ye,Pm(ye)):Vt=null}break t}}vn=0,ws=null,ed(e,a,v,5);break;case 6:vn=0,ws=null,ed(e,a,v,6);break;case 8:Ah(),Xn=6;break e;default:throw Error(i(462))}}V0();break}catch(Re){cy(e,Re)}while(!0);return Ps=ci=null,B.H=c,B.A=m,dn=s,Vt!==null?0:(Mn=null,Zt=0,Au(),Xn)}function V0(){for(;Vt!==null&&!Ee();)my(Vt)}function my(e){var a=mf(e.alternate,e,Xo);e.memoizedProps=e.pendingProps,a===null?Pm(e):Vt=a}function py(e){var a=e,s=a.alternate;switch(a.tag){case 15:case 0:a=df(s,a,a.pendingProps,a.type,void 0,Zt);break;case 11:a=df(s,a,a.pendingProps,a.type.render,a.ref,Zt);break;case 5:Fo(a);default:Ku(s,a),a=Vt=is(a,Xo),a=mf(s,a,Xo)}e.memoizedProps=e.pendingProps,a===null?Pm(e):Vt=a}function ed(e,a,s,c){Ps=ci=null,Fo(a),Ka=null,Vi=0;var m=a.return;try{if(gh(e,m,a,s,Zt)){Xn=1,Fc(e,_a(s,e.current)),Vt=null;return}}catch(v){if(m!==null)throw Vt=m,v;Xn=1,Fc(e,_a(s,e.current)),Vt=null;return}a.flags&32768?(Gt||c===1?e=!0:Yu||(Zt&536870912)!==0?e=!1:(Pl=e=!0,(c===2||c===9||c===3||c===6)&&(c=Mr.current,c!==null&&c.tag===13&&(c.flags|=16384))),hy(a,e)):Pm(a)}function Pm(e){var a=e;do{if((a.flags&32768)!==0){hy(a,Pl);return}e=a.return;var s=yh(a.alternate,a,Xo);if(s!==null){Vt=s;return}if(a=a.sibling,a!==null){Vt=a;return}Vt=a=e}while(a!==null);Xn===0&&(Xn=5)}function hy(e,a){do{var s=bh(e.alternate,e);if(s!==null){s.flags&=32767,Vt=s;return}if(s=e.return,s!==null&&(s.flags|=32768,s.subtreeFlags=0,s.deletions=null),!a&&(e=e.sibling,e!==null)){Vt=e;return}Vt=e=s}while(e!==null);Xn=6,Vt=null}function gy(e,a,s,c,m,v,A,_,J){e.cancelPendingCommit=null;do Fm();while(Aa!==0);if((dn&6)!==0)throw Error(i(327));if(a!==null){if(a===e.current)throw Error(i(177));if(v=a.lanes|a.childLanes,v|=cm,ia(e,s,v,A,_,J),e===Mn&&(Vt=Mn=null,Zt=0),Zu=a,Hl=e,Zo=s,Ch=v,kh=m,sy=c,(a.subtreeFlags&10256)!==0||(a.flags&10256)!==0?(e.callbackNode=null,e.callbackPriority=0,X0(lt,function(){return xy(),null})):(e.callbackNode=null,e.callbackPriority=0),c=(a.flags&13878)!==0,(a.subtreeFlags&13878)!==0||c){c=B.T,B.T=null,m=L.p,L.p=2,A=dn,dn|=4;try{Qo(e,a,s)}finally{dn=A,L.p=m,B.T=c}}Aa=1,vy(),yy(),by()}}function vy(){if(Aa===1){Aa=0;var e=Hl,a=Zu,s=(a.flags&13878)!==0;if((a.subtreeFlags&13878)!==0||s){s=B.T,B.T=null;var c=L.p;L.p=2;var m=dn;dn|=4;try{Ye(a,e);var v=Hh,A=jd(e.containerInfo),_=v.focusedElem,J=v.selectionRange;if(A!==_&&_&&_.ownerDocument&&hc(_.ownerDocument.documentElement,_)){if(J!==null&&Mu(_)){var ye=J.start,Re=J.end;if(Re===void 0&&(Re=ye),"selectionStart"in _)_.selectionStart=ye,_.selectionEnd=Math.min(Re,_.value.length);else{var Ie=_.ownerDocument||document,we=Ie&&Ie.defaultView||window;if(we.getSelection){var ke=we.getSelection(),it=_.textContent.length,Ct=Math.min(J.start,it),wn=J.end===void 0?Ct:Math.min(J.end,it);!ke.extend&&Ct>wn&&(A=wn,wn=Ct,Ct=A);var de=ku(_,Ct),se=ku(_,wn);if(de&&se&&(ke.rangeCount!==1||ke.anchorNode!==de.node||ke.anchorOffset!==de.offset||ke.focusNode!==se.node||ke.focusOffset!==se.offset)){var ve=Ie.createRange();ve.setStart(de.node,de.offset),ke.removeAllRanges(),Ct>wn?(ke.addRange(ve),ke.extend(se.node,se.offset)):(ve.setEnd(se.node,se.offset),ke.addRange(ve))}}}}for(Ie=[],ke=_;ke=ke.parentNode;)ke.nodeType===1&&Ie.push({element:ke,left:ke.scrollLeft,top:ke.scrollTop});for(typeof _.focus=="function"&&_.focus(),_=0;_<Ie.length;_++){var je=Ie[_];je.element.scrollLeft=je.left,je.element.scrollTop=je.top}}Qm=!!Oh,Hh=Oh=null}finally{dn=m,L.p=c,B.T=s}}e.current=a,Aa=2}}function yy(){if(Aa===2){Aa=0;var e=Hl,a=Zu,s=(a.flags&8772)!==0;if((a.subtreeFlags&8772)!==0||s){s=B.T,B.T=null;var c=L.p;L.p=2;var m=dn;dn|=4;try{gf(e,a.alternate,a)}finally{dn=m,L.p=c,B.T=s}}Aa=3}}function by(){if(Aa===4||Aa===3){Aa=0,Ge();var e=Hl,a=Zu,s=Zo,c=sy;(a.subtreeFlags&10256)!==0||(a.flags&10256)!==0?Aa=5:(Aa=0,Zu=Hl=null,wy(e,e.pendingLanes));var m=e.pendingLanes;if(m===0&&(Ol=null),nn(s),a=a.stateNode,ge&&typeof ge.onCommitFiberRoot=="function")try{ge.onCommitFiberRoot(G,a,void 0,(a.current.flags&128)===128)}catch{}if(c!==null){a=B.T,m=L.p,L.p=2,B.T=null;try{for(var v=e.onRecoverableError,A=0;A<c.length;A++){var _=c[A];v(_.value,{componentStack:_.stack})}}finally{B.T=a,L.p=m}}(Zo&3)!==0&&Fm(),oo(e),m=e.pendingLanes,(s&261930)!==0&&(m&42)!==0?e===Mh?xf++:(xf=0,Mh=e):xf=0,Sf(0)}}function wy(e,a){(e.pooledCacheLanes&=a)===0&&(a=e.pooledCache,a!=null&&(e.pooledCache=null,Do(a)))}function Fm(){return vy(),yy(),by(),xy()}function xy(){if(Aa!==5)return!1;var e=Hl,a=Ch;Ch=0;var s=nn(Zo),c=B.T,m=L.p;try{L.p=32>s?32:s,B.T=null,s=kh,kh=null;var v=Hl,A=Zo;if(Aa=0,Zu=Hl=null,Zo=0,(dn&6)!==0)throw Error(i(331));var _=dn;if(dn|=4,ny(v.current),Kc(v,v.current,A,s),dn=_,Sf(0,!1),ge&&typeof ge.onPostCommitFiberRoot=="function")try{ge.onPostCommitFiberRoot(G,v)}catch{}return!0}finally{L.p=m,B.T=c,wy(e,a)}}function Sy(e,a,s){a=_a(s,a),a=rf(e.stateNode,a,2),e=Oa(e,a,2),e!==null&&($n(e,2),oo(e))}function yn(e,a,s){if(e.tag===3)Sy(e,e,s);else for(;a!==null;){if(a.tag===3){Sy(a,e,s);break}else if(a.tag===1){var c=a.stateNode;if(typeof a.type.getDerivedStateFromError=="function"||typeof c.componentDidCatch=="function"&&(Ol===null||!Ol.has(c))){e=_a(s,e),s=Oc(2),c=Oa(a,s,2),c!==null&&(km(s,c,a,e),$n(c,2),oo(c));break}}a=a.return}}function Th(e,a,s){var c=e.pingCache;if(c===null){c=e.pingCache=new U0;var m=new Set;c.set(a,m)}else m=c.get(a),m===void 0&&(m=new Set,c.set(a,m));m.has(s)||(wh=!0,m.add(s),e=K0.bind(null,e,a,s),a.then(e,e))}function K0(e,a,s){var c=e.pingCache;c!==null&&c.delete(a),e.pingedLanes|=e.suspendedLanes&s,e.warmLanes&=~s,Mn===e&&(Zt&s)===s&&(Xn===4||Xn===3&&(Zt&62914560)===Zt&&300>ze()-Em?(dn&2)===0&&Ju(e,0):xh|=s,Xu===Zt&&(Xu=0)),oo(e)}function Cy(e,a){a===0&&(a=Ra()),e=To(e,a),e!==null&&($n(e,a),oo(e))}function Q0(e){var a=e.memoizedState,s=0;a!==null&&(s=a.retryLane),Cy(e,s)}function Y0(e,a){var s=0;switch(e.tag){case 31:case 13:var c=e.stateNode,m=e.memoizedState;m!==null&&(s=m.retryLane);break;case 19:c=e.stateNode;break;case 22:c=e.stateNode._retryCache;break;default:throw Error(i(314))}c!==null&&c.delete(a),Cy(e,s)}function X0(e,a){return Z(e,a)}var Om=null,td=null,Rh=!1,Hm=!1,jh=!1,zl=0;function oo(e){e!==td&&e.next===null&&(td===null?Om=td=e:td=td.next=e),Hm=!0,Rh||(Rh=!0,J0())}function Sf(e,a){if(!jh&&Hm){jh=!0;do for(var s=!1,c=Om;c!==null;){if(e!==0){var m=c.pendingLanes;if(m===0)var v=0;else{var A=c.suspendedLanes,_=c.pingedLanes;v=(1<<31-z(42|e)+1)-1,v&=m&~(A&~_),v=v&201326741?v&201326741|1:v?v|2:0}v!==0&&(s=!0,Ny(c,v))}else v=Zt,v=Ut(c,c===Mn?v:0,c.cancelPendingCommit!==null||c.timeoutHandle!==-1),(v&3)===0||Qt(c,v)||(s=!0,Ny(c,v));c=c.next}while(s);jh=!1}}function Z0(){ky()}function ky(){Hm=Rh=!1;var e=0;zl!==0&&cC()&&(e=zl);for(var a=ze(),s=null,c=Om;c!==null;){var m=c.next,v=My(c,a);v===0?(c.next=null,s===null?Om=m:s.next=m,m===null&&(td=s)):(s=c,(e!==0||(v&3)!==0)&&(Hm=!0)),c=m}Aa!==0&&Aa!==5||Sf(e),zl!==0&&(zl=0)}function My(e,a){for(var s=e.suspendedLanes,c=e.pingedLanes,m=e.expirationTimes,v=e.pendingLanes&-62914561;0<v;){var A=31-z(v),_=1<<A,J=m[A];J===-1?((_&s)===0||(_&c)!==0)&&(m[A]=sa(_,a)):J<=a&&(e.expiredLanes|=_),v&=~_}if(a=Mn,s=Zt,s=Ut(e,e===a?s:0,e.cancelPendingCommit!==null||e.timeoutHandle!==-1),c=e.callbackNode,s===0||e===a&&(vn===2||vn===9)||e.cancelPendingCommit!==null)return c!==null&&c!==null&&$t(c),e.callbackNode=null,e.callbackPriority=0;if((s&3)===0||Qt(e,s)){if(a=s&-s,a===e.callbackPriority)return a;switch(c!==null&&$t(c),nn(s)){case 2:case 8:s=nt;break;case 32:s=lt;break;case 268435456:s=Mt;break;default:s=lt}return c=Ay.bind(null,e),s=Z(s,c),e.callbackPriority=a,e.callbackNode=s,a}return c!==null&&c!==null&&$t(c),e.callbackPriority=2,e.callbackNode=null,2}function Ay(e,a){if(Aa!==0&&Aa!==5)return e.callbackNode=null,e.callbackPriority=0,null;var s=e.callbackNode;if(Fm()&&e.callbackNode!==s)return null;var c=Zt;return c=Ut(e,e===Mn?c:0,e.cancelPendingCommit!==null||e.timeoutHandle!==-1),c===0?null:(oy(e,c,a),My(e,ze()),e.callbackNode!=null&&e.callbackNode===s?Ay.bind(null,e):null)}function Ny(e,a){if(Fm())return null;oy(e,a,!0)}function J0(){dC(function(){(dn&6)!==0?Z(Ze,Z0):ky()})}function Eh(){if(zl===0){var e=ls;e===0&&(e=Xe,Xe<<=1,(Xe&261888)===0&&(Xe=256)),zl=e}return zl}function Ty(e){return e==null||typeof e=="symbol"||typeof e=="boolean"?null:typeof e=="function"?e:Zs(""+e)}function Ry(e,a){var s=a.ownerDocument.createElement("input");return s.name=a.name,s.value=a.value,e.id&&s.setAttribute("form",e.id),a.parentNode.insertBefore(s,a),e=new FormData(e),s.parentNode.removeChild(s),e}function eC(e,a,s,c,m){if(a==="submit"&&s&&s.stateNode===m){var v=Ty((m[_e]||null).action),A=c.submitter;A&&(a=(a=A[_e]||null)?Ty(a.formAction):A.getAttribute("formAction"),a!==null&&(v=a,A=null));var _=new er("action","action",null,c,m);e.push({event:_,listeners:[{instance:null,listener:function(){if(c.defaultPrevented){if(zl!==0){var J=A?Ry(m,A):new FormData(m);Ic(s,{pending:!0,data:J,method:m.method,action:v},null,J)}}else typeof v=="function"&&(_.preventDefault(),J=A?Ry(m,A):new FormData(m),Ic(s,{pending:!0,data:J,method:m.method,action:v},v,J))},currentTarget:m}]})}}for(var Dh=0;Dh<Dd.length;Dh++){var Ih=Dd[Dh],tC=Ih.toLowerCase(),nC=Ih[0].toUpperCase()+Ih.slice(1);Ia(tC,"on"+nC)}Ia(ca,"onAnimationEnd"),Ia(Hi,"onAnimationIteration"),Ia(oi,"onAnimationStart"),Ia("dblclick","onDoubleClick"),Ia("focusin","onFocus"),Ia("focusout","onBlur"),Ia(mh,"onTransitionRun"),Ia(Ed,"onTransitionStart"),Ia(Jv,"onTransitionCancel"),Ia(lm,"onTransitionEnd"),Un("onMouseEnter",["mouseout","mouseover"]),Un("onMouseLeave",["mouseout","mouseover"]),Un("onPointerEnter",["pointerout","pointerover"]),Un("onPointerLeave",["pointerout","pointerover"]),Nn("onChange","change click focusin focusout input keydown keyup selectionchange".split(" ")),Nn("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" ")),Nn("onBeforeInput",["compositionend","keypress","textInput","paste"]),Nn("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" ")),Nn("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" ")),Nn("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var Cf="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(" "),aC=new Set("beforetoggle cancel close invalid load scroll scrollend toggle".split(" ").concat(Cf));function jy(e,a){a=(a&4)!==0;for(var s=0;s<e.length;s++){var c=e[s],m=c.event;c=c.listeners;e:{var v=void 0;if(a)for(var A=c.length-1;0<=A;A--){var _=c[A],J=_.instance,ye=_.currentTarget;if(_=_.listener,J!==v&&m.isPropagationStopped())break e;v=_,m.currentTarget=ye;try{v(m)}catch(Re){gl(Re)}m.currentTarget=null,v=J}else for(A=0;A<c.length;A++){if(_=c[A],J=_.instance,ye=_.currentTarget,_=_.listener,J!==v&&m.isPropagationStopped())break e;v=_,m.currentTarget=ye;try{v(m)}catch(Re){gl(Re)}m.currentTarget=null,v=J}}}}function Kt(e,a){var s=a[Rt];s===void 0&&(s=a[Rt]=new Set);var c=e+"__bubble";s.has(c)||(Ey(a,e,2,!1),s.add(c))}function Lh(e,a,s){var c=0;a&&(c|=4),Ey(s,e,c,a)}var Bm="_reactListening"+Math.random().toString(36).slice(2);function _h(e){if(!e[Bm]){e[Bm]=!0,jr.forEach(function(s){s!=="selectionchange"&&(aC.has(s)||Lh(s,!1,e),Lh(s,!0,e))});var a=e.nodeType===9?e:e.ownerDocument;a===null||a[Bm]||(a[Bm]=!0,Lh("selectionchange",!1,a))}}function Ey(e,a,s,c){switch(ib(a)){case 2:var m=EC;break;case 8:m=DC;break;default:m=Yh}s=m.bind(null,a,s,e),m=void 0,!ts||a!=="touchstart"&&a!=="touchmove"&&a!=="wheel"||(m=!0),c?m!==void 0?e.addEventListener(a,s,{capture:!0,passive:m}):e.addEventListener(a,s,!0):m!==void 0?e.addEventListener(a,s,{passive:m}):e.addEventListener(a,s,!1)}function Ph(e,a,s,c,m){var v=c;if((a&1)===0&&(a&2)===0&&c!==null)e:for(;;){if(c===null)return;var A=c.tag;if(A===3||A===4){var _=c.stateNode.containerInfo;if(_===m)break;if(A===4)for(A=c.return;A!==null;){var J=A.tag;if((J===3||J===4)&&A.stateNode.containerInfo===m)return;A=A.return}for(;_!==null;){if(A=Yt(_),A===null)return;if(J=A.tag,J===5||J===6||J===26||J===27){c=v=A;continue e}_=_.parentNode}}c=c.return}ta(function(){var ye=v,Re=yo(s),Ie=[];e:{var we=No.get(e);if(we!==void 0){var ke=er,it=e;switch(e){case"keypress":if(ol(s)===0)break e;case"keydown":case"keyup":ke=Ad;break;case"focusin":it="focus",ke=ll;break;case"focusout":it="blur",ke=ll;break;case"beforeblur":case"afterblur":ke=ll;break;case"click":if(s.button===2)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":ke=uc;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":ke=nr;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":ke=bu;break;case ca:case Hi:case oi:ke=yr;break;case lm:ke=Wa;break;case"scroll":case"scrollend":ke=js;break;case"wheel":ke=ch;break;case"copy":case"cut":case"paste":ke=br;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":ke=fc;break;case"toggle":case"beforetoggle":ke=om}var Ct=(a&4)!==0,wn=!Ct&&(e==="scroll"||e==="scrollend"),de=Ct?we!==null?we+"Capture":null:we;Ct=[];for(var se=ye,ve;se!==null;){var je=se;if(ve=je.stateNode,je=je.tag,je!==5&&je!==26&&je!==27||ve===null||de===null||(je=Ts(se,de),je!=null&&Ct.push(kf(se,je,ve))),wn)break;se=se.return}0<Ct.length&&(we=new ke(we,it,null,s,Re),Ie.push({event:we,listeners:Ct}))}}if((a&7)===0){e:{if(we=e==="mouseover"||e==="pointerover",ke=e==="mouseout"||e==="pointerout",we&&s!==Ns&&(it=s.relatedTarget||s.fromElement)&&(Yt(it)||it[et]))break e;if((ke||we)&&(we=Re.window===Re?Re:(we=Re.ownerDocument)?we.defaultView||we.parentWindow:window,ke?(it=s.relatedTarget||s.toElement,ke=ye,it=it?Yt(it):null,it!==null&&(wn=u(it),Ct=it.tag,it!==wn||Ct!==5&&Ct!==27&&Ct!==6)&&(it=null)):(ke=null,it=ye),ke!==it)){if(Ct=uc,je="onMouseLeave",de="onMouseEnter",se="mouse",(e==="pointerout"||e==="pointerover")&&(Ct=fc,je="onPointerLeave",de="onPointerEnter",se="pointer"),wn=ke==null?we:Xt(ke),ve=it==null?we:Xt(it),we=new Ct(je,se+"leave",ke,s,Re),we.target=wn,we.relatedTarget=ve,je=null,Yt(Re)===ye&&(Ct=new Ct(de,se+"enter",it,s,Re),Ct.target=ve,Ct.relatedTarget=wn,je=Ct),wn=je,ke&&it)t:{for(Ct=rC,de=ke,se=it,ve=0,je=de;je;je=Ct(je))ve++;je=0;for(var bt=se;bt;bt=Ct(bt))je++;for(;0<ve-je;)de=Ct(de),ve--;for(;0<je-ve;)se=Ct(se),je--;for(;ve--;){if(de===se||se!==null&&de===se.alternate){Ct=de;break t}de=Ct(de),se=Ct(se)}Ct=null}else Ct=null;ke!==null&&Dy(Ie,we,ke,Ct,!1),it!==null&&wn!==null&&Dy(Ie,wn,it,Ct,!0)}}e:{if(we=ye?Xt(ye):window,ke=we.nodeName&&we.nodeName.toLowerCase(),ke==="select"||ke==="input"&&we.type==="file")var on=Li;else if(ml(we))if(Mo)on=pc;else{on=dh;var ft=uh}else ke=we.nodeName,!ke||ke.toLowerCase()!=="input"||we.type!=="checkbox"&&we.type!=="radio"?ye&&qn(ye.elementType)&&(on=Li):on=fh;if(on&&(on=on(e,ye))){ai(Ie,on,s,Re);break e}ft&&ft(e,we,ye),e==="focusout"&&ye&&we.type==="number"&&ye.memoizedProps.value!=null&&Ti(we,"number",we.value)}switch(ft=ye?Xt(ye):window,e){case"focusin":(ml(ft)||ft.contentEditable==="true")&&(si=ft,Fi=ye,Ds=null);break;case"focusout":Ds=Fi=si=null;break;case"mousedown":ii=!0;break;case"contextmenu":case"mouseup":case"dragend":ii=!1,Gn(Ie,s,Re);break;case"selectionchange":if(ri)break;case"keydown":case"keyup":Gn(Ie,s,Re)}var zt;if(ar)e:{switch(e){case"compositionstart":var Jt="onCompositionStart";break e;case"compositionend":Jt="onCompositionEnd";break e;case"compositionupdate":Jt="onCompositionUpdate";break e}Jt=void 0}else pt?Rd(e,s)&&(Jt="onCompositionEnd"):e==="keydown"&&s.keyCode===229&&(Jt="onCompositionStart");Jt&&(Td&&s.locale!=="ko"&&(pt||Jt!=="onCompositionStart"?Jt==="onCompositionEnd"&&pt&&(zt=pu()):(Rs=Re,cc="value"in Rs?Rs.value:Rs.textContent,pt=!0)),ft=zm(ye,Jt),0<ft.length&&(Jt=new dl(Jt,e,null,s,Re),Ie.push({event:Jt,listeners:ft}),zt?Jt.data=zt:(zt=Co(s),zt!==null&&(Jt.data=zt)))),(zt=mc?_r(e,s):ko(e,s))&&(Jt=zm(ye,"onBeforeInput"),0<Jt.length&&(ft=new dl("onBeforeInput","beforeinput",null,s,Re),Ie.push({event:ft,listeners:Jt}),ft.data=zt)),eC(Ie,e,ye,s,Re)}jy(Ie,a)})}function kf(e,a,s){return{instance:e,listener:a,currentTarget:s}}function zm(e,a){for(var s=a+"Capture",c=[];e!==null;){var m=e,v=m.stateNode;if(m=m.tag,m!==5&&m!==26&&m!==27||v===null||(m=Ts(e,s),m!=null&&c.unshift(kf(e,m,v)),m=Ts(e,a),m!=null&&c.push(kf(e,m,v))),e.tag===3)return c;e=e.return}return[]}function rC(e){if(e===null)return null;do e=e.return;while(e&&e.tag!==5&&e.tag!==27);return e||null}function Dy(e,a,s,c,m){for(var v=a._reactName,A=[];s!==null&&s!==c;){var _=s,J=_.alternate,ye=_.stateNode;if(_=_.tag,J!==null&&J===c)break;_!==5&&_!==26&&_!==27||ye===null||(J=ye,m?(ye=Ts(s,v),ye!=null&&A.unshift(kf(s,ye,J))):m||(ye=Ts(s,v),ye!=null&&A.push(kf(s,ye,J)))),s=s.return}A.length!==0&&e.push({event:a,listeners:A})}var sC=/\r\n?/g,iC=/\u0000|\uFFFD/g;function Iy(e){return(typeof e=="string"?e:""+e).replace(sC,`
9
+ `).replace(iC,"")}function Ly(e,a){return a=Iy(a),Iy(e)===a}function bn(e,a,s,c,m,v){switch(s){case"children":typeof c=="string"?a==="body"||a==="textarea"&&c===""||Ri(e,c):(typeof c=="number"||typeof c=="bigint")&&a!=="body"&&Ri(e,""+c);break;case"className":In(e,"class",c);break;case"tabIndex":In(e,"tabindex",c);break;case"dir":case"role":case"viewBox":case"width":case"height":In(e,s,c);break;case"style":St(e,c,v);break;case"data":if(a!=="object"){In(e,"data",c);break}case"src":case"href":if(c===""&&(a!=="a"||s!=="href")){e.removeAttribute(s);break}if(c==null||typeof c=="function"||typeof c=="symbol"||typeof c=="boolean"){e.removeAttribute(s);break}c=Zs(""+c),e.setAttribute(s,c);break;case"action":case"formAction":if(typeof c=="function"){e.setAttribute(s,"javascript:throw new Error('A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you\\'re trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().')");break}else typeof v=="function"&&(s==="formAction"?(a!=="input"&&bn(e,a,"name",m.name,m,null),bn(e,a,"formEncType",m.formEncType,m,null),bn(e,a,"formMethod",m.formMethod,m,null),bn(e,a,"formTarget",m.formTarget,m,null)):(bn(e,a,"encType",m.encType,m,null),bn(e,a,"method",m.method,m,null),bn(e,a,"target",m.target,m,null)));if(c==null||typeof c=="symbol"||typeof c=="boolean"){e.removeAttribute(s);break}c=Zs(""+c),e.setAttribute(s,c);break;case"onClick":c!=null&&(e.onclick=vr);break;case"onScroll":c!=null&&Kt("scroll",e);break;case"onScrollEnd":c!=null&&Kt("scrollend",e);break;case"dangerouslySetInnerHTML":if(c!=null){if(typeof c!="object"||!("__html"in c))throw Error(i(61));if(s=c.__html,s!=null){if(m.children!=null)throw Error(i(60));e.innerHTML=s}}break;case"multiple":e.multiple=c&&typeof c!="function"&&typeof c!="symbol";break;case"muted":e.muted=c&&typeof c!="function"&&typeof c!="symbol";break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"defaultValue":case"defaultChecked":case"innerHTML":case"ref":break;case"autoFocus":break;case"xlinkHref":if(c==null||typeof c=="function"||typeof c=="boolean"||typeof c=="symbol"){e.removeAttribute("xlink:href");break}s=Zs(""+c),e.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",s);break;case"contentEditable":case"spellCheck":case"draggable":case"value":case"autoReverse":case"externalResourcesRequired":case"focusable":case"preserveAlpha":c!=null&&typeof c!="function"&&typeof c!="symbol"?e.setAttribute(s,""+c):e.removeAttribute(s);break;case"inert":case"allowFullScreen":case"async":case"autoPlay":case"controls":case"default":case"defer":case"disabled":case"disablePictureInPicture":case"disableRemotePlayback":case"formNoValidate":case"hidden":case"loop":case"noModule":case"noValidate":case"open":case"playsInline":case"readOnly":case"required":case"reversed":case"scoped":case"seamless":case"itemScope":c&&typeof c!="function"&&typeof c!="symbol"?e.setAttribute(s,""):e.removeAttribute(s);break;case"capture":case"download":c===!0?e.setAttribute(s,""):c!==!1&&c!=null&&typeof c!="function"&&typeof c!="symbol"?e.setAttribute(s,c):e.removeAttribute(s);break;case"cols":case"rows":case"size":case"span":c!=null&&typeof c!="function"&&typeof c!="symbol"&&!isNaN(c)&&1<=c?e.setAttribute(s,c):e.removeAttribute(s);break;case"rowSpan":case"start":c==null||typeof c=="function"||typeof c=="symbol"||isNaN(c)?e.removeAttribute(s):e.setAttribute(s,c);break;case"popover":Kt("beforetoggle",e),Kt("toggle",e),Dr(e,"popover",c);break;case"xlinkActuate":ea(e,"http://www.w3.org/1999/xlink","xlink:actuate",c);break;case"xlinkArcrole":ea(e,"http://www.w3.org/1999/xlink","xlink:arcrole",c);break;case"xlinkRole":ea(e,"http://www.w3.org/1999/xlink","xlink:role",c);break;case"xlinkShow":ea(e,"http://www.w3.org/1999/xlink","xlink:show",c);break;case"xlinkTitle":ea(e,"http://www.w3.org/1999/xlink","xlink:title",c);break;case"xlinkType":ea(e,"http://www.w3.org/1999/xlink","xlink:type",c);break;case"xmlBase":ea(e,"http://www.w3.org/XML/1998/namespace","xml:base",c);break;case"xmlLang":ea(e,"http://www.w3.org/XML/1998/namespace","xml:lang",c);break;case"xmlSpace":ea(e,"http://www.w3.org/XML/1998/namespace","xml:space",c);break;case"is":Dr(e,"is",c);break;case"innerText":case"textContent":break;default:(!(2<s.length)||s[0]!=="o"&&s[0]!=="O"||s[1]!=="n"&&s[1]!=="N")&&(s=il.get(s)||s,Dr(e,s,c))}}function Fh(e,a,s,c,m,v){switch(s){case"style":St(e,c,v);break;case"dangerouslySetInnerHTML":if(c!=null){if(typeof c!="object"||!("__html"in c))throw Error(i(61));if(s=c.__html,s!=null){if(m.children!=null)throw Error(i(60));e.innerHTML=s}}break;case"children":typeof c=="string"?Ri(e,c):(typeof c=="number"||typeof c=="bigint")&&Ri(e,""+c);break;case"onScroll":c!=null&&Kt("scroll",e);break;case"onScrollEnd":c!=null&&Kt("scrollend",e);break;case"onClick":c!=null&&(e.onclick=vr);break;case"suppressContentEditableWarning":case"suppressHydrationWarning":case"innerHTML":case"ref":break;case"innerText":case"textContent":break;default:if(!Ks.hasOwnProperty(s))e:{if(s[0]==="o"&&s[1]==="n"&&(m=s.endsWith("Capture"),a=s.slice(2,m?s.length-7:void 0),v=e[_e]||null,v=v!=null?v[s]:null,typeof v=="function"&&e.removeEventListener(a,v,m),typeof c=="function")){typeof v!="function"&&v!==null&&(s in e?e[s]=null:e.hasAttribute(s)&&e.removeAttribute(s)),e.addEventListener(a,c,m);break e}s in e?e[s]=c:c===!0?e.setAttribute(s,""):Dr(e,s,c)}}}function Xa(e,a,s){switch(a){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"img":Kt("error",e),Kt("load",e);var c=!1,m=!1,v;for(v in s)if(s.hasOwnProperty(v)){var A=s[v];if(A!=null)switch(v){case"src":c=!0;break;case"srcSet":m=!0;break;case"children":case"dangerouslySetInnerHTML":throw Error(i(137,a));default:bn(e,a,v,A,s,null)}}m&&bn(e,a,"srcSet",s.srcSet,s,null),c&&bn(e,a,"src",s.src,s,null);return;case"input":Kt("invalid",e);var _=v=A=m=null,J=null,ye=null;for(c in s)if(s.hasOwnProperty(c)){var Re=s[c];if(Re!=null)switch(c){case"name":m=Re;break;case"type":A=Re;break;case"checked":J=Re;break;case"defaultChecked":ye=Re;break;case"value":v=Re;break;case"defaultValue":_=Re;break;case"children":case"dangerouslySetInnerHTML":if(Re!=null)throw Error(i(137,a));break;default:bn(e,a,c,Re,s,null)}}Zr(e,v,_,J,ye,A,m,!1);return;case"select":Kt("invalid",e),c=A=v=null;for(m in s)if(s.hasOwnProperty(m)&&(_=s[m],_!=null))switch(m){case"value":v=_;break;case"defaultValue":A=_;break;case"multiple":c=_;default:bn(e,a,m,_,s,null)}a=v,s=A,e.multiple=!!c,a!=null?Jr(e,!!c,a,!1):s!=null&&Jr(e,!!c,s,!0);return;case"textarea":Kt("invalid",e),v=m=c=null;for(A in s)if(s.hasOwnProperty(A)&&(_=s[A],_!=null))switch(A){case"value":c=_;break;case"defaultValue":m=_;break;case"children":v=_;break;case"dangerouslySetInnerHTML":if(_!=null)throw Error(i(91));break;default:bn(e,a,A,_,s,null)}mu(e,c,m,v);return;case"option":for(J in s)s.hasOwnProperty(J)&&(c=s[J],c!=null)&&(J==="selected"?e.selected=c&&typeof c!="function"&&typeof c!="symbol":bn(e,a,J,c,s,null));return;case"dialog":Kt("beforetoggle",e),Kt("toggle",e),Kt("cancel",e),Kt("close",e);break;case"iframe":case"object":Kt("load",e);break;case"video":case"audio":for(c=0;c<Cf.length;c++)Kt(Cf[c],e);break;case"image":Kt("error",e),Kt("load",e);break;case"details":Kt("toggle",e);break;case"embed":case"source":case"link":Kt("error",e),Kt("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(ye in s)if(s.hasOwnProperty(ye)&&(c=s[ye],c!=null))switch(ye){case"children":case"dangerouslySetInnerHTML":throw Error(i(137,a));default:bn(e,a,ye,c,s,null)}return;default:if(qn(a)){for(Re in s)s.hasOwnProperty(Re)&&(c=s[Re],c!==void 0&&Fh(e,a,Re,c,s,void 0));return}}for(_ in s)s.hasOwnProperty(_)&&(c=s[_],c!=null&&bn(e,a,_,c,s,null))}function oC(e,a,s,c){switch(a){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"input":var m=null,v=null,A=null,_=null,J=null,ye=null,Re=null;for(ke in s){var Ie=s[ke];if(s.hasOwnProperty(ke)&&Ie!=null)switch(ke){case"checked":break;case"value":break;case"defaultValue":J=Ie;default:c.hasOwnProperty(ke)||bn(e,a,ke,null,c,Ie)}}for(var we in c){var ke=c[we];if(Ie=s[we],c.hasOwnProperty(we)&&(ke!=null||Ie!=null))switch(we){case"type":v=ke;break;case"name":m=ke;break;case"checked":ye=ke;break;case"defaultChecked":Re=ke;break;case"value":A=ke;break;case"defaultValue":_=ke;break;case"children":case"dangerouslySetInnerHTML":if(ke!=null)throw Error(i(137,a));break;default:ke!==Ie&&bn(e,a,we,ke,c,Ie)}}vo(e,A,_,J,ye,Re,v,m);return;case"select":ke=A=_=we=null;for(v in s)if(J=s[v],s.hasOwnProperty(v)&&J!=null)switch(v){case"value":break;case"multiple":ke=J;default:c.hasOwnProperty(v)||bn(e,a,v,null,c,J)}for(m in c)if(v=c[m],J=s[m],c.hasOwnProperty(m)&&(v!=null||J!=null))switch(m){case"value":we=v;break;case"defaultValue":_=v;break;case"multiple":A=v;default:v!==J&&bn(e,a,m,v,c,J)}a=_,s=A,c=ke,we!=null?Jr(e,!!s,we,!1):!!c!=!!s&&(a!=null?Jr(e,!!s,a,!0):Jr(e,!!s,s?[]:"",!1));return;case"textarea":ke=we=null;for(_ in s)if(m=s[_],s.hasOwnProperty(_)&&m!=null&&!c.hasOwnProperty(_))switch(_){case"value":break;case"children":break;default:bn(e,a,_,null,c,m)}for(A in c)if(m=c[A],v=s[A],c.hasOwnProperty(A)&&(m!=null||v!=null))switch(A){case"value":we=m;break;case"defaultValue":ke=m;break;case"children":break;case"dangerouslySetInnerHTML":if(m!=null)throw Error(i(91));break;default:m!==v&&bn(e,a,A,m,c,v)}es(e,we,ke);return;case"option":for(var it in s)we=s[it],s.hasOwnProperty(it)&&we!=null&&!c.hasOwnProperty(it)&&(it==="selected"?e.selected=!1:bn(e,a,it,null,c,we));for(J in c)we=c[J],ke=s[J],c.hasOwnProperty(J)&&we!==ke&&(we!=null||ke!=null)&&(J==="selected"?e.selected=we&&typeof we!="function"&&typeof we!="symbol":bn(e,a,J,we,c,ke));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 Ct in s)we=s[Ct],s.hasOwnProperty(Ct)&&we!=null&&!c.hasOwnProperty(Ct)&&bn(e,a,Ct,null,c,we);for(ye in c)if(we=c[ye],ke=s[ye],c.hasOwnProperty(ye)&&we!==ke&&(we!=null||ke!=null))switch(ye){case"children":case"dangerouslySetInnerHTML":if(we!=null)throw Error(i(137,a));break;default:bn(e,a,ye,we,c,ke)}return;default:if(qn(a)){for(var wn in s)we=s[wn],s.hasOwnProperty(wn)&&we!==void 0&&!c.hasOwnProperty(wn)&&Fh(e,a,wn,void 0,c,we);for(Re in c)we=c[Re],ke=s[Re],!c.hasOwnProperty(Re)||we===ke||we===void 0&&ke===void 0||Fh(e,a,Re,we,c,ke);return}}for(var de in s)we=s[de],s.hasOwnProperty(de)&&we!=null&&!c.hasOwnProperty(de)&&bn(e,a,de,null,c,we);for(Ie in c)we=c[Ie],ke=s[Ie],!c.hasOwnProperty(Ie)||we===ke||we==null&&ke==null||bn(e,a,Ie,we,c,ke)}function _y(e){switch(e){case"css":case"script":case"font":case"img":case"image":case"input":case"link":return!0;default:return!1}}function lC(){if(typeof performance.getEntriesByType=="function"){for(var e=0,a=0,s=performance.getEntriesByType("resource"),c=0;c<s.length;c++){var m=s[c],v=m.transferSize,A=m.initiatorType,_=m.duration;if(v&&_&&_y(A)){for(A=0,_=m.responseEnd,c+=1;c<s.length;c++){var J=s[c],ye=J.startTime;if(ye>_)break;var Re=J.transferSize,Ie=J.initiatorType;Re&&_y(Ie)&&(J=J.responseEnd,A+=Re*(J<_?1:(_-ye)/(J-ye)))}if(--c,a+=8*(v+A)/(m.duration/1e3),e++,10<e)break}}if(0<e)return a/e/1e6}return navigator.connection&&(e=navigator.connection.downlink,typeof e=="number")?e:5}var Oh=null,Hh=null;function $m(e){return e.nodeType===9?e:e.ownerDocument}function Py(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 Fy(e,a){if(e===0)switch(a){case"svg":return 1;case"math":return 2;default:return 0}return e===1&&a==="foreignObject"?0:e}function Bh(e,a){return e==="textarea"||e==="noscript"||typeof a.children=="string"||typeof a.children=="number"||typeof a.children=="bigint"||typeof a.dangerouslySetInnerHTML=="object"&&a.dangerouslySetInnerHTML!==null&&a.dangerouslySetInnerHTML.__html!=null}var zh=null;function cC(){var e=window.event;return e&&e.type==="popstate"?e===zh?!1:(zh=e,!0):(zh=null,!1)}var Oy=typeof setTimeout=="function"?setTimeout:void 0,uC=typeof clearTimeout=="function"?clearTimeout:void 0,Hy=typeof Promise=="function"?Promise:void 0,dC=typeof queueMicrotask=="function"?queueMicrotask:typeof Hy<"u"?function(e){return Hy.resolve(null).then(e).catch(fC)}:Oy;function fC(e){setTimeout(function(){throw e})}function $l(e){return e==="head"}function By(e,a){var s=a,c=0;do{var m=s.nextSibling;if(e.removeChild(s),m&&m.nodeType===8)if(s=m.data,s==="/$"||s==="/&"){if(c===0){e.removeChild(m),sd(a);return}c--}else if(s==="$"||s==="$?"||s==="$~"||s==="$!"||s==="&")c++;else if(s==="html")Mf(e.ownerDocument.documentElement);else if(s==="head"){s=e.ownerDocument.head,Mf(s);for(var v=s.firstChild;v;){var A=v.nextSibling,_=v.nodeName;v[jt]||_==="SCRIPT"||_==="STYLE"||_==="LINK"&&v.rel.toLowerCase()==="stylesheet"||s.removeChild(v),v=A}}else s==="body"&&Mf(e.ownerDocument.body);s=m}while(s);sd(a)}function zy(e,a){var s=e;e=0;do{var c=s.nextSibling;if(s.nodeType===1?a?(s._stashedDisplay=s.style.display,s.style.display="none"):(s.style.display=s._stashedDisplay||"",s.getAttribute("style")===""&&s.removeAttribute("style")):s.nodeType===3&&(a?(s._stashedText=s.nodeValue,s.nodeValue=""):s.nodeValue=s._stashedText||""),c&&c.nodeType===8)if(s=c.data,s==="/$"){if(e===0)break;e--}else s!=="$"&&s!=="$?"&&s!=="$~"&&s!=="$!"||e++;s=c}while(s)}function $h(e){var a=e.firstChild;for(a&&a.nodeType===10&&(a=a.nextSibling);a;){var s=a;switch(a=a.nextSibling,s.nodeName){case"HTML":case"HEAD":case"BODY":$h(s),mt(s);continue;case"SCRIPT":case"STYLE":continue;case"LINK":if(s.rel.toLowerCase()==="stylesheet")continue}e.removeChild(s)}}function mC(e,a,s,c){for(;e.nodeType===1;){var m=s;if(e.nodeName.toLowerCase()!==a.toLowerCase()){if(!c&&(e.nodeName!=="INPUT"||e.type!=="hidden"))break}else if(c){if(!e[jt])switch(a){case"meta":if(!e.hasAttribute("itemprop"))break;return e;case"link":if(v=e.getAttribute("rel"),v==="stylesheet"&&e.hasAttribute("data-precedence"))break;if(v!==m.rel||e.getAttribute("href")!==(m.href==null||m.href===""?null:m.href)||e.getAttribute("crossorigin")!==(m.crossOrigin==null?null:m.crossOrigin)||e.getAttribute("title")!==(m.title==null?null:m.title))break;return e;case"style":if(e.hasAttribute("data-precedence"))break;return e;case"script":if(v=e.getAttribute("src"),(v!==(m.src==null?null:m.src)||e.getAttribute("type")!==(m.type==null?null:m.type)||e.getAttribute("crossorigin")!==(m.crossOrigin==null?null:m.crossOrigin))&&v&&e.hasAttribute("async")&&!e.hasAttribute("itemprop"))break;return e;default:return e}}else if(a==="input"&&e.type==="hidden"){var v=m.name==null?null:""+m.name;if(m.type==="hidden"&&e.getAttribute("name")===v)return e}else return e;if(e=$s(e.nextSibling),e===null)break}return null}function pC(e,a,s){if(a==="")return null;for(;e.nodeType!==3;)if((e.nodeType!==1||e.nodeName!=="INPUT"||e.type!=="hidden")&&!s||(e=$s(e.nextSibling),e===null))return null;return e}function $y(e,a){for(;e.nodeType!==8;)if((e.nodeType!==1||e.nodeName!=="INPUT"||e.type!=="hidden")&&!a||(e=$s(e.nextSibling),e===null))return null;return e}function Uh(e){return e.data==="$?"||e.data==="$~"}function qh(e){return e.data==="$!"||e.data==="$?"&&e.ownerDocument.readyState!=="loading"}function hC(e,a){var s=e.ownerDocument;if(e.data==="$~")e._reactRetry=a;else if(e.data!=="$?"||s.readyState!=="loading")a();else{var c=function(){a(),s.removeEventListener("DOMContentLoaded",c)};s.addEventListener("DOMContentLoaded",c),e._reactRetry=c}}function $s(e){for(;e!=null;e=e.nextSibling){var a=e.nodeType;if(a===1||a===3)break;if(a===8){if(a=e.data,a==="$"||a==="$!"||a==="$?"||a==="$~"||a==="&"||a==="F!"||a==="F")break;if(a==="/$"||a==="/&")return null}}return e}var Wh=null;function Uy(e){e=e.nextSibling;for(var a=0;e;){if(e.nodeType===8){var s=e.data;if(s==="/$"||s==="/&"){if(a===0)return $s(e.nextSibling);a--}else s!=="$"&&s!=="$!"&&s!=="$?"&&s!=="$~"&&s!=="&"||a++}e=e.nextSibling}return null}function qy(e){e=e.previousSibling;for(var a=0;e;){if(e.nodeType===8){var s=e.data;if(s==="$"||s==="$!"||s==="$?"||s==="$~"||s==="&"){if(a===0)return e;a--}else s!=="/$"&&s!=="/&"||a++}e=e.previousSibling}return null}function Wy(e,a,s){switch(a=$m(s),e){case"html":if(e=a.documentElement,!e)throw Error(i(452));return e;case"head":if(e=a.head,!e)throw Error(i(453));return e;case"body":if(e=a.body,!e)throw Error(i(454));return e;default:throw Error(i(451))}}function Mf(e){for(var a=e.attributes;a.length;)e.removeAttributeNode(a[0]);mt(e)}var Us=new Map,Gy=new Set;function Um(e){return typeof e.getRootNode=="function"?e.getRootNode():e.nodeType===9?e:e.ownerDocument}var Jo=L.d;L.d={f:gC,r:vC,D:yC,C:bC,L:wC,m:xC,X:CC,S:SC,M:kC};function gC(){var e=Jo.f(),a=Lm();return e||a}function vC(e){var a=fn(e);a!==null&&a.tag===5&&a.type==="form"?Xd(a):Jo.r(e)}var nd=typeof document>"u"?null:document;function Vy(e,a,s){var c=nd;if(c&&typeof a=="string"&&a){var m=Ln(a);m='link[rel="'+e+'"][href="'+m+'"]',typeof s=="string"&&(m+='[crossorigin="'+s+'"]'),Gy.has(m)||(Gy.add(m),e={rel:e,crossOrigin:s,href:a},c.querySelector(m)===null&&(a=c.createElement("link"),Xa(a,"link",e),Wt(a),c.head.appendChild(a)))}}function yC(e){Jo.D(e),Vy("dns-prefetch",e,null)}function bC(e,a){Jo.C(e,a),Vy("preconnect",e,a)}function wC(e,a,s){Jo.L(e,a,s);var c=nd;if(c&&e&&a){var m='link[rel="preload"][as="'+Ln(a)+'"]';a==="image"&&s&&s.imageSrcSet?(m+='[imagesrcset="'+Ln(s.imageSrcSet)+'"]',typeof s.imageSizes=="string"&&(m+='[imagesizes="'+Ln(s.imageSizes)+'"]')):m+='[href="'+Ln(e)+'"]';var v=m;switch(a){case"style":v=ad(e);break;case"script":v=rd(e)}Us.has(v)||(e=b({rel:"preload",href:a==="image"&&s&&s.imageSrcSet?void 0:e,as:a},s),Us.set(v,e),c.querySelector(m)!==null||a==="style"&&c.querySelector(Af(v))||a==="script"&&c.querySelector(Nf(v))||(a=c.createElement("link"),Xa(a,"link",e),Wt(a),c.head.appendChild(a)))}}function xC(e,a){Jo.m(e,a);var s=nd;if(s&&e){var c=a&&typeof a.as=="string"?a.as:"script",m='link[rel="modulepreload"][as="'+Ln(c)+'"][href="'+Ln(e)+'"]',v=m;switch(c){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":v=rd(e)}if(!Us.has(v)&&(e=b({rel:"modulepreload",href:e},a),Us.set(v,e),s.querySelector(m)===null)){switch(c){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(s.querySelector(Nf(v)))return}c=s.createElement("link"),Xa(c,"link",e),Wt(c),s.head.appendChild(c)}}}function SC(e,a,s){Jo.S(e,a,s);var c=nd;if(c&&e){var m=Rn(c).hoistableStyles,v=ad(e);a=a||"default";var A=m.get(v);if(!A){var _={loading:0,preload:null};if(A=c.querySelector(Af(v)))_.loading=5;else{e=b({rel:"stylesheet",href:e,"data-precedence":a},s),(s=Us.get(v))&&Gh(e,s);var J=A=c.createElement("link");Wt(J),Xa(J,"link",e),J._p=new Promise(function(ye,Re){J.onload=ye,J.onerror=Re}),J.addEventListener("load",function(){_.loading|=1}),J.addEventListener("error",function(){_.loading|=2}),_.loading|=4,qm(A,a,c)}A={type:"stylesheet",instance:A,count:1,state:_},m.set(v,A)}}}function CC(e,a){Jo.X(e,a);var s=nd;if(s&&e){var c=Rn(s).hoistableScripts,m=rd(e),v=c.get(m);v||(v=s.querySelector(Nf(m)),v||(e=b({src:e,async:!0},a),(a=Us.get(m))&&Vh(e,a),v=s.createElement("script"),Wt(v),Xa(v,"link",e),s.head.appendChild(v)),v={type:"script",instance:v,count:1,state:null},c.set(m,v))}}function kC(e,a){Jo.M(e,a);var s=nd;if(s&&e){var c=Rn(s).hoistableScripts,m=rd(e),v=c.get(m);v||(v=s.querySelector(Nf(m)),v||(e=b({src:e,async:!0,type:"module"},a),(a=Us.get(m))&&Vh(e,a),v=s.createElement("script"),Wt(v),Xa(v,"link",e),s.head.appendChild(v)),v={type:"script",instance:v,count:1,state:null},c.set(m,v))}}function Ky(e,a,s,c){var m=(m=He.current)?Um(m):null;if(!m)throw Error(i(446));switch(e){case"meta":case"title":return null;case"style":return typeof s.precedence=="string"&&typeof s.href=="string"?(a=ad(s.href),s=Rn(m).hoistableStyles,c=s.get(a),c||(c={type:"style",instance:null,count:0,state:null},s.set(a,c)),c):{type:"void",instance:null,count:0,state:null};case"link":if(s.rel==="stylesheet"&&typeof s.href=="string"&&typeof s.precedence=="string"){e=ad(s.href);var v=Rn(m).hoistableStyles,A=v.get(e);if(A||(m=m.ownerDocument||m,A={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},v.set(e,A),(v=m.querySelector(Af(e)))&&!v._p&&(A.instance=v,A.state.loading=5),Us.has(e)||(s={rel:"preload",as:"style",href:s.href,crossOrigin:s.crossOrigin,integrity:s.integrity,media:s.media,hrefLang:s.hrefLang,referrerPolicy:s.referrerPolicy},Us.set(e,s),v||MC(m,e,s,A.state))),a&&c===null)throw Error(i(528,""));return A}if(a&&c!==null)throw Error(i(529,""));return null;case"script":return a=s.async,s=s.src,typeof s=="string"&&a&&typeof a!="function"&&typeof a!="symbol"?(a=rd(s),s=Rn(m).hoistableScripts,c=s.get(a),c||(c={type:"script",instance:null,count:0,state:null},s.set(a,c)),c):{type:"void",instance:null,count:0,state:null};default:throw Error(i(444,e))}}function ad(e){return'href="'+Ln(e)+'"'}function Af(e){return'link[rel="stylesheet"]['+e+"]"}function Qy(e){return b({},e,{"data-precedence":e.precedence,precedence:null})}function MC(e,a,s,c){e.querySelector('link[rel="preload"][as="style"]['+a+"]")?c.loading=1:(a=e.createElement("link"),c.preload=a,a.addEventListener("load",function(){return c.loading|=1}),a.addEventListener("error",function(){return c.loading|=2}),Xa(a,"link",s),Wt(a),e.head.appendChild(a))}function rd(e){return'[src="'+Ln(e)+'"]'}function Nf(e){return"script[async]"+e}function Yy(e,a,s){if(a.count++,a.instance===null)switch(a.type){case"style":var c=e.querySelector('style[data-href~="'+Ln(s.href)+'"]');if(c)return a.instance=c,Wt(c),c;var m=b({},s,{"data-href":s.href,"data-precedence":s.precedence,href:null,precedence:null});return c=(e.ownerDocument||e).createElement("style"),Wt(c),Xa(c,"style",m),qm(c,s.precedence,e),a.instance=c;case"stylesheet":m=ad(s.href);var v=e.querySelector(Af(m));if(v)return a.state.loading|=4,a.instance=v,Wt(v),v;c=Qy(s),(m=Us.get(m))&&Gh(c,m),v=(e.ownerDocument||e).createElement("link"),Wt(v);var A=v;return A._p=new Promise(function(_,J){A.onload=_,A.onerror=J}),Xa(v,"link",c),a.state.loading|=4,qm(v,s.precedence,e),a.instance=v;case"script":return v=rd(s.src),(m=e.querySelector(Nf(v)))?(a.instance=m,Wt(m),m):(c=s,(m=Us.get(v))&&(c=b({},s),Vh(c,m)),e=e.ownerDocument||e,m=e.createElement("script"),Wt(m),Xa(m,"link",c),e.head.appendChild(m),a.instance=m);case"void":return null;default:throw Error(i(443,a.type))}else a.type==="stylesheet"&&(a.state.loading&4)===0&&(c=a.instance,a.state.loading|=4,qm(c,s.precedence,e));return a.instance}function qm(e,a,s){for(var c=s.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),m=c.length?c[c.length-1]:null,v=m,A=0;A<c.length;A++){var _=c[A];if(_.dataset.precedence===a)v=_;else if(v!==m)break}v?v.parentNode.insertBefore(e,v.nextSibling):(a=s.nodeType===9?s.head:s,a.insertBefore(e,a.firstChild))}function Gh(e,a){e.crossOrigin==null&&(e.crossOrigin=a.crossOrigin),e.referrerPolicy==null&&(e.referrerPolicy=a.referrerPolicy),e.title==null&&(e.title=a.title)}function Vh(e,a){e.crossOrigin==null&&(e.crossOrigin=a.crossOrigin),e.referrerPolicy==null&&(e.referrerPolicy=a.referrerPolicy),e.integrity==null&&(e.integrity=a.integrity)}var Wm=null;function Xy(e,a,s){if(Wm===null){var c=new Map,m=Wm=new Map;m.set(s,c)}else m=Wm,c=m.get(s),c||(c=new Map,m.set(s,c));if(c.has(e))return c;for(c.set(e,null),s=s.getElementsByTagName(e),m=0;m<s.length;m++){var v=s[m];if(!(v[jt]||v[fe]||e==="link"&&v.getAttribute("rel")==="stylesheet")&&v.namespaceURI!=="http://www.w3.org/2000/svg"){var A=v.getAttribute(a)||"";A=e+A;var _=c.get(A);_?_.push(v):c.set(A,[v])}}return c}function Zy(e,a,s){e=e.ownerDocument||e,e.head.insertBefore(s,a==="title"?e.querySelector("head > title"):null)}function AC(e,a,s){if(s===1||a.itemProp!=null)return!1;switch(e){case"meta":case"title":return!0;case"style":if(typeof a.precedence!="string"||typeof a.href!="string"||a.href==="")break;return!0;case"link":if(typeof a.rel!="string"||typeof a.href!="string"||a.href===""||a.onLoad||a.onError)break;return a.rel==="stylesheet"?(e=a.disabled,typeof a.precedence=="string"&&e==null):!0;case"script":if(a.async&&typeof a.async!="function"&&typeof a.async!="symbol"&&!a.onLoad&&!a.onError&&a.src&&typeof a.src=="string")return!0}return!1}function Jy(e){return!(e.type==="stylesheet"&&(e.state.loading&3)===0)}function NC(e,a,s,c){if(s.type==="stylesheet"&&(typeof c.media!="string"||matchMedia(c.media).matches!==!1)&&(s.state.loading&4)===0){if(s.instance===null){var m=ad(c.href),v=a.querySelector(Af(m));if(v){a=v._p,a!==null&&typeof a=="object"&&typeof a.then=="function"&&(e.count++,e=Gm.bind(e),a.then(e,e)),s.state.loading|=4,s.instance=v,Wt(v);return}v=a.ownerDocument||a,c=Qy(c),(m=Us.get(m))&&Gh(c,m),v=v.createElement("link"),Wt(v);var A=v;A._p=new Promise(function(_,J){A.onload=_,A.onerror=J}),Xa(v,"link",c),s.instance=v}e.stylesheets===null&&(e.stylesheets=new Map),e.stylesheets.set(s,a),(a=s.state.preload)&&(s.state.loading&3)===0&&(e.count++,s=Gm.bind(e),a.addEventListener("load",s),a.addEventListener("error",s))}}var Kh=0;function TC(e,a){return e.stylesheets&&e.count===0&&Km(e,e.stylesheets),0<e.count||0<e.imgCount?function(s){var c=setTimeout(function(){if(e.stylesheets&&Km(e,e.stylesheets),e.unsuspend){var v=e.unsuspend;e.unsuspend=null,v()}},6e4+a);0<e.imgBytes&&Kh===0&&(Kh=62500*lC());var m=setTimeout(function(){if(e.waitingForImages=!1,e.count===0&&(e.stylesheets&&Km(e,e.stylesheets),e.unsuspend)){var v=e.unsuspend;e.unsuspend=null,v()}},(e.imgBytes>Kh?50:800)+a);return e.unsuspend=s,function(){e.unsuspend=null,clearTimeout(c),clearTimeout(m)}}:null}function Gm(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Km(this,this.stylesheets);else if(this.unsuspend){var e=this.unsuspend;this.unsuspend=null,e()}}}var Vm=null;function Km(e,a){e.stylesheets=null,e.unsuspend!==null&&(e.count++,Vm=new Map,a.forEach(RC,e),Vm=null,Gm.call(e))}function RC(e,a){if(!(a.state.loading&4)){var s=Vm.get(e);if(s)var c=s.get(null);else{s=new Map,Vm.set(e,s);for(var m=e.querySelectorAll("link[data-precedence],style[data-precedence]"),v=0;v<m.length;v++){var A=m[v];(A.nodeName==="LINK"||A.getAttribute("media")!=="not all")&&(s.set(A.dataset.precedence,A),c=A)}c&&s.set(null,c)}m=a.instance,A=m.getAttribute("data-precedence"),v=s.get(A)||c,v===c&&s.set(null,m),s.set(A,m),this.count++,c=Gm.bind(this),m.addEventListener("load",c),m.addEventListener("error",c),v?v.parentNode.insertBefore(m,v.nextSibling):(e=e.nodeType===9?e.head:e,e.insertBefore(m,e.firstChild)),a.state.loading|=4}}var Tf={$$typeof:P,Provider:null,Consumer:null,_currentValue:oe,_currentValue2:oe,_threadCount:0};function jC(e,a,s,c,m,v,A,_,J){this.tag=1,this.containerInfo=e,this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.next=this.pendingContext=this.context=this.cancelPendingCommit=null,this.callbackPriority=0,this.expirationTimes=Pn(-1),this.entangledLanes=this.shellSuspendCounter=this.errorRecoveryDisabledLanes=this.expiredLanes=this.warmLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Pn(0),this.hiddenUpdates=Pn(null),this.identifierPrefix=c,this.onUncaughtError=m,this.onCaughtError=v,this.onRecoverableError=A,this.pooledCache=null,this.pooledCacheLanes=0,this.formState=J,this.incompleteTransitions=new Map}function eb(e,a,s,c,m,v,A,_,J,ye,Re,Ie){return e=new jC(e,a,s,A,J,ye,Re,Ie,_),a=1,v===!0&&(a|=24),v=La(3,null,null,a),e.current=v,v.stateNode=e,a=Od(),a.refCount++,e.pooledCache=a,a.refCount++,v.memoizedState={element:c,isDehydrated:s,cache:a},Yi(v),e}function tb(e){return e?(e=Bi,e):Bi}function nb(e,a,s,c,m,v){m=tb(m),c.context===null?c.context=m:c.pendingContext=m,c=ds(a),c.payload={element:s},v=v===void 0?null:v,v!==null&&(c.callback=v),s=Oa(e,c,a),s!==null&&(Kr(s,e,a),fs(s,e,a))}function ab(e,a){if(e=e.memoizedState,e!==null&&e.dehydrated!==null){var s=e.retryLane;e.retryLane=s!==0&&s<a?s:a}}function Qh(e,a){ab(e,a),(e=e.alternate)&&ab(e,a)}function rb(e){if(e.tag===13||e.tag===31){var a=To(e,67108864);a!==null&&Kr(a,e,67108864),Qh(e,67108864)}}function sb(e){if(e.tag===13||e.tag===31){var a=Ss();a=gt(a);var s=To(e,a);s!==null&&Kr(s,e,a),Qh(e,a)}}var Qm=!0;function EC(e,a,s,c){var m=B.T;B.T=null;var v=L.p;try{L.p=2,Yh(e,a,s,c)}finally{L.p=v,B.T=m}}function DC(e,a,s,c){var m=B.T;B.T=null;var v=L.p;try{L.p=8,Yh(e,a,s,c)}finally{L.p=v,B.T=m}}function Yh(e,a,s,c){if(Qm){var m=Xh(c);if(m===null)Ph(e,a,c,Ym,s),ob(e,c);else if(LC(m,e,a,s,c))c.stopPropagation();else if(ob(e,c),a&4&&-1<IC.indexOf(e)){for(;m!==null;){var v=fn(m);if(v!==null)switch(v.tag){case 3:if(v=v.stateNode,v.current.memoizedState.isDehydrated){var A=At(v.pendingLanes);if(A!==0){var _=v;for(_.pendingLanes|=2,_.entangledLanes|=2;A;){var J=1<<31-z(A);_.entanglements[1]|=J,A&=~J}oo(v),(dn&6)===0&&(Dm=ze()+500,Sf(0))}}break;case 31:case 13:_=To(v,2),_!==null&&Kr(_,v,2),Lm(),Qh(v,2)}if(v=Xh(c),v===null&&Ph(e,a,c,Ym,s),v===m)break;m=v}m!==null&&c.stopPropagation()}else Ph(e,a,c,null,s)}}function Xh(e){return e=yo(e),Zh(e)}var Ym=null;function Zh(e){if(Ym=null,e=Yt(e),e!==null){var a=u(e);if(a===null)e=null;else{var s=a.tag;if(s===13){if(e=f(a),e!==null)return e;e=null}else if(s===31){if(e=h(a),e!==null)return e;e=null}else if(s===3){if(a.stateNode.current.memoizedState.isDehydrated)return a.tag===3?a.stateNode.containerInfo:null;e=null}else a!==e&&(e=null)}}return Ym=e,null}function ib(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(Ft()){case Ze:return 2;case nt:return 8;case lt:case Tt:return 32;case Mt:return 268435456;default:return 32}default:return 32}}var Jh=!1,Ul=null,ql=null,Wl=null,Rf=new Map,jf=new Map,Gl=[],IC="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 ob(e,a){switch(e){case"focusin":case"focusout":Ul=null;break;case"dragenter":case"dragleave":ql=null;break;case"mouseover":case"mouseout":Wl=null;break;case"pointerover":case"pointerout":Rf.delete(a.pointerId);break;case"gotpointercapture":case"lostpointercapture":jf.delete(a.pointerId)}}function Ef(e,a,s,c,m,v){return e===null||e.nativeEvent!==v?(e={blockedOn:a,domEventName:s,eventSystemFlags:c,nativeEvent:v,targetContainers:[m]},a!==null&&(a=fn(a),a!==null&&rb(a)),e):(e.eventSystemFlags|=c,a=e.targetContainers,m!==null&&a.indexOf(m)===-1&&a.push(m),e)}function LC(e,a,s,c,m){switch(a){case"focusin":return Ul=Ef(Ul,e,a,s,c,m),!0;case"dragenter":return ql=Ef(ql,e,a,s,c,m),!0;case"mouseover":return Wl=Ef(Wl,e,a,s,c,m),!0;case"pointerover":var v=m.pointerId;return Rf.set(v,Ef(Rf.get(v)||null,e,a,s,c,m)),!0;case"gotpointercapture":return v=m.pointerId,jf.set(v,Ef(jf.get(v)||null,e,a,s,c,m)),!0}return!1}function lb(e){var a=Yt(e.target);if(a!==null){var s=u(a);if(s!==null){if(a=s.tag,a===13){if(a=f(s),a!==null){e.blockedOn=a,Ms(e.priority,function(){sb(s)});return}}else if(a===31){if(a=h(s),a!==null){e.blockedOn=a,Ms(e.priority,function(){sb(s)});return}}else if(a===3&&s.stateNode.current.memoizedState.isDehydrated){e.blockedOn=s.tag===3?s.stateNode.containerInfo:null;return}}}e.blockedOn=null}function Xm(e){if(e.blockedOn!==null)return!1;for(var a=e.targetContainers;0<a.length;){var s=Xh(e.nativeEvent);if(s===null){s=e.nativeEvent;var c=new s.constructor(s.type,s);Ns=c,s.target.dispatchEvent(c),Ns=null}else return a=fn(s),a!==null&&rb(a),e.blockedOn=s,!1;a.shift()}return!0}function cb(e,a,s){Xm(e)&&s.delete(a)}function _C(){Jh=!1,Ul!==null&&Xm(Ul)&&(Ul=null),ql!==null&&Xm(ql)&&(ql=null),Wl!==null&&Xm(Wl)&&(Wl=null),Rf.forEach(cb),jf.forEach(cb)}function Zm(e,a){e.blockedOn===a&&(e.blockedOn=null,Jh||(Jh=!0,t.unstable_scheduleCallback(t.unstable_NormalPriority,_C)))}var Jm=null;function ub(e){Jm!==e&&(Jm=e,t.unstable_scheduleCallback(t.unstable_NormalPriority,function(){Jm===e&&(Jm=null);for(var a=0;a<e.length;a+=3){var s=e[a],c=e[a+1],m=e[a+2];if(typeof c!="function"){if(Zh(c||s)===null)continue;break}var v=fn(s);v!==null&&(e.splice(a,3),a-=3,Ic(v,{pending:!0,data:m,method:s.method,action:c},c,m))}}))}function sd(e){function a(J){return Zm(J,e)}Ul!==null&&Zm(Ul,e),ql!==null&&Zm(ql,e),Wl!==null&&Zm(Wl,e),Rf.forEach(a),jf.forEach(a);for(var s=0;s<Gl.length;s++){var c=Gl[s];c.blockedOn===e&&(c.blockedOn=null)}for(;0<Gl.length&&(s=Gl[0],s.blockedOn===null);)lb(s),s.blockedOn===null&&Gl.shift();if(s=(e.ownerDocument||e).$$reactFormReplay,s!=null)for(c=0;c<s.length;c+=3){var m=s[c],v=s[c+1],A=m[_e]||null;if(typeof v=="function")A||ub(s);else if(A){var _=null;if(v&&v.hasAttribute("formAction")){if(m=v,A=v[_e]||null)_=A.formAction;else if(Zh(m)!==null)continue}else _=A.action;typeof _=="function"?s[c+1]=_:(s.splice(c,3),c-=3),ub(s)}}}function db(){function e(v){v.canIntercept&&v.info==="react-transition"&&v.intercept({handler:function(){return new Promise(function(A){return m=A})},focusReset:"manual",scroll:"manual"})}function a(){m!==null&&(m(),m=null),c||setTimeout(s,20)}function s(){if(!c&&!navigation.transition){var v=navigation.currentEntry;v&&v.url!=null&&navigation.navigate(v.url,{state:v.getState(),info:"react-transition",history:"replace"})}}if(typeof navigation=="object"){var c=!1,m=null;return navigation.addEventListener("navigate",e),navigation.addEventListener("navigatesuccess",a),navigation.addEventListener("navigateerror",a),setTimeout(s,100),function(){c=!0,navigation.removeEventListener("navigate",e),navigation.removeEventListener("navigatesuccess",a),navigation.removeEventListener("navigateerror",a),m!==null&&(m(),m=null)}}}function eg(e){this._internalRoot=e}ep.prototype.render=eg.prototype.render=function(e){var a=this._internalRoot;if(a===null)throw Error(i(409));var s=a.current,c=Ss();nb(s,c,e,a,null,null)},ep.prototype.unmount=eg.prototype.unmount=function(){var e=this._internalRoot;if(e!==null){this._internalRoot=null;var a=e.containerInfo;nb(e.current,2,null,e,null,null),Lm(),a[et]=null}};function ep(e){this._internalRoot=e}ep.prototype.unstable_scheduleHydration=function(e){if(e){var a=Sn();e={blockedOn:null,target:e,priority:a};for(var s=0;s<Gl.length&&a!==0&&a<Gl[s].priority;s++);Gl.splice(s,0,e),s===0&&lb(e)}};var fb=n.version;if(fb!=="19.2.7")throw Error(i(527,fb,"19.2.7"));L.findDOMNode=function(e){var a=e._reactInternals;if(a===void 0)throw typeof e.render=="function"?Error(i(188)):(e=Object.keys(e).join(","),Error(i(268,e)));return e=y(a),e=e!==null?w(e):null,e=e===null?null:e.stateNode,e};var PC={bundleType:0,version:"19.2.7",rendererPackageName:"react-dom",currentDispatcherRef:B,reconcilerVersion:"19.2.7"};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"){var tp=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!tp.isDisabled&&tp.supportsFiber)try{G=tp.inject(PC),ge=tp}catch{}}return If.createRoot=function(e,a){if(!l(e))throw Error(i(299));var s=!1,c="",m=nf,v=El,A=af;return a!=null&&(a.unstable_strictMode===!0&&(s=!0),a.identifierPrefix!==void 0&&(c=a.identifierPrefix),a.onUncaughtError!==void 0&&(m=a.onUncaughtError),a.onCaughtError!==void 0&&(v=a.onCaughtError),a.onRecoverableError!==void 0&&(A=a.onRecoverableError)),a=eb(e,1,!1,null,null,s,c,null,m,v,A,db),e[et]=a.current,_h(e),new eg(a)},If.hydrateRoot=function(e,a,s){if(!l(e))throw Error(i(299));var c=!1,m="",v=nf,A=El,_=af,J=null;return s!=null&&(s.unstable_strictMode===!0&&(c=!0),s.identifierPrefix!==void 0&&(m=s.identifierPrefix),s.onUncaughtError!==void 0&&(v=s.onUncaughtError),s.onCaughtError!==void 0&&(A=s.onCaughtError),s.onRecoverableError!==void 0&&(_=s.onRecoverableError),s.formState!==void 0&&(J=s.formState)),a=eb(e,1,!0,a,s??null,c,m,J,v,A,_,db),a.context=tb(null),s=a.current,c=Ss(),c=gt(c),m=ds(c),m.callback=null,Oa(s,m,c),s=c,a.current.lanes=s,$n(a,s),oo(a),e[et]=a.current,_h(e),new ep(a)},If.version="19.2.7",If}var Ab;function Nk(){if(Ab)return rg.exports;Ab=1;function t(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(t)}catch(n){console.error(n)}}return t(),rg.exports=Ak(),rg.exports}var Tk=Nk();const Rk="https://otbyfkjxrkngvjziawki.supabase.co",jk="sb_publishable_NpUs0RDJH2YnllsqTKO6TQ_1jTdSsNQ",Ek={getItem:()=>null,setItem:()=>{},removeItem:()=>{}},Nb=typeof window<"u"&&!!window.liveDesk,Pt=xk(Rk,jk,{auth:{autoRefreshToken:!0,persistSession:!Nb,storage:Nb?Ek:void 0,detectSessionInUrl:!0,flowType:"pkce",storageKey:"livedesk.mindexec.supabase.auth"}}),Dk=new Set(["browserLanguage","platform","online","viewport","timezone","screen"]),Ik={id:"browser-safe-v1",collect(){if(typeof navigator>"u")return{};const t={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(t).filter(([n,r])=>Dk.has(n)&&r!==void 0))}};function Lk(t,n="Support request failed."){if(t&&typeof t=="object"&&"message"in t){const r=String(t.message||"").trim();if(r)return r.replace(/^.*Support request failed:\s*/i,"")}return t instanceof Error?t.message:n}function _k(t=Ik){return t.collect()}async function Pk(t,n="livedesk"){const{data:r,error:i}=await Pt.from("app_admins").select("role").eq("user_id",t).limit(1);if(i)throw i;const l=r?.[0]?.role||"user";if(l!=="owner"){const{error:M}=await Pt.rpc("register_product_access",{p_product_key:n,p_access_type:"free"});if(M)throw M}const[u,f,h]=await Promise.all([Pt.from("products").select("id, product_key, name, description, sort_order").order("sort_order"),Pt.from("product_admins").select("product_id, role").eq("user_id",t),Pt.from("user_products").select("product_id").eq("user_id",t).eq("is_active",!0)]);if(u.error)throw u.error;if(f.error)throw f.error;if(h.error)throw h.error;const g=u.data||[],y=(f.data||[]).map(M=>String(M.product_id)),w=(h.data||[]).map(M=>String(M.product_id)),b=l==="owner",x=b?g.map(M=>M.id):[...new Set([...y,...w])];return{products:g,access:{userId:t,globalRole:l,accessibleProductIds:x,managedProductIds:b?g.map(M=>M.id):y,canViewAllProducts:b,canViewAllPrivatePosts:b,canManageAllProducts:b,canCreateAnnouncements:b||y.length>0}}}async function Fk(t=""){const{data:n,error:r}=await Pt.rpc("search_support_posts",{p_query:t.trim()||null,p_limit:250});if(r)throw r;return n||[]}async function Ok(t){const{data:n,error:r}=await Pt.from("support_attachments").select("*").eq("post_id",t).order("created_at");if(r)throw r;const i=n||[];return Promise.all(i.map(async l=>{const u=await Pt.storage.from("support-attachments").createSignedUrl(l.storage_path,3600);return{...l,signed_url:u.data?.signedUrl||void 0}}))}async function Hk(){const{data:t,error:n}=await Pt.from("support_notifications").select("*").order("created_at",{ascending:!1}).limit(30);if(n)throw n;return t||[]}async function Bk(t){const{error:n}=await Pt.rpc("mark_support_notification_read",{p_notification_id:t});if(n)throw n}async function Tb(t){const{data:n,error:r}=await Pt.from("support_comments").select("*").eq("post_id",t).order("created_at");if(r)throw r;return n||[]}async function zk(t){const{data:n,error:r}=await Pt.from("support_votes").select("post_id").eq("user_id",t);if(r)throw r;return new Set((n||[]).map(i=>String(i.post_id)))}async function $k(t){const{data:n,error:r}=await Pt.rpc("create_support_post",{p_product_id:t.productId,p_post_type:t.postType,p_title:t.title,p_body:t.body,p_visibility:t.visibility,p_app_version:t.appVersion||null,p_platform:typeof navigator>"u"?null:navigator.platform||null,p_os_version:typeof navigator>"u"?null:navigator.platform||null,p_environment:t.includeEnvironment?_k():{}});if(r)throw r;const i=Array.isArray(n)?n[0]?.post_id:n?.post_id;if(!i)throw new Error("Support post was not created.");return String(i)}const Uk=new Set(["image/png","image/jpeg","image/webp","text/plain","text/markdown","application/json","application/pdf"]);async function qk(t,n){if(!Uk.has(n.type))throw new Error("This file type is not allowed.");if(n.size<=0||n.size>10*1024*1024)throw new Error("Attachments must be smaller than 10 MB.");const r=n.name.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"attachment",i=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`,l=`${t}/${i}-${r}`,u=await Pt.storage.from("support-attachments").upload(l,n,{contentType:n.type,upsert:!1});if(u.error)throw u.error;const{data:f,error:h}=await Pt.rpc("add_support_attachment",{p_post_id:t,p_storage_path:l,p_file_name:r,p_mime_type:n.type,p_size_bytes:n.size});if(h)throw await Pt.storage.from("support-attachments").remove([l]),h;const g=Array.isArray(f)?f[0]?.attachment_id:f?.attachment_id;if(!g)throw new Error("Attachment metadata was not created.");return String(g)}async function Wk(t,n,r,i){const{error:l}=await Pt.rpc("update_support_post",{p_post_id:t,p_title:n,p_body:r,p_visibility:i});if(l)throw l}async function Gk(t,n){const{error:r}=await Pt.rpc("add_support_comment",{p_post_id:t,p_body:n});if(r)throw r}async function Vk(t){const{data:n,error:r}=await Pt.rpc("toggle_support_vote",{p_post_id:t});if(r)throw r;const i=Array.isArray(n)?n[0]:n;return{voted:!!i?.voted,totalVotes:Number(i?.total_votes||0)}}async function Kk(t,n){const{error:r}=await Pt.rpc("change_support_post_status",{p_post_id:t,p_target_status:n});if(r)throw r}async function Qk(t){const{error:n}=await Pt.rpc("set_support_post_hidden",{p_post_id:t,p_hidden:!0});if(n)throw n}async function Yk(t,n){const{error:r}=await Pt.rpc("set_support_post_locked",{p_post_id:t,p_locked:n});if(r)throw r}async function Xk(t,n){const{error:r}=await Pt.rpc("set_support_post_pinned",{p_post_id:t,p_pinned:n});if(r)throw r}async function Zk(t,n){const{error:r}=await Pt.rpc("mark_support_duplicate",{p_post_id:t,p_duplicate_of_post_id:n});if(r)throw r}async function Jk(t,n){const{error:r}=await Pt.rpc("accept_support_answer",{p_post_id:t,p_comment_id:n});if(r)throw r}async function eM(t,n=!0){const{error:r}=await Pt.rpc("hide_support_comment",{p_comment_id:t,p_hidden:n});if(r)throw r}const Gg=[{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"}],tM=[{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"}],nM={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"]},aM={type:"all",product:"",status:"all",visibility:"all",sort:"recent",query:""};function og(){if(typeof window>"u")return aM;const t=new URLSearchParams(window.location.search),n=window.location.pathname.match(/^\/support\/(questions|issues|features|announcements)$/)?.[1],r=t.get("type")||n||"",i=r==="questions"||r==="question"?"question":r==="issues"||r==="issue"?"issue":r==="features"||r==="feature"?"feature":r==="announcements"||r==="announcement"?"announcement":"all",l=t.get("visibility"),u=t.get("sort");return{type:i,product:t.get("product")||"",status:t.get("status")||"all",visibility:l==="public"||l==="private"?l:"all",sort:u==="votes"||u==="newest"?u:"recent",query:t.get("q")||""}}function rM(t){return t==="all"?"":t==="question"?"questions":t==="issue"?"issues":t==="feature"?"features":"announcements"}function sM(t,n){const r={...t,...n},i=new URLSearchParams;r.product&&i.set("product",r.product),r.status!=="all"&&i.set("status",r.status),r.visibility!=="all"&&i.set("visibility",r.visibility),r.sort!=="recent"&&i.set("sort",r.sort),r.query&&i.set("q",r.query);const l=rM(r.type),u=i.toString();return`/support${l?`/${l}`:""}${u?`?${u}`:""}`}function np(t){const n=new Date(t);return Number.isFinite(n.getTime())?n.toLocaleString(void 0,{dateStyle:"medium",timeStyle:"short"}):t}function lg(t){return t.replaceAll("-"," ").replace(/\b\w/g,n=>n.toUpperCase())}function Rb(t){return t==="question"?$C:t==="issue"?Ex:t==="feature"?UC:qC}function jb(t){return Gg.find(n=>n.id===t)?.shortLabel||t}function cg(t,n){return t.find(r=>r.id===n)?.name||"Product"}function Qr(t){const n=Lk(t);return/relation .* does not exist|function .* does not exist|schema cache/i.test(n)?"Support Board database is not installed yet. Apply the latest Supabase migration first.":/not-authenticated|jwt/i.test(n)?"Sign in again to use Support.":/product-access-denied|product-not-found/i.test(n)?"You do not have access to this product.":n}function Ux({session:t,currentProductKey:n="livedesk",appVersion:r="",onSignIn:i}){const[l,u]=d.useState(()=>og()),[f,h]=d.useState(null),[g,y]=d.useState([]),[w,b]=d.useState([]),[x,M]=d.useState(""),[k,N]=d.useState([]),[E,I]=d.useState([]),[T,P]=d.useState([]),[U,F]=d.useState(()=>new Set),[Y,D]=d.useState(!0),[K,ne]=d.useState(""),[q,O]=d.useState(""),[W,ce]=d.useState(!1),[$,ee]=d.useState(!1),[B,L]=d.useState(""),[oe,be]=d.useState(()=>og().query),[H,me]=d.useState(!1),[ue,Ce]=d.useState(!1),[Me,Ne]=d.useState(""),[He,Ve]=d.useState(""),[ie,Oe]=d.useState("free"),[$e,qe]=d.useState(""),[vt,xe]=d.useState(""),[he,pe]=d.useState("admin"),[Ae,Se]=d.useState(""),[Pe,Qe]=d.useState(""),[Z,$t]=d.useState(""),[Ee,Ge]=d.useState(""),[ze,Ft]=d.useState(""),[Ze,nt]=d.useState([]),[lt,Tt]=d.useState({productId:"",postType:"question",title:"",body:"",visibility:"public",includeEnvironment:!0,files:[]}),Mt=d.useCallback(V=>{const Je={...l,...V};u(Je),typeof window<"u"&&window.history.pushState({},"",sM(l,V))},[l]);d.useEffect(()=>{const V=()=>u(og());return window.addEventListener("popstate",V),()=>window.removeEventListener("popstate",V)},[]);const rt=d.useCallback(async()=>{const V=await Fk(l.query);return b(V),t?.user.id&&F(await zk(t.user.id)),V},[l.query,t?.user.id]),dt=d.useCallback(async()=>{if(!t?.user.id){h(null),y([]),b([]),M(""),P([]),D(!1);return}D(!0),O("");try{const V=await Pk(t.user.id,n);h(V.access),y(V.products),await rt(),P(await Hk())}catch(V){O(Qr(V))}finally{D(!1)}},[n,rt,t?.user.id]);d.useEffect(()=>{dt()},[dt]);const G=d.useMemo(()=>f?f.canViewAllProducts?g:g.filter(V=>f.accessibleProductIds.includes(V.id)):[],[f,g]),ge=d.useMemo(()=>{const V=G.find(Je=>Je.product_key===l.product);return f?.canViewAllProducts&&!l.product||l.product==="all"&&f?.canViewAllProducts?"all":V?V.product_key:G.some(Je=>Je.product_key===n)?n:G[0]?.product_key||""},[f?.canViewAllProducts,G,n,l.product]),De=ge==="all"?"":G.find(V=>V.product_key===ge)?.id||"",z=d.useMemo(()=>{const V=new Map(g.map(gt=>[gt.id,gt.product_key]));return[...w.filter(gt=>l.type!=="all"&&gt.post_type!==l.type||ge!=="all"&&De&&gt.product_id!==De||l.status==="needs-response"&&!["open","needs-info"].includes(gt.status)||l.status!=="all"&&l.status!=="needs-response"&&gt.status!==l.status||l.visibility!=="all"&&gt.visibility!==l.visibility?!1:V.has(gt.product_id))].sort((gt,nn)=>l.sort==="votes"?nn.vote_count-gt.vote_count||nn.updated_at.localeCompare(gt.updated_at):l.sort==="newest"?nn.created_at.localeCompare(gt.created_at):Number(nn.is_pinned)-Number(gt.is_pinned)||nn.updated_at.localeCompare(gt.updated_at))},[w,g,l.sort,l.status,l.type,l.visibility,De,ge]),ae=z.find(V=>V.id===x)||z[0]||null,Te=!!(ae&&f&&(f.canViewAllProducts||f.managedProductIds.includes(ae.product_id))),Ue=!!(ae&&t?.user.id===ae.author_id)||Te;d.useEffect(()=>{if(!ae){M(""),N([]),ee(!1);return}ae.id!==x&&M(ae.id)},[ae,x]),d.useEffect(()=>{let V=!0;return x?(Tb(x).then(Je=>{V&&N(Je)}).catch(Je=>{V&&O(Qr(Je))}),Ok(x).then(Je=>{V&&I(Je)}).catch(Je=>{V&&O(Qr(Je))}),()=>{V=!1}):(N([]),I([]),()=>{V=!1})},[x]),d.useEffect(()=>{!lt.productId&&G[0]&&Tt(V=>({...V,productId:De||G[0].id}))},[G,lt.productId,De]),d.useEffect(()=>{be(l.query)},[l.query]),d.useEffect(()=>{!He&&G[0]&&Ve(G[0].id),!vt&&G[0]&&xe(G[0].id)},[G,He,vt]);const Xe=V=>{ae&&b(Je=>Je.map(gt=>gt.id===ae.id?{...gt,...V}:gt))},at=async V=>{if(V.preventDefault(),!(!t||!lt.productId)){ne("create"),O("");try{const Je=await $k({productId:lt.productId,postType:lt.postType,title:lt.title,body:lt.body,visibility:lt.postType==="announcement"?"public":lt.visibility,appVersion:r,includeEnvironment:lt.postType==="issue"&&lt.includeEnvironment});for(const nn of Ze)await qk(Je,nn);const gt=await rt();ce(!1),nt([]),Tt(nn=>({...nn,title:"",body:"",files:[]})),M(Je),gt.some(nn=>nn.id===Je)||await dt()}catch(Je){O(Qr(Je))}finally{ne("")}}},kt=async V=>{if(V.preventDefault(),!!ae){ne("edit"),O("");try{await Wk(ae.id,ae.title,ae.body,ae.visibility),ee(!1),await rt()}catch(Je){O(Qr(Je))}finally{ne("")}}},At=async V=>{if(V.preventDefault(),!(!ae||!B.trim())){ne("comment"),O("");try{await Gk(ae.id,B),L(""),N(await Tb(ae.id)),await rt()}catch(Je){O(Qr(Je))}finally{ne("")}}},Ut=async()=>{if(!(!ae||ae.post_type!=="feature")){ne("vote"),O("");try{const V=await Vk(ae.id);F(Je=>{const gt=new Set(Je);return V.voted?gt.add(ae.id):gt.delete(ae.id),gt}),Xe({vote_count:V.totalVotes})}catch(V){O(Qr(V))}finally{ne("")}}},Qt=async V=>{if(ae){ne("status"),O("");try{await Kk(ae.id,V),Xe({status:V}),await rt()}catch(Je){O(Qr(Je))}finally{ne("")}}},sa=async()=>{if(!(!ae||!window.confirm("Hide this Support post from the board?"))){ne("hide"),O("");try{await Qk(ae.id),M(""),await rt()}catch(V){O(Qr(V))}finally{ne("")}}},Ra=async()=>{if(ae){ne("lock"),O("");try{await Yk(ae.id,!ae.is_locked),Xe({is_locked:!ae.is_locked}),await rt()}catch(V){O(Qr(V))}finally{ne("")}}},Pn=async()=>{if(ae){ne("pin"),O("");try{await Xk(ae.id,!ae.is_pinned),Xe({is_pinned:!ae.is_pinned}),await rt()}catch(V){O(Qr(V))}finally{ne("")}}},$n=async V=>{if(ae){ne(`accept-${V}`),O("");try{await Jk(ae.id,V),Xe({accepted_comment_id:V,status:ae.post_type==="question"?"answered":ae.status}),await rt()}catch(Je){O(Qr(Je))}finally{ne("")}}},ia=async()=>{if(!(!ae||!Ee||Ee===ae.id)){ne("duplicate"),O("");try{await Zk(ae.id,Ee),M(""),Ge(""),await rt()}catch(V){O(Qr(V))}finally{ne("")}}},Fe=async V=>{if(!V.read_at)try{await Bk(V.id),P(Je=>Je.map(gt=>gt.id===V.id?{...gt,read_at:new Date().toISOString()}:gt))}catch(Je){O(Qr(Je))}V.post_id&&M(V.post_id),me(!1)};return t?Y&&!f?o.jsxs("section",{className:"support-page support-loading",children:[o.jsx(bd,{className:"support-spin",size:23})," Loading Support Board..."]}):o.jsxs("section",{className:"support-page",children:[o.jsx("header",{className:"support-page-header support-page-actions-only",children:o.jsxs("div",{className:"support-header-actions",children:[o.jsxs("div",{className:"support-notification-wrap",children:[o.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>me(V=>!V),title:"Notifications",children:[o.jsx(HC,{size:16})," ",T.filter(V=>!V.read_at).length>0&&o.jsx("b",{children:T.filter(V=>!V.read_at).length})]}),H&&o.jsxs("div",{className:"support-notification-popover",children:[o.jsx("strong",{children:"Notifications"}),T.length===0?o.jsx("span",{className:"support-muted",children:"No notifications yet."}):T.map(V=>o.jsxs("button",{type:"button",className:V.read_at?"":"unread",onClick:()=>{Fe(V)},children:[o.jsx("b",{children:V.title}),o.jsx("span",{children:V.body}),o.jsx("small",{children:np(V.created_at)})]},V.id))]})]}),f?.canViewAllProducts&&o.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>Ce(V=>!V),children:[o.jsx(Na,{size:16})," Admin"]}),o.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>{dt()},disabled:Y,children:[o.jsx(bd,{size:16,className:Y?"support-spin":""})," Refresh"]}),o.jsxs("button",{className:"support-primary-button",type:"button",onClick:()=>ce(!0),disabled:G.length===0,children:[o.jsx(tg,{size:17})," New request"]})]})}),q&&o.jsxs("div",{className:"support-error",role:"alert",children:[o.jsx(hr,{size:17})," ",o.jsx("span",{children:q}),o.jsx("button",{type:"button",onClick:()=>O(""),"aria-label":"Dismiss error",children:o.jsx(hr,{size:15})})]}),W&&o.jsxs("form",{className:"support-composer",onSubmit:V=>{at(V)},children:[o.jsxs("div",{className:"support-section-heading",children:[o.jsxs("div",{children:[o.jsx("span",{children:"New Support request"}),o.jsx("strong",{children:"Describe one actionable problem or idea."})]}),o.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>ce(!1),"aria-label":"Close composer",children:o.jsx(hr,{size:18})})]}),o.jsxs("div",{className:"support-form-grid",children:[o.jsxs("label",{children:[o.jsx("span",{children:"Product"}),o.jsx("select",{value:lt.productId,onChange:V=>Tt(Je=>({...Je,productId:V.target.value})),children:G.map(V=>o.jsx("option",{value:V.id,children:V.name},V.id))})]}),o.jsxs("label",{children:[o.jsx("span",{children:"Type"}),o.jsx("select",{value:lt.postType,onChange:V=>Tt(Je=>({...Je,postType:V.target.value})),children:Gg.filter(V=>V.id!=="announcement"||f?.canCreateAnnouncements).map(V=>o.jsx("option",{value:V.id,children:V.label},V.id))})]}),o.jsxs("label",{className:"support-form-wide",children:[o.jsx("span",{children:"Title"}),o.jsx("input",{required:!0,minLength:3,maxLength:180,value:lt.title,onChange:V=>Tt(Je=>({...Je,title:V.target.value})),placeholder:"A short, searchable summary"})]}),o.jsxs("label",{className:"support-form-wide",children:[o.jsx("span",{children:lt.postType==="issue"?"What happened?":lt.postType==="feature"?"Describe the desired behavior":lt.postType==="announcement"?"Announcement":"Question"}),o.jsx("textarea",{required:!0,value:lt.body,onChange:V=>Tt(Je=>({...Je,body:V.target.value})),placeholder:"Include the context another person needs to respond.",rows:6})]}),o.jsxs("label",{children:[o.jsx("span",{children:"Visibility"}),o.jsxs("select",{value:lt.visibility,disabled:lt.postType==="announcement",onChange:V=>Tt(Je=>({...Je,visibility:V.target.value})),children:[o.jsx("option",{value:"public",children:"Public"}),o.jsx("option",{value:"private",children:"Private"})]})]}),lt.postType==="issue"&&o.jsxs("label",{className:"support-checkbox",children:[o.jsx("input",{type:"checkbox",checked:lt.includeEnvironment,onChange:V=>Tt(Je=>({...Je,includeEnvironment:V.target.checked}))}),o.jsx("span",{children:"Attach safe browser/runtime details"})]}),o.jsxs("label",{className:"support-form-wide",children:[o.jsx("span",{children:"Attachments"}),o.jsx("input",{type:"file",multiple:!0,accept:"image/png,image/jpeg,image/webp,text/plain,text/markdown,application/json,application/pdf",onChange:V=>nt(Array.from(V.target.files||[]).slice(0,5))}),o.jsx("small",{className:"support-muted",children:"Up to 5 files, 10 MB each. Images, text, JSON, Markdown, and PDF."})]})]}),o.jsxs("div",{className:"support-composer-footer",children:[o.jsx("span",{children:Ze.length>0?`${Ze.length} attachment${Ze.length===1?"":"s"} selected.`:"Private posts are visible only to you and the product support staff."}),o.jsxs("button",{className:"support-primary-button",type:"submit",disabled:K==="create",children:[o.jsx(Yf,{size:16})," ",K==="create"?"Submitting...":"Submit request"]})]})]}),o.jsxs("div",{className:"support-tabs",role:"tablist","aria-label":"Support post type",children:[o.jsx("button",{className:l.type==="all"?"active":"",type:"button",onClick:()=>Mt({type:"all"}),children:"All"}),Gg.map(V=>{const Je=Rb(V.id);return o.jsxs("button",{className:l.type===V.id?"active":"",type:"button",onClick:()=>Mt({type:V.id}),children:[o.jsx(Je,{size:15})," ",V.label]},V.id)})]}),ue&&f?.canViewAllProducts&&o.jsxs("section",{className:"support-admin-panel",children:[o.jsxs("div",{className:"support-section-heading",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Owner controls"}),o.jsx("strong",{children:"Products and access are managed by immutable user IDs behind these email lookup forms."})]}),o.jsx(Na,{size:19})]}),o.jsxs("div",{className:"support-admin-grid",children:[o.jsxs("form",{onSubmit:V=>{},children:[o.jsx("strong",{children:"Grant product access"}),o.jsx("input",{type:"email",required:!0,placeholder:"User email",value:Me,onChange:V=>Ne(V.target.value)}),o.jsx("select",{value:He,onChange:V=>Ve(V.target.value),children:G.map(V=>o.jsx("option",{value:V.id,children:V.name},V.id))}),o.jsxs("select",{value:ie,onChange:V=>Oe(V.target.value),children:[o.jsx("option",{value:"free",children:"Free"}),o.jsx("option",{value:"user",children:"User"}),o.jsx("option",{value:"paid",children:"Paid"}),o.jsx("option",{value:"beta",children:"Beta"}),o.jsx("option",{value:"staff",children:"Staff"})]}),o.jsxs("button",{className:"support-secondary-button",type:"submit",disabled:ze==="access",children:[o.jsx(fo,{size:15})," Grant access"]})]}),o.jsxs("form",{onSubmit:V=>{},children:[o.jsx("strong",{children:"Assign product admin"}),o.jsx("input",{type:"email",required:!0,placeholder:"Admin email",value:$e,onChange:V=>qe(V.target.value)}),o.jsx("select",{value:vt,onChange:V=>xe(V.target.value),children:G.map(V=>o.jsx("option",{value:V.id,children:V.name},V.id))}),o.jsxs("select",{value:he,onChange:V=>pe(V.target.value),children:[o.jsx("option",{value:"admin",children:"Admin"}),o.jsx("option",{value:"support",children:"Support"}),o.jsx("option",{value:"moderator",children:"Moderator"})]}),o.jsxs("button",{className:"support-secondary-button",type:"submit",disabled:ze==="product-admin",children:[o.jsx(Na,{size:15})," Assign admin"]})]}),o.jsxs("form",{onSubmit:V=>{},children:[o.jsx("strong",{children:"Add a product"}),o.jsx("input",{required:!0,pattern:"[a-z0-9][a-z0-9_-]{1,48}",placeholder:"product-key",value:Ae,onChange:V=>Se(V.target.value)}),o.jsx("input",{required:!0,placeholder:"Product name",value:Pe,onChange:V=>Qe(V.target.value)}),o.jsx("input",{placeholder:"Description",value:Z,onChange:V=>$t(V.target.value)}),o.jsxs("button",{className:"support-secondary-button",type:"submit",disabled:ze==="product",children:[o.jsx(tg,{size:15})," Add product"]})]})]})]}),o.jsxs("form",{className:"support-search-bar",onSubmit:V=>{V.preventDefault(),Mt({query:oe.trim()})},children:[o.jsxs("label",{children:[o.jsx("span",{children:"Search Support"}),o.jsx("input",{value:oe,onChange:V=>be(V.target.value),placeholder:"Search titles and request details"})]}),o.jsxs("button",{className:"support-secondary-button",type:"submit",children:[o.jsx(mb,{size:15})," Search"]}),l.query&&o.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>{be(""),Mt({query:""})},"aria-label":"Clear search",children:o.jsx(hr,{size:16})})]}),o.jsxs("div",{className:"support-filter-bar",children:[o.jsxs("div",{className:"support-filter-title",children:[o.jsx(mb,{size:16}),o.jsx("span",{children:"Filter"})]}),o.jsxs("label",{children:[o.jsx("span",{children:"Product"}),o.jsxs("select",{value:ge,onChange:V=>Mt({product:V.target.value}),disabled:!f?.canViewAllProducts&&G.length<=1,children:[o.jsx("option",{value:"all",children:"All products"}),G.map(V=>o.jsx("option",{value:V.product_key,children:V.name},V.id))]})]}),o.jsxs("label",{children:[o.jsx("span",{children:"Status"}),o.jsx("select",{value:l.status,onChange:V=>Mt({status:V.target.value}),children:tM.map(V=>o.jsx("option",{value:V.id,children:V.label},V.id))})]}),o.jsxs("label",{children:[o.jsx("span",{children:"Visibility"}),o.jsxs("select",{value:l.visibility,onChange:V=>Mt({visibility:V.target.value}),children:[o.jsx("option",{value:"all",children:"All visibility"}),o.jsx("option",{value:"public",children:"Public"}),o.jsx("option",{value:"private",children:"Private"})]})]}),o.jsxs("label",{children:[o.jsx("span",{children:"Sort"}),o.jsxs("select",{value:l.sort,onChange:V=>Mt({sort:V.target.value}),children:[o.jsx("option",{value:"recent",children:"Recently updated"}),o.jsx("option",{value:"newest",children:"Newest"}),o.jsx("option",{value:"votes",children:"Most votes"})]})]})]}),f?.canViewAllProducts&&o.jsxs("div",{className:"support-admin-shortcuts",children:[o.jsxs("span",{children:[o.jsx(Na,{size:15})," Owner view"]}),o.jsx("button",{type:"button",onClick:()=>Mt({status:"needs-response"}),children:"Needs response"}),o.jsx("button",{type:"button",onClick:()=>Mt({visibility:"private"}),children:"Private requests"}),o.jsx("button",{type:"button",onClick:()=>Mt({type:"feature",status:"all",sort:"votes"}),children:"High-vote features"})]}),o.jsxs("div",{className:"support-board-layout",children:[o.jsxs("section",{className:"support-post-list","aria-label":"Support posts",children:[o.jsxs("div",{className:"support-list-heading",children:[o.jsxs("span",{children:[z.length," request",z.length===1?"":"s"]}),o.jsx("small",{children:ge==="all"?"All products":cg(G,De)})]}),z.length===0?o.jsxs("div",{className:"support-list-empty",children:[o.jsx(qf,{size:25}),o.jsx("strong",{children:"No posts match these filters."}),o.jsx("span",{children:"Start with a focused question, issue report, or feature request."}),G.length>0&&o.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>ce(!0),children:[o.jsx(tg,{size:16})," Create the first request"]})]}):z.map(V=>{const Je=Rb(V.post_type);return o.jsxs("button",{type:"button",className:`support-post-row ${V.id===ae?.id?"active":""}`,onClick:()=>{M(V.id),ee(!1)},children:[o.jsx("span",{className:"support-post-row-icon",children:o.jsx(Je,{size:17})}),o.jsxs("span",{className:"support-post-row-copy",children:[o.jsxs("span",{className:"support-post-row-meta",children:[o.jsx("b",{children:cg(g,V.product_id)}),o.jsx("em",{children:jb(V.post_type)}),V.visibility==="private"&&o.jsx(Ci,{size:13})]}),o.jsx("strong",{children:V.title}),o.jsxs("small",{children:[lg(V.status)," · ",np(V.updated_at)," · ",V.comment_count," comments"]})]}),V.post_type==="feature"&&o.jsxs("span",{className:"support-vote-count",children:[o.jsx(jx,{size:14})," ",V.vote_count]})]},V.id)})]}),o.jsx("section",{className:"support-post-detail","aria-label":"Support post detail",children:ae?o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"support-detail-head",children:[o.jsxs("div",{className:"support-detail-badges",children:[o.jsx("span",{className:"support-product-badge",children:cg(g,ae.product_id)}),o.jsx("span",{className:"support-type-badge",children:jb(ae.post_type)}),o.jsx("span",{className:`support-status-badge status-${ae.status}`,children:lg(ae.status)}),ae.visibility==="private"&&o.jsxs("span",{className:"support-private-badge",children:[o.jsx(Ci,{size:13})," Private"]})]}),o.jsxs("div",{className:"support-detail-actions",children:[Ue&&o.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>ee(V=>!V),title:"Edit post",children:o.jsx(BC,{size:16})}),Te&&o.jsxs(o.Fragment,{children:[o.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>{Pn()},disabled:K==="pin",title:ae.is_pinned?"Unpin post":"Pin post",children:o.jsx(pb,{size:16})}),o.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>{Ra()},disabled:K==="lock",title:ae.is_locked?"Unlock post":"Lock post",children:o.jsx(Ci,{size:16})}),o.jsx("button",{className:"support-icon-button danger",type:"button",onClick:()=>{sa()},disabled:K==="hide",title:"Hide post",children:o.jsx(hb,{size:16})})]})]})]}),$?o.jsxs("form",{className:"support-edit-form",onSubmit:V=>{kt(V)},children:[o.jsx("input",{value:ae.title,onChange:V=>Xe({title:V.target.value}),minLength:3,maxLength:180,required:!0}),o.jsx("textarea",{value:ae.body,onChange:V=>Xe({body:V.target.value}),rows:9,required:!0}),o.jsxs("div",{className:"support-edit-actions",children:[o.jsxs("select",{value:ae.visibility,onChange:V=>Xe({visibility:V.target.value}),children:[o.jsx("option",{value:"public",children:"Public"}),o.jsx("option",{value:"private",children:"Private"})]}),o.jsxs("button",{className:"support-primary-button",type:"submit",disabled:K==="edit",children:[o.jsx(fo,{size:16})," Save changes"]})]})]}):o.jsxs(o.Fragment,{children:[o.jsx("h3",{children:ae.title}),o.jsx("div",{className:"support-detail-body",children:ae.body.split(`
10
+ `).map((V,Je)=>o.jsx("p",{children:V||" "},`${ae.id}-body-${Je}`))})]}),o.jsxs("div",{className:"support-detail-meta",children:[o.jsxs("span",{children:["Opened ",np(ae.created_at)]}),ae.app_version&&o.jsxs("span",{children:["Version ",ae.app_version]}),ae.platform&&o.jsx("span",{children:ae.platform}),ae.is_locked&&o.jsxs("span",{children:[o.jsx(Ci,{size:13})," Locked"]}),ae.is_pinned&&o.jsxs("span",{children:[o.jsx(pb,{size:13})," Pinned"]})]}),o.jsxs("div",{className:"support-detail-controls",children:[ae.post_type==="feature"&&o.jsxs("button",{className:`support-vote-button ${U.has(ae.id)?"voted":""}`,type:"button",onClick:()=>{Ut()},disabled:K==="vote",children:[o.jsx(zC,{size:16})," ",U.has(ae.id)?"Voted":"Vote"," ",o.jsx("b",{children:ae.vote_count})]}),Te&&o.jsxs("label",{className:"support-status-control",children:[o.jsx("span",{children:"Change status"}),o.jsx("select",{value:ae.status,onChange:V=>{Qt(V.target.value)},disabled:K==="status",children:(nM[ae.post_type]||[]).map(V=>o.jsx("option",{value:V,children:lg(V)},V))})]}),Te&&o.jsxs(o.Fragment,{children:[o.jsxs("select",{className:"support-status-control",value:Ee,onChange:V=>Ge(V.target.value),children:[o.jsx("option",{value:"",children:"Duplicate of..."}),z.filter(V=>V.id!==ae.id&&V.product_id===ae.product_id).map(V=>o.jsx("option",{value:V.id,children:V.title.slice(0,55)},V.id))]}),o.jsx("button",{className:"support-secondary-button",type:"button",onClick:()=>{ia()},disabled:!Ee||K==="duplicate",children:"Merge duplicate"})]})]}),E.length>0&&o.jsxs("div",{className:"support-attachments",children:[o.jsx("div",{className:"support-section-heading",children:o.jsxs("div",{children:[o.jsx("span",{children:"Attachments"}),o.jsxs("strong",{children:[E.length," file",E.length===1?"":"s"]})]})}),E.map(V=>o.jsxs("a",{href:V.signed_url,target:"_blank",rel:"noreferrer",children:[o.jsx(Sv,{size:14})," ",V.file_name,o.jsxs("small",{children:[Math.ceil(V.size_bytes/1024)," KB"]})]},V.id))]}),o.jsxs("div",{className:"support-comments",children:[o.jsxs("div",{className:"support-section-heading",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Discussion"}),o.jsxs("strong",{children:[k.length," comment",k.length===1?"":"s"]})]}),ae.is_locked&&o.jsxs("span",{className:"support-locked-label",children:[o.jsx(Ci,{size:14})," Locked"]})]}),k.length===0?o.jsx("p",{className:"support-muted",children:"No response yet. Keep the conversation focused on this request."}):o.jsx("div",{className:"support-comment-list",children:k.map(V=>o.jsxs("article",{className:`support-comment ${V.is_staff_answer?"staff":""} ${ae.accepted_comment_id===V.id?"accepted":""}`,children:[o.jsxs("div",{className:"support-comment-head",children:[o.jsx("strong",{children:V.is_staff_answer?"LiveDesk Support":V.author_id===t.user.id?"You":"Support user"}),V.is_staff_answer&&o.jsxs("span",{children:[o.jsx(Na,{size:13})," Staff answer"]}),ae.accepted_comment_id===V.id&&o.jsxs("span",{children:[o.jsx(Ba,{size:13})," Accepted"]}),o.jsx("time",{children:np(V.created_at)})]}),o.jsx("p",{children:V.body}),o.jsxs("div",{className:"support-comment-actions",children:[(t.user.id===ae.author_id||Te)&&ae.post_type==="question"&&ae.accepted_comment_id!==V.id&&o.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>{$n(V.id)},disabled:K===`accept-${V.id}`,children:[o.jsx(fo,{size:14})," Accept answer"]}),Te&&o.jsx("button",{className:"support-icon-button danger",type:"button",onClick:()=>{eM(V.id)},title:"Hide comment",children:o.jsx(hb,{size:14})})]})]},V.id))}),!ae.is_locked&&o.jsxs("form",{className:"support-comment-form",onSubmit:V=>{At(V)},children:[o.jsx("textarea",{value:B,onChange:V=>L(V.target.value),placeholder:"Add a focused reply...",rows:3}),o.jsxs("button",{className:"support-primary-button",type:"submit",disabled:K==="comment"||!B.trim(),children:[o.jsx(Yf,{size:15})," Reply"]})]})]})]}):o.jsxs("div",{className:"support-detail-empty",children:[o.jsx(qf,{size:28}),o.jsx("strong",{children:"Select a Support request"}),o.jsx("span",{children:"Its discussion and staff actions will appear here."})]})})]})]}):o.jsx("section",{className:"support-page support-auth-page",children:o.jsxs("div",{className:"support-empty-hero",children:[o.jsx("span",{className:"support-hero-icon",children:o.jsx(qf,{size:28})}),o.jsx("p",{className:"support-eyebrow",children:"LiveDesk Support"}),o.jsx("h2",{children:"Get help, report issues, and shape the product."}),o.jsx("p",{children:"Sign in to see the products attached to your account and submit a private or public request."}),o.jsxs("button",{className:"support-primary-button",type:"button",onClick:i,children:[o.jsx(Na,{size:17})," Sign in with Google"]})]})})}function ap(t){return!!t&&typeof t=="object"}function qx(t){let n=t;return ap(n)&&"data"in n&&(n=n.data),ap(n)&&"session"in n&&(n=n.session),!ap(n)||typeof n.access_token!="string"||!n.access_token||!ap(n.user)||typeof n.user.id!="string"||!n.user.id?null:n}function Eb(t){return t?.access_token?t.refresh_token?"":"refresh-token-required":"access-token-required"}const Vg=15e3;function iM(t,n=Vg){const r=Number(t),i=Number.isFinite(Number(n))?Number(n):Vg;return Math.max(250,Math.min(12e4,Math.trunc(Number.isFinite(r)?r:i)))}class Db extends Error{constructor(n){super(`LiveDesk Hub request timed out after ${n} ms.`),this.name="HubRequestTimeoutError",this.code="livedesk-hub-request-timeout",this.timeoutMs=n}}async function oM(t,n,r){const i=iM(n),l=new AbortController;let u=!1;const f=()=>{l.signal.aborted||l.abort(t?.reason)};t?.aborted?f():t?.addEventListener("abort",f,{once:!0});const h=setTimeout(()=>{u=!0,l.signal.aborted||l.abort(new Db(i))},i);try{return await r(l.signal)}catch(g){throw u?new Db(i):g}finally{clearTimeout(h),t?.removeEventListener("abort",f)}}function Op(t,n){if(t.current)return t.current;const r=Promise.resolve().then(n);return t.current=r,r.finally(()=>{t.current===r&&(t.current=null)}).catch(()=>{}),r}const Gf=5179,Dn=ho(`http://127.0.0.1:${Gf}`);function lM(t){const n=t.split(".").map(r=>Number(r));return n.length===4&&n.every(r=>Number.isInteger(r)&&r>=0&&r<=255)?n:[]}function cM(t){const n=t.trim().toLowerCase();return n==="localhost"||n==="127.0.0.1"||n==="::1"||n==="[::1]"}function uM(t){const n=t.trim().toLowerCase();return!n||n==="0.0.0.0"||n==="::"||n==="[::]"}function dM(t){const n=lM(t);return n.length===0?!1:n[0]===10||n[0]===172&&n[1]>=16&&n[1]<=31||n[0]===192&&n[1]===168}function fM(t){return t.includes(":")&&!t.startsWith("[")?`[${t}]`:t}function mM(t){const n=String(t||"").trim();if(!n)return null;const r=/^[a-z][a-z\d+.-]*:\/\//i.test(n)?n:`tcp://${n}`;try{const i=new URL(r),l=i.hostname.replace(/^\[|\]$/g,""),u=Number(i.port);return!l||!Number.isInteger(u)||u<1||u>65535||uM(l)?null:{host:l,port:u}}catch{return null}}function ho(t){const n=String(t||"").trim()||`http://127.0.0.1:${Gf}`,r=/^[a-z][a-z\d+.-]*:\/\//i.test(n)?n:`http://${n}`;try{const i=new URL(r);return i.port||(i.port=String(Gf)),i.hash="",i.search="",i.toString().replace(/\/+$/,"")}catch{return`http://127.0.0.1:${Gf}`}}function pM(t){const n=mM(t);return n?ho(`http://${fM(n.host)}:${Gf}`):""}function Ib(t){const r=[t?.endpoint,...Array.isArray(t?.endpoint_candidates)?t.endpoint_candidates:[]].map(i=>pM(String(i||""))).filter(Boolean);return[...new Set(r)]}function hd(t=Dn){if(!(typeof window>"u"||window.location.protocol!=="https:"))try{const n=new URL(t);if(n.protocol!=="http:")return;if(cM(n.hostname))return"loopback";if(dM(n.hostname))return"local"}catch{return}}function Yp(t,n=Dn){const r=new URL(t,ho(n));return r.protocol=r.protocol==="https:"?"wss:":"ws:",r.toString()}const Tp=new Map,rp=new Map;async function Lb(t=Dn,n=!1,r){const i=ho(t);n&&(Tp.delete(i),rp.delete(i));const l=Tp.get(i);if(l)return l;const u=rp.get(i);if(u)return u;const f=(async()=>{const h={cache:"no-store"};h.signal=r||AbortSignal.timeout(1e4);const g=hd(i);g&&(h.targetAddressSpace=g);const y=await fetch(`${i}/api/security/session`,h);if(y.status===404)return null;const w=await y.json().catch(()=>null);if(!y.ok||!w?.sessionId||!w.adminToken||!w.csrfToken)throw new Error(`${y.status} local-admin-session-unavailable`);const b={sessionId:String(w.sessionId),adminToken:String(w.adminToken),csrfToken:String(w.csrfToken)};return Tp.set(i,b),b})().finally(()=>rp.delete(i));return rp.set(i,f),f}function Xp(t=Dn){const n=Tp.get(ho(t));return n?["livedesk-v1",`livedesk-admin-${n.adminToken}`,`livedesk-admin-csrf-${n.csrfToken}`]:["livedesk-v1"]}async function tt(t,n,r=Dn){const i=ho(r),{timeoutMs:l=Vg,signal:u,...f}=n||{},g=["POST","PUT","PATCH","DELETE"].includes(String(f.method||"GET").toUpperCase())||["/api/security/audit","/api/privacy/inventory"].includes(t.split("?")[0]),y=hd(i);return oM(u,l,async w=>{let b=t==="/api/security/session"?null:await Lb(i,!1,w);for(let x=0;x<2;x+=1){const M=new Headers(f.headers||{});M.has("Content-Type")||M.set("Content-Type","application/json"),g&&b&&(M.set("X-LiveDesk-Admin-Session",b.adminToken),M.set("X-LiveDesk-Admin-CSRF",b.csrfToken));const k={...f,headers:M,cache:"no-store"};k.signal=w,y&&(k.targetAddressSpace=y);let N;try{N=await fetch(`${i}${t}`,k)}catch(T){throw!w.aborted&&y?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."):T}let E=null;try{E=await N.json()}catch(T){if(w.aborted)throw T}const I=E&&typeof E=="object"&&"error"in E?String(E.error||""):"";if(g&&x===0&&N.status===401&&I==="local-admin-session-required"){b=await Lb(i,!0,w);continue}if(!N.ok)throw new Error(`${N.status} ${I||N.statusText}`);return E}throw new Error("local-admin-session-unavailable")})}async function Wx({baseUrl:t=Dn,targetRole:n,previousRuntimePid:r=0,allowedStates:i=["running","waiting-auth"],timeoutMs:l=3e4}){const u=Date.now()+l;let f=null;for(;Date.now()<u;){try{const g=await tt("/api/runtime/status",void 0,t),y=String(g.role||"").toLowerCase(),w=String(g.state||"").toLowerCase(),b=Number(g.runtimePid||0),x=r>1?b>1&&b!==r:b>1;if(y===n&&i.map(M=>M.toLowerCase()).includes(w)&&x)return g}catch(g){f=g}await new Promise(g=>setTimeout(g,300))}const h=f instanceof Error?` ${f.message}`:"";throw new Error(`LiveDesk runtime did not become ${n} with a new process.${h}`)}function hM(t,n=120){if(typeof window>"u")return;const r=new URL(window.location.href);r.port=String(t),r.pathname="/",r.search="",r.hash="";const i=r.toString();let l=0;const u=()=>{fetch(i,{cache:"no-store",mode:"no-cors"}).then(()=>window.location.replace(i)).catch(()=>{if(l+=1,l>=n){window.location.replace(i);return}window.setTimeout(u,250)})};u()}function Gx(t){if(!t)return"-";const n=Date.now()-Date.parse(t);return Number.isFinite(n)?n<1e3?"now":n<6e4?`${Math.round(n/1e3)}s`:n<36e5?`${Math.round(n/6e4)}m`:`${Math.round(n/36e5)}h`:"-"}async function Rp(t){await navigator.clipboard.writeText(t)}function Vx({size:t=22}){return o.jsxs("svg",{width:t,height:t,viewBox:"0 0 28 28",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",children:[o.jsx("rect",{x:"2.5",y:"4",width:"14",height:"9",rx:"1.5",stroke:"currentColor",strokeWidth:"1.7",opacity:"0.42"}),o.jsx("path",{d:"M7 16v1.5h5",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",opacity:"0.42"}),o.jsx("rect",{x:"10.5",y:"2.5",width:"14",height:"9",rx:"1.5",stroke:"currentColor",strokeWidth:"1.7",opacity:"0.62"}),o.jsx("path",{d:"M15 14.5V16h5",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",opacity:"0.62"}),o.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"}),o.jsx("path",{d:"M12 21v1.5H9.5M16 21v1.5h2.5M9.5 22.5h9",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round"})]})}const Kx={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 approved commands on connected Clients through the Hub-hosted Codex Agent and LiveDesk permission controls."},Kg={en:Kx,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에서 LiveDesk 권한과 승인 범위 안의 명령을 실행합니다."},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 Agent が、LiveDesk の権限と承認の範囲内で接続中の 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:"Hub 的 Codex Agent 会在 LiveDesk 权限与批准范围内,对已连接的 Client 执行命令。"},"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:"Hub 的 Codex Agent 會在 LiveDesk 權限與核准範圍內,對已連線的 Client 執行命令。"},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:"El Codex Agent del Hub ejecuta comandos en los Clients conectados dentro de los permisos y aprobaciones de LiveDesk."},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:"Le Codex Agent du Hub exécute des commandes sur les Clients connectés selon les permissions et approbations de LiveDesk."},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:"Der Codex Agent des Hubs führt Befehle auf verbundenen Clients innerhalb der LiveDesk-Berechtigungen und Freigaben 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:"O Codex Agent do Hub executa comandos nos Clients conectados dentro das permissões e aprovações do LiveDesk."},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:"Il Codex Agent dell’Hub esegue comandi sui Client connessi entro i permessi e le approvazioni di LiveDesk."},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:"Codex Agent di Hub menjalankan perintah pada Client terhubung sesuai izin dan persetujuan LiveDesk."},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:"Codex Agent trên Hub chạy lệnh trên các Client đã kết nối trong phạm vi quyền và phê duyệt của LiveDesk."},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 Agent บน Hub เรียกใช้คำสั่งบน Client ที่เชื่อมต่อภายใต้สิทธิ์และการอนุมัติของ LiveDesk"},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:"Hub का Codex Agent LiveDesk permissions और approvals के भीतर जुड़े Clients पर commands चलाता है।"},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 Agent على Hub الأوامر في Clients المتصلين ضمن صلاحيات وموافقات LiveDesk."},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 Codex Agent, bağlı Client’larda LiveDesk izinleri ve onayları kapsamında komut çalıştırır."}};function Zp(t){const n=t?[t]:typeof navigator>"u"?["en"]:navigator.languages?.length?navigator.languages:[navigator.language];for(const r of n){const i=String(r||"").trim(),l=i.toLowerCase();if(!l)continue;if(l.startsWith("zh-tw")||l.startsWith("zh-hk"))return"zh-TW";if(l.startsWith("zh"))return"zh";if(l.startsWith("pt"))return"pt-BR";const u=l.split("-")[0];if(Kg[i])return i;if(Kg[u])return u}return"en"}function Hp(t,n){const r=Zp(n);return Kg[r]?.[t]||Kx[t]}function Qg(t,n,r){return`${t}
11
+ ${Hp(n,r)}`}const Qx={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"},gM={en:Qx,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"}},Yx={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"},vM={en:Yx,ko:{eyebrow:"컴퓨터 역할",title:"이 컴퓨터를 Hub로 사용할까요?",description:"Hub는 Client 컴퓨터를 연결하고 관리합니다.",restartNotice:"다른 컴퓨터가 Hub라면 이 컴퓨터가 새 Hub가 됩니다.",cancel:"취소",confirm:"Hub로 설정",closeLabel:"Hub 설정 확인 닫기"}};function yM(t){const n=Zp(t);return gM[n]||Qx}function bM(t){const n=Zp(t);return vM[n]||Yx}function wM(t=[]){return[...new Set(t.filter(n=>typeof n=="string").map(n=>n.trim()).filter(Boolean))]}function xM(t=[],n=new Set){return t.find(r=>!n.has(r))||""}const SM=new Set(["supabase-session-required"]),_b=new Map([["auth-provider-unavailable","Google sign-in is temporarily unavailable. Try again in a moment."],["auth-provider-delayed","Google sign-in is taking longer than expected. Try again in a moment."],["refresh-token-required","Sign in again to finish setting up this computer."],["access-token-required","Sign in again to continue."],["google-authorization-url-missing","Google sign-in could not start. Try again."],["client-google-sign-in-unavailable","Google sign-in is temporarily unavailable. Try again in a moment."],["client-google-callback-unavailable","Google sign-in could not finish. Try again."]]);function CM(t,{authenticated:n=!1}={}){const r=String(t||"").trim();return!r||SM.has(r)?"":_b.has(r)?_b.get(r):r.startsWith("supabase-user-verification-failed:")?"LiveDesk could not verify this sign-in. Sign in again.":r.startsWith("session-persistence-failed:")?"LiveDesk could not save this sign-in. Sign in again.":/^[a-z0-9]+(?:[-_:][a-z0-9]+)+(?:\s*\[.*\])?$/i.test(r)?n?"LiveDesk is still trying to connect. It will retry automatically.":"LiveDesk could not finish this action. Try again.":r}const kM=[{id:"docs",label:"Doc",icon:Pp},{id:"support",label:"Support",icon:qf},{id:"pricing",label:"Pricing",icon:Wf},{id:"settings",label:"Settings",icon:Cv}],Pb=[0,1e3,2e3,5e3,1e4,2e4,3e4],ug="livedesk.client.pending-hub-role-switch";function MM(t){return t?.authRequired===!0||t?.error==="role-change-auth-required"?!0:/sign in again|refresh-token-required|invalid refresh token/i.test(`${t?.error||""} ${t?.message||""}`)}function AM(t=""){const n=t.trim().replace(/\/+$/,"");return n||(typeof window>"u"?"":window.location.port==="5179"?window.location.origin:"http://127.0.0.1:5179")}async function Yc(t,n=!1){const r=n?"":sessionStorage.getItem("livedesk.client.csrf");if(r)return r;const i=await fetch(`${t}/api/runtime/status`,{cache:"no-store"}),l=await i.json().catch(()=>({}));if(!i.ok)throw new Error(l.error||`Client runtime returned HTTP ${i.status}.`);const u=String(l.csrfToken||"");return u&&sessionStorage.setItem("livedesk.client.csrf",u),u}function Yg(t){return`${Math.max(0,Math.min(100,Number(t||0))).toFixed(0)}%`}function dg(t){return Number.isFinite(t)?`${Math.max(0,Math.min(100,Number(t))).toFixed(0)}%`:"—"}function Xx(t){return Number.isFinite(t)?Yg(Number(t)):"0%"}function iu(t){const n=Number(t);return!Number.isFinite(n)||n<0?"—":n>=1024**4?`${(n/1024**4).toFixed(n>=10*1024**4?0:1)} TB`:n>=1024**3?`${(n/1024**3).toFixed(n>=10*1024**3?0:1)} GB`:`${(n/1024**2).toFixed(0)} MB`}function Fb(t){const n=Math.max(0,Number(t||0));return n>=1024**3?`${(n/1024**3).toFixed(1)} GB/s`:n>=1024**2?`${(n/1024**2).toFixed(1)} MB/s`:n>=1024?`${(n/1024).toFixed(1)} KB/s`:`${n.toFixed(0)} B/s`}function NM(t,n){const r=Number(t||0)/1073741824,i=Number(n||0)/1024**3;return i>0?`${r.toFixed(1)} / ${i.toFixed(1)} GB`:"Checking..."}function TM(t,n){return!Number.isFinite(n)||Number(n)<=0?"Dedicated memory unavailable":Number.isFinite(t)?`${iu(t)} / ${iu(n)}`:`${iu(n)} available`}function RM(t){const n=Math.max(0,Math.floor(Number(t||0)/60)),r=Math.floor(n/1440),i=Math.floor(n%1440/60),l=n%60;return r>0?`${r}d ${i}h`:i>0?`${i}h ${l}m`:`${l}m`}function sp({icon:t,label:n,value:r,detail:i,percent:l}){return o.jsxs("article",{className:"client-resource-metric",children:[o.jsxs("div",{className:"client-resource-metric-head",children:[o.jsx(t,{size:17}),o.jsx("span",{children:n}),o.jsx("strong",{children:r})]}),o.jsx("small",{title:i,children:i}),o.jsx("i",{"aria-hidden":"true",children:o.jsx("b",{style:{width:Xx(l)}})})]})}function jM(t,n){const r=t?.user.user_metadata||{},i=r.full_name||r.name||r.preferred_username||t?.user.email||t?.user.id||n?.userName||n?.auth?.name||n?.userEmail||n?.userId||"Account";return String(i).trim()||"Account"}function EM(t,n){const r=t?.user.user_metadata||{};return wM([r.avatar_url,r.picture,n?.userAvatarUrl,n?.auth?.avatarUrl])}function DM({page:t,status:n}){const i={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."}}[t];return o.jsxs("section",{className:"client-service-page",children:[o.jsx("span",{className:"client-unified-section-label",children:i.label}),o.jsx("h2",{children:i.title}),o.jsx("p",{children:i.body}),o.jsxs("div",{className:"client-service-page-card",children:[t==="docs"&&o.jsxs(o.Fragment,{children:[o.jsx("strong",{children:"Automatic connection"}),o.jsx("span",{children:"Start LiveDesk. This computer signs in, finds the Hub, and becomes available without another action."})]}),t==="pricing"&&o.jsxs(o.Fragment,{children:[o.jsx("strong",{children:"One plan, managed at the Hub"}),o.jsx("span",{children:"Computer access follows the account and plan used by the Hub."})]}),t==="settings"&&o.jsxs(o.Fragment,{children:[o.jsx("strong",{children:"Saved sign-in"}),o.jsx("span",{children:n?.auth?.persisted?"Enabled on this computer":"Sign in once to enable automatic reconnection"})]})]})]})}function IM({session:t,status:n,pin:r,error:i,roleChangeMessage:l,videoAccelerationBusy:u,slotInput:f,slotBusy:h,onSignIn:g,onPinChange:y,onSubmitPin:w,onSlotInputChange:b,onSaveSlot:x,onEnableVideoAcceleration:M}){const k=n?.connectionState==="connected",N=l?"":CM(i||n?.lastError,{authenticated:!!(t||n?.authenticated)}),E=n?.videoAcceleration,I=u||E?.busy||E?.state==="installing",T=E?.ready?`${E.encoder||"H.264"} · ${E.driver||"VAAPI"}`:I?"Setting up…":E?.message||"Setup available",P=n?.system?.memoryTotalBytes?Number(n.system.memoryUsedBytes||0)/n.system.memoryTotalBytes*100:0,U=n?.system?.gpus||[],F=U.find($=>Number.isFinite($.usagePercent)||Number.isFinite($.memoryTotalBytes))||U[0],Y=Number.isFinite(F?.usagePercent)?Number(F?.usagePercent):null,D=Number.isFinite(F?.memoryTotalBytes)&&Number(F?.memoryTotalBytes)>0&&Number.isFinite(F?.memoryUsedBytes)?Number(F?.memoryUsedBytes)/Number(F?.memoryTotalBytes)*100:null,K=n?.system?.disks||[],ne=n?.system?.network,q=!!ne?.sampledAt,O=ne?.interfaces||[],W=[...new Set(O.map($=>$.name).filter(Boolean))],ce=O.map($=>$.address).filter(Boolean);return o.jsxs("section",{className:"client-home-page",children:[o.jsxs("header",{className:"client-home-heading",children:[o.jsxs("div",{children:[o.jsx("p",{className:"client-unified-eyebrow",children:"THIS COMPUTER"}),o.jsx("h2",{children:n?.deviceName||"This Computer"})]}),o.jsxs("span",{className:`client-unified-role-chip ${k?"connected":""}`,children:[o.jsx(Ta,{size:15})," ",k?"Online":"Connecting"]})]}),o.jsxs("div",{className:"client-home-layout",children:[o.jsxs("section",{className:"client-main-surface","aria-label":"Client computer",children:[o.jsxs("div",{className:"client-main-surface-head",children:[o.jsxs("div",{children:[o.jsx("span",{className:"client-unified-section-label",children:"SYSTEM STATUS"}),o.jsx("strong",{children:"Hardware at a glance"})]}),o.jsxs("small",{children:[o.jsx(Lx,{size:14})," Uptime ",RM(n?.system?.uptimeSeconds)]})]}),o.jsxs("div",{className:"client-system-dashboard",children:[o.jsxs("section",{className:"client-performance-panel","aria-label":"Performance",children:[o.jsxs("div",{className:"client-system-subhead",children:[o.jsxs("div",{children:[o.jsx("span",{className:"client-unified-section-label",children:"PERFORMANCE"}),o.jsx("strong",{children:"Live resources"})]}),o.jsx("small",{children:"Live updates"})]}),o.jsxs("div",{className:"client-live-metrics",children:[o.jsx(sp,{icon:gb,label:"CPU",value:Yg(n?.system?.cpuUsagePercent),detail:n?.system?.cpuLogicalCores?`${n.system.cpuLogicalCores} logical cores · Current processor usage`:"Current processor usage",percent:n?.system?.cpuUsagePercent}),o.jsx(sp,{icon:WC,label:"Memory",value:Yg(P),detail:NM(n?.system?.memoryUsedBytes,n?.system?.memoryTotalBytes),percent:P}),o.jsx(sp,{icon:GC,label:"GPU",value:dg(Y),detail:F?.name||(n?.system?.hardwareCollecting?"Detecting graphics hardware…":"Graphics usage unavailable"),percent:Y}),o.jsx(sp,{icon:mo,label:"VRAM",value:dg(D),detail:TM(F?.memoryUsedBytes,F?.memoryTotalBytes),percent:D})]})]}),o.jsxs("section",{className:"client-storage-panel","aria-label":"Local storage",children:[o.jsxs("div",{className:"client-system-subhead",children:[o.jsxs("div",{children:[o.jsx("span",{className:"client-unified-section-label",children:"STORAGE"}),o.jsx("strong",{children:"Local drives"})]}),o.jsx("small",{children:K.length>0?`${K.length} ${K.length===1?"drive":"drives"}`:n?.system?.hardwareCollecting?"Detecting…":"Unavailable"})]}),o.jsxs("div",{className:"client-disk-list",children:[K.map($=>o.jsxs("article",{className:"client-disk-row",children:[o.jsxs("div",{className:"client-disk-row-head",children:[o.jsxs("span",{children:[o.jsx(su,{size:16}),o.jsx("strong",{children:$.mount||"Disk"}),o.jsx("small",{children:$.name||"Local disk"})]}),o.jsx("strong",{children:dg($.usedPercent)})]}),o.jsxs("small",{children:[iu($.freeBytes)," free · ",iu($.totalBytes)," total"]}),o.jsx("i",{"aria-hidden":"true",children:o.jsx("b",{style:{width:Xx($.usedPercent)}})})]},`${$.mount}-${$.name||""}`)),K.length===0&&o.jsxs("div",{className:"client-disk-empty",children:[o.jsx(su,{size:18}),o.jsx("span",{children:n?.system?.hardwareCollecting?"Detecting local drives…":"Storage information is not available."})]})]})]}),o.jsxs("section",{className:"client-network-panel","aria-label":"Network activity",children:[o.jsxs("div",{className:"client-system-subhead",children:[o.jsxs("div",{children:[o.jsx("span",{className:"client-unified-section-label",children:"NETWORK"}),o.jsx("strong",{children:"Live traffic"})]}),o.jsx("small",{children:W.length>0?W.join(", "):"Detecting adapter"})]}),o.jsxs("div",{className:"client-network-live",children:[o.jsxs("div",{className:"client-network-adapter",children:[o.jsx(wd,{size:18}),o.jsxs("span",{children:[o.jsx("strong",{children:W.join(", ")||"Network"}),o.jsx("small",{children:ce.join(" / ")||"Checking active connection"})]})]}),o.jsxs("div",{className:"client-network-rate download",children:[o.jsx(VC,{size:17}),o.jsxs("span",{children:[o.jsx("small",{children:"Receive"}),o.jsx("strong",{children:Fb(q?ne?.receiveBytesPerSecond:void 0)})]})]}),o.jsxs("div",{className:"client-network-rate upload",children:[o.jsx(KC,{size:17}),o.jsxs("span",{children:[o.jsx("small",{children:"Send"}),o.jsx("strong",{children:Fb(q?ne?.sendBytesPerSecond:void 0)})]})]}),o.jsx("small",{className:"client-network-total",children:q?`Total ${iu(ne?.receivedBytes)} received / ${iu(ne?.sentBytes)} sent`:"Traffic has not been measured yet."})]})]})]})]}),o.jsxs("aside",{className:"client-connection-panel",children:[o.jsx("span",{className:"client-unified-section-label",children:"LIVEDESK SERVICES"}),o.jsx("h3",{children:k?"Connected to the Hub":n?.authenticated?"Finding the Hub":"Connect this computer"}),k?o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"client-unified-copy",children:"This computer is available from the LiveDesk Hub."}),o.jsxs("div",{className:"client-service-status-list",children:[o.jsxs("div",{children:[o.jsx(Ta,{size:17}),o.jsxs("span",{children:[o.jsx("strong",{children:"Screen sharing"}),o.jsx("small",{children:n?.permissions?.screenCapture?"Active":"Waiting"})]})]}),o.jsxs("div",{children:[o.jsx(Na,{size:17}),o.jsxs("span",{children:[o.jsx("strong",{children:"Remote control"}),o.jsx("small",{children:n?.permissions?.remoteInput?"Available":"Unavailable"})]})]}),o.jsxs("div",{children:[o.jsx(pd,{size:17}),o.jsxs("span",{children:[o.jsx("strong",{children:"File delivery"}),o.jsx("small",{children:n?.permissions?.files?"Ready to receive":"Unavailable"})]})]}),o.jsxs("div",{children:[o.jsx(Zl,{size:17}),o.jsxs("span",{children:[o.jsx("strong",{children:"Computer audio"}),o.jsx("small",{children:n?.permissions?.audio?"Available":"Unavailable"})]})]})]})]}):o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"client-unified-copy",children:n?.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."}),!t&&!n?.authenticated?o.jsxs("button",{className:"client-unified-primary",type:"button",onClick:g,children:[o.jsx(lu,{size:16})," Sign in with Google"]}):o.jsxs("p",{className:"client-unified-success",children:[o.jsx(Ba,{size:16})," Signed in as ",t?.user.email||t?.user.id||n?.userEmail||n?.userId||"saved account"]}),o.jsxs("div",{className:"client-unified-pin-row",children:[o.jsx(QC,{size:16}),o.jsx("input",{value:r,onChange:$=>y($.target.value),placeholder:"6-digit Hub PIN",inputMode:"numeric","aria-label":"6-digit Hub PIN"}),o.jsx("button",{className:"client-unified-secondary",type:"button",onClick:w,disabled:r.length!==6,children:"Connect"})]})]}),E?.supported&&o.jsxs("div",{className:`client-video-acceleration state-${E.ready?"ready":E.state||"setup-required"}`,children:[o.jsx(gb,{size:17}),o.jsxs("span",{children:[o.jsx("strong",{children:"Hardware video"}),o.jsx("small",{children:T})]}),!E.ready&&E.canInstall&&o.jsx("button",{type:"button",onClick:M,disabled:I,title:"Install and verify Linux FFmpeg hardware video support",children:I?"Setting up":"Enable"})]}),N&&o.jsxs("p",{className:"client-unified-error",role:"alert",children:[o.jsx(Ix,{size:15})," ",N]}),l&&o.jsx("p",{className:"client-unified-success",children:l}),o.jsxs("div",{className:"client-slot-setting",children:[o.jsxs("label",{htmlFor:"client-slot-number",children:[o.jsx("span",{children:"Slot"}),o.jsx("input",{id:"client-slot-number",value:f,onChange:$=>b($.target.value),inputMode:"numeric",pattern:"[0-9]*",placeholder:"1-999","aria-label":"Wall slot number",disabled:!k||h})]}),o.jsxs("button",{type:"button",onClick:x,disabled:!k||h||!f,"aria-label":"Save slot number",title:"Save slot number",children:[o.jsx(Cv,{size:17}),o.jsx("span",{children:h?"Saving":"Set"})]})]})]})]})]})}function LM({runtimeBaseUrl:t=""}){const[n,r]=d.useState(null),[i,l]=d.useState(null),[u,f]=d.useState(!1),[h,g]=d.useState(""),[y,w]=d.useState(""),[b,x]=d.useState(""),[M,k]=d.useState(!1),[N,E]=d.useState(()=>typeof window<"u"&&sessionStorage.getItem(ug)==="hub"),[I,T]=d.useState(!1),[P,U]=d.useState(""),[F,Y]=d.useState(!1),[D,K]=d.useState(null),[ne,q]=d.useState(!1),[O,W]=d.useState("computer"),[ce,$]=d.useState(!1),ee=d.useRef(null),B=d.useRef(null),L=d.useRef(!1),oe=d.useRef(null),be=d.useRef(!1),H=d.useRef(!1),me=d.useRef(!1),ue=d.useRef(!1),Ce=d.useRef(0),Me=d.useRef(!1),Ne=d.useMemo(()=>AM(t),[t]),He=d.useMemo(()=>jM(i,n),[i,n]),Ve=d.useMemo(()=>EM(i,n),[i,n]),ie=JSON.stringify(Ve),[Oe,$e]=d.useState(()=>new Set),qe=xM(Ve,Oe),vt=He.slice(0,1).toUpperCase()||"L";d.useEffect(()=>{$e(new Set)},[ie]);const xe=d.useCallback(z=>{$e(ae=>{if(!z||ae.has(z))return ae;const Te=new Set(ae);return Te.add(z),Te})},[]),he=d.useCallback(async()=>{if(w(""),window.liveDesk?.auth?.signInWithGoogle){const z=await window.liveDesk.auth.signInWithGoogle();return z?.ok===!1?(w(z.error||"LiveDesk could not open the system browser for Google sign-in."),!1):!0}return window.location.assign(`${Ne}/auth/google`),!0},[Ne]),pe=d.useCallback(()=>{sessionStorage.setItem(ug,"hub"),E(!0)},[]),Ae=d.useCallback(()=>{sessionStorage.removeItem(ug),E(!1),me.current=!1},[]),Se=d.useCallback(async()=>{H.current||(H.current=!0,w("Your saved Google sign-in is incomplete. LiveDesk is reopening sign-in once to repair it."),await Pt.auth.signOut({scope:"local"}).catch(()=>{}),l(null),await he()||(H.current=!1))},[he]),Pe=d.useCallback(async z=>{const ae=Eb(z);if(ae)throw new Error(ae);if(L.current)return!1;L.current=!0;try{const Te=await window.liveDesk?.auth?.persistSession?.(z);if(Te?.ok===!1)throw new Error(Te.error||"LiveDesk could not validate the desktop session.");for(let Ue=0;Ue<2;Ue+=1){const Xe=await Yc(Ne,Ue>0),at=await fetch(`${Ne}/api/auth/session`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":Xe},signal:AbortSignal.timeout(1e4),body:JSON.stringify({accessToken:z.access_token,refreshToken:z.refresh_token,expiresAt:z.expires_at,user:{id:z.user.id,email:z.user.email}})}),kt=await at.json().catch(()=>({}));if(at.status===403&&Ue===0){sessionStorage.removeItem("livedesk.client.csrf");continue}if(!at.ok)throw new Error(kt.error||`Client runtime returned HTTP ${at.status}.`);return w(""),!0}throw new Error("Client runtime rejected the session transfer.")}finally{L.current=!1}},[Ne]),Qe=d.useCallback(()=>{const z=oe.current;if(z)return z;const ae=(async()=>{try{const Te=await fetch(`${Ne}/api/client/status`,{cache:"no-store",signal:AbortSignal.timeout(1500)}),Ue=await Te.json().catch(()=>({}));if(!Te.ok)throw new Error(Ue.error||`Client runtime returned HTTP ${Te.status}.`);if(Ue.csrfToken&&sessionStorage.setItem("livedesk.client.csrf",Ue.csrfToken),String(Ue.role||"").toLowerCase()==="hub"){if(ue.current)return;throw new Error("This computer is assigned to the Hub role.")}if(ue.current)return;r(Ue)}catch(Te){if(ue.current)return;w(Te instanceof Error?Te.message:String(Te))}})();return oe.current=ae,ae.finally(()=>{oe.current===ae&&(oe.current=null)}),ae},[Ne]);d.useEffect(()=>{let z=!1,ae=null;const Te=async()=>{await Qe(),z||(ae=window.setTimeout(()=>{Te()},2e3))};return Te(),()=>{z=!0,ae!==null&&window.clearTimeout(ae)}},[Qe]),d.useEffect(()=>{if(Me.current)return;const z=Number(n?.slotNumber||0);U(z>0?String(z):"")},[n?.slotNumber]),d.useEffect(()=>{if(!D)return;const z=window.setTimeout(()=>K(null),5e3);return()=>window.clearTimeout(z)},[D]);const Z=d.useCallback(async()=>{const z=Date.now();if(!(!n?.authenticated||n.connectionState==="connected"||!["waiting","reconnecting"].includes(String(n.agent?.state||""))||z-Ce.current<4e3)){Ce.current=z;try{const ae=await fetch(`${Ne}/api/client/reconnect`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await Yc(Ne)},body:JSON.stringify({onlyIfWaiting:!0,reason:"app-active"})});if(!ae.ok)throw new Error(`Client reconnect returned HTTP ${ae.status}.`);await Qe()}catch(ae){w(ae instanceof Error?ae.message:String(ae))}}},[Ne,Qe,n]);d.useEffect(()=>{const z=()=>{Z()},ae=()=>{Z()},Te=()=>{document.visibilityState==="visible"&&Z()};return window.addEventListener("online",z),window.addEventListener("focus",ae),document.addEventListener("visibilitychange",Te),()=>{window.removeEventListener("online",z),window.removeEventListener("focus",ae),document.removeEventListener("visibilitychange",Te)}},[Z]),d.useEffect(()=>{if(!u||!n||!i?.access_token||n.authenticated)return;if(Eb(i)==="refresh-token-required"){Se().catch(Xe=>{H.current=!1,w(Xe instanceof Error?Xe.message:String(Xe))});return}let z=!1,ae,Te=0;const Ue=async()=>{if(z)return;try{const at=await Pe(i);if(await Qe(),at)return}catch(at){w(at instanceof Error?at.message:String(at))}if(z)return;const Xe=Pb[Math.min(Te,Pb.length-1)];Te+=1,ae=window.setTimeout(()=>{Ue()},Xe)};return Ue(),()=>{z=!0,ae!==void 0&&window.clearTimeout(ae)}},[u,Qe,Se,i,n,Pe]),d.useEffect(()=>{const z=new URLSearchParams(window.location.search),ae=z.get("auth_error");if(!ae)return;Ae(),k(!1),x(""),w(ae),z.delete("auth_error");const Te=z.toString();window.history.replaceState(window.history.state,"",`${window.location.pathname}${Te?`?${Te}`:""}${window.location.hash}`)},[Ae]),d.useEffect(()=>{let z=!0;if(!window.liveDesk?.auth)return l(null),f(!0),Qe(),()=>{z=!1};const ae=window.liveDesk?.auth?.onComplete?.(Ue=>{Ue.ok&&Ue.session?Pt.auth.setSession(Ue.session).catch(Xe=>w(Xe instanceof Error?Xe.message:String(Xe))):Ue.error&&(Ae(),k(!1),x(""),w(Ue.error))});(async()=>{try{const Ue=window.liveDesk?.auth?.getSession?await window.liveDesk.auth.getSession():await Pt.auth.getSession();if(!z)return;const Xe=qx(Ue);l(Xe),Qe()}catch(Ue){z&&w(Ue instanceof Error?Ue.message:String(Ue))}finally{z&&f(!0)}})();const{data:Te}=Pt.auth.onAuthStateChange((Ue,Xe)=>{z&&(l(Xe),f(!0),Qe())});return()=>{z=!1,ae?.(),Te.subscription.unsubscribe()}},[Ae,Qe]),d.useEffect(()=>{if(!u||!n||be.current||H.current||i||n.authenticated)return;const z=new URLSearchParams(window.location.search);if(!z.has("livedesk_launch"))return;be.current=!0,z.delete("livedesk_launch");const ae=z.toString();window.history.replaceState(window.history.state,"",`${window.location.pathname}${ae?`?${ae}`:""}${window.location.hash}`),he().catch(Te=>w(Te instanceof Error?Te.message:String(Te)))},[u,i,he,n]);const $t=async()=>{$(!1),window.liveDesk?.auth?.persistSession?(await Pt.auth.signOut({scope:"local"}),(await window.liveDesk.auth.persistSession(null))?.runtimeCleared===!1&&w("Signed out locally. The LiveDesk runtime could not be reached to clear its session.")):await fetch(`${Ne}/api/auth/session`,{method:"DELETE",headers:{"X-LiveDesk-CSRF":await Yc(Ne)}}).catch(()=>{}),l(null),await Qe()};d.useEffect(()=>{if(!ce)return;const z=Te=>{Te.target instanceof Element&&Te.target.closest(".account-popover, .rail-account")||$(!1)},ae=Te=>{Te.key==="Escape"&&$(!1)};return window.addEventListener("pointerdown",z),window.addEventListener("keydown",ae),()=>{window.removeEventListener("pointerdown",z),window.removeEventListener("keydown",ae)}},[ce]);const Ee=d.useCallback((z=!0)=>{M||(q(!1),z&&window.requestAnimationFrame(()=>B.current?.focus()))},[M]),Ge=d.useCallback(()=>{M||(B.current=document.activeElement instanceof HTMLElement?document.activeElement:null,x(""),q(!0))},[M]);d.useEffect(()=>{if(!ne)return;const z=window.requestAnimationFrame(()=>ee.current?.focus()),ae=Ue=>{Ue.target instanceof Element&&Ue.target.closest(".client-hub-switch-popover, .client-hub-switch-trigger")||Ee(!1)},Te=Ue=>{Ue.key==="Escape"&&Ee()};return window.addEventListener("pointerdown",ae),window.addEventListener("keydown",Te),()=>{window.cancelAnimationFrame(z),window.removeEventListener("pointerdown",ae),window.removeEventListener("keydown",Te)}},[Ee,ne]);const ze=async()=>{w("");try{const z=await fetch(`${Ne}/api/client/pin`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await Yc(Ne)},body:JSON.stringify({pin:h})}),ae=await z.json().catch(()=>({}));if(!z.ok||ae?.ok===!1)throw new Error(ae?.error||"PIN could not be accepted.");g(""),await Qe()}catch(z){w(z instanceof Error?z.message:String(z))}},Ft=d.useCallback(async()=>{ue.current=!1,k(!0),x("Switching this computer to Hub. LiveDesk will restart automatically."),w("");const z=Number(n?.runtimePid||0),ae=await fetch(`${Ne}/api/runtime/switch-role`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await Yc(Ne)},body:JSON.stringify({role:"hub"})}),Te=await ae.json().catch(()=>({}));if(!ae.ok||Te?.ok===!1){const Ue=Te?.message||Te?.error||`Role change failed with HTTP ${ae.status}.`;throw Object.assign(new Error(Ue),{authRequired:MM(Te)})}ue.current=!0,Ae(),x("Hub role accepted. LiveDesk is restarting this computer with the Hub Wall."),await Wx({baseUrl:Ne,targetRole:"hub",previousRuntimePid:z,allowedStates:["running"]}),window.location.reload()},[Ne,Ae,n?.runtimePid]),Ze=d.useCallback(async()=>{if(pe(),k(!0),x("Google sign-in is required. After sign-in, LiveDesk will continue switching to Hub automatically."),w(""),i?.access_token){await Pe(i),await Qe();return}if(!await he())throw new Error("LiveDesk could not start Google sign-in.")},[pe,Qe,i,he,Pe]),nt=d.useCallback(z=>{ue.current=!1,Ae(),x(""),w(z instanceof Error?z.message:String(z)),k(!1)},[Ae]),lt=async()=>{q(!1);try{if(!n?.authenticated){await Ze();return}await Ft()}catch(z){if(!!z?.authRequired)try{await Ze();return}catch(Te){nt(Te);return}nt(z)}};d.useEffect(()=>{!N||!u||n?.authenticated!==!0||me.current||(me.current=!0,k(!0),x("Google sign-in completed. Continuing the Hub switch now."),Ft().catch(z=>{nt(z)}))},[u,Ft,nt,N,n?.authenticated]);const Tt=async()=>{if(F)return;const z=Number(P);if(!Number.isInteger(z)||z<1||z>999){K({kind:"error",message:"Enter a slot number from 1 to 999."});return}Y(!0),K(null);try{const ae=await fetch(`${Ne}/api/client/slot`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await Yc(Ne)},body:JSON.stringify({slotNumber:z})}),Te=await ae.json().catch(()=>({}));if(!ae.ok||Te.ok===!1){if(Te.error==="slot-taken"){const Ue=Te.conflict?.deviceName||Te.conflict?.hostname||Te.conflict?.deviceId||"another computer";throw new Error(`Slot ${String(z).padStart(3,"0")} is already used by ${Ue}.`)}throw new Error(Te.error||`Slot update failed with HTTP ${ae.status}.`)}Me.current=!1,U(String(z)),r(Te),K({kind:"success",message:`Slot ${String(z).padStart(3,"0")} saved. LiveDesk is reconnecting this Client.`})}catch(ae){K({kind:"error",message:ae instanceof Error?ae.message:String(ae)})}finally{Y(!1),await Qe()}},Mt=async()=>{if(!I){T(!0),w("");try{const z=await fetch(`${Ne}/api/client/video-acceleration/install`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await Yc(Ne)},body:JSON.stringify({confirm:!0})}),ae=await z.json().catch(()=>({}));if(r(ae),!z.ok||ae.videoAcceleration?.ready!==!0)throw new Error(ae.videoAcceleration?.error||ae.error||"Linux hardware video setup did not complete.")}catch(z){w(z instanceof Error?z.message:String(z))}finally{T(!1),await Qe()}}},rt=!!(n?.authenticated||i),dt=d.useMemo(()=>Zp(),[]),G=Hp("switch-to-hub",dt),ge=Hp("client",dt),De=yM(dt);return o.jsxs("main",{className:"app-shell client-unified-shell",children:[o.jsxs("aside",{className:"tool-rail","aria-label":"LiveDesk Client tools",children:[o.jsx("div",{className:"rail-brand",title:"LiveDesk",children:o.jsx(Vx,{size:25})}),o.jsx("nav",{className:"rail-tools","aria-label":"Client navigation",children:o.jsxs("div",{className:"client-main-tool-slot",children:[o.jsxs("button",{className:"rail-tool client-main-tool client-hub-tool client-hub-switch-trigger accent-blue",type:"button",onClick:Ge,disabled:M,"aria-busy":M,"aria-expanded":ne,"aria-haspopup":"dialog","aria-controls":ne?"client-hub-switch-popover":void 0,"aria-label":`Hub. ${G}`,"data-tooltip":ne?void 0:Qg("Hub","switch-to-hub",dt),children:[o.jsx(mo,{size:19}),o.jsx("span",{children:M?"Switching…":"Hub"})]}),o.jsxs("button",{className:`rail-tool client-main-tool accent-blue ${O==="computer"?"active":""}`,type:"button",onClick:()=>W("computer"),"aria-current":O==="computer"?"page":void 0,"aria-label":`Client. ${ge}`,"data-tooltip":Qg("Client","client",dt),children:[o.jsx(Ta,{size:19}),o.jsx("span",{children:"Client"})]})]})}),o.jsxs("div",{className:"rail-footer",children:[kM.map(z=>{const ae=z.icon;return o.jsxs("button",{className:`rail-tool compact ${O===z.id?"active":""}`,type:"button",onClick:()=>W(z.id),title:z.label,children:[o.jsx(ae,{size:18}),o.jsx("span",{children:z.label})]},z.id)}),o.jsxs("button",{className:`rail-account ${rt?"signed-in":""}`,type:"button",onClick:()=>$(z=>!z),"aria-expanded":ce,"aria-haspopup":"dialog",title:rt?"Account":"Sign in",children:[rt&&qe?o.jsx("img",{src:qe,alt:He,referrerPolicy:"no-referrer",onError:()=>xe(qe)},qe):rt?o.jsx("span",{className:"avatar-fallback",children:vt}):o.jsx(lu,{size:18}),o.jsx("span",{children:rt?"Account":"Sign in"})]})]})]}),ne&&o.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:[o.jsxs("header",{className:"client-hub-switch-head",children:[o.jsx("span",{className:"client-hub-switch-mark","aria-hidden":"true",children:o.jsx(mo,{size:19})}),o.jsx("span",{className:"client-hub-switch-eyebrow",children:De.eyebrow}),o.jsx("button",{className:"client-hub-switch-close",type:"button",onClick:()=>Ee(),"aria-label":De.closeLabel,children:o.jsx(hr,{size:17})})]}),o.jsx("h2",{id:"client-hub-switch-title",children:De.title}),o.jsx("p",{id:"client-hub-switch-description",children:De.description}),o.jsxs("p",{id:"client-hub-switch-restart",className:"client-hub-switch-notice",children:[o.jsx(Na,{size:16,"aria-hidden":"true"}),o.jsx("span",{children:De.restartNotice})]}),o.jsxs("div",{className:"client-hub-switch-actions",children:[o.jsx("button",{type:"button",onClick:()=>Ee(),children:De.cancel}),o.jsxs("button",{ref:ee,className:"primary",type:"button",onClick:()=>{lt()},disabled:M,children:[o.jsx(mo,{size:16}),De.confirm]})]})]}),ce&&o.jsxs("section",{className:"account-popover",role:"dialog","aria-label":"LiveDesk account",children:[o.jsxs("div",{className:"account-popover-head",children:[o.jsx("div",{className:"account-popover-avatar",children:rt&&qe?o.jsx("img",{src:qe,alt:He,referrerPolicy:"no-referrer",onError:()=>xe(qe)},qe):rt?o.jsx("span",{children:vt}):o.jsx(lu,{size:18})}),o.jsxs("div",{children:[o.jsx("strong",{children:rt?He:"Account"}),o.jsx("p",{children:i?.user.email||n?.userEmail||n?.userId||"Not signed in"})]})]}),o.jsxs("dl",{className:"account-popover-facts",children:[o.jsx("dt",{children:"User"}),o.jsx("dd",{children:i?.user.email||n?.userEmail||n?.userId||"Not signed in"}),o.jsx("dt",{children:"Runtime"}),o.jsx("dd",{children:n?"Local app ready":"Checking local app"}),o.jsx("dt",{children:"Session"}),o.jsx("dd",{children:n?.auth?.persisted?"Saved on this computer":rt?"Active for this run":"Not saved"}),o.jsx("dt",{children:"Role"}),o.jsx("dd",{children:"Client"})]}),rt?o.jsxs("button",{className:"account-popover-action",onClick:()=>{$t()},type:"button",children:[o.jsx(Dx,{size:16}),"Logout"]}):o.jsxs("button",{className:"account-popover-action primary",onClick:()=>{$(!1),he()},type:"button",children:[o.jsx(lu,{size:16}),"Sign in with Google"]})]}),o.jsxs("section",{className:"desk-stage client-unified-stage",children:[o.jsx("header",{className:"topbar",children:o.jsxs("div",{className:"brand",children:[o.jsx("span",{className:"brand-mark",children:o.jsx(Zl,{size:18})}),o.jsxs("div",{children:[o.jsx("h1",{children:"LiveDesk"}),o.jsx("p",{children:"Client workspace"})]})]})}),O==="support"?o.jsx("section",{className:"client-unified-page",children:o.jsx(Ux,{session:i,currentProductKey:"livedesk",appVersion:n?.appVersion||"",onSignIn:()=>{he()}})}):O!=="computer"?o.jsx("section",{className:"client-unified-page",children:o.jsx(DM,{page:O,status:n})}):o.jsx(IM,{session:i,status:n,pin:h,error:y,roleChangeMessage:b,videoAccelerationBusy:I,slotInput:P,slotBusy:F,onSignIn:()=>{he()},onPinChange:z=>g(z.replace(/\D/g,"").slice(0,6)),onSubmitPin:()=>{ze()},onSlotInputChange:z=>{Me.current=!0,U(z.replace(/\D/g,"").slice(0,3))},onSaveSlot:()=>{Tt()},onEnableVideoAcceleration:()=>{Mt()}})]}),D&&o.jsxs("div",{className:`client-side-toast ${D.kind}`,role:D.kind==="error"?"alert":"status",children:[D.kind==="error"?o.jsx(Ix,{size:18}):o.jsx(Ba,{size:18}),o.jsx("span",{children:D.message}),o.jsx("button",{type:"button",onClick:()=>K(null),"aria-label":"Dismiss notification",children:o.jsx(hr,{size:16})})]})]})}function Xl(t,n,r){if(r<0||n<0||n+r>t.length)throw new Error("Invalid LZO1X block: input overrun.")}function fg(t,n,r){let i=0;for(;Xl(t,n.inputIndex,1),t[n.inputIndex]===0;)i+=1,n.inputIndex+=1;const l=i*255+r+t[n.inputIndex];return n.inputIndex+=1,l}function ip(t,n,r,i){if(Xl(t,n.inputIndex,i),n.outputIndex+i>r.length)throw new Error("Invalid LZO1X block: output overrun.");r.set(t.subarray(n.inputIndex,n.inputIndex+i),n.outputIndex),n.inputIndex+=i,n.outputIndex+=i}function _M(t,n,r,i){const l=n-r;if(l<=0||i<=0)throw new Error("Invalid LZO1X block: invalid match distance.");let u=Math.min(l,i);for(t.set(t.subarray(r,r+u),n);u<i;){const f=Math.min(u,i-u);t.copyWithin(n+u,n,n+f),u+=f}return n+i}function Zx(t,n){if(!(t instanceof Uint8Array)||t.length<3||n<0)throw new Error("Invalid LZO1X block.");const r=new Uint8Array(n),i={inputIndex:0,outputIndex:0};let l=0,u=0;if(t[i.inputIndex]>=22){const f=t[i.inputIndex]-17;i.inputIndex+=1,ip(t,i,r,f),l=4}else t[i.inputIndex]>=18&&(l=t[i.inputIndex]-17,i.inputIndex+=1,ip(t,i,r,l));for(;;){Xl(t,i.inputIndex,1);const f=t[i.inputIndex];i.inputIndex+=1;let h,g;if((f&192)!==0)Xl(t,i.inputIndex,1),g=i.outputIndex-((t[i.inputIndex]<<3)+(f>>2&7)+1),i.inputIndex+=1,u=(f>>5)+1,h=f&3;else if((f&32)!==0){u=(f&31)+2,u===2&&(u+=fg(t,i,31)),Xl(t,i.inputIndex,2);const y=t[i.inputIndex]|t[i.inputIndex+1]<<8;i.inputIndex+=2,g=i.outputIndex-((y>>2)+1),h=y&3}else if((f&16)!==0){u=(f&7)+2,u===2&&(u+=fg(t,i,7)),Xl(t,i.inputIndex,2);const y=t[i.inputIndex]|t[i.inputIndex+1]<<8;if(i.inputIndex+=2,g=i.outputIndex-(((f&8)<<11)+(y>>2)),h=y&3,g===i.outputIndex)break;g-=16384}else if(l===0){let y=f+3;y===3&&(y+=fg(t,i,15)),ip(t,i,r,y),l=4;continue}else l!==4?(Xl(t,i.inputIndex,1),h=f&3,g=i.outputIndex-((f>>2)+(t[i.inputIndex]<<2)+1),i.inputIndex+=1,u=2):(Xl(t,i.inputIndex,1),h=f&3,g=i.outputIndex-((f>>2)+(t[i.inputIndex]<<2)+2049),i.inputIndex+=1,u=3);if(g<0||i.outputIndex+u+h>r.length)throw new Error("Invalid LZO1X block: lookbehind overrun.");i.outputIndex=_M(r,i.outputIndex,g,u),l=h,ip(t,i,r,h)}if(u!==3||i.inputIndex!==t.length||i.outputIndex!==r.length)throw new Error("Invalid LZO1X block: incomplete output.");return r}const Ob=16,Hb=8,PM=24*1024*1024,Jx=new Uint8Array(new Uint32Array([16909060]).buffer)[0]===4,Xg=new Uint32Array(65536);for(let t=0;t<Xg.length;t+=1){const n=Math.round((t>>11&31)*255/31),r=Math.round((t>>5&63)*255/63),i=Math.round((t&31)*255/31);Xg[t]=Jx?(n|r<<8|i<<16|4278190080)>>>0:(n<<24|r<<16|i<<8|255)>>>0}function Kl(t,n){return t[n]|t[n+1]<<8}function FM(t,n){const r=Number(n);if(!Number.isSafeInteger(r)||r<Ob||r>PM)throw new Error(`Invalid Mode 5 packet length: ${n}.`);const i=t instanceof Uint8Array?t:new Uint8Array(t),l=Zx(i,r);if(l[0]!==76||l[1]!==68||l[2]!==53||l[3]!==68)throw new Error("Invalid Mode 5 packet magic.");if(l[4]!==1)throw new Error(`Unsupported Mode 5 packet version: ${l[4]}.`);const u=(l[5]&1)!==0,f=Kl(l,6),h=Kl(l,8),g=Kl(l,10),y=Kl(l,12);if(f<=0||h<=0||f>3840||h>2160)throw new Error(`Invalid Mode 5 frame size: ${f}x${h}.`);if(g<=0||g>256||y>8192)throw new Error(`Invalid Mode 5 tile header: ${g}/${y}.`);const w=[];let b=Ob;for(let x=0;x<y;x+=1){if(b+Hb>l.length)throw new Error("Mode 5 tile header is truncated.");const M=Kl(l,b),k=Kl(l,b+2),N=Kl(l,b+4),E=Kl(l,b+6);b+=Hb;const I=N*E*2;if(N<=0||E<=0||N>g||E>g||M+N>f||k+E>h||b+I>l.length)throw new Error(`Invalid Mode 5 tile ${x}.`);w.push({x:M,y:k,width:N,height:E,pixels:l.subarray(b,b+I)}),b+=I}if(b!==l.length)throw new Error(`Mode 5 packet has ${l.length-b} trailing bytes.`);return{keyFrame:u,width:f,height:h,tileSize:g,tiles:w}}function OM(t,n,r,i){if(!(t instanceof Uint8ClampedArray)||t.length!==n*r*4||i.width!==n||i.height!==r)throw new Error("Mode 5 canvas state does not match the packet dimensions.");let l=n,u=r,f=0,h=0;const g=new Uint32Array(t.buffer,t.byteOffset,t.byteLength>>>2);for(const y of i.tiles){const w=Jx&&(y.pixels.byteOffset&1)===0?new Uint16Array(y.pixels.buffer,y.pixels.byteOffset,y.pixels.byteLength>>>1):null;let b=0;for(let x=0;x<y.height;x+=1){let M=(y.y+x)*n+y.x;for(let k=0;k<y.width;k+=1){const N=b<<1,E=w?w[b]:y.pixels[N]|y.pixels[N+1]<<8;g[M]=Xg[E],b+=1,M+=1}}l=Math.min(l,y.x),u=Math.min(u,y.y),f=Math.max(f,y.x+y.width),h=Math.max(h,y.y+y.height)}return i.tiles.length>0?{x:l,y:u,width:f-l,height:h-u}:null}const gr=new WeakMap,Bb=854,zb=480,HM=3840,BM=2160,zM=500,Zf=new WeakMap,Zg=new WeakMap,fu=new Set,cu=new Set,rc=new WeakMap,uu=new Set,xd=new WeakMap,Jg=new WeakMap,ev=new WeakMap,Bp=new WeakMap,tv=4,$M=2,UM=2,qM=2,WM=18,GM=0,VM=250,KM=80,QM=5,YM=150,XM=1200,ZM=18,JM=.65,eA=8,tA=16,nA=180,aA=3,Nv=2e3,eS=64,tS=32*1024*1024,rA=500,sA=new Uint8Array(0),Tv=250,iA=globalThis.LIVEDESK_ENABLE_CANVAS_VISUAL_SAMPLING===!0;let nS=1,aS=0,rS=0,nv=0,oA=0;const Hf=[];let nm=0,sS=0,iS,oS=0,lS,cS;function am(t,n){Hf.push({sequence:++oA,type:t,canvasId:xd.get(n)||0,observedAt:Date.now(),activeDecoderCount:fu.size,hardwareLeaseCount:cu.size,hardwareReleaseGeneration:nm}),Hf.length>256&&Hf.splice(0,Hf.length-256)}let rl={h264DecodeAcceleration:"prefer-hardware"};function lA(t){t.h264DecodeAcceleration&&(rl={...rl,h264DecodeAcceleration:t.h264DecodeAcceleration})}function cA(t){const{payload:n,...r}=t;return r}function uA(t){return{...t,payload:sA}}function uS(t){try{return t.paintIsCancelled()}catch{return!0}}function Jp(t,n){const r=t.pendingFrames.get(n);if(r)return t.pendingFrames.delete(n),t.pendingFrameBytes=Math.max(0,t.pendingFrameBytes-r.encodedByteLength),t.pendingFrames.size===0&&t.pendingTrimTimer!==null&&(window.clearTimeout(t.pendingTrimTimer),t.pendingTrimTimer=null),r}function dA(t){const n=t.pendingFrames.entries().next().value;return n?Jp(t,n[0]):void 0}function dS(t){t.pendingTrimTimer!==null&&(window.clearTimeout(t.pendingTrimTimer),t.pendingTrimTimer=null),t.pendingFrames.clear(),t.pendingFrameBytes=0,t.pendingFrameEvictedThroughTimestamp=-1}function eh(t,n=performance.now()){for(;t.pendingFrames.size>0;){const r=t.pendingFrames.entries().next().value;if(!r)break;const i=n-r[1].queuedAt>Nv,l=t.pendingFrames.size>eS,u=t.pendingFrameBytes>tS;if(!i&&!l&&!u)break;t.pendingFrameEvictedThroughTimestamp=Math.max(t.pendingFrameEvictedThroughTimestamp,r[0]),Jp(t,r[0]),t.pendingFrameEvictionCount+=1}}function fA(t,n,r,i,l,u=performance.now()){Jp(t,n);const f={frame:cA(r),queuedAt:u,queueSize:i,encodedByteLength:Math.max(0,Math.floor(Number(r.payload.byteLength||0))),paintIsCancelled:l};t.pendingFrames.set(n,f),t.pendingFrameBytes+=f.encodedByteLength,eh(t,u),t.pendingFrameHighWaterMark=Math.max(t.pendingFrameHighWaterMark,t.pendingFrames.size),t.pendingFrameByteHighWaterMark=Math.max(t.pendingFrameByteHighWaterMark,t.pendingFrameBytes)}function fS(t,n){if(n.pendingTrimTimer!==null||n.pendingFrames.size===0)return;const r=n.pendingFrames.values().next().value;if(!r)return;const i=Math.max(1,Nv-(performance.now()-r.queuedAt)+1);n.pendingTrimTimer=window.setTimeout(()=>{n.pendingTrimTimer=null,gr.get(t)===n&&(eh(n),fS(t,n))},i)}function mS(t){return cu.delete(t)?(nm+=1,am("hardware-release",t),!0):!1}function mA(t,n,r){if(n!=="prefer-hardware"||!r)return!1;const i=rc.get(t);return!i||i.requested!==n||i.actual!=="prefer-software"||nm<=i.failedHardwareReleaseGeneration?!1:(rc.delete(t),uu.delete(t),sS+=1,iS=Date.now(),!0)}function av(t,n=rl.h264DecodeAcceleration){const r=rc.get(t);return r?.requested===n?(r.actual!=="prefer-hardware"&&(cu.delete(t),uu.add(t)),r.actual):(r&&(rc.delete(t),uu.delete(t)),n!=="prefer-hardware"?(mS(t),uu.delete(t),n):(cu.has(t)||cu.add(t),"prefer-hardware"))}function Rv(t,n,r){if(n!=="prefer-hardware")return!1;const i=rc.get(t),l=gr.get(t),u=Date.now();return xd.has(t)||xd.set(t,nS++),rc.set(t,{requested:n,actual:"prefer-software",reason:r,failedAt:u,failureCount:(i?.requested===n?i.failureCount:0)+1,codec:l?.codec||i?.codec||"",latencyMode:l?.latencyMode||i?.latencyMode||"smooth",inputCount:l?.inputSerial??i?.inputCount??0,outputCount:l?.outputSerial??i?.outputCount??0,lastInputAt:l?.lastInputAt??i?.lastInputAt??0,lastOutputAt:l?.lastOutputAt??i?.lastOutputAt??0,lastPaintAt:l?.lastPaintAt??i?.lastPaintAt??0,decodeQueueHighWaterMark:Math.max(l?.decodeQueueHighWaterMark??0,i?.decodeQueueHighWaterMark??0),decodeQueueOverflowSamples:Math.max(l?.decodeQueueOverflowSamples??0,i?.decodeQueueOverflowSamples??0),decodeQueueOverflowAgeMs:l?.decodeQueueOverflowStartedAt?Math.max(0,performance.now()-l.decodeQueueOverflowStartedAt):i?.decodeQueueOverflowAgeMs,failedHardwareReleaseGeneration:nm}),cu.delete(t),uu.add(t),oS+=1,lS=r,cS=u,!0}function pA(t,n,r,i=64){try{let l=Jg.get(t);l||(l={canvas:document.createElement("canvas"),lastHash:"",initialized:!1},Jg.set(t,l));const u=Math.max(8,Math.min(64,Math.round(i))),f=Math.max(1,Math.round(u*Math.max(1,r)/Math.max(1,n)));(l.canvas.width!==u||l.canvas.height!==f)&&(l.canvas.width=u,l.canvas.height=f);const h=l.canvas.getContext("2d",{willReadFrequently:!0});if(!h)return{visualHash:"",visualChanged:!0};h.drawImage(t,0,0,Math.max(1,n),Math.max(1,r),0,0,u,f);const g=h.getImageData(0,0,u,f).data;let y=2166136261;for(let x=0;x<g.length;x+=4)y^=g[x],y=Math.imul(y,16777619),y^=g[x+1],y=Math.imul(y,16777619),y^=g[x+2],y=Math.imul(y,16777619);const w=(y>>>0).toString(16).padStart(8,"0"),b=!l.initialized||w!==l.lastHash;return l.initialized=!0,l.lastHash=w,{visualHash:w,visualChanged:b}}catch{return{visualHash:"",visualChanged:!0}}}function rv(t,n,r,i=Tv,l=64,u){if(!iA&&u)return pS(t,u);let f=ev.get(t);f||(f={lastHash:"",initialized:!1,lastCanvasSampleAt:0},ev.set(t,f));const h=performance.now();if(f.initialized&&i>0&&h-f.lastCanvasSampleAt<i)return{visualHash:f.lastHash,visualChanged:!1};const g=pA(t,n,r,l);return f.initialized=!0,f.lastHash=g.visualHash,f.lastCanvasSampleAt=h,g}function pS(t,n){let r=Bp.get(t);r||(r={lastHash:"",initialized:!1},Bp.set(t,r));const i=String(n.contentHash||""),l=!r.initialized||!i||i!==r.lastHash;return r.initialized=!0,r.lastHash=i,{visualHash:i,visualChanged:l}}function hS(t,n,r=!1){const i=Zg.get(t);if(i)return i;const l=t.getContext("2d",{alpha:!1,desynchronized:n==="interactive",willReadFrequently:r});if(l){const u=l.getContextAttributes?.(),f={context:l,presentation:u?.desynchronized?"desync":"sync"};return Zg.set(t,f),f}return null}function hA(t){const n=String(t.frameMode||t.mode||"").toLowerCase(),r=String(t.compression||"").toLowerCase(),i=String(t.mimeType||"").toLowerCase();return n==="mode2-lzo"||r==="lzo1x"||i==="application/vnd.livedesk.lzo-rgb565"||n==="mode2-lz4"||String(t.compression||"").toLowerCase()==="lz4"||i==="application/vnd.livedesk.lz4-raw"}function gA(t){return String(t.frameMode||t.mode||"").toLowerCase()==="mode3-h264-hw"||String(t.codec||"").toLowerCase()==="h264"||String(t.mimeType||"").toLowerCase()==="video/h264"}function vA(t){const n=String(t.frameMode||t.mode||"").toLowerCase(),r=String(t.mimeType||"").toLowerCase();return n==="mode5-lzo-delta"||r==="application/vnd.livedesk.lzo-rgb565-delta"}function $b(t,n,r){let i=r,l=n;if(i===15){let u=255;for(;u===255;){if(l>=t.length)throw new Error("Invalid LZ4 block: length overrun.");u=t[l],l+=1,i+=u}}return{length:i,cursor:l}}function yA(t,n){const r=new Uint8Array(n);let i=0,l=0;for(;i<t.length;){const u=t[i];i+=1;const f=$b(t,i,u>>4);i=f.cursor;const h=f.length;if(i+h>t.length||l+h>r.length)throw new Error("Invalid LZ4 block: literal overrun.");if(r.set(t.subarray(i,i+h),l),i+=h,l+=h,i>=t.length)break;if(i+2>t.length)throw new Error("Invalid LZ4 block: missing offset.");const g=t[i]|t[i+1]<<8;if(i+=2,g<=0||g>l)throw new Error("Invalid LZ4 block: bad match offset.");const y=$b(t,i,u&15);i=y.cursor;const w=y.length+4;if(l+w>r.length)throw new Error("Invalid LZ4 block: match overrun.");let b=l-g;for(let x=0;x<w;x+=1)r[l]=r[b],l+=1,b+=1}if(l!==r.length)throw new Error("Invalid LZ4 block: incomplete output.");return r}function bA(t){const n=Math.max(1,Math.floor(t.width||0)),r=Math.max(1,Math.floor(t.height||0)),i=String(t.compression||"").toLowerCase(),l=String(t.pixelFormat||t.codec||"").toLowerCase();if(i==="lzo1x"||String(t.frameMode||t.mode||"").toLowerCase()==="mode2-lzo"||String(t.mimeType||"").toLowerCase()==="application/vnd.livedesk.lzo-rgb565"){const w=Math.max(1,Math.floor(t.bytesPerPixel||2)),b=n*r*2,x=Math.floor(t.uncompressedByteLength||b);if(w!==2||x!==b)throw new Error(`Invalid mode2 RGB565 frame size: ${x} for ${n}x${r}.`);if(l&&l!=="rgb565le"&&l!=="rgb565")throw new Error(`Unsupported mode2 pixel format: ${l}`);const M=Zx(t.payload,b),k=new Uint8ClampedArray(n*r*4);for(let N=0,E=0;N<M.length;N+=2,E+=4){const I=M[N]|M[N+1]<<8,T=I>>11&31,P=I>>5&63,U=I&31;k[E]=T<<3|T>>2,k[E+1]=P<<2|P>>4,k[E+2]=U<<3|U>>2,k[E+3]=255}return new ImageData(k,n,r)}const f=Math.max(1,Math.floor(t.bytesPerPixel||4)),h=Math.max(n*r*f,Math.floor(t.uncompressedByteLength||0)),g=yA(t.payload,h);if(f!==4)throw new Error(`Unsupported mode2 pixel size: ${f}`);const y=new Uint8ClampedArray(n*r*4);if(l==="rgba32"||l==="rgba")y.set(g.subarray(0,y.length));else for(let w=0,b=0;b<y.length;w+=4,b+=4)y[b]=g[w+2],y[b+1]=g[w+1],y[b+2]=g[w],y[b+3]=g[w+3];return new ImageData(y,n,r)}function Ub(t,n="smooth",r=rl.h264DecodeAcceleration){const i=window.VideoDecoder;if(!i||!window.EncodedVideoChunk)throw new Error("WebCodecs H.264 decode is not supported in this browser.");const l=gr.get(t);if(l&&l.decoder.state!=="closed"&&l.latencyMode===n)return l;l&&Gs(t);let u;const f=new i({output:h=>{if(gr.get(t)!==u){h.close();return}const g=Number(h.timestamp||0),y=performance.now();u.outputSerial+=1,eh(u,y);let w=Jp(u,g);if(!w&&g>u.pendingFrameEvictedThroughTimestamp&&u.pendingFrames.size>0&&(w=dA(u),u.timestampFallbacks+=1),!w){u.pendingFrameUnmatchedOutputCount+=1,u.droppedForLatency+=1,u.lastOutputAt=y,h.close();return}if(uS(w)){u.droppedForLatency+=1,u.lastOutputAt=y,h.close();return}const b=h.displayWidth||h.codedWidth||t.width||960,x=h.displayHeight||h.codedHeight||t.height||540,M=Number(w?.frame.durationUs||0),k=Number(h.duration||0),N=Math.max(16,Math.min(250,(M>0?M:k||83333)/1e3));for(u.targetPaintIntervalMs=N,u.decodedFrames.push({videoFrame:h,pending:w,decodedAt:y,width:b,height:x,durationMs:N}),u.lastOutputAt=y;u.decodedFrames.length>jv(u);)zp(u,u.decodedFrames.shift(),"capacity");u.renderQueueHighWaterMark=Math.max(u.renderQueueHighWaterMark,u.decodedFrames.length),vS(u),u.renderTimer!==null&&u.renderScheduledAt>0&&performance.now()-u.renderScheduledAt>rA&&(typeof document>"u"||document.visibilityState==="visible")&&(window.cancelAnimationFrame(u.renderTimer),u.renderTimer=null,u.renderScheduledAt=0),u.renderTimer!==null&&u.decodedFrames.length>=tv&&(window.cancelAnimationFrame(u.renderTimer),u.renderTimer=null,u.renderScheduledAt=0),$p(t,u)},error:()=>{gr.get(t)===u&&(Rv(t,u.requestedAcceleration,"decoder-error"),Gs(t))}});return aS+=1,xd.has(t)||xd.set(t,nS++),u={decoder:f,configured:!1,configKey:"",codec:"",requestedAcceleration:r,hardwareAcceleration:av(t,r),latencyMode:n,keyFrameSeen:!1,droppedForLatency:0,pendingFrames:new Map,pendingFrameBytes:0,pendingFrameHighWaterMark:0,pendingFrameByteHighWaterMark:0,pendingFrameEvictionCount:0,pendingFrameUnmatchedOutputCount:0,pendingFrameEvictedThroughTimestamp:-1,pendingTrimTimer:null,decodedFrames:[],renderQueueHighWaterMark:0,renderQueueCapacityDropCount:0,renderQueueAgeDropCount:0,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,interactiveBackingWidth:0,interactiveBackingHeight:0,interactiveBackingSourceWidth:0,interactiveBackingSourceHeight:0,interactiveBackingMeasuredAt:0,lastInputFrameSeq:void 0,targetPaintIntervalMs:1e3/12,nextChunkTimestampUs:0,healthSampleStartedAt:performance.now(),healthInputSerial:0,healthOutputSerial:0,decodeQueueHighWaterMark:0,decodeQueueOverflowStartedAt:0,decodeQueueOverflowSamples:0},gr.set(t,u),fu.add(t),nv=Math.max(nv,fu.size),am("create",t),u}function gS(t){t.renderTimer!==null&&(window.cancelAnimationFrame(t.renderTimer),t.renderTimer=null),t.renderScheduledAt=0,t.flushTimer!==null&&(window.clearTimeout(t.flushTimer),t.flushTimer=null),t.flushInFlight=!1;const n=t.decodedFrames;t.decodedFrames=[];for(const r of n)try{r.videoFrame.close()}catch{}t.interactiveBufferPrimed=!1,t.interactiveBufferStartedAt=0}function zp(t,n,r="other"){n&&(n.videoFrame.close(),t.droppedForLatency+=1,r==="capacity"?t.renderQueueCapacityDropCount+=1:r==="age"&&(t.renderQueueAgeDropCount+=1))}function jv(t){return t.latencyMode==="interactive"?t.targetPaintIntervalMs<=20?UM:tv:String(t.decodedFrames[0]?.pending?.frame.frameMode||t.decodedFrames[0]?.pending?.frame.mode||"").toLowerCase()==="mode4-h264-atlas"?$M:tv}function vS(t,n=performance.now()){const r=jv(t);for(;t.decodedFrames.length>r;)zp(t,t.decodedFrames.shift(),"capacity");const i=t.latencyMode==="interactive"?KM:VM;let l=t.decodedFrames[0];for(;t.decodedFrames.length>0&&l&&n-l.decodedAt>i;)zp(t,t.decodedFrames.shift(),"age"),l=t.decodedFrames[0]}function yS(t,n){if(n.hardwareAcceleration!=="prefer-hardware"||n.latencyMode==="interactive"||n.flushTimer!==null||n.flushInFlight)return;const r=YM;n.flushTimer=window.setTimeout(async()=>{n.flushTimer=null;const i=performance.now();if(eh(n,i),gr.get(t)!==n||n.decoder.state!=="configured"||n.pendingFrames.size===0||n.inputSerial<=n.lastFlushInputSerial||n.lastOutputAt>0&&i-n.lastOutputAt<r)return;const l=n.inputSerial;n.flushInFlight=!0,n.flushCount+=1,n.keyFrameSeen=!1;try{await n.decoder.flush(),n.lastFlushInputSerial=Math.max(n.lastFlushInputSerial,l)}catch{gr.get(t)===n&&jp(n)}finally{n.flushInFlight=!1,gr.get(t)===n&&n.inputSerial>l&&n.pendingFrames.size>0&&performance.now()-n.lastOutputAt>=r&&yS(t,n)}},r)}function wA(t,n,r,i){const l=performance.now();if(n.interactiveBackingWidth>0&&n.interactiveBackingHeight>0&&l-n.interactiveBackingMeasuredAt<zM)return{width:Math.min(r,n.interactiveBackingWidth),height:Math.min(i,n.interactiveBackingHeight)};const u=typeof t.getBoundingClientRect=="function"?t.getBoundingClientRect():{width:Number(t.clientWidth||t.width||0),height:Number(t.clientHeight||t.height||0)},f=Math.max(1,Math.min(2,Number(globalThis.devicePixelRatio)||1)),h=u.width>0?Math.round(u.width*f):Bb,g=u.height>0?Math.round(u.height*f):zb,y=Math.min(1,h/r,g/i),w=Math.min(1,Math.max(Bb/r,zb/i)),b=Math.min(1,HM/r,BM/i),x=Math.max(.01,Math.min(b,Math.max(w,y)));return n.interactiveBackingWidth=Math.max(1,Math.round(r*x)),n.interactiveBackingHeight=Math.max(1,Math.round(i*x)),n.interactiveBackingMeasuredAt=l,{width:n.interactiveBackingWidth,height:n.interactiveBackingHeight}}function qb(t,n,r){const i=performance.now();try{if(!r.pending||uS(r.pending)){n.droppedForLatency+=1;return}const l=n.latencyMode==="interactive"?wA(t,n,r.width,r.height):{width:r.width,height:r.height},u=l.width,f=l.height;(t.width!==u||t.height!==f)&&(t.width=u,t.height=f);const h=hS(t,n.latencyMode,n.hardwareAcceleration==="prefer-software");if(h?.context.drawImage(r.videoFrame,0,0,r.width,r.height,0,0,u,f),r.pending){const g=performance.now(),w=n.latencyMode==="interactive"?pS(t,r.pending.frame):rv(t,r.width,r.height,Tv,64,r.pending.frame),b=uA(r.pending.frame);try{n.onPaint?.(b,{deviceId:b.deviceId,frameSeq:b.frameSeq,mode:b.frameMode||b.mode||b.codec||b.mimeType,width:r.width,height:r.height,byteLength:b.byteLength,queuedForMs:Math.max(0,i-r.pending.queuedAt),decodedForMs:Math.max(0,r.decodedAt-r.pending.queuedAt),scheduledForMs:Math.max(0,i-r.decodedAt),drawMs:Math.max(0,g-i),queueSize:r.pending.queueSize,renderQueueSize:n.decodedFrames.length,droppedForLatency:n.droppedForLatency,h264DecodeAcceleration:n.hardwareAcceleration,decoderLabel:n.hardwareAcceleration,decoderFlushCount:n.flushCount,decoderTimestampFallbacks:n.timestampFallbacks,decoderInputCount:n.inputSerial,decoderOutputCount:n.outputSerial,targetPaintIntervalMs:n.targetPaintIntervalMs,canvasPresentation:h?.presentation||"sync",interactiveBufferWaitCount:n.interactiveBufferWaitCount,interactiveBufferWaitMs:n.interactiveBufferWaitMs,interactiveQueueDrainCount:n.interactiveQueueDrainCount,visualHash:w.visualHash,visualChanged:w.visualChanged,paintedAt:g})}catch{}}n.lastPaintAt=performance.now()}finally{r.videoFrame.close()}}function $p(t,n){if(n.renderTimer!==null||n.decodedFrames.length===0)return;const r=Math.max(16,Math.min(250,n.targetPaintIntervalMs||1e3/12)),i=()=>{if(n.renderTimer=null,n.renderScheduledAt=0,n.decodedFrames.length===0)return;const l=performance.now();if(vS(n,l),n.decodedFrames.length===0)return;if(n.latencyMode==="interactive"){const g=n.targetPaintIntervalMs<=20;if(g&&!n.interactiveBufferPrimed){n.interactiveBufferStartedAt<=0&&(n.interactiveBufferStartedAt=l,n.interactiveBufferWaitCount+=1);const w=n.decodedFrames.length>=qM,b=l-n.interactiveBufferStartedAt>=WM;if(!w&&!b){n.renderScheduledAt=performance.now(),n.renderTimer=window.requestAnimationFrame(i);return}n.interactiveBufferWaitMs+=Math.max(0,l-n.interactiveBufferStartedAt),n.interactiveBufferPrimed=!0}else g||(n.interactiveBufferPrimed=!0);const y=n.decodedFrames.shift();if(y)try{qb(t,n,y)}catch{}n.decodedFrames.length===0&&(n.interactiveQueueDrainCount+=1,n.interactiveBufferPrimed=!1,n.interactiveBufferStartedAt=0),$p(t,n);return}const u=n.lastPaintAt>0?n.lastPaintAt+r:l+GM;if(!(l+QM>=u||n.decodedFrames.length>=Math.max(1,jv(n)-1))){n.renderScheduledAt=performance.now(),n.renderTimer=window.requestAnimationFrame(i);return}const h=n.decodedFrames.shift();if(h)try{qb(t,n,h)}catch{}$p(t,n)};n.renderScheduledAt=performance.now(),n.renderTimer=window.requestAnimationFrame(i)}function bS(t,n){if(gr.get(t)!==n||n.decoder.state==="closed")return!1;for(n.renderTimer!==null&&(window.cancelAnimationFrame(n.renderTimer),n.renderTimer=null),n.renderScheduledAt=0;n.decodedFrames.length>1;)zp(n,n.decodedFrames.shift());return n.lastPaintAt=0,n.interactiveBufferPrimed=!1,n.interactiveBufferStartedAt=0,$p(t,n),!0}function mg(){if(!(typeof document>"u"||document.visibilityState!=="visible"))for(const t of fu){const n=gr.get(t);if(!n||n.decoder.state==="closed"){fu.delete(t);continue}bS(t,n)}}typeof document<"u"&&typeof window<"u"&&(document.addEventListener("visibilitychange",mg),window.addEventListener("focus",mg),window.addEventListener("pageshow",mg));function Gs(t){mS(t),fu.delete(t),Bp.delete(t);const n=gr.get(t);if(n){gr.delete(t),rS+=1,dS(n),n.onPaint=void 0,gS(n);try{n.decoder.state!=="closed"&&n.decoder.close()}catch{}am("close",t)}}function id(t){t&&(rc.delete(t),uu.delete(t),Zg.delete(t),ev.delete(t),Jg.delete(t),Bp.delete(t),Zf.delete(t),Gs(t))}function xA(t,n){const r=gr.get(t),i=rc.get(t);if(!r&&!i)return null;const l=f=>f>0?Math.max(0,n-f):void 0,u=r?.pendingFrames.values().next().value;return{canvasId:xd.get(t)||0,canvasWidth:Math.max(0,Number(t.width||0)),canvasHeight:Math.max(0,Number(t.height||0)),decoderState:r?.decoder.state||"fallback-pending",configured:r?.configured||!1,keyFrameSeen:r?.keyFrameSeen||!1,codec:r?.codec||i?.codec||"",requestedAcceleration:r?.requestedAcceleration||i?.requested||rl.h264DecodeAcceleration,configuredAcceleration:r?.hardwareAcceleration||i?.actual||rl.h264DecodeAcceleration,latencyMode:r?.latencyMode||i?.latencyMode||"smooth",decodeQueueSize:Math.max(0,Number(r?.decoder.decodeQueueSize||0)),decodeQueueHighWaterMark:Math.max(0,Number(r?.decodeQueueHighWaterMark??0),Number(i?.decodeQueueHighWaterMark??0)),decodeQueueOverflowSamples:Math.max(0,Number(r?.decodeQueueOverflowSamples??0),Number(i?.decodeQueueOverflowSamples??0)),decodeQueueOverflowAgeMs:r?.decodeQueueOverflowStartedAt?Math.max(0,n-r.decodeQueueOverflowStartedAt):i?.decodeQueueOverflowAgeMs,pendingFrameCount:r?.pendingFrames.size||0,pendingFrameBytes:r?.pendingFrameBytes||0,pendingFrameHighWaterMark:r?.pendingFrameHighWaterMark||0,pendingFrameByteHighWaterMark:r?.pendingFrameByteHighWaterMark||0,pendingFrameEvictionCount:r?.pendingFrameEvictionCount||0,pendingFrameUnmatchedOutputCount:r?.pendingFrameUnmatchedOutputCount||0,pendingFrameOldestAgeMs:u?Math.max(0,n-u.queuedAt):void 0,pendingFrameMaxCount:eS,pendingFrameMaxBytes:tS,pendingFrameMaxAgeMs:Nv,renderQueueSize:r?.decodedFrames.length||0,renderQueueHighWaterMark:r?.renderQueueHighWaterMark||0,renderQueueCapacityDropCount:r?.renderQueueCapacityDropCount||0,renderQueueAgeDropCount:r?.renderQueueAgeDropCount||0,targetPaintIntervalMs:Math.max(0,Number(r?.targetPaintIntervalMs||0)),droppedForLatency:Math.max(0,Number(r?.droppedForLatency||0)),inputCount:r?.inputSerial??i?.inputCount??0,outputCount:r?.outputSerial??i?.outputCount??0,lastInputAgeMs:l(r?.lastInputAt??i?.lastInputAt??0),lastOutputAgeMs:l(r?.lastOutputAt??i?.lastOutputAt??0),lastPaintAgeMs:l(r?.lastPaintAt??i?.lastPaintAt??0),softwareFallbackReason:i?.reason,softwareFallbackAt:i?.failedAt,softwareFallbackCount:i?.failureCount||0}}function op(t){const n=performance.now(),i=(t?[t]:[...new Set([...fu,...uu])]).map(f=>xA(f,n)).filter(f=>f!==null),l=i.reduce((f,h)=>f+h.pendingFrameCount,0),u=i.reduce((f,h)=>f+h.pendingFrameBytes,0);return{capturedAt:Date.now(),hardwareRequestPolicy:"all-active",activeDecoderCount:i.filter(f=>f.decoderState!=="fallback-pending").length,hardwareLeaseCount:cu.size,hardwareReleaseGeneration:nm,hardwareRecoveryProbeCount:sS,lastHardwareRecoveryProbeAt:iS,activeSoftwareFallbackCount:i.filter(f=>f.configuredAcceleration==="prefer-software"&&f.requestedAcceleration==="prefer-hardware").length,decoderCreateCount:aS,decoderCloseCount:rS,activeDecoderHighWaterMark:nv,decoderLifecycleEvents:Hf.map(f=>({...f})),softwareFallbackEventCount:oS,lastSoftwareFallbackReason:lS,lastSoftwareFallbackAt:cS,pendingFrameCount:l,pendingFrameBytes:u,canvases:i}}function jp(t,n=1){try{t.decoder.state!=="closed"&&t.decoder.reset()}catch{}t.configured=!1,t.configKey="",t.keyFrameSeen=!1,dS(t),gS(t),t.lastPaintAt=0,t.lastOutputAt=0,t.lastInputAt=0,t.interactiveBufferPrimed=!1,t.interactiveBufferStartedAt=0,t.lastInputFrameSeq=void 0,t.nextChunkTimestampUs=0,t.healthSampleStartedAt=performance.now(),t.healthInputSerial=t.inputSerial,t.healthOutputSerial=t.outputSerial,t.decodeQueueOverflowStartedAt=0,t.decodeQueueOverflowSamples=0,t.droppedForLatency+=Math.max(1,Math.min(1e4,Math.floor(n)))}function SA(t,n,r=performance.now()){const i=Math.max(0,Number.isFinite(n)?n:0);if(t.decodeQueueHighWaterMark=Math.max(t.decodeQueueHighWaterMark,i),i<=eA)return t.decodeQueueOverflowStartedAt=0,t.decodeQueueOverflowSamples=0,!1;t.decodeQueueOverflowStartedAt<=0?(t.decodeQueueOverflowStartedAt=r,t.decodeQueueOverflowSamples=1):t.decodeQueueOverflowSamples+=1;const l=Math.max(0,r-t.decodeQueueOverflowStartedAt);return i>=tA||t.decodeQueueOverflowSamples>=aA&&l>=nA}function CA(t,n,r,i,l,u){n.decoder.configure(r),n.configured=!0,n.configKey=i,n.codec=r.codec,n.requestedAcceleration=u,n.hardwareAcceleration=l,n.keyFrameSeen=!1,n.nextChunkTimestampUs=0,n.lastInputFrameSeq=void 0,am("configure",t)}function kA(t,n){if(n.latencyMode!=="interactive"||n.hardwareAcceleration!=="prefer-hardware")return!1;const r=performance.now();if(r-n.healthSampleStartedAt<XM)return!1;const i=n.inputSerial-n.healthInputSerial,l=n.outputSerial-n.healthOutputSerial;return n.healthSampleStartedAt=r,n.healthInputSerial=n.inputSerial,n.healthOutputSerial=n.outputSerial,i<ZM||l/Math.max(1,i)>=JM?!1:(Rv(t,n.requestedAcceleration,"interactive-health"),Gs(t),!0)}function od(t,n=1){if(!t)return!1;const r=gr.get(t);return r?(r.droppedForLatency+=Math.max(1,Math.min(1e4,Math.floor(n))),Gs(t),!0):!1}function MA(t){if(!t)return!1;const n=gr.get(t);return n?bS(t,n):!1}function AA(t,n,r,i="interactive"){Gs(t);const l=performance.now(),u=FM(n.payload,n.uncompressedByteLength||0),f=String(n.streamId||"mode5");let h=Zf.get(t);if(!h||h.streamId!==f||h.width!==u.width||h.height!==u.height){const N=new Uint8ClampedArray(u.width*u.height*4);for(let E=3;E<N.length;E+=4)N[E]=255;h={streamId:f,width:u.width,height:u.height,rgba:N,imageData:new ImageData(N,u.width,u.height),keyFrameSeen:!1,inputSerial:0,outputSerial:0},Zf.set(t,h)}if(!h)throw new Error("Mode 5 canvas state could not be initialized.");h.inputSerial+=1;const y=Number(n.streamFrameSeq||0);if(y>0&&(h.lastStreamFrameSeq=y),!u.keyFrame&&!h.keyFrameSeen)return;u.keyFrame&&(h.keyFrameSeen=!0);const w=OM(h.rgba,h.width,h.height,u),b=performance.now();(t.width!==h.width||t.height!==h.height)&&(t.width=h.width,t.height=h.height);const x=hS(t,i),M=performance.now();w&&x?.context.putImageData(h.imageData,0,0,w.x,w.y,w.width,w.height);const k=performance.now();h.outputSerial+=1,r?.(n,{deviceId:n.deviceId,frameSeq:n.frameSeq,mode:n.frameMode||n.mode||n.mimeType,width:h.width,height:h.height,byteLength:n.byteLength,queuedForMs:Math.max(0,k-l),decodedForMs:Math.max(0,b-l),scheduledForMs:0,drawMs:Math.max(0,k-M),queueSize:0,renderQueueSize:0,droppedForLatency:0,h264DecodeAcceleration:"prefer-software",decoderLabel:"lzo-rgb565-delta",decoderFlushCount:0,decoderTimestampFallbacks:0,decoderInputCount:h.inputSerial,decoderOutputCount:h.outputSerial,targetPaintIntervalMs:Math.max(1,Number(n.durationUs||0)/1e3||1e3/30),canvasPresentation:x?.presentation||"sync",interactiveBufferWaitCount:0,interactiveBufferWaitMs:0,interactiveQueueDrainCount:0,visualHash:String(n.contentHash||""),visualChanged:Number(n.deltaVisualTileCount||0)>0,paintedAt:k})}const pg=[{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 Wb(t,n){for(let r=Math.max(0,n);r+3<t.length;r+=1)if(!(t[r]!==0||t[r+1]!==0)){if(t[r+2]===1)return{index:r,length:3};if(t[r+2]===0&&t[r+3]===1)return{index:r,length:4}}return null}function NA(t){let n=0;for(;n<t.length;){const r=Wb(t,n);if(!r)break;const i=r.index+r.length,l=Wb(t,i),u=l?.index??t.length;if(i<u&&(t[i]&31)===7){const f=[];let h=0;for(let g=i+1;g<u;g+=1){const y=t[g];if(h>=2&&y===3){h=0;continue}f.push(y),h=y===0?h+1:0}if(f.length>=3)return`avc1.${f.slice(0,3).map(g=>g.toString(16).toUpperCase().padStart(2,"0")).join("")}`}n=l?l.index:t.length}return""}function TA(t,n,r,i,l=""){const u=Math.ceil(t/16)*Math.ceil(n/16),f=r>0?1e6/r:30,h=u*f,g=pg.find(y=>u<=y.maxFrameSize&&h<=y.maxMacroblocksPerSecond)||pg[pg.length-1];return NA(i)||l||`avc1.42E0${g.code.toString(16).toUpperCase().padStart(2,"0")}`}function wS(t,n,r,i,l="smooth",u=()=>!1,f=!0){Zf.delete(t);const h=String(n.h264Format||"").toLowerCase()==="avc"?"avc":"annexb",g=Math.max(1,Math.floor(n.width||960)),y=Math.max(1,Math.floor(n.height||540)),w=Math.max(1,Math.floor(n.durationUs||1e6/12)),b=i||rl.h264DecodeAcceleration,x=n.isKeyFrame===!0||String(n.chunkType||"").toLowerCase()==="key";mA(t,b,x);let M=Ub(t,l,b);const k=TA(g,y,w,n.payload,M.codec);let N=av(t,b),E="";const I=()=>{E=[n.streamId||"",n.commandId||"",g,y,k,h,b,N,l].join("|")};I(),M.onPaint=r,M.configured&&M.decoder.state!=="configured"&&(M.configured=!1,M.configKey=""),M.configured&&M.configKey!==E&&(Gs(t),M=Ub(t,l,b),M.onPaint=r,N=av(t,b),I());const T=()=>({codec:k,codedWidth:g,codedHeight:y,hardwareAcceleration:N,optimizeForLatency:!0,avc:{format:h}}),P=ne=>M.hardwareAcceleration!=="prefer-hardware"||!Rv(t,M.requestedAcceleration,ne)?!1:(Gs(t),f&&x&&wS(t,n,r,b,l,u,!1),!0),U=()=>{try{return CA(t,M,T(),E,N,b),!0}catch(ne){if(P("configure-error"))return!1;throw Gs(t),ne}};if(!M.configured&&!U())return;const F=Number(n.streamFrameSeq||0);if(F>0&&M.lastInputFrameSeq!==void 0&&(F<=M.lastInputFrameSeq&&(!x||F===M.lastInputFrameSeq||(jp(M,M.lastInputFrameSeq-F+1),!U()))||F>M.lastInputFrameSeq+1&&(jp(M,F-M.lastInputFrameSeq-1),!x||!U()))||(F>0&&(M.lastInputFrameSeq=F),!x&&!M.keyFrameSeen))return;x&&(M.keyFrameSeen=!0);const Y=Number(M.decoder.decodeQueueSize||0);if(SA(M,Y)){if(M.latencyMode==="interactive"&&M.hardwareAcceleration==="prefer-hardware"){P("decode-queue-overflow");return}if(jp(M),!x||!U())return;M.keyFrameSeen=!0}const D=M.nextChunkTimestampUs;M.nextChunkTimestampUs+=w,fA(M,D,n,Y,u),fS(t,M),M.inputSerial+=1,M.lastInputAt=performance.now(),M.inputSerial===1&&am("first-input",t);const K=new EncodedVideoChunk({type:x?"key":"delta",timestamp:D,duration:w,data:n.payload});try{M.decoder.decode(K)}catch(ne){if(P("decode-error"))return;throw Gs(t),ne}yS(t,M),kA(t,M)}async function hg(t,n,r,i,l,u="smooth",f=r){if(vA(n)){r()||AA(t,n,i,u);return}if(gA(n)){r()||wS(t,n,i,l,u,f);return}if(Zf.delete(t),hA(n)){Gs(t);const x=bA(n);if(r())return;(t.width!==x.width||t.height!==x.height)&&(t.width=x.width,t.height=x.height);const M=t.getContext("2d"),k=performance.now();M?.putImageData(x,0,0);const N=performance.now(),E=rv(t,x.width,x.height,Tv,64,n);i?.(n,{deviceId:n.deviceId,frameSeq:n.frameSeq,mode:n.frameMode||n.mode||n.codec||n.mimeType,width:x.width,height:x.height,byteLength:n.byteLength,queuedForMs:0,decodedForMs:0,scheduledForMs:0,drawMs:Math.max(0,N-k),queueSize:0,renderQueueSize:0,droppedForLatency:0,h264DecodeAcceleration:rl.h264DecodeAcceleration,decoderLabel:"lzo-rgb565",decoderFlushCount:0,decoderTimestampFallbacks:0,decoderInputCount:0,decoderOutputCount:0,targetPaintIntervalMs:0,canvasPresentation:"sync",interactiveBufferWaitCount:0,interactiveBufferWaitMs:0,interactiveQueueDrainCount:0,visualHash:E.visualHash,visualChanged:E.visualChanged,paintedAt:N});return}Gs(t);const h=new Blob([n.payload],{type:n.mimeType}),g=await createImageBitmap(h);if(r()){g.close();return}const y=n.width||g.width||960,w=n.height||g.height||540;(t.width!==y||t.height!==w)&&(t.width=y,t.height=w);const b=t.getContext("2d");if(b){const x=performance.now();b.clearRect(0,0,y,w),b.drawImage(g,0,0,y,w);const M=performance.now(),k=rv(t,y,w);i?.(n,{deviceId:n.deviceId,frameSeq:n.frameSeq,mode:n.frameMode||n.mode||n.codec||n.mimeType,width:y,height:w,byteLength:n.byteLength,queuedForMs:0,decodedForMs:0,scheduledForMs:0,drawMs:Math.max(0,M-x),queueSize:0,renderQueueSize:0,droppedForLatency:0,h264DecodeAcceleration:rl.h264DecodeAcceleration,decoderLabel:"image",decoderFlushCount:0,decoderTimestampFallbacks:0,decoderInputCount:0,decoderOutputCount:0,targetPaintIntervalMs:0,canvasPresentation:"sync",interactiveBufferWaitCount:0,interactiveBufferWaitMs:0,interactiveQueueDrainCount:0,visualHash:k.visualHash,visualChanged:k.visualChanged,paintedAt:M})}g.close()}function RA(t){queueMicrotask(t)}function jA(t){return t?(t.width=0,t.height=0,!0):!1}function th(t,n){if(!t)return!1;try{n?.(t)}finally{jA(t)}return!0}function Ev(t,n){if(!t||!n)return 0;const r=Math.max(0,Number(t.get(n)||0))+1;return t.set(n,r),r}function EA(t,n){if(!t||!n)return 0;const r=Number(t.get(n)||0);return Number.isSafeInteger(r)&&r>0?r:Ev(t,n)}function Gb(t,n){return Ev(t,n)}function Vb(t,n,r){return!!t&&!!n&&Number(r)>0&&Number(t.get(n)||0)===Number(r)}function DA(t,n,r){if(!t||!t.has(n))return!1;const i=t.get(n);return t.delete(n),th(i,r)}function IA(t,n,r){const i=new Set;for(const l of t||[])if(l){for(const u of l.values())u&&i.add(u);l.clear()}for(const l of n||[])l&&i.add(l);for(const l of i)th(l,r);return i.size}function LA(t,{isCurrent:n,dispose:r,schedule:i=RA}){return!t||typeof n!="function"?!1:(i(()=>{n(t)||th(t,r)}),!0)}const _A=new Uint8Array(0);function au(t){if(!t||typeof t!="object")return t;const n=t.payload;return n instanceof Uint8Array&&n.byteLength===0?t:{...t,payload:_A}}function PA(t,n){const r=au(n);return t.set(n.deviceId,r),r}function FA(t,n){for(const[r,i]of n.entries())t.set(r,au(i));return n.clear(),new Map(t)}const OA=1500;function HA(t={}){const n=Math.max(10,Math.min(1e4,Number(t.closeDeadlineMs)||OA)),r=typeof t.setTimeout=="function"?t.setTimeout:setTimeout,i=typeof t.clearTimeout=="function"?t.clearTimeout:clearTimeout,l=new Set,u=new WeakMap;let f=0,h=0;const g=(y,w)=>{if(!y||y.settled)return!1;y.settled=!0,y.timer!==null&&(i(y.timer),y.timer=null);try{y.socket.removeEventListener?.("close",y.handleClose)}catch{}return l.delete(y),u.delete(y.entry),w&&(f+=1),!0};return Object.freeze({beginClosing(y,w="livedesk-frame-socket-release"){if(!y?.socket||u.has(y))return!1;const b=y.socket;if(Number(b.readyState)===3)return!1;const x={entry:y,socket:b,timer:null,settled:!1,handleClose:null};x.handleClose=()=>g(x,!1),u.set(y,x),l.add(x),h=Math.max(h,l.size);try{b.addEventListener?.("close",x.handleClose)}catch{}x.timer=r(()=>{if(!x.settled){try{b.close()}catch{}g(x,Number(b.readyState)!==3)}},n);try{Number(b.readyState)===0||Number(b.readyState)===1?b.close(1e3,w):b.close()}catch{try{b.close()}catch{}}return Number(b.readyState)===3&&g(x,!1),!0},snapshot(){return{closingSocketCount:l.size,closingSocketTimerCount:[...l].filter(y=>y.timer!==null).length,closingSocketTimeoutCount:f,maximumClosingSocketCount:h}}})}function BA(t,n="livedesk-frame-socket-release",r=null){if(!t)return 0;const i=[t],l=new Set;let u=0;for(;i.length>0;){const f=i.pop();if(!f||l.has(f))continue;l.add(f);const h=f.handoffFrom;f.handoffFrom=void 0,h&&!l.has(h)&&i.push(h);const g=f.disposed===!0;f.disposed=!0,f.handoffCompleted=!0;const y=f.detachListeners;f.detachListeners=void 0;try{y?.()}catch{}const w=f.releaseOwnedState;f.releaseOwnedState=void 0;try{w?.()}catch{}if(!g){if(r?.beginClosing)r.beginClosing(f,n);else try{f.socket.readyState===0||f.socket.readyState===1?f.socket.close(1e3,n):f.socket.close()}catch{try{f.socket.close()}catch{}}u+=1}}return u}const Kb=Object.freeze(["nativeCaptureTelemetryAvailable","nativeCaptureTelemetryVersion","nativeEncoderHardwareAccelerationKnown","nativeEncoderHardwareAccelerated","nativeEncoderHardwareQueryStatus","nativeCaptureDisplayId","nativeCaptureFps","nativeCompressionFps","nativeEncodedFps","nativeCaptureSampleCount","nativeEncodableFrameCount","nativeSkippedFrameCount","nativeCompressionOutputCount","nativeEncodedFrameCount","nativeEncodeFramesInFlight","nativeEncodePendingFrameCount","nativeEncodeTimestampOwnerCount","nativeEncodeTimestampOwnerHighWatermark","nativeBackpressureCoalescedFrameCount","nativeBackpressureSkippedFrameCount","nativeEncodePendingReplacedFrameCount","nativeIdleSkippedFrameCount","nativeVideoToolboxActiveSessionCount","nativeVideoToolboxSessionHighWatermark","nativeOutputQueueDepth","nativeOutputQueueBytes","nativeOutputQueueOldestAgeMs","nativeOutputQueueHighWatermark","nativeOutputQueueDroppedCount","nativeOutputQueueAwaitingKeyFrame","nativeCopyTelemetryAvailable","nativeAnnexBAccessUnitAllocationCount","nativeAnnexBPayloadCopyCount","nativeAnnexBPayloadCopiedBytes","nativeAndPipeResidenceAgeMs","pipePayloadAllocationCount","pipePayloadCopyCount","pipePayloadCopiedBytes","handoffDroppedFrameCount","handoffRecoveryKeyFrameRequestCount","handoffOldestFrameAgeMs","nativeCaptureResourceTelemetryAvailable","nativeCaptureTelemetryAt"]),zA=Object.freeze(["nativeEncodeFramesInFlight","nativeEncodePendingFrameCount","nativeEncodeTimestampOwnerCount","nativeEncodeTimestampOwnerHighWatermark","nativeBackpressureCoalescedFrameCount","nativeBackpressureSkippedFrameCount","nativeEncodePendingReplacedFrameCount","nativeIdleSkippedFrameCount","nativeVideoToolboxActiveSessionCount","nativeVideoToolboxSessionHighWatermark","nativeOutputQueueDepth","nativeOutputQueueBytes","nativeOutputQueueOldestAgeMs","nativeOutputQueueHighWatermark","nativeOutputQueueDroppedCount","nativeOutputQueueAwaitingKeyFrame","nativeCopyTelemetryAvailable","nativeAnnexBAccessUnitAllocationCount","nativeAnnexBPayloadCopyCount","nativeAnnexBPayloadCopiedBytes","nativeAndPipeResidenceAgeMs","pipePayloadAllocationCount","pipePayloadCopyCount","pipePayloadCopiedBytes","handoffDroppedFrameCount","handoffRecoveryKeyFrameRequestCount","handoffOldestFrameAgeMs"]);function $A(t){return[String(t?.deviceId||""),String(t?.sessionId||""),String(t?.streamId||""),String(t?.commandId||""),String(Number(t?.captureGeneration||0)||0),String(Number.isFinite(Number(t?.monitorIndex))?Number(t.monitorIndex):-1),String(t?.streamPurpose||"")].join("\0")}function UA(t,n){return!!n&&String(t?.deviceId||"")===String(n.deviceId||"")&&String(t?.sessionId||"")===String(n.sessionId||"")&&String(t?.streamId||"")===String(n.streamId||"")&&String(t?.commandId||"")===String(n.commandId||"")&&(Number(t?.captureGeneration||0)||0)===(Number(n.captureGeneration||0)||0)&&(Number.isFinite(Number(t?.monitorIndex))?Number(t.monitorIndex):-1)===(Number.isFinite(Number(n.monitorIndex))?Number(n.monitorIndex):-1)&&String(t?.streamPurpose||"")===String(n.streamPurpose||"")}function qA(){return{ownerKey:"",values:Object.create(null)}}function Qb(t){t&&(t.ownerKey="",t.values=Object.create(null))}function WA(t,n,r){if(!t||!n||!UA(t,r))return!1;const i=$A(r);if(n.ownerKey!==i&&(n.ownerKey=i,n.values=Object.create(null)),t.nativeCaptureTelemetryAvailable===!1){for(const l of Kb)l!=="nativeCaptureTelemetryAvailable"&&(delete n.values[l],delete t[l]);return n.values.nativeCaptureTelemetryAvailable=!1,!0}if(t.nativeCaptureResourceTelemetryAvailable===!1)for(const l of zA)delete n.values[l],delete t[l];for(const l of Kb)Object.prototype.hasOwnProperty.call(t,l)?n.values[l]=t[l]:Object.prototype.hasOwnProperty.call(n.values,l)&&(t[l]=n.values[l]);return!0}const xS=new ArrayBuffer(0);function GA(t){return`${String(t?.streamId||"")}:${Number(t?.frameSeq||0)}`}function VA(t){return!t||typeof t!="object"||t.payload instanceof ArrayBuffer&&t.payload.byteLength===0?t:{...t,payload:xS}}function KA(){let t=null,n="";return{accept(r){t=VA(r)},publish(){const r=t;if(t=null,!r)return null;const i=GA(r);return i===n?null:(n=i,r)},clear(){t=null,n=""},inspect(){return{pending:t?1:0,pendingPayloadBytes:Number(t?.payload?.byteLength||0),publishedKey:n}}}}const QA=0,YA=1,Yb=3;function dr(t){return Math.max(0,Math.floor(Number(t)||0))}function wi(t,n){return!n||n.active||n.socket!==null||n.audioContext!==null||n.statsTimer!==null||n.scheduledSourceCount!==0||n.pendingDecodeCount!==0||n.workletNodeCount!==0||n.workletPortCount!==0||n.pcmRingCapacityBytes!==0||n.pcmRingBufferedBytes!==0||n.pendingWorkletPacketCount!==0||n.pendingWorkletPacketBytes!==0||n.retainedFrameCount!==0||n.retainedPayloadBytes!==0?!1:t.delete(n)}function XA(){const t=new Set;let n=null;const r={ownerCount:0,socketCount:0,audioContextCount:0,workletNodeCount:0,workletPortCount:0},i=()=>{let l=0,u=0,f=0,h=0;for(const g of t){const y=Number(g.socket?.readyState);l+=g.socket&&y!==Yb?1:0,u+=g.audioContext===null?0:1,f+=dr(g.workletNodeCount),h+=dr(g.workletPortCount)}r.ownerCount=Math.max(r.ownerCount,t.size),r.socketCount=Math.max(r.socketCount,l),r.audioContextCount=Math.max(r.audioContextCount,u),r.workletNodeCount=Math.max(r.workletNodeCount,f),r.workletPortCount=Math.max(r.workletPortCount,h)};return{createOwner({deviceId:l,socket:u,audioContext:f,statsTimer:h=null}){n=null;const g={deviceId:String(l||""),active:!0,socket:u||null,audioContext:f||null,statsTimer:h,scheduledSourceCount:0,pendingDecodeCount:0,workletNodeCount:0,workletPortCount:0,workletNodeCreateCount:0,pcmRingCapacityBytes:0,pcmRingBufferedBytes:0,pendingWorkletPacketCount:0,pendingWorkletPacketBytes:0,pendingWorkletPacketHighWater:0,pendingWorkletByteHighWater:0,retainedFrameCount:0,retainedPayloadBytes:0};return t.add(g),i(),g},recordTerminalFailure(l,u,f="playback"){return t.has(l)?(n={deviceId:l.deviceId,phase:String(f||"playback").slice(0,64),message:String(u||"Remote audio playback failed.").slice(0,512)},!0):!1},deactivate(l){return t.has(l)?(l.active=!1,wi(t,l)):!1},setSocket(l,u){return t.has(l)?(l.socket=u||null,i(),wi(t,l)):!1},setAudioContext(l,u){return t.has(l)?(l.audioContext=u||null,i(),wi(t,l)):!1},setStatsTimer(l,u){return t.has(l)?(l.statsTimer=u??null,wi(t,l)):!1},setScheduledSourceCount(l,u){return t.has(l)?(l.scheduledSourceCount=dr(u),wi(t,l)):!1},setPendingDecodeCount(l,u){return t.has(l)?(l.pendingDecodeCount=dr(u),wi(t,l)):!1},setWorkletNode(l,u,f,h=l?.workletNodeCreateCount){return t.has(l)?(l.workletNodeCount=dr(u),l.workletPortCount=dr(f),l.workletNodeCreateCount=dr(h),i(),wi(t,l)):!1},setPcmRing(l,u,f){return t.has(l)?(l.pcmRingCapacityBytes=dr(u),l.pcmRingBufferedBytes=Math.min(l.pcmRingCapacityBytes,dr(f)),wi(t,l)):!1},setPendingWorkletPackets(l,u,f,h=l?.pendingWorkletPacketHighWater,g=l?.pendingWorkletByteHighWater){return t.has(l)?(l.pendingWorkletPacketCount=dr(u),l.pendingWorkletPacketBytes=dr(f),l.pendingWorkletPacketHighWater=Math.max(l.pendingWorkletPacketHighWater,dr(h)),l.pendingWorkletByteHighWater=Math.max(l.pendingWorkletByteHighWater,dr(g)),wi(t,l)):!1},setRetainedFrame(l,u,f=0){return t.has(l)?(l.retainedFrameCount=dr(u),l.retainedPayloadBytes=dr(f),wi(t,l)):!1},releaseIfDrained(l){return wi(t,l)},hasOwner(l){return t.has(l)},snapshot(){const l=[...t].map(f=>{const h=Number(f.socket?.readyState),g=f.socket&&h!==Yb?1:0;return{deviceId:f.deviceId,active:f.active,socketCount:g,openSocketCount:h===YA?1:0,connectingSocketCount:h===QA?1:0,audioContextCount:f.audioContext===null?0:1,statsTimerCount:f.statsTimer===null?0:1,scheduledSourceCount:f.scheduledSourceCount,pendingDecodeCount:f.pendingDecodeCount,workletNodeCount:f.workletNodeCount,workletPortCount:f.workletPortCount,workletNodeCreateCount:f.workletNodeCreateCount,pcmRingCapacityBytes:f.pcmRingCapacityBytes,pcmRingBufferedBytes:f.pcmRingBufferedBytes,pendingWorkletPacketCount:f.pendingWorkletPacketCount,pendingWorkletPacketBytes:f.pendingWorkletPacketBytes,pendingWorkletPacketHighWater:f.pendingWorkletPacketHighWater,pendingWorkletByteHighWater:f.pendingWorkletByteHighWater,retainedFrameCount:f.retainedFrameCount,retainedPayloadBytes:f.retainedPayloadBytes}}),u=f=>l.reduce((h,g)=>h+dr(g[f]),0);return{ownerCount:l.length,activeOwnerCount:l.filter(f=>f.active).length,socketCount:u("socketCount"),openSocketCount:u("openSocketCount"),connectingSocketCount:u("connectingSocketCount"),audioContextCount:u("audioContextCount"),statsTimerCount:u("statsTimerCount"),scheduledSourceCount:u("scheduledSourceCount"),pendingDecodeCount:u("pendingDecodeCount"),workletNodeCount:u("workletNodeCount"),workletPortCount:u("workletPortCount"),workletNodeCreateCount:u("workletNodeCreateCount"),pcmRingCapacityBytes:u("pcmRingCapacityBytes"),pcmRingBufferedBytes:u("pcmRingBufferedBytes"),pendingWorkletPacketCount:u("pendingWorkletPacketCount"),pendingWorkletPacketBytes:u("pendingWorkletPacketBytes"),pendingWorkletPacketHighWater:u("pendingWorkletPacketHighWater"),pendingWorkletByteHighWater:u("pendingWorkletByteHighWater"),retainedFrameCount:u("retainedFrameCount"),retainedPayloadBytes:u("retainedPayloadBytes"),ownerHighWater:r.ownerCount,socketHighWater:r.socketCount,audioContextHighWater:r.audioContextCount,workletNodeHighWater:r.workletNodeCount,workletPortHighWater:r.workletPortCount,lastTerminalFailure:n,owners:l}}}}const ha=XA();function ZA(){let t=Promise.resolve(),n=0,r=0,i=0;return{acquire(l){const u=++i;let f=!1,h=!1,g=!1,y;const w=new Promise(k=>{y=k}),b=Promise.resolve(t).catch(()=>{});t=b.then(()=>w);const x=()=>g?!1:(g=!0,f&&(n=Math.max(0,n-1)),y(),!0),M=b.then(async()=>{if(h||g)return x(),null;f=!0,n+=1,r=Math.max(r,n);try{return await l({ownerId:u,release:x})}catch(k){throw x(),k}});return{ownerId:u,ready:M,release:x,cancel(){h=!0,f||x()}}},snapshot(){return{activeOwnerCount:n,ownerHighWater:r,nextOwnerId:i}}}}const JA=ZA(),Xb=1e3;function e1({enabled:t,now:n,lastPublishedAt:r,intervalMs:i=Xb}){if(!t)return!1;const l=Math.max(0,Number(n)||0),u=Math.max(0,Number(r)||0),f=Math.max(1,Number(i)||Xb);return u<=0||l-u>=f}const SS="livedesk-remote-audio-v1",t1=250,n1=80,sv=4;function a1(t){const n=String(t||"").toLowerCase();return n.includes("audio/pcm")||n.includes("f32le")||n.includes("s16le")}function iv(t={},n={}){const r=String(n.deviceId||""),i=String(n.streamId||"");return!!r&&!!i&&String(t.deviceId||"")===r&&String(t.streamId||"")===i}function r1(t={},n={}){if(!iv(t,n))return{accepted:!1,reason:"owner-mismatch",nextFrameSeq:Math.max(0,Math.floor(Number(n.lastFrameSeq)||0))};const r=Math.max(0,Math.floor(Number(t.frameSeq)||0)),i=Math.max(0,Math.floor(Number(n.lastFrameSeq)||0));return r>0&&r<=i?{accepted:!1,reason:"sequence-not-newer",nextFrameSeq:i}:{accepted:!0,reason:"",nextFrameSeq:r}}function s1(t={}){const n=String(t.capturePhase||"").toLowerCase(),r=String(t.backendKind||"").toLowerCase(),i=t.captureAlive===!0?!0:t.captureAlive===!1?!1:null,l=t.helperAlive===!0?!0:t.helperAlive===!1?!1:null,u=Math.max(0,Math.floor(Number(t.helperPid)||0)),f=r==="windows-wasapi-in-process",h=r==="macos-screencapturekit-helper"||r==="linux-system-audio-helper",g=f||h,y=t.helperRequired===!0?!0:t.helperRequired===!1?!1:h?!0:f?!1:null,w=y===!1?!0:y===!0?l===!0&&u>0:!1,b=n==="starting"||n==="capture-active-awaiting-current-pcm",x=n==="active"&&i===!0&&g&&w,M=n==="failed"||n==="stopped"||i===!1||n==="active"&&(!g||!w);let k="";return b?k="awaiting-current-pcm":!f&&!h?k="backend-unknown":n!=="active"?k=n?`phase-${n}`:"phase-unknown":i!==!0?k="capture-not-alive":y===!0&&l!==!0?k="external-helper-not-alive":y===!0&&u<=0&&(k="external-helper-pid-missing"),{capturePhase:n,backendKind:r,captureAlive:i,helperAlive:l,helperPid:u,helperRequired:y,inProcessBackend:f,externalHelperBackend:h,backendKnown:g,helperReady:w,awaitingCurrentPcm:b,healthy:x,failed:M,reason:k}}function sc(t,n){const r=Math.floor(Number(t));return Number.isFinite(r)&&r>0?r:n}function Dv(t={}){const n=Math.max(8e3,Math.min(192e3,sc(t.sampleRate,48e3))),r=Math.max(1,Math.min(8,sc(t.channels,2))),i=String(t.mimeType||"").toLowerCase(),u=String(t.sampleFormat||"").toLowerCase()==="s16le"||i.includes("s16le")||i.includes("audio/l16")?"s16le":"f32le";return{sampleRate:n,channels:r,sampleFormat:u}}function Iv(t={}){const n=Dv(t),r=Math.max(1,Math.min(250,sc(t.maxDurationMs,250))),i=Math.max(1,Math.ceil(n.sampleRate*r/1e3));return{...n,maxDurationMs:r,capacityFrames:i,capacityBytes:i*n.channels*Float32Array.BYTES_PER_ELEMENT}}function i1(t={}){const n=Iv(t),r=Math.max(0,Math.min(n.maxDurationMs,sc(t.targetLeadMs,80))),i=Math.min(n.capacityFrames,Math.max(1,Math.ceil(n.sampleRate*r/1e3)));let l=new Float32Array(n.capacityFrames*n.channels),u=0,f=0,h=0,g=0,y=!1,w=!1,b=0,x=0,M=0;const k={acceptedFrames:0,droppedFrames:0},N=()=>(M+=1,{sampleRate:n.sampleRate,channels:n.channels,sampleFormat:n.sampleFormat,maxDurationMs:n.maxDurationMs,targetLeadMs:r,capacityFrames:w?0:n.capacityFrames,capacityBytes:w?0:n.capacityBytes,bufferedFrames:w?0:h,bufferedBytes:w?0:h*n.channels*Float32Array.BYTES_PER_ELEMENT,bufferedMs:w?0:h*1e3/n.sampleRate,droppedFrames:b,underflowCount:x,started:!w&&y,disposed:w}),E=()=>{u=0,f=0,h=0,g=0,y=!1},I=()=>{w||(E(),l=new Float32Array(0),w=!0)},T=(F,Y=0,D,K=n.sampleFormat)=>{if(k.acceptedFrames=0,k.droppedFrames=0,w||!(F instanceof ArrayBuffer))return k;const ne=Math.max(0,Math.floor(Number(Y)||0)),q=Math.max(0,F.byteLength-ne),O=Math.min(q,Math.max(0,Math.floor(Number(D??q)||0))),W=K==="s16le",ce=W?2:4,$=ce*n.channels,ee=Math.floor(O/$);if(ee<=0)return k;const B=Math.min(ee,n.capacityFrames),L=ee-B,oe=Math.max(0,h+B-n.capacityFrames);oe>0&&(u=(u+oe)%n.capacityFrames,h-=oe);const be=L+oe;b+=be;const H=new DataView(F,ne,O);for(let me=L;me<ee;me+=1){const ue=f*n.channels,Ce=me*n.channels;for(let Me=0;Me<n.channels;Me+=1){const He=(Ce+Me)*ce,Ve=W?H.getInt16(He,!0)/32768:H.getFloat32(He,!0);l[ue+Me]=Number.isFinite(Ve)?Math.max(-1,Math.min(1,Ve)):0}f=(f+1)%n.capacityFrames}return h+=B,!y&&h>=i&&(y=!0),k.acceptedFrames=B,k.droppedFrames=be,k};return{writePcm:(F={})=>T(F.buffer,F.byteOffset,F.byteLength,F.sampleFormat),writePcmBuffer:T,readToChannels:(F,Y=n.sampleRate)=>{if(!Array.isArray(F)||F.length===0)return;let D=Number.POSITIVE_INFINITY;for(let q=0;q<F.length;q+=1){const O=F[q];D=Math.min(D,O?.length||0)}if(w||!Number.isFinite(D)||D<=0||!y){for(let q=0;q<F.length;q+=1)F[q]?.fill?.(0);return}const K=Math.max(8e3,Math.min(192e3,sc(Y,n.sampleRate))),ne=n.sampleRate/K;for(let q=0;q<D;q+=1){if(h<=0){y=!1,x+=1,g=0;for(let ce=0;ce<F.length;ce+=1)F[ce].fill(0,q);break}const O=u*n.channels;for(let ce=0;ce<F.length;ce+=1){const $=Math.min(ce,n.channels-1);F[ce][q]=l[O+$]}g+=ne;const W=Math.min(h,Math.floor(g));W>0&&(u=(u+W)%n.capacityFrames,h-=W,g-=W)}},flush:E,dispose:I,snapshot:N,getSnapshotCount:()=>M}}function o1(t={}){const n=Math.max(1,Math.min(sv,sc(t.maxPendingPackets,sv))),r=Math.max(1,sc(t.maxPendingBytes,1)),i=new Map;let l=0,u=0,f=0,h=0,g=0,y=!1;const w=()=>({terminal:y,maxPendingPackets:n,maxPendingBytes:r,pendingPacketCount:i.size,pendingPacketBytes:l,pendingPacketHighWater:u,pendingByteHighWater:f,acceptedCount:h,droppedCount:g});return{claim(b,x){const M=typeof b=="number"&&Number.isFinite(b)?b:String(b||""),k=Math.max(0,Math.floor(Number(x)||0));return y||!M||k<=0||i.has(M)||i.size>=n||l+k>r?(g+=1,!1):(i.set(M,k),l+=k,u=Math.max(u,i.size),f=Math.max(f,l),h+=1,!0)},acknowledge(b){const x=typeof b=="number"&&Number.isFinite(b)?b:String(b||""),M=i.get(x);return M===void 0?!1:(i.delete(x),l=Math.max(0,l-M),!0)},terminate(){return i.clear(),l=0,y=!0,w()},getPendingPacketCount:()=>i.size,getPendingPacketBytes:()=>l,getPendingPacketHighWater:()=>u,getPendingByteHighWater:()=>f,snapshot:w}}function nh(t,n){const r=String(t?.name||"");if(!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(r)||!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(n))throw new Error("Remote Audio worklet function binding name is invalid.");const i=`const ${r} = ${Function.prototype.toString.call(t)};`;return r===n?i:`${i}
12
+ const ${n} = ${r};`}const l1=nh(sc,"positiveInteger"),c1=nh(Dv,"normalizeRemoteAudioPcmFormat"),u1=nh(Iv,"remoteAudioPcmRingCapacity"),d1=nh(i1,"createRemoteAudioPcmRing"),f1=`
13
+ const REMOTE_AUDIO_PCM_RING_MAX_MS = ${t1};
14
+ const REMOTE_AUDIO_PCM_TARGET_LEAD_MS = ${n1};
15
+ ${l1}
16
+ ${c1}
17
+ ${u1}
18
+ ${d1}
19
+
20
+ class LiveDeskRemoteAudioProcessor extends AudioWorkletProcessor {
21
+ constructor() {
22
+ super();
23
+ this.ring = null;
24
+ this.ringSampleRate = 0;
25
+ this.ringChannels = 0;
26
+ this.ringSampleFormat = '';
27
+ this.disposed = false;
28
+ this.reportFrames = 0;
29
+ this.port.onmessage = event => this.handleMessage(event?.data || {});
30
+ }
31
+
32
+ postRingState(type, extra = {}) {
33
+ const ringState = this.ring?.snapshot?.() || {
34
+ capacityBytes: 0,
35
+ bufferedBytes: 0,
36
+ bufferedMs: 0,
37
+ droppedFrames: 0,
38
+ underflowCount: 0
39
+ };
40
+ this.port.postMessage({
41
+ type,
42
+ ...extra,
43
+ ringCapacityBytes: Number(ringState.capacityBytes || 0),
44
+ ringBufferedBytes: Number(ringState.bufferedBytes || 0),
45
+ ringBufferedMs: Number(ringState.bufferedMs || 0),
46
+ ringDroppedFrames: Number(ringState.droppedFrames || 0),
47
+ ringUnderflowCount: Number(ringState.underflowCount || 0)
48
+ });
49
+ }
50
+
51
+ handleMessage(message) {
52
+ const type = String(message.type || '');
53
+ if (type === 'dispose') {
54
+ this.disposed = true;
55
+ this.ring?.dispose?.();
56
+ this.ring = null;
57
+ this.ringSampleRate = 0;
58
+ this.ringChannels = 0;
59
+ this.ringSampleFormat = '';
60
+ this.postRingState('disposed');
61
+ return;
62
+ }
63
+ if (this.disposed) {
64
+ if (type === 'pcm') {
65
+ this.port.postMessage({
66
+ type: 'packet-terminal',
67
+ packetId: message.packetId ?? 0,
68
+ acceptedFrames: 0,
69
+ droppedFrames: 0
70
+ });
71
+ }
72
+ return;
73
+ }
74
+ if (type === 'flush') {
75
+ this.ring?.flush?.();
76
+ this.postRingState('ring-state');
77
+ return;
78
+ }
79
+ if (type !== 'pcm') {
80
+ return;
81
+ }
82
+
83
+ try {
84
+ const sourceSampleRate = Math.max(
85
+ 8_000,
86
+ Math.min(192_000, positiveInteger(message.sampleRate, 48_000))
87
+ );
88
+ const sourceChannels = Math.max(
89
+ 1,
90
+ Math.min(8, positiveInteger(message.channels, 2))
91
+ );
92
+ const sourceSampleFormat =
93
+ message.sampleFormat === 's16le' ? 's16le' : 'f32le';
94
+ const ringCreated = !this.ring
95
+ || this.ringSampleRate !== sourceSampleRate
96
+ || this.ringChannels !== sourceChannels
97
+ || this.ringSampleFormat !== sourceSampleFormat;
98
+ if (ringCreated) {
99
+ this.ring?.dispose?.();
100
+ this.ring = createRemoteAudioPcmRing({
101
+ sampleRate: sourceSampleRate,
102
+ channels: sourceChannels,
103
+ sampleFormat: sourceSampleFormat,
104
+ maxDurationMs: REMOTE_AUDIO_PCM_RING_MAX_MS,
105
+ targetLeadMs: REMOTE_AUDIO_PCM_TARGET_LEAD_MS
106
+ });
107
+ this.ringSampleRate = sourceSampleRate;
108
+ this.ringChannels = sourceChannels;
109
+ this.ringSampleFormat = sourceSampleFormat;
110
+ this.postRingState('ring-configured');
111
+ }
112
+ const result = this.ring.writePcmBuffer(
113
+ message.buffer,
114
+ message.byteOffset,
115
+ message.byteLength,
116
+ sourceSampleFormat
117
+ );
118
+ this.port.postMessage({
119
+ type: 'packet-terminal',
120
+ packetId: message.packetId ?? 0,
121
+ acceptedFrames: Number(result.acceptedFrames || 0),
122
+ droppedFrames: Number(result.droppedFrames || 0)
123
+ });
124
+ } catch (error) {
125
+ this.port.postMessage({
126
+ type: 'processor-error',
127
+ packetId: message.packetId ?? 0,
128
+ error: error instanceof Error ? error.message : String(error)
129
+ });
130
+ }
131
+ }
132
+
133
+ process(_inputs, outputs) {
134
+ try {
135
+ if (this.disposed) {
136
+ return false;
137
+ }
138
+ const output = outputs && outputs.length > 0 ? outputs[0] : null;
139
+ if (!output) {
140
+ return true;
141
+ }
142
+ const outputFrames = output.length > 0 ? output[0].length : 0;
143
+ if (this.ring) {
144
+ this.ring.readToChannels(output, sampleRate);
145
+ } else {
146
+ for (let channelIndex = 0; channelIndex < output.length; channelIndex += 1) {
147
+ output[channelIndex].fill(0);
148
+ }
149
+ }
150
+ this.reportFrames += outputFrames;
151
+ if (this.reportFrames >= Math.max(1, Math.floor(sampleRate / 4))) {
152
+ this.reportFrames = 0;
153
+ this.postRingState('ring-state');
154
+ }
155
+ return true;
156
+ } catch (error) {
157
+ this.disposed = true;
158
+ this.port.postMessage({
159
+ type: 'processor-error',
160
+ packetId: 0,
161
+ error: error instanceof Error ? error.message : String(error)
162
+ });
163
+ return false;
164
+ }
165
+ }
166
+ }
167
+
168
+ registerProcessor(
169
+ '${SS}',
170
+ LiveDeskRemoteAudioProcessor
171
+ );
172
+ `,Zb="livedesk_remote_host_targets",m1="livedesk_entitlements",Jb=4e3,p1=2500,Lv=new TextDecoder,ov=new Set;function h1(){const t=[...ov].map(r=>r()),n=r=>t.reduce((i,l)=>i+Number(l[r]||0),0);return{ownerCount:t.length,activeOwnerCount:t.filter(r=>r.active).length,socketCount:n("socketCount"),openSocketCount:n("openSocketCount"),connectingSocketCount:n("connectingSocketCount"),closingSocketCount:n("closingSocketCount"),closingSocketTimerCount:n("closingSocketTimerCount"),closingSocketTimeoutCount:n("closingSocketTimeoutCount"),expectedBindingCount:n("expectedBindingCount"),reconnectTimerCount:n("reconnectTimerCount"),statsTimerCount:n("statsTimerCount"),configurationRefreshTimerCount:n("configurationRefreshTimerCount"),restartTokenCount:n("restartTokenCount"),retainedFrameCount:n("retainedFrameCount"),retainedPayloadBytes:n("retainedPayloadBytes"),owners:t}}function g1(){return ha.snapshot()}function v1(t){const r=(Array.isArray(t)?t:[t||Dn]).map(i=>ho(i||Dn));return[...new Set(r.filter(Boolean))]}function y1(){const[t,n]=d.useState(null),[r,i]=d.useState(!0);return d.useEffect(()=>{let l=!0;const u=window.liveDesk?.auth?.onComplete?.(h=>{h.ok&&h.session&&Pt.auth.setSession(h.session)});(window.liveDesk?.auth?.getSession?.()||Pt.auth.getSession()).then(h=>{l&&(n(qx(h)),i(!1))});const{data:{subscription:f}}=Pt.auth.onAuthStateChange((h,g)=>{n(g),i(!1),window.liveDesk?.auth?.persistSession?.(g)});return()=>{l=!1,u?.(),f.unsubscribe()}},[]),{session:t,loading:r}}function b1(t,n=!0){const[r,i]=d.useState(null),[l,u]=d.useState([]),[f,h]=d.useState(""),[g,y]=d.useState(""),w=d.useRef(new Map),b=d.useRef(null),x=Array.isArray(t)?t.join(`
173
+ `):String(t||""),M=d.useMemo(()=>v1(t),[x]),k=d.useMemo(()=>M.find(I=>hd(I)==="loopback")||M[0]||Dn,[M]),N=d.useCallback(async I=>{if(!n){i(null),u([]),y(""),h("");return}let T=null;const P=Date.now(),U=M.filter(F=>(w.current.get(F)||0)<=P);if(U.length===0)throw new Error("No LiveDesk Hub endpoint is reachable. Retrying shortly.");for(const F of U)try{const[Y,D]=await Promise.all([tt("/api/remote/status",{signal:I,timeoutMs:Jb},F),tt("/api/remote/devices",{signal:I,timeoutMs:Jb},F)]);if(I?.aborted)throw I.reason||new Error("LiveDesk Hub snapshot cancelled.");if(!Array.isArray(D.devices))throw new Error("Invalid Hub devices response.");w.current.delete(F),i(Y),u(D.devices),y(F),h("");return}catch(Y){if(I?.aborted)throw Y;T=Y,w.current.set(F,Date.now()+1e4)}throw y(""),T||new Error("No LiveDesk Hub endpoint is reachable.")},[n,M]),E=d.useCallback(()=>{w.current.clear(),Op(b,()=>N()).catch(I=>{h(I instanceof Error?I.message:String(I))})},[N]);return d.useEffect(()=>{if(!n){i(null),u([]),y(""),h("");return}let I=!0,T=null;const P=new AbortController,U=()=>{Op(b,()=>N(P.signal)).catch(Y=>{I&&!P.signal.aborted&&h(Y instanceof Error?Y.message:String(Y))}).finally(()=>{I&&!P.signal.aborted&&(T=window.setTimeout(U,p1))})};return U(),()=>{I=!1,P.abort(new Error("LiveDesk Hub snapshot polling stopped.")),T!==null&&window.clearTimeout(T)}},[n,N]),{status:r,devices:l,error:f,refresh:E,hubBaseUrl:g||k,hubCandidates:M}}function w1(t){const[n,r]=d.useState(null),[i,l]=d.useState(""),u=t?.user?.id||"",f=d.useCallback(async()=>{if(!u){r(null);return}const{data:h,error:g}=await Pt.from(Zb).select("*").eq("user_id",u).maybeSingle();if(g){l(g.message);return}r(h),l("")},[u]);return d.useEffect(()=>{f()},[f]),d.useEffect(()=>{if(!u)return;const h=Pt.channel(`livedesk-remote-host-targets-${u.replace(/[^a-zA-Z0-9]/g,"")}`).on("postgres_changes",{event:"*",schema:"public",table:Zb,filter:`user_id=eq.${u}`},g=>r(g.new)).subscribe();return()=>{Pt.removeChannel(h)}},[u]),{target:n,error:i,refresh:f}}function x1(t){const[n,r]=d.useState(null),[i,l]=d.useState(!1),[u,f]=d.useState(""),h=t?.user?.id||"",g=d.useCallback(async()=>{if(!h){r(null),f(""),l(!1);return}l(!0);const{data:w,error:b}=await Pt.from(m1).select("*").eq("user_id",h).eq("product_key","livedesk").maybeSingle();if(b){f(b.message),l(!1);return}r(w),f(""),l(!1)},[h]);d.useEffect(()=>{g()},[g]);const y=d.useMemo(()=>!n||n.status!=="active"?!1:n.expires_at?new Date(n.expires_at).getTime()>Date.now():!0,[n]);return{entitlement:n,licensed:y,loading:i,error:u,refresh:g}}const Vf={totalFrames:0,totalBytes:0,framesPerSecond:0,bytesPerSecond:0,sampleMs:0,lastUpdatedAt:0},S1=2500,C1=3e4,k1=64*1024,M1=64*1024,A1=64,gg=1500,N1=150,T1=1e3,R1=6,j1=R1,CS=new Map;function E1(t){return CS.get(t)}const ew={totalSent:0,totalDropped:0,sentPerSecond:0,droppedPerSecond:0,bufferedAmount:0,lastInputType:"",lastInputSeq:0,lastRoundTripMs:0,lastAgentApplyMs:0,lastUpdatedAt:0};function D1(t,n,r){const i=Number(n);if(!Number.isFinite(i)||i<=0)return 0;const l=r-i,u=t.minimumHubClockOffsetMs;if(!Number.isFinite(u)||l<Number(u))return t.minimumHubClockOffsetMs=l,0;const f=Math.max(0,l-Number(u));return f>C1?(t.minimumHubClockOffsetMs=l,0):f}function ht(t){if(t==null||t==="")return;const n=Number(t);return Number.isFinite(n)?n:void 0}const I1=["nativeEncodeFramesInFlight","nativeEncodePendingFrameCount","nativeEncodeTimestampOwnerCount","nativeEncodeTimestampOwnerHighWatermark","nativeBackpressureCoalescedFrameCount","nativeBackpressureSkippedFrameCount","nativeEncodePendingReplacedFrameCount","nativeIdleSkippedFrameCount","nativeVideoToolboxActiveSessionCount","nativeVideoToolboxSessionHighWatermark","nativeOutputQueueDepth","nativeOutputQueueBytes","nativeOutputQueueOldestAgeMs","nativeOutputQueueHighWatermark","nativeOutputQueueDroppedCount","nativeAnnexBAccessUnitAllocationCount","nativeAnnexBPayloadCopyCount","nativeAnnexBPayloadCopiedBytes","nativeAndPipeResidenceAgeMs","pipePayloadAllocationCount","pipePayloadCopyCount","pipePayloadCopiedBytes","handoffDroppedFrameCount","handoffRecoveryKeyFrameRequestCount","handoffOldestFrameAgeMs"];function L1(t){return Number(t.nativeCaptureTelemetryVersion)>=5&&I1.every(n=>ht(t[n])!==void 0)&&typeof t.nativeOutputQueueAwaitingKeyFrame=="boolean"&&t.nativeCopyTelemetryAvailable===!0}function _1(t,n,r){if(!t||typeof t!="object")return null;const i=t,l=String(i.deviceId||n||"").trim(),u=String(i.sessionId||"").trim(),f=String(i.streamId||"").trim(),h=i.streamPurpose==="control"?"control":i.streamPurpose==="wall"?"wall":null,g=String(i.commandId||"").trim(),y=Number(i.captureGeneration||0),w=Number(i.monitorIndex??-1);return!l||l!==n||!h||h!==r||!u||!f||!g||!Number.isSafeInteger(y)||y<=0||!Number.isSafeInteger(w)||w<0?null:{deviceId:l,sessionId:u,streamId:f,streamPurpose:h,commandId:g,captureGeneration:y,monitorIndex:w}}function tw(t,n,r=Dn,i={}){const[l,u]=d.useState(new Map),[f,h]=d.useState("idle"),[g,y]=d.useState(""),[w,b]=d.useState(Vf),x=d.useRef(new Map),M=d.useRef(new Map),k=d.useRef(new Map),N=d.useRef(null);N.current===null&&(N.current=HA());const E=d.useRef(0),I=d.useRef(new Map),T=d.useRef({enabled:!1,token:"",reason:""}),P=d.useRef(new Map),U=d.useRef(null),F=d.useRef(null),[Y,D]=d.useState(0),K=d.useRef(i.onFrame),ne=d.useRef(i.onStreamReady),q=d.useRef({totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0}),O=d.useMemo(()=>[...t].sort().join(","),[t]),W=n&&O.length>0,ce=d.useRef(!1);d.useLayoutEffect(()=>(ce.current=W,()=>{ce.current=!1}),[W]);const $=Number.isFinite(i.fps)?Number(i.fps):2,ee=Number.isFinite(i.maxWidth)?Number(i.maxWidth):640,B=Number.isFinite(i.maxHeight)?Number(i.maxHeight):360,L=Number.isFinite(i.quality)?Number(i.quality):45,oe=Number.isFinite(i.configurationRefreshMs)?Math.max(0,Math.round(Number(i.configurationRefreshMs))):0,be=String(i.frameMode||i.mode||"mode3-h264-hw").trim()||"mode3-h264-hw",H=i.streamPurpose==="control"?"control":"wall",me=i.forceRestart===!0,ue=String(i.forceRestartToken||"").trim(),Ce=String(i.restartReason||"").trim();T.current={enabled:me,token:ue,reason:Ce};const Me=d.useMemo(()=>{const he=Object.entries(i.monitorSelections||{}).filter(([pe])=>!!pe).sort(([pe],[Ae])=>pe.localeCompare(Ae));return JSON.stringify(Object.fromEntries(he))},[i.monitorSelections]),Ne=d.useMemo(()=>{const he=Object.entries(i.connectionSessionIds||{}).filter(([pe])=>!!pe).map(([pe,Ae])=>[pe,String(Ae||"").trim()]).sort(([pe],[Ae])=>pe.localeCompare(Ae));return JSON.stringify(Object.fromEntries(he))},[i.connectionSessionIds]);d.useEffect(()=>{K.current=i.onFrame},[i.onFrame]),d.useEffect(()=>{ne.current=i.onStreamReady},[i.onStreamReady]);const He=d.useCallback((he,pe="livedesk-frame-socket-release")=>{BA(he,pe,N.current)},[]),Ve=d.useCallback(he=>{const pe=P.current.get(he);pe!==void 0&&(window.clearTimeout(pe),P.current.delete(he))},[]),ie=d.useCallback((he,pe=!0)=>{for(const Ae of P.current.values())window.clearTimeout(Ae);P.current.clear();for(const Ae of k.current.values())Ae.expectedBinding=void 0,He(Ae,he);k.current.clear(),I.current.clear(),x.current=new Map,M.current.clear(),q.current={totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0},pe&&(u(new Map),y(""),b(Vf),h("idle"))},[He]),Oe=d.useCallback(()=>{const he=[...k.current.values()].map(pe=>pe.socket);if(he.length===0){h("idle");return}if(he.some(pe=>pe.readyState===WebSocket.OPEN)){h("open");return}if(he.some(pe=>pe.readyState===WebSocket.CONNECTING)){h("connecting");return}h("closed")},[]),$e=d.useCallback((he,pe,Ae,Se)=>{if(pe.disposed||pe.socket.readyState!==WebSocket.OPEN)return!1;try{return pe.socket.send(JSON.stringify({...pe.payload,type:"restart-live",deviceIds:[he],forceRestart:!0,restartReason:Ae,restartToken:Se})),pe.expectedBinding=void 0,Qb(pe.sparseTelemetry),!0}catch{return!1}},[]),qe=d.useCallback((he,pe)=>{if(!ce.current||pe.disposed||!he||he.byteLength<5)return;const Ae=Date.now(),Pe=new DataView(he).getUint32(0,!1);if(Pe<=0||Pe+4>he.byteLength)return;const Qe=new Uint8Array(he,4,Pe),Z=JSON.parse(Lv.decode(Qe));WA(Z,pe.sparseTelemetry,pe.expectedBinding);const $t=ht(Z.hubPacketEpochMs),Ee=$t!==void 0&&$t>0?$t:void 0,Ge=D1(pe,Ee,Ae);if(Ge>S1)return;const ze=new Uint8Array(he,4+Pe),Ft=ht(Z.nativeCaptureTelemetryVersion),Ze=ht(Z.nativeCaptureTelemetryAgeMs),nt=ht(Z.hubClientDropped),lt=ht(Z.hubClientQueueDepth),Tt=ht(Z.hubClientQueueLimit),Mt=ht(Z.hubClientBufferedBytes),rt=nt!==void 0&&lt!==void 0&&Tt!==void 0&&Mt!==void 0,dt={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,currentGenerationVerified:!1,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,inputFeedbackEventId:Z.inputFeedbackEventId?String(Z.inputFeedbackEventId):void 0,inputFeedbackInputSeq:ht(Z.inputFeedbackInputSeq),inputFeedbackInputType:Z.inputFeedbackInputType?String(Z.inputFeedbackInputType):void 0,inputFeedbackIssuedAtEpochMs:ht(Z.inputFeedbackIssuedAtEpochMs),inputFeedbackHubReceivedAtEpochMs:ht(Z.inputFeedbackHubReceivedAtEpochMs),inputFeedbackHubForwardedAtEpochMs:ht(Z.inputFeedbackHubForwardedAtEpochMs),inputFeedbackAgentReceivedAtEpochMs:ht(Z.inputFeedbackAgentReceivedAtEpochMs),inputFeedbackAppliedAtEpochMs:ht(Z.inputFeedbackAppliedAtEpochMs),inputFeedbackAgentApplyMs:ht(Z.inputFeedbackAgentApplyMs),inputFeedbackApplyToCaptureMs:ht(Z.inputFeedbackApplyToCaptureMs),inputFeedbackCaptureTimestampAvailable:typeof Z.inputFeedbackCaptureTimestampAvailable=="boolean"?Z.inputFeedbackCaptureTimestampAvailable:void 0,nativeCaptureTelemetryAvailable:typeof Z.nativeCaptureTelemetryAvailable=="boolean"?Z.nativeCaptureTelemetryAvailable:void 0,nativeCaptureTelemetryVersion:Ft===void 0?void 0:Math.max(0,Ft),nativeCaptureTelemetryAgeMs:Ze===void 0?void 0:Math.max(0,Ze),nativeEncoderHardwareAccelerationKnown:typeof Z.nativeEncoderHardwareAccelerationKnown=="boolean"?Z.nativeEncoderHardwareAccelerationKnown:void 0,nativeEncoderHardwareAccelerated:typeof Z.nativeEncoderHardwareAccelerated=="boolean"?Z.nativeEncoderHardwareAccelerated:void 0,nativeEncoderHardwareQueryStatus:Z.nativeEncoderHardwareQueryStatus?String(Z.nativeEncoderHardwareQueryStatus):void 0,nativeCaptureDisplayId:ht(Z.nativeCaptureDisplayId),nativeCaptureFps:ht(Z.nativeCaptureFps),nativeCompressionFps:ht(Z.nativeCompressionFps),nativeEncodedFps:ht(Z.nativeEncodedFps),nativeCaptureSampleCount:ht(Z.nativeCaptureSampleCount),nativeEncodableFrameCount:ht(Z.nativeEncodableFrameCount),nativeSkippedFrameCount:ht(Z.nativeSkippedFrameCount),nativeCompressionOutputCount:ht(Z.nativeCompressionOutputCount),nativeEncodedFrameCount:ht(Z.nativeEncodedFrameCount),nativeEncodeFramesInFlight:ht(Z.nativeEncodeFramesInFlight),nativeEncodePendingFrameCount:ht(Z.nativeEncodePendingFrameCount),nativeEncodeTimestampOwnerCount:ht(Z.nativeEncodeTimestampOwnerCount),nativeEncodeTimestampOwnerHighWatermark:ht(Z.nativeEncodeTimestampOwnerHighWatermark),nativeBackpressureCoalescedFrameCount:ht(Z.nativeBackpressureCoalescedFrameCount),nativeBackpressureSkippedFrameCount:ht(Z.nativeBackpressureSkippedFrameCount),nativeEncodePendingReplacedFrameCount:ht(Z.nativeEncodePendingReplacedFrameCount),nativeIdleSkippedFrameCount:ht(Z.nativeIdleSkippedFrameCount),nativeVideoToolboxActiveSessionCount:ht(Z.nativeVideoToolboxActiveSessionCount),nativeVideoToolboxSessionHighWatermark:ht(Z.nativeVideoToolboxSessionHighWatermark),nativeOutputQueueDepth:ht(Z.nativeOutputQueueDepth),nativeOutputQueueBytes:ht(Z.nativeOutputQueueBytes),nativeOutputQueueOldestAgeMs:ht(Z.nativeOutputQueueOldestAgeMs),nativeOutputQueueHighWatermark:ht(Z.nativeOutputQueueHighWatermark),nativeOutputQueueDroppedCount:ht(Z.nativeOutputQueueDroppedCount),nativeOutputQueueAwaitingKeyFrame:typeof Z.nativeOutputQueueAwaitingKeyFrame=="boolean"?Z.nativeOutputQueueAwaitingKeyFrame:void 0,nativeCopyTelemetryAvailable:typeof Z.nativeCopyTelemetryAvailable=="boolean"?Z.nativeCopyTelemetryAvailable:void 0,nativeAnnexBAccessUnitAllocationCount:ht(Z.nativeAnnexBAccessUnitAllocationCount),nativeAnnexBPayloadCopyCount:ht(Z.nativeAnnexBPayloadCopyCount),nativeAnnexBPayloadCopiedBytes:ht(Z.nativeAnnexBPayloadCopiedBytes),nativeAndPipeResidenceAgeMs:ht(Z.nativeAndPipeResidenceAgeMs),pipePayloadAllocationCount:ht(Z.pipePayloadAllocationCount),pipePayloadCopyCount:ht(Z.pipePayloadCopyCount),pipePayloadCopiedBytes:ht(Z.pipePayloadCopiedBytes),handoffDroppedFrameCount:ht(Z.handoffDroppedFrameCount),handoffRecoveryKeyFrameRequestCount:ht(Z.handoffRecoveryKeyFrameRequestCount),handoffOldestFrameAgeMs:ht(Z.handoffOldestFrameAgeMs),nativeCaptureResourceTelemetryAvailable:Z.nativeCaptureResourceTelemetryAvailable===!0?L1(Z):Z.nativeCaptureResourceTelemetryAvailable===!1?!1:void 0,nativeCaptureTelemetryAt:Z.nativeCaptureTelemetryAt?String(Z.nativeCaptureTelemetryAt):void 0,droppedByAgent:Number(Z.droppedByAgent||0)||0,hubIngressDropped:Number(Z.hubIngressDropped||0)||0,hubClientDropped:nt,transport:Z.transport?String(Z.transport):void 0,videoTransport:Z.videoTransport?String(Z.videoTransport):void 0,frameTransportActive:Z.frameTransportActive?String(Z.frameTransportActive):void 0,frameTransportProtocol:Z.frameTransportProtocol?String(Z.frameTransportProtocol):void 0,frameTransportState:Z.frameTransportState?String(Z.frameTransportState):void 0,frameTransportReason:Z.frameTransportReason?String(Z.frameTransportReason):void 0,frameTransportChangedAt:Z.frameTransportChangedAt?String(Z.frameTransportChangedAt):void 0,frameTransportSwitchCount:Number(Z.frameTransportSwitchCount||0)||0,frameTransportTcpFailureCount:Number(Z.frameTransportTcpFailureCount||0)||0,frameTransportP2pReady:Z.frameTransportP2pReady===!0,hubClientQueueTelemetryAvailable:rt,hubClientQueueDepth:lt,hubClientQueueLimit:Tt,hubClientBufferedBytes:Mt,udpIncompleteFrames:Number(Z.udpIncompleteFrames||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,captureTimingAvailable:Z.captureTimingAvailable===!0,captureAverageMs:ht(Z.captureAverageMs),captureP95Ms:ht(Z.captureP95Ms),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:Ee,browserReceivedEpochMs:Ae,hubPacketTransitAgeMs:Ee!==void 0?Ge:void 0,byteLength:Number(Z.byteLength||ze.byteLength),contentHash:Z.contentHash?String(Z.contentHash):void 0,captureMs:ht(Z.captureMs),captureStageMs:ht(Z.captureStageMs),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:ze};if(!dt.deviceId)return;const G=pe.expectedBinding;if(!G)return;const ge=dt.deviceId===G.deviceId&&String(dt.sessionId||"")===G.sessionId&&dt.streamId===G.streamId&&String(dt.commandId||"")===G.commandId&&Number(dt.captureGeneration||0)===G.captureGeneration&&Number(dt.monitorIndex??-1)===G.monitorIndex&&String(dt.streamPurpose||"")===G.streamPurpose;if(!ge)return;dt.currentGenerationVerified=ge;const De=Number(pe.payload.monitorSelections?.[dt.deviceId]);if(Number.isFinite(De)&&Number.isFinite(Number(dt.monitorIndex))&&Number(dt.monitorIndex)!==De)return;const z={streamId:pe.lastFrameStreamId,commandId:pe.lastFrameCommandId,order:pe.lastFrameOrder},ae=Number(dt.streamFrameSeq||dt.frameSeq||0),Te=!!z.commandId&&!!dt.commandId,Ue=z.streamId===dt.streamId&&(!Te||z.commandId===dt.commandId),Xe=z.order;if(Ue&&Xe>=ae&&(Xe===ae||Te))return;pe.lastFrameStreamId=dt.streamId,pe.lastFrameCommandId=dt.commandId||"",pe.lastFrameOrder=ae;const at=q.current;at.totalFrames+=1,at.totalBytes+=ze.byteLength,at.sampleFrames+=1,at.sampleBytes+=ze.byteLength;const kt=!x.current.has(dt.deviceId)&&!M.current.has(dt.deviceId),At=PA(M.current,dt);kt&&(x.current.set(dt.deviceId,At),M.current.delete(dt.deviceId),u(new Map(x.current))),K.current?.(dt)},[]);d.useEffect(()=>{if(!n||!O)return;q.current.sampleStartedAt=performance.now();const he=window.setInterval(()=>{if(!ce.current)return;const pe=performance.now(),Ae=q.current,Se=Math.max(1,pe-Ae.sampleStartedAt);b({totalFrames:Ae.totalFrames,totalBytes:Ae.totalBytes,framesPerSecond:Ae.sampleFrames*1e3/Se,bytesPerSecond:Ae.sampleBytes*1e3/Se,sampleMs:Se,lastUpdatedAt:Date.now()}),u(FA(x.current,M.current)),Ae.sampleFrames=0,Ae.sampleBytes=0,Ae.sampleStartedAt=pe},2e3);return U.current=he,()=>{window.clearInterval(he),U.current===he&&(U.current=null)}},[n,O]),d.useEffect(()=>{const he=()=>{const pe=new Set,Ae=[...k.current.values()];for(;Ae.length>0;){const Z=Ae.pop();!Z||pe.has(Z)||(pe.add(Z),Z.handoffFrom&&Ae.push(Z.handoffFrom))}const Se=[...x.current.values(),...M.current.values()],Pe=[...pe],Qe=N.current?.snapshot()||{closingSocketCount:0,closingSocketTimerCount:0,closingSocketTimeoutCount:0};return{deviceKey:O,active:ce.current,socketCount:Pe.length+Qe.closingSocketCount,openSocketCount:Pe.filter(Z=>Z.socket.readyState===WebSocket.OPEN).length,connectingSocketCount:Pe.filter(Z=>Z.socket.readyState===WebSocket.CONNECTING).length,closingSocketCount:Qe.closingSocketCount,closingSocketTimerCount:Qe.closingSocketTimerCount,closingSocketTimeoutCount:Qe.closingSocketTimeoutCount,expectedBindingCount:Pe.filter(Z=>!!Z.expectedBinding).length,reconnectTimerCount:P.current.size,statsTimerCount:U.current===null?0:1,configurationRefreshTimerCount:F.current===null?0:1,restartTokenCount:I.current.size,retainedFrameCount:Se.length,retainedPayloadBytes:Se.reduce((Z,$t)=>Z+Math.max(0,Number($t.payload?.byteLength||0)),0)}};return ov.add(he),()=>{ov.delete(he)}},[O]),d.useEffect(()=>{const he=O?O.split(",").filter(Boolean):[];if(!W){ie(n?"livedesk-no-devices":"livedesk-stream-inactive");return}const pe=new Set(he),Ae=performance.now();for(const Se of P.current.keys())pe.has(Se)||Ve(Se);for(const[Se,Pe]of k.current.entries())pe.has(Se)||(Ve(Se),He(Pe,"livedesk-device-unsubscribed"),k.current.delete(Se),I.current.delete(Se),x.current.delete(Se),M.current.delete(Se));q.current.sampleStartedAt<=0&&(q.current.sampleStartedAt=Ae,b({...Vf,lastUpdatedAt:Date.now()}));for(const Se of he){Ve(Se);const Pe=Number(i.monitorSelections?.[Se]),Qe=Number.isInteger(Pe)&&Pe>=0?Pe:0,Z={[Se]:Qe},$t={type:"subscribe",deviceIds:[Se],autoStartLive:n,fps:$,maxWidth:ee,maxHeight:B,quality:L,mode:be,frameMode:be,streamPurpose:H,monitorSelections:Z},Ee=String(i.connectionSessionIds?.[Se]||"").trim(),Ge=JSON.stringify({subscribePayload:$t,connectionSessionId:Ee}),ze=k.current.get(Se),Ft=Number(ze?.payload.monitorSelections?.[Se]),Ze=Number(Z[Se]),nt=!!ze&&Number.isFinite(Ft)&&Number.isFinite(Ze)&&Ft!==Ze,lt=!!ze&&ze?.connectionSessionId!==Ee;if(ze){const Te=ze.socket.readyState===WebSocket.CONNECTING||ze.socket.readyState===WebSocket.OPEN;if(ze.payloadKey===Ge&&Te&&!ze.disposed)continue}const Tt=ze&&(ze.socket.readyState===WebSocket.CONNECTING||ze.socket.readyState===WebSocket.OPEN)&&!ze.disposed?ze.handoffFrom&&!ze.handoffCompleted?ze.handoffFrom:ze:void 0,Mt=ze&&ze!==Tt?ze:void 0,rt=new WebSocket(Yp(`/api/remote/frames/ws?devices=${encodeURIComponent(Se)}`,r),Xp(r));rt.binaryType="arraybuffer";const dt=qA(),G={socket:rt,payload:$t,payloadKey:Ge,connectionSessionId:Ee,generation:E.current+1,monitorRestartToken:nt?`monitor-${Se}-${Ze}-${E.current+1}`:"",disposed:!1,handoffFrom:Tt,handoffCompleted:!1,lastFrameStreamId:"",lastFrameCommandId:"",lastFrameOrder:-1,sparseTelemetry:dt,releaseOwnedState:()=>Qb(dt)};E.current=G.generation,(nt||lt)&&(x.current.delete(Se),M.current.delete(Se),u(new Map(x.current))),k.current.set(Se,G),Mt&&(Mt.handoffFrom=void 0,He(Mt,"livedesk-subscription-superseded"));const ge=()=>{if(!ce.current||G.disposed||k.current.get(Se)!==G){He(G,"livedesk-stale-frame-socket");return}Ve(Se),y("");const Te=T.current,Ue=Te.enabled&&(!Te.token||I.current.get(Se)!==Te.token),Xe=Ue||G.monitorRestartToken!=="",at=Ue?Te.token:G.monitorRestartToken,kt=Ue?Te.reason:G.monitorRestartToken?"monitor-selection-change":"";rt.send(JSON.stringify({...G.payload,forceRestart:Xe,restartReason:Xe?kt:"",restartToken:Xe?at:""})),Ue&&Te.token&&I.current.set(Se,Te.token);const At=G.handoffFrom;G.handoffFrom=void 0,G.handoffCompleted=!0,At&&!At.disposed&&He(At,"livedesk-subscription-replaced"),Oe()},De=Te=>{if(!ce.current||G.disposed||k.current.get(Se)!==G)return;if(typeof Te.data=="string"){try{const Xe=JSON.parse(Te.data),at=(kt,At=!0)=>{const Ut=_1(kt,Se,H);return Ut?(G.expectedBinding=Ut,At&&ne.current?.(Ut),!0):!1};if(Xe?.type==="RemoteFrameSubscriptionError")y(String(Xe.error||"control-stream-start-failed"));else if(Xe?.type==="RemoteFrameLiveAutoStart"){const At=(Array.isArray(Xe.skipped)?Xe.skipped:[]).find(Ut=>Ut?.deviceId===Se);if(At)At.reason==="CAPTURE_TRANSITION_IN_PROGRESS"&&At.retryScheduled===!0?y(""):y(String(At.reason||"control-stream-start-failed"));else if(Array.isArray(Xe.started)){const Ut=Xe.started.find(Qt=>Qt?.deviceId===Se);Ut&&(y(""),at(Ut,Ut.ready===!0))}}else Xe?.type==="RemoteFrameStreamReady"&&Xe.deviceId===Se&&at(Xe)&&y("")}catch{}return}const Ue=Te.data instanceof ArrayBuffer?Te.data:null;Ue&&(y(""),qe(Ue,G))},z=()=>{!ce.current||G.disposed||k.current.get(Se)!==G||h("connecting")},ae=()=>{const Te=!G.disposed;G.disposed=!0,G.handoffCompleted=!0;const Ue=G.detachListeners;G.detachListeners=void 0,Ue?.();const Xe=k.current.get(Se);let at=!1;if(Xe===G){const kt=G.handoffFrom;G.handoffFrom=void 0,kt&&!kt.disposed&&(kt.socket.readyState===WebSocket.CONNECTING||kt.socket.readyState===WebSocket.OPEN)?(k.current.set(Se,kt),at=!0):k.current.delete(Se)}if(Oe(),Te&&ce.current&&Xe===G&&!at){const kt=window.setTimeout(()=>{P.current.get(Se)===kt&&P.current.delete(Se),ce.current&&D(At=>At+1)},750);Ve(Se),P.current.set(Se,kt)}};G.detachListeners=()=>{rt.removeEventListener("open",ge),rt.removeEventListener("message",De),rt.removeEventListener("error",z),rt.removeEventListener("close",ae)},rt.addEventListener("open",ge),rt.addEventListener("message",De),rt.addEventListener("error",z),rt.addEventListener("close",ae)}Oe()},[n,Ve,He,Ne,O,$,be,qe,r,B,ee,Me,i.monitorSelections,L,Y,ie,H,W,Oe]),d.useEffect(()=>{if(!W||oe<=0){F.current!==null&&(window.clearInterval(F.current),F.current=null);return}const he=Math.max(1e3,oe),pe=window.setInterval(()=>{for(const[Ae,Se]of k.current.entries())if(!(Se.disposed||Se.socket.readyState!==WebSocket.OPEN))try{Se.socket.send(JSON.stringify({...Se.payload,type:"refresh-live",deviceIds:[Ae],reason:"periodic-configuration"}))}catch{try{Se.socket.close(4003,"configuration-refresh-failed")}catch{}}},he);return F.current=pe,()=>{window.clearInterval(pe),F.current===pe&&(F.current=null)}},[oe,W]),d.useEffect(()=>{if(!W||!me||!ue)return;const he=O?O.split(",").filter(Boolean):[];for(const pe of he){if(I.current.get(pe)===ue)continue;const Ae=k.current.get(pe);!Ae||!$e(pe,Ae,Ce,ue)||I.current.set(pe,ue)}},[O,me,ue,Ce,$e,W]),d.useEffect(()=>()=>{ie("livedesk-hook-unmount",!1)},[ie]);const vt=d.useCallback((he,pe="browser-stale")=>{if(!W)return!1;const Ae=Array.isArray(he)&&he.length>0?he:O.split(",").filter(Boolean);if(Ae.length===0)return!1;let Se=!1;for(const Pe of Ae){const Qe=k.current.get(Pe);!Qe||Qe.socket.readyState!==WebSocket.OPEN||(Se=$e(Pe,Qe,pe,`${Date.now()}-${Math.random().toString(36).slice(2)}`)||Se)}return Se},[O,$e,W]),xe=d.useCallback((he,pe="browser-reconnect")=>{if(!W)return!1;const Ae=Array.isArray(he)&&he.length>0?he:O.split(",").filter(Boolean);if(Ae.length===0)return!1;let Se=!1;for(const Pe of Ae){const Qe=k.current.get(Pe);Qe&&(Ve(Pe),He(Qe,`livedesk-${pe}`),k.current.delete(Pe),I.current.delete(Pe),x.current.delete(Pe),M.current.delete(Pe),Se=!0)}return Se&&u(new Map(x.current)),D(Pe=>Pe+1),Oe(),!0},[Ve,He,O,W,Oe]);return{frames:l,state:f,error:g,stats:w,restartLive:vt,reconnectLive:xe}}function P1(t,n,r=Dn,i={}){const[l,u]=d.useState(null),[f,h]=d.useState(null),[g,y]=d.useState("idle"),[w,b]=d.useState(Vf),x=d.useRef(null),M=d.useRef(i.onFrame),k=d.useRef(null),N=d.useRef(0),E=d.useRef({totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0}),I=d.useMemo(()=>[...new Set(t.filter(Boolean))].join(","),[t]),T=d.useMemo(()=>[...new Set((i.captureDeviceIds||t).filter(Boolean))].join(","),[t,i.captureDeviceIds]),P=d.useMemo(()=>JSON.stringify(i.monitorSelections||{}),[i.monitorSelections]),U=d.useMemo(()=>{const O=Object.entries(i.connectionSessionIds||{}).filter(([W])=>!!W).map(([W,ce])=>[W,String(ce||"").trim()]).sort(([W],[ce])=>W.localeCompare(ce));return JSON.stringify(Object.fromEntries(O))},[i.connectionSessionIds]),F=d.useMemo(()=>({deviceIds:I.split(",").filter(Boolean),captureDeviceIds:T.split(",").filter(Boolean),fps:Number(i.fps||20),inputFps:Number(i.inputFps||8),width:Number(i.width||1920),height:Number(i.height||1080),tileWidth:Number(i.tileWidth||320),tileHeight:Number(i.tileHeight||180),monitorSelections:i.monitorSelections||{}}),[T,I,P,i.fps,i.height,i.inputFps,i.monitorSelections,i.tileHeight,i.tileWidth,i.width]),Y=d.useMemo(()=>JSON.stringify({atlasConfiguration:F,connectionSessionKey:U}),[F,U]),D=d.useRef(F);D.current=F;const K=n&&F.deviceIds.length>0,ne=d.useCallback(O=>O.readyState!==WebSocket.OPEN?!1:(O.send(JSON.stringify({type:"configure",...D.current})),!0),[]);d.useEffect(()=>{M.current=i.onFrame},[i.onFrame]),d.useEffect(()=>{if(!K)return;E.current.sampleStartedAt=performance.now();const O=window.setInterval(()=>{const W=E.current,ce=performance.now(),$=Math.max(1,ce-W.sampleStartedAt);b({totalFrames:W.totalFrames,totalBytes:W.totalBytes,framesPerSecond:W.sampleFrames*1e3/$,bytesPerSecond:W.sampleBytes*1e3/$,sampleMs:$,lastUpdatedAt:Date.now()});const ee=k.current;ee&&ee.frameSeq!==N.current&&(N.current=ee.frameSeq,u(ee)),W.sampleFrames=0,W.sampleBytes=0,W.sampleStartedAt=ce},1e3);return()=>window.clearInterval(O)},[K]),d.useEffect(()=>{if(!K){x.current?.close(),x.current=null,u(null),k.current=null,N.current=0,h(null),y("idle"),b(Vf);return}let O=!1,W=0;const ce=()=>{if(O)return;const $=new WebSocket(Yp("/api/remote/atlas/ws",r),Xp(r));$.binaryType="arraybuffer",x.current=$,y("connecting"),$.addEventListener("open",()=>{E.current.sampleStartedAt=performance.now(),y("open"),ne($)}),$.addEventListener("message",ee=>{if(typeof ee.data=="string"){try{const L=JSON.parse(ee.data);L?.type==="Mode4AtlasLayout"&&h({layoutVersion:Number(L.layoutVersion||0),width:Number(L.width||1920),height:Number(L.height||1080),columns:Number(L.columns||1),rows:Number(L.rows||1),tiles:Array.isArray(L.tiles)?L.tiles:[]})}catch{}return}const B=ee.data instanceof ArrayBuffer?ee.data:null;if(!(!B||B.byteLength<5))try{const L=Date.now(),be=new DataView(B).getUint32(0,!1);if(be<=0||be+4>B.byteLength)return;const H=JSON.parse(Lv.decode(new Uint8Array(B,4,be))),me=new Uint8Array(B,4+be),ue=ht(H.hubClientDropped),Ce=ht(H.hubClientQueueDepth),Me=ht(H.hubClientQueueLimit),Ne=ht(H.hubClientBufferedBytes),He={deviceId:String(H.deviceId||"__livedesk_mode4_atlas__"),kind:"live",frameSeq:Number(H.frameSeq||0),streamFrameSeq:Number(H.streamFrameSeq||0)||void 0,streamId:String(H.streamId||"mode4-atlas"),commandId:H.commandId?String(H.commandId):void 0,width:Number(H.width||1920),height:Number(H.height||1080),sourceWidth:Number(H.sourceWidth||H.width||1920),sourceHeight:Number(H.sourceHeight||H.height||1080),mimeType:String(H.mimeType||"video/h264"),mode:String(H.mode||"mode4-h264-atlas"),frameMode:String(H.frameMode||"mode4-h264-atlas"),frameProfile:String(H.frameProfile||"mode4-h264-atlas-v1"),encoding:String(H.encoding||"video-atlas"),codec:String(H.codec||"h264"),compression:String(H.compression||"video/h264"),h264Format:String(H.h264Format||"annexb"),isKeyFrame:H.isKeyFrame===!0,chunkType:String(H.chunkType||""),timestampUs:Number(H.timestampUs||0),durationUs:Number(H.durationUs||0),transport:H.transport?String(H.transport):void 0,videoTransport:H.videoTransport?String(H.videoTransport):void 0,frameTransportActive:H.frameTransportActive?String(H.frameTransportActive):void 0,frameTransportProtocol:H.frameTransportProtocol?String(H.frameTransportProtocol):void 0,frameTransportState:H.frameTransportState?String(H.frameTransportState):void 0,frameTransportReason:H.frameTransportReason?String(H.frameTransportReason):void 0,frameTransportChangedAt:H.frameTransportChangedAt?String(H.frameTransportChangedAt):void 0,frameTransportSwitchCount:Number(H.frameTransportSwitchCount||0)||0,frameTransportTcpFailureCount:Number(H.frameTransportTcpFailureCount||0)||0,frameTransportP2pReady:H.frameTransportP2pReady===!0,hubClientQueueTelemetryAvailable:ue!==void 0&&Ce!==void 0&&Me!==void 0&&Ne!==void 0,hubClientDropped:ue,hubClientQueueDepth:Ce,hubClientQueueLimit:Me,hubClientBufferedBytes:Ne,udpIncompleteFrames:Number(H.udpIncompleteFrames||0)||0,hardwareEncoder:H.hardwareEncoder?String(H.hardwareEncoder):void 0,platformProfile:H.platformProfile?String(H.platformProfile):void 0,capturedAt:String(H.capturedAt||""),receivedAt:String(H.receivedAt||""),hubPacketAt:H.hubPacketAt?String(H.hubPacketAt):void 0,hubPacketEpochMs:Number(H.hubPacketEpochMs||0)||void 0,browserReceivedEpochMs:L,byteLength:me.byteLength,layoutVersion:Number(H.layoutVersion||0),atlasComposeMs:Number(H.atlasComposeMs||0),atlasPoolStarved:Number(H.atlasPoolStarved||0),atlasReadyTiles:Number(H.atlasReadyTiles||0),atlasTileCount:Number(H.atlasTileCount||0),atlasInputRevision:Number(H.atlasInputRevision||0),atlasSourceNewestAtEpochMs:Number(H.atlasSourceNewestAtEpochMs||0),atlasSourceOldestAtEpochMs:Number(H.atlasSourceOldestAtEpochMs||0),atlasSourceMaxAgeMs:Number(H.atlasSourceMaxAgeMs||0),payload:me},Ve=E.current;Ve.totalFrames+=1,Ve.totalBytes+=me.byteLength,Ve.sampleFrames+=1,Ve.sampleBytes+=me.byteLength,k.current=He,N.current===0&&(N.current=He.frameSeq,u(He)),M.current?.(He)}catch{}}),$.addEventListener("error",()=>y("error")),$.addEventListener("close",()=>{x.current===$&&(x.current=null),!O&&(y("closed"),W=window.setTimeout(ce,1200))})};return ce(),()=>{O=!0,window.clearTimeout(W),x.current?.close(),x.current=null}},[K,r,ne]),d.useEffect(()=>{if(!K)return;const O=x.current;O&&ne(O)},[Y,K,ne]);const q=d.useCallback(()=>{const O=x.current;return O?ne(O):!1},[ne]);return{frame:l,layout:f,state:g,stats:w,refreshInputs:q}}function F1(t,n=Dn,r=""){const i=d.useRef(null),l=d.useRef(0),u=d.useRef(0),f=d.useRef(new Map),h=d.useRef(""),g=d.useRef(r);g.current=r;const y=d.useRef(r),w=d.useRef(0),b=d.useRef([]),[x,M]=d.useState("idle"),[k,N]=d.useState(""),[E,I]=d.useState(ew),T=d.useRef({totalSent:0,totalDropped:0,sampleSent:0,sampleDropped:0,sampleStartedAt:0,lastInputType:"",lastInputSeq:0,lastRoundTripMs:0,lastAgentApplyMs:0}),P=d.useCallback((K=performance.now())=>{const ne=g.current;b.current=b.current.filter(q=>!!ne&&q.ownerKey===ne&&K-q.queuedAt<=gg)},[]),U=d.useCallback((K,ne)=>{const q=g.current,O=String(ne.type||"input").toLowerCase();return!q||!K?(T.current.totalDropped+=1,T.current.sampleDropped+=1,T.current.lastInputType=O+"-owner-unavailable",!1):(P(),b.current.length>=A1?(b.current=[],T.current.totalDropped+=1,T.current.sampleDropped+=1,T.current.lastInputType=O+"-queue-overflow",N("Remote input queue was reset because ordered input could not drain."),!1):(b.current.push({ownerKey:q,deviceId:K,input:{...ne},queuedAt:performance.now()}),T.current.lastInputType=O+"-queued",!0))},[P]),F=d.useCallback((K,ne,q)=>{if(K.readyState!==WebSocket.OPEN||!ne)return!1;const O=String(q.type||"").toLowerCase(),W=O==="pointermove",$=W||O==="wheel",ee=T.current;if($&&K.bufferedAmount>k1)return ee.totalDropped+=1,ee.sampleDropped+=1,ee.lastInputType=O+"-coalescible-drop",!1;const B=l.current+1;l.current=B;const L=B+"-"+crypto.randomUUID(),oe=Date.now(),be=!$||B-u.current>=j1;for(be&&(f.current.set(B,{sentAt:performance.now(),deviceId:ne,inputEventId:L}),$&&(u.current=B)),h.current=ne,W||CS.set(ne,{inputSeq:B,inputType:O||"input",sentAt:performance.now()});f.current.size>256;){const H=f.current.keys().next().value;if(H===void 0)break;f.current.delete(H)}try{K.send(JSON.stringify({type:"input",requestId:$?"":crypto.randomUUID(),fireAndForget:$,deviceId:ne,input:{...q,inputEventId:L,inputSeq:B,requestAck:be,issuedAtEpochMs:oe,issuedAt:new Date(oe).toISOString()}}))}catch{return f.current.delete(B),!1}return ee.totalSent+=1,ee.sampleSent+=1,ee.lastInputType=O||"input",!0},[]),Y=d.useCallback(K=>{P();const ne=g.current;if(!ne||K.readyState!==WebSocket.OPEN)return;const q=b.current;b.current=[];for(let O=0;O<q.length;O+=1){const W=q[O];if(!(W.ownerKey!==ne||performance.now()-W.queuedAt>gg)&&(K.readyState!==WebSocket.OPEN||!F(K,W.deviceId,W.input))){b.current=q.slice(O).filter(ce=>ce.ownerKey===ne&&performance.now()-ce.queuedAt<=gg);return}}},[F,P]);d.useLayoutEffect(()=>{y.current!==r&&(y.current=r,b.current=[],f.current.clear(),u.current=0,h.current="")},[r]),d.useEffect(()=>{if(!t){i.current?.close(),i.current=null,w.current=0,b.current=[],u.current=0,h.current="",f.current.clear(),M("idle"),N(""),I(ew);return}let K=!1,ne=0;const q=()=>{if(K)return;const O=new WebSocket(Yp("/api/remote/input/ws",n),Xp(n));i.current=O,T.current.sampleStartedAt=performance.now(),M("connecting"),N(""),O.addEventListener("open",()=>{K||i.current!==O||(w.current=0,N(""),M("open"),Y(O))}),O.addEventListener("message",W=>{if(!(K||i.current!==O||typeof W.data!="string"))try{const ce=JSON.parse(W.data),$=Number(ce.inputSeq||ce.result?.inputSeq||0),ee=String(ce.deviceId||ce.result?.deviceId||""),B=String(ce.inputEventId||ce.result?.inputEventId||""),L=f.current.get($);if(ee&&(L&&L.deviceId!==ee||!L&&h.current&&h.current!==ee)||L?.inputEventId&&B&&L.inputEventId!==B)return;if(ce?.type==="RemoteInputError"){$>0&&f.current.delete($),N(String(ce.error||ce.result?.error||"Remote input failed.")),O.readyState===WebSocket.OPEN&&M("open");return}if(ce?.type!=="RemoteInputApplied")return;L&&(T.current.lastRoundTripMs=Math.max(0,performance.now()-L.sentAt),f.current.delete($)),T.current.lastInputSeq=$,T.current.lastAgentApplyMs=Math.max(0,Number(ce.agentApplyMs||0)),N(""),M("open")}catch{}}),O.addEventListener("close",()=>{if(K||i.current!==O)return;i.current=null,f.current.clear(),M("closed");const W=w.current;w.current=W+1;const ce=Math.min(T1,N1*2**Math.min(W,3));ne=window.setTimeout(q,ce)}),O.addEventListener("error",()=>{!K&&i.current===O&&M("error")})};return q(),()=>{K=!0,window.clearTimeout(ne);const O=i.current;i.current=null,O?.close(),f.current.clear()}},[t,Y,n]),d.useEffect(()=>{if(!t)return;const K=window.setInterval(()=>{const ne=performance.now();P(ne);const q=T.current,O=Math.max(1,ne-q.sampleStartedAt);I({totalSent:q.totalSent,totalDropped:q.totalDropped,sentPerSecond:q.sampleSent*1e3/O,droppedPerSecond:q.sampleDropped*1e3/O,bufferedAmount:i.current?.bufferedAmount||0,lastInputType:q.lastInputType,lastInputSeq:q.lastInputSeq,lastRoundTripMs:q.lastRoundTripMs,lastAgentApplyMs:q.lastAgentApplyMs,lastUpdatedAt:Date.now()}),q.sampleSent=0,q.sampleDropped=0,q.sampleStartedAt=ne},1e3);return()=>window.clearInterval(K)},[t,P]);const D=d.useCallback((K,ne)=>{const q=String(ne.type||"").toLowerCase(),O=q==="pointermove"||q==="wheel",W=i.current;if(!W||W.readyState!==WebSocket.OPEN)return O?(T.current.totalDropped+=1,T.current.sampleDropped+=1,T.current.lastInputType=(q||"input")+"-transport-unavailable",!1):U(K,ne);if(!O&&W.bufferedAmount>M1){const ee=U(K,ne);N("Remote input is reconnecting because ordered input could not drain immediately.");try{W.close(4001,"ordered-input-backpressure")}catch{}return ee}const ce=F(W,K,ne);if(ce||O)return ce;const $=U(K,ne);N("Remote input is reconnecting after a send failure.");try{W.close(4002,"input-send-failed")}catch{}return $},[F,U]);return{state:x,sendInput:D,stats:E,error:k}}const ld={queuedMs:0,browserAgeMs:0,captureAgeMs:0,captureStatusAgeMs:0,silentForMs:0,captureAlive:null,helperAlive:null,helperReady:!1,captureHealthy:!1,captureAwaitingCurrentPcm:!1,capturePhase:"",backendKind:"",helperRequired:!1,helperPid:0,captureRestartCount:0,nativeCallbackDiagnosticsAvailable:!1,nativeRejectedCallbackCount:0,nativeCurrentnessDropCount:0,nativeLastDropReason:"",localProcessingAgeMs:0,lastPacketAgeMs:0,lastAcceptedAgeMs:0,framesReceived:0,drops:0,resyncs:0,pendingDecodes:0,lastFrameSeq:0,audioContextState:"closed",stalledCount:0,automaticRestarts:0,maximumAcceptedGapMs:0,workletRingCapacityBytes:0,workletRingBufferedBytes:0,workletRingDroppedFrames:0,workletRingUnderflowCount:0,lastUpdatedAt:0},O1=.25,nw=300,aw=2,lp=1500,vg=5e3,H1=2e3,rw=1e4,Lf=[0,1e3,3e3];function sw(t){const n=Date.parse(String(t||""));return Number.isFinite(n)?Math.max(0,Date.now()-n):0}function B1(t,n,r=Dn,i=0,l=!1,u="",f,h){const g=d.useRef(null),[y,w]=d.useState("idle"),[b,x]=d.useState(null),[M,k]=d.useState(ld),[N,E]=d.useState(""),I=d.useRef(l);return I.current=l,d.useEffect(()=>{l||(x(T=>T===null?T:null),k(T=>T===ld?T:ld))},[l]),d.useEffect(()=>{if(!n||!t){w("idle"),x(null),k(ld),E("");return}w("connecting"),x(null),k(ld),E("");const T=window.AudioContext||window.webkitAudioContext;if(!T){w("unsupported"),k(ld),E("Audio playback is not supported in this browser.");return}let P=!1,U=null;const F=JA.acquire(({release:Y})=>{if(P){Y();return}const D=new T({latencyHint:"interactive"});g.current=D;let K=String(u||"").trim();const ne="/api/remote/audio/ws?devices="+encodeURIComponent(t)+(K?"&streamId="+encodeURIComponent(K):""),q=new WebSocket(Yp(ne,r),Xp(r));q.binaryType="arraybuffer";const O=ha.createOwner({deviceId:t,socket:q,audioContext:D,statsTimer:null});let W=!1;const ce=()=>{const G=ha.releaseIfDrained(O);return(G||!ha.hasOwner(O))&&!W&&(W=!0,Y()),G},$=Iv({sampleRate:192e3,channels:8}).capacityBytes,ee=o1({maxPendingPackets:sv,maxPendingBytes:$}),B=KA(),L={browserAgeMs:0,captureAgeMs:0,captureStatusAgeMs:0,silentForMs:0,captureAlive:null,helperAlive:null,helperReady:!1,captureHealthy:!1,captureStatusFailed:!1,captureAwaitingCurrentPcm:!1,captureAwaitingSinceAt:0,capturePhase:"",backendKind:"",helperRequired:!1,helperPid:0,captureRestartCount:0,nativeCallbackDiagnosticsAvailable:!1,nativeRejectedCallbackCount:0,nativeCurrentnessDropCount:0,nativeLastDropReason:"",localProcessingAgeMs:0,lastPacketAt:0,lastAcceptedAt:0,framesReceived:0,drops:0,resyncs:0,pendingDecodes:0,lastFrameSeq:0,audioContextState:String(D.state),stalledCount:0,automaticRestarts:0,maximumAcceptedGapMs:0,activeStreamId:K,lastCaptureStatusAt:0,lastPcmAtEpochMs:0,workletRingCapacityBytes:0,workletRingBufferedBytes:0,workletRingBufferedMs:0,workletRingDroppedFrames:0,workletRingUnderflowCount:0};let oe=!1,be=!1,H=null,me=0,ue=0,Ce="",Me=!1,Ne=()=>{},He="connecting",Ve="";const ie=G=>{oe||G===He||(He=G,w(G))},Oe=G=>{oe||G===Ve||(Ve=G,E(G))};let $e=0,qe=!1,vt=0,xe=0,he=0,pe=!1;const Ae=()=>{ha.setPendingWorkletPackets(O,ee.getPendingPacketCount(),ee.getPendingPacketBytes(),ee.getPendingPacketHighWater(),ee.getPendingByteHighWater())},Se=G=>{L.workletRingCapacityBytes=Math.max(0,Math.min($,Number(G.ringCapacityBytes||0)||0)),L.workletRingBufferedBytes=Math.max(0,Math.min(L.workletRingCapacityBytes,Number(G.ringBufferedBytes||0)||0)),L.workletRingBufferedMs=Math.max(0,Math.min(O1*1e3,Number(G.ringBufferedMs||0)||0)),L.workletRingDroppedFrames=Math.max(L.workletRingDroppedFrames,Number(G.ringDroppedFrames||0)||0),L.workletRingUnderflowCount=Math.max(L.workletRingUnderflowCount,Number(G.ringUnderflowCount||0)||0),ha.setPcmRing(O,L.workletRingCapacityBytes,L.workletRingBufferedBytes)},Pe=()=>{const G=H;if(H=null,Me=!1,G){G.onprocessorerror=null,G.port.onmessage=null;try{G.disconnect()}catch{}try{G.port.close()}catch{}}ee.terminate(),Ae(),L.workletRingCapacityBytes=0,L.workletRingBufferedBytes=0,L.workletRingBufferedMs=0,ha.setPcmRing(O,0,0),ha.setWorkletNode(O,0,0,me),ce()},Qe=G=>{const ge=G.data||{},De=String(ge.type||"");if((De==="packet-terminal"||De==="processor-error")&&(ee.acknowledge(typeof ge.packetId=="number"?ge.packetId:String(ge.packetId||"")),Ae()),De==="packet-terminal"){const z=Math.max(0,Number(ge.droppedFrames||0)||0);z>0&&(L.workletRingDroppedFrames+=z,L.resyncs+=1)}if(De==="ring-configured"||De==="ring-state"||De==="disposed"){const z=L.workletRingDroppedFrames;Se(ge),L.workletRingDroppedFrames>z&&(L.resyncs+=1)}De==="disposed"?Pe():De==="processor-error"&&Ne(String(ge.error||"Remote audio worklet processing failed."))},Z=()=>{if(!(!H||!Me))try{H.port.postMessage({type:"flush"})}catch{Ne("Remote audio worklet could not be flushed.")}},$t=()=>{q.readyState===WebSocket.OPEN&&q.send(JSON.stringify({type:"subscribe",deviceIds:[t],streamIdsByDeviceId:K?{[t]:K}:{}}))},Ee=()=>{L.audioContextState=String(D.state),!oe&&(L.audioContextState==="suspended"||L.audioContextState==="interrupted"?ie("suspended"):L.audioContextState==="closed"&&(ie("error"),Oe("The browser audio context is closed. Toggle Remote Audio off and on to recover.")))},Ge=async()=>{if(oe||String(D.state)==="closed")return!1;try{if(String(D.state)!=="running"&&await D.resume(),L.audioContextState=String(D.state),!oe&&!qe&&L.audioContextState==="running"){const G=L.lastAcceptedAt>0&&performance.now()-L.lastAcceptedAt<=lp,ge=L.lastCaptureStatusAt>0&&performance.now()-L.lastCaptureStatusAt<=vg&&L.captureHealthy;ie(G?"playing":ge?"silent":"open")}return L.audioContextState==="running"}catch(G){return oe||(ie("suspended"),Oe(G instanceof Error?"Audio playback is suspended: "+G.message:"Audio playback is suspended.")),!1}},ze=async()=>{if(!D.audioWorklet||typeof AudioWorkletNode>"u")throw new Error("AudioWorklet is unavailable in this browser.");const G=new Blob([f1],{type:"text/javascript"});Ce=URL.createObjectURL(G);try{await D.audioWorklet.addModule(Ce)}finally{URL.revokeObjectURL(Ce),Ce=""}if(oe||String(D.state)==="closed")return;const ge=new AudioWorkletNode(D,SS,{numberOfInputs:0,numberOfOutputs:1,outputChannelCount:[aw],channelCount:aw,channelCountMode:"explicit"});me+=1,H=ge,ge.port.onmessage=Qe,ge.onprocessorerror=()=>{Ne("Remote audio worklet stopped unexpectedly.")},ge.connect(D.destination),Me=!0,ha.setWorkletNode(O,1,1,me)},Ft=(G,ge,De,z)=>{const ae=H;if(oe||!Me||!ae||ge.byteLength<=0)return!1;const Te=Dv({sampleRate:G.sampleRate,channels:G.channels,mimeType:G.mimeType}),Ue=++ue;if(!ee.claim(Ue,ge.byteLength))return Ae(),!1;Ae();try{return ae.port.postMessage({type:"pcm",packetId:Ue,buffer:ge,byteOffset:De,byteLength:z,sampleRate:Te.sampleRate,channels:Te.channels,mimeType:G.mimeType,sampleFormat:Te.sampleFormat},[ge]),!0}catch{return ee.acknowledge(Ue),Ae(),!1}},Ze=async()=>{if(oe||qe||q.readyState!==WebSocket.OPEN)return;if(vt>=Lf.length){ie("error"),Oe("Remote audio stopped sending frames. Toggle Audio off and on to retry.");return}const G=vt;vt+=1,qe=!0,L.stalledCount+=1,L.automaticRestarts+=1,ie("reconnecting");try{if(!f)throw new Error("Remote audio restart owner is unavailable.");const ge=await f(t);if(oe||!ge)return;K=ge,$t();const De=performance.now();$e=De,L.lastPacketAt=De,L.lastAcceptedAt=0,L.lastCaptureStatusAt=0,L.lastPcmAtEpochMs=0,L.captureAlive=null,L.helperAlive=null,L.helperReady=!1,L.captureHealthy=!1,L.captureStatusFailed=!1,L.captureAwaitingCurrentPcm=!1,L.captureAwaitingSinceAt=0,L.capturePhase="",L.backendKind="",L.helperRequired=!1,L.helperPid=0,L.nativeCallbackDiagnosticsAvailable=!1,L.nativeRejectedCallbackCount=0,L.nativeCurrentnessDropCount=0,L.nativeLastDropReason="",L.silentForMs=0,L.activeStreamId=K,L.lastFrameSeq=0,L.maximumAcceptedGapMs=0,Z(),xe=De+(Lf[G+1]??3e3),Oe(""),oe||ie("open")}catch(ge){oe||(xe=performance.now()+(Lf[G+1]??3e3),ie("error"),Oe(ge instanceof Error?"Remote audio restart failed: "+ge.message:"Remote audio restart failed."))}finally{qe=!1}},nt=()=>{L.drops+=1},lt=window.setInterval(()=>{if(oe)return;const G=performance.now(),ge=L.lastPacketAt>0?Math.max(0,G-L.lastPacketAt):$e>0?Math.max(0,G-$e):0,De=L.lastAcceptedAt>0?Math.max(0,G-L.lastAcceptedAt):0,z=L.lastCaptureStatusAt>0?Math.max(0,G-L.lastCaptureStatusAt):0,ae=q.readyState===WebSocket.OPEN,Te=L.lastCaptureStatusAt>0,Ue=Te&&z<=vg&&L.captureHealthy,Xe=Te&&L.captureStatusFailed&&z>H1,at=Te&&z>vg,kt=!Te&&$e>0&&G-$e>rw,At=L.captureAwaitingCurrentPcm&&L.captureAwaitingSinceAt>0&&G-L.captureAwaitingSinceAt>rw,Ut=$e>0&&(L.lastAcceptedAt<=0?G-$e>lp:De>lp);if(ae&&$e>0&&(Xe||at||kt||At)?vt>=Lf.length&&!qe?(ie("error"),Oe("Remote audio capture heartbeat stopped. Toggle Audio off and on to retry.")):!qe&&G>=xe?Ze():qe||ie("stalled"):ae&&Ut&&!qe&&L.audioContextState!=="suspended"&&L.audioContextState!=="interrupted"&&ie(Ue?"silent":"open"),e1({enabled:I.current,now:G,lastPublishedAt:he})){he=G,k({queuedMs:L.workletRingBufferedMs,browserAgeMs:L.browserAgeMs,captureAgeMs:L.captureAgeMs,captureStatusAgeMs:z,silentForMs:L.silentForMs,captureAlive:L.captureAlive,helperAlive:L.helperAlive,helperReady:L.helperReady,captureHealthy:L.captureHealthy,captureAwaitingCurrentPcm:L.captureAwaitingCurrentPcm,capturePhase:L.capturePhase,backendKind:L.backendKind,helperRequired:L.helperRequired,helperPid:L.helperPid,captureRestartCount:L.captureRestartCount,nativeCallbackDiagnosticsAvailable:L.nativeCallbackDiagnosticsAvailable,nativeRejectedCallbackCount:L.nativeRejectedCallbackCount,nativeCurrentnessDropCount:L.nativeCurrentnessDropCount,nativeLastDropReason:L.nativeLastDropReason,localProcessingAgeMs:L.localProcessingAgeMs,lastPacketAgeMs:ge,lastAcceptedAgeMs:De,framesReceived:L.framesReceived,drops:L.drops,resyncs:L.resyncs,pendingDecodes:L.pendingDecodes,lastFrameSeq:L.lastFrameSeq,audioContextState:L.audioContextState,stalledCount:L.stalledCount,automaticRestarts:L.automaticRestarts,maximumAcceptedGapMs:L.maximumAcceptedGapMs,workletRingCapacityBytes:L.workletRingCapacityBytes,workletRingBufferedBytes:L.workletRingBufferedBytes,workletRingDroppedFrames:L.workletRingDroppedFrames,workletRingUnderflowCount:L.workletRingUnderflowCount,lastUpdatedAt:Date.now()});const Qt=B.publish();Qt&&(pe=!0,ha.setRetainedFrame(O,1,Qt.payload.byteLength),x(Qt))}else!I.current&&pe&&(pe=!1,B.clear(),ha.setRetainedFrame(O,0,0))},250);ha.setStatsTimer(O,lt);const Tt=()=>{Ee(),(String(D.state)==="suspended"||String(D.state)==="interrupted")&&Ge()},Mt=()=>{document.visibilityState==="visible"&&Ge()},rt=()=>{Ge()};D.addEventListener("statechange",Tt),document.addEventListener("visibilitychange",Mt),window.addEventListener("pageshow",rt),window.addEventListener("pointerdown",rt),window.addEventListener("keydown",rt),ie("connecting"),Oe(""),Ee();const dt=(G,ge,De,z,ae)=>{if(L.localProcessingAgeMs=Math.max(0,performance.now()-ae),oe||L.localProcessingAgeMs>nw||!iv(G,{deviceId:t,streamId:K}))return nt(),!1;L.activeStreamId!==K&&(L.activeStreamId=K,L.lastFrameSeq=0,L.maximumAcceptedGapMs=0,Z());const Te=r1(G,{deviceId:t,streamId:K,lastFrameSeq:L.lastFrameSeq});if(!Te.accepted||!Ft(G,ge,De,z))return nt(),!1;L.browserAgeMs=sw(G.receivedAt),L.captureAgeMs=sw(G.capturedAt);const Ue=performance.now();L.lastAcceptedAt>0&&(L.maximumAcceptedGapMs=Math.max(L.maximumAcceptedGapMs,Ue-L.lastAcceptedAt)),L.lastAcceptedAt=Ue,L.framesReceived+=1,L.lastFrameSeq=Te.nextFrameSeq,vt=0,xe=0,I.current&&(B.accept(G),pe=!0,ha.setRetainedFrame(O,1,0)),String(D.state)!=="running"&&Ge();const Xe=String(D.state)==="running";return Xe&&Oe(""),ie(Xe?"playing":"suspended"),!0};Ne=(G="")=>{if(!be){if(be=!0,G&&(ha.recordTerminalFailure(O,G,G.includes("setup failed")?"setup":"processor"),ie(G.includes("AudioWorklet is unavailable")?"unsupported":"error"),Oe(G),h?.(t,K,"browser-audio-playback-failed").catch(()=>{})),oe=!0,ha.deactivate(O),window.clearInterval(lt),ha.setStatsTimer(O,null),D.removeEventListener("statechange",Tt),document.removeEventListener("visibilitychange",Mt),window.removeEventListener("pageshow",rt),window.removeEventListener("pointerdown",rt),window.removeEventListener("keydown",rt),B.clear(),ha.setRetainedFrame(O,0,0),H)try{H.port.postMessage({type:"dispose"})}catch{}try{q.close()}catch{}q.readyState===WebSocket.CLOSED&&ha.setSocket(O,null),D.close().catch(()=>{}).finally(()=>{Pe(),String(D.state)==="closed"&&ha.setAudioContext(O,null),ce()}),g.current===D&&(g.current=null),ce()}},ze().catch(G=>{Ne(G instanceof Error?`Remote audio worklet setup failed: ${G.message}`:"Remote audio worklet setup failed.")}),q.addEventListener("open",()=>{oe||($e=performance.now(),L.lastPacketAt=$e,L.lastAcceptedAt=0,L.lastCaptureStatusAt=0,L.lastPcmAtEpochMs=0,L.captureAlive=null,L.helperAlive=null,L.helperReady=!1,L.captureHealthy=!1,L.captureStatusFailed=!1,L.captureAwaitingCurrentPcm=!1,L.captureAwaitingSinceAt=0,L.capturePhase="",L.backendKind="",L.helperRequired=!1,L.helperPid=0,L.maximumAcceptedGapMs=0,L.silentForMs=0,ie("open"),$t(),Ge())}),q.addEventListener("message",G=>{if(typeof G.data=="string")return;const ge=G.data instanceof ArrayBuffer?G.data:null;if(!ge||ge.byteLength<5)return;const De=performance.now();L.lastPacketAt=De;try{const ae=new DataView(ge).getUint32(0,!1);if(ae<=0||ae+4>ge.byteLength){nt();return}const Te=new Uint8Array(ge,4,ae),Ue=JSON.parse(Lv.decode(Te)),Xe=new Uint8Array(ge,4+ae),at=String(Ue.deviceId||""),kt=String(Ue.streamId||"");if(!iv({deviceId:at,streamId:kt},{deviceId:t,streamId:K})){nt();return}const At=String(Ue.frameKind||Ue.kind||"").toLowerCase();if(Ue.type==="remote.audio.status"||At==="audio-status"){L.lastCaptureStatusAt=De;const Qt=s1(Ue);if(L.captureAlive=Qt.captureAlive,L.helperAlive=Qt.helperAlive,L.helperReady=Qt.helperReady,L.captureHealthy=Qt.healthy,L.captureStatusFailed=Qt.failed,L.captureAwaitingCurrentPcm=Qt.awaitingCurrentPcm,Qt.awaitingCurrentPcm?L.captureAwaitingSinceAt||=De:L.captureAwaitingSinceAt=0,L.capturePhase=Qt.capturePhase,L.backendKind=Qt.backendKind,L.helperRequired=Qt.helperRequired===!0,L.helperPid=Qt.helperPid,L.captureRestartCount=Math.max(0,Number(Ue.restartCount||0)||0),L.nativeCallbackDiagnosticsAvailable=Ue.callbackDiagnosticsAvailable===!0,L.nativeRejectedCallbackCount=L.nativeCallbackDiagnosticsAvailable?Math.max(0,Number(Ue.rejectedCallbackCount||0)||0):0,L.nativeCurrentnessDropCount=L.nativeCallbackDiagnosticsAvailable?Math.max(0,Number(Ue.currentnessDropCount||0)||0):0,L.nativeLastDropReason=L.nativeCallbackDiagnosticsAvailable?String(Ue.lastDropReason||""):"",L.lastPcmAtEpochMs=Math.max(0,Number(Ue.lastPcmAtEpochMs||0)||0),L.silentForMs=Math.max(0,Number(Ue.silentForMs||0)||0),L.captureAgeMs=L.lastPcmAtEpochMs>0?Math.max(0,Date.now()-L.lastPcmAtEpochMs):L.silentForMs,L.captureHealthy){if(vt=0,xe=0,!qe){Oe("");const sa=String(D.state)==="running",Ra=L.lastAcceptedAt>0&&performance.now()-L.lastAcceptedAt<=lp;ie(sa?Ra?"playing":"silent":"suspended")}}else L.captureAwaitingCurrentPcm&&!qe?ie("open"):L.captureStatusFailed&&!qe&&ie("stalled");return}const Ut={deviceId:at,frameSeq:Number(Ue.frameSeq||0),streamId:kt,mimeType:String(Ue.mimeType||"audio/webm;codecs=opus"),sampleRate:Number(Ue.sampleRate||48e3),channels:Number(Ue.channels||2),capturedAt:String(Ue.capturedAt||""),receivedAt:String(Ue.receivedAt||""),byteLength:Number(Ue.byteLength||Xe.byteLength),payload:xS};if(!Ut.deviceId||oe)return;if(performance.now()-De>nw){nt();return}if(a1(Ut.mimeType)){dt(Ut,ge,Xe.byteOffset,Xe.byteLength,De);return}nt(),ie("error"),Oe(`Unsupported remote audio format "${Ut.mimeType}". Requesting a bounded PCM restart.`),!qe&&vt<Lf.length&&(xe=0,Ze());return}catch(z){oe||(ie("error"),Oe(z instanceof Error?z.message:String(z)))}}),q.addEventListener("error",()=>{oe||(ie("error"),Oe("Remote audio WebSocket error."))}),q.addEventListener("close",()=>{ha.setSocket(O,null),ce(),oe||ie("closed")}),U=()=>{Ne()}});return F.ready.catch(Y=>{P||(w("error"),E(Y instanceof Error?`Remote audio owner setup failed: ${Y.message}`:"Remote audio owner setup failed."))}),()=>{P=!0,U?U():F.cancel()}},[t,n,r,i,f,h]),{state:y,lastFrame:b,stats:M,error:N}}const z1=3;function iw(t,n,r){const i=Math.max(1,Number(r)||1),l=Math.max(0,Math.min(i,Number(t)-Number(n))),u=Math.min(i/2,z1);return l<=u?0:l>=i-u?1:l/i}function $1(t,n,r){return{normalizedX:iw(t,r.left,r.width),normalizedY:iw(n,r.top,r.height)}}const Up=Object.freeze({shiftKey:Object.freeze(["ShiftLeft","ShiftRight"]),ctrlKey:Object.freeze(["ControlLeft","ControlRight"]),altKey:Object.freeze(["AltLeft","AltRight"]),metaKey:Object.freeze(["MetaLeft","MetaRight"])}),U1=Object.freeze({shiftKey:"ShiftLeft",ctrlKey:"ControlLeft",altKey:"AltLeft",metaKey:"MetaLeft"}),ow=Object.freeze({OSLeft:"MetaLeft",OSRight:"MetaRight"}),lv=64;function ah(t,n=80){return String(t||"").replace(/[\u0000-\u001f\u007f]/g,"").trim().slice(0,n)}function cv(t){const n=ah(t);return Object.prototype.hasOwnProperty.call(ow,n)?ow[n]:n}function lw(t={}){const n=ah(t.key),r=Number.isFinite(Number(t.location))?Math.max(0,Math.min(3,Math.trunc(Number(t.location)))):0,i=r===2?"Right":"Left";return n==="Shift"?`Shift${i}`:n==="Control"?`Control${i}`:n==="Alt"||n==="AltGraph"?`Alt${i}`:n==="Meta"||n==="OS"?`Meta${i}`:n?`Key:${r}:${n}`.slice(0,80):""}function uv(t={}){const n=cv(t.code);return["Shift","Control","Alt","AltGraph","Meta","OS"].includes(n)?lw({...t,key:n}):n||lw(t)}function Ep(t){for(const[n,r]of Object.entries(Up))if(r.includes(t))return n;return""}function Jl(t,n){return Up[n].some(r=>t.has(r))}function cp(t,n,r={},i="",l=""){for(const u of Object.keys(Up)){const f=r[u]===!0,h=Up[u];if(u===i){if(l==="keyup"&&!f)for(const g of h)n.has(g)||t.delete(g);continue}if(f){!Jl(t,u)&&t.size<lv&&t.add(U1[u]);continue}for(const g of h)n.has(g)||t.delete(g)}}function q1(t,n){if(t.length!==n.size)return!1;let r=0;for(const i of n){if(t[r]!==i)return!1;r+=1}return!0}function cw(t){for(const n of[...t])Ep(n)||t.delete(n)}function dv(t){return{shiftKey:Jl(t,"shiftKey"),ctrlKey:Jl(t,"ctrlKey"),altKey:Jl(t,"altKey"),metaKey:Jl(t,"metaKey")}}function W1(t={},n={}){return{shiftKey:t.shiftKey===!0||n.shiftKey===!0,ctrlKey:t.ctrlKey===!0||n.ctrlKey===!0,altKey:t.altKey===!0||n.altKey===!0,metaKey:t.metaKey===!0||n.metaKey===!0}}function G1(t,n,r){const i=uv(t),l=ah(t.key),u=Number(t.keyCode??t.which),f=Number(t.location);return{type:n,key:l,code:i,keyCode:Number.isFinite(u)?Math.max(0,Math.min(65535,Math.trunc(u))):0,location:Number.isFinite(f)?Math.max(0,Math.min(255,Math.trunc(f))):0,text:l.length===1?l:"",repeat:n==="keydown"&&t.repeat===!0,pressedCodes:[...r],...dv(r)}}function V1(){const t=new Set,n=new Set,r=()=>({pressedCodes:[...t]});return{event(i={},l=""){if(l!=="keydown"&&l!=="keyup")return null;const u=uv(i);if(!u)return null;const f=Ep(u),h=t.has(u),g=[...t];return f?l==="keydown"?(cp(t,n,i,f,l),t.size<lv&&t.add(u)):(n.has(u)||t.delete(u),cp(t,n,i,f,l)):(cp(t,n,i),l==="keydown"?t.size<lv&&t.add(u):t.delete(u)),l==="keyup"&&f==="metaKey"&&!Jl(t,"metaKey")&&cw(t),l==="keydown"&&h&&i.repeat!==!0&&q1(g,t)?null:G1(i,l,t)},modifier(i,l){const u=cv(i),f=Ep(u);if(!f)return null;const h=n.has(u);return l===h?null:(l?(n.add(u),t.add(u)):(n.delete(u),t.delete(u),f==="metaKey"&&!Jl(t,"metaKey")&&cw(t)),{type:l?"keydown":"keyup",key:f==="metaKey"?"Meta":f==="ctrlKey"?"Control":f==="altKey"?"Alt":"Shift",code:u,keyCode:0,location:u.endsWith("Right")?2:1,text:"",repeat:!1,...r(),...dv(t)})},reset(i="keyboard-owner-reset",l=!1){const u=t.size>0;return t.clear(),n.clear(),!u&&!l?null:{type:"keyboard.reset",reason:ah(i,120)||"keyboard-owner-reset",pressedCodes:[],shiftKey:!1,ctrlKey:!1,altKey:!1,metaKey:!1,repeat:!1}},isPressed(i={}){const l=typeof i=="string"?cv(i):uv(i);if(t.has(l))return!0;const u=Ep(l);return!!u&&Jl(t,u)},snapshot(){return{...r(),latchedCodes:[...n],...dv(t)}}}}const kS=64,K1=2;function MS(t){const n=Math.floor(Number(t));return Number.isFinite(n)?Math.max(1,Math.min(kS,n)):1}function _v(t){const n=Math.floor(Number(t));return Number.isFinite(n)?Math.max(0,Math.min(kS-1,n)):0}function AS(t){const n=String(t||"").trim().toLowerCase();return n==="macos"||n==="darwin"||n==="mac"||n==="macosx"||n==="linux"||n.startsWith("linux ")}function Q1(t,n,r){const i=String(n||"").trim();if(!i)return t||null;const l=String(r||"").trim();return t&&t.fingerprint===i&&(l?t.sampleId===l:t.sampleId==="")?t:{fingerprint:i,sampleId:l,consecutiveSamples:t?.fingerprint===i?t.consecutiveSamples+1:1}}function NS({platform:t,topologyFingerprint:n,consecutiveTopologySamples:r}){return AS(t)?!!String(n||"").trim()&&Number(r)>=K1:!0}function Y1({requestedIndex:t,monitorCount:n,platform:r,topologyFingerprint:i,consecutiveTopologySamples:l}){const u=_v(t),f=MS(n);return u<f||!NS({platform:r,topologyFingerprint:i,consecutiveTopologySamples:l})?u:f-1}function X1(t,n,r){const i=_v(t),l=MS(n);return i<l||AS(r)?i:l-1}function ic(t){const n=Number(t);return Number.isSafeInteger(n)&&n>0?n:0}function ga(t){return String(t||"").trim()}function up(t,n,r={}){return{deviceId:ga(t),transitionGeneration:ic(n),sessionId:ga(r.sessionId),streamId:ga(r.streamId),commandId:ga(r.commandId),captureGeneration:ic(r.captureGeneration),monitorIndex:Math.max(0,Math.floor(Number(r.monitorIndex)||0))}}function Bn(t,n){return!!t&&!!n&&ga(t.deviceId)===ga(n.deviceId)&&ic(t.transitionGeneration)===ic(n.transitionGeneration)}function uw({deviceId:t,requestTransitionGeneration:n,currentTransitionGeneration:r,actualControlOwner:i}){const l=ga(t),u=ic(n),f=ic(r);return!!l&&u>0&&u===f&&(!i||ga(i.deviceId)===l)}function dw(t,n){const r=Promise.resolve(t).catch(()=>{}).then(n);return{result:r,tail:r.then(()=>{},()=>{})}}function dp(t,n,r){const i=ga(t);return!i||!n||ga(n.deviceId)!==i?!1:!r||ga(r.deviceId)!==i}function yg(t,n){if(!t||!n)return!1;const r=ic(n.captureGeneration),i=ga(n.commandId),l=ga(n.sessionId),u=ga(n.streamId),f=Number(t.monitorIndex);return!r||!i||!l||!u||!Number.isInteger(f)||f<0?!1:ga(t.deviceId)===ga(n.deviceId)&&ga(t.sessionId)===l&&ga(t.streamId)===u&&ga(t.commandId)===i&&ic(t.captureGeneration)===r&&ga(t.streamPurpose).toLowerCase()==="control"&&f===n.monitorIndex}function Z1(t,n){const r=Promise.resolve(t).catch(()=>{}).then(n);return{result:r,tail:r.then(()=>{},()=>{})}}function J1(){let t=Promise.resolve(),n=Promise.resolve();const r=i=>{const l=Z1(t,i);return t=l.tail,l.result};return{enqueue:r,enqueueStop(i){const l=r(i);return n=l.then(()=>{}),n.catch(()=>{}),l},enqueueStart(i){const l=n;return r(async()=>(await l,i()))}}}function eN(t={}){return Number(t.generation)===Number(t.currentGeneration)&&t.enabled===!0&&String(t.deviceId||"")!==""&&String(t.deviceId||"")===String(t.currentDeviceId||"")&&t.documentVisible===!0&&t.presentationVisible===!0&&String(t.streamId||"")!==""&&String(t.streamId||"")===String(t.currentStreamId||"")}function tN(t={}){const n=t.ok!==!1,r=n&&t.staleOwner===!0;return{confirmed:n&&(r||t.captureStopConfirmed===!0||t.alreadyStopped===!0),staleOwner:r,preserveNewerOwner:r&&(t.retainedNewerOwner===!0||String(t.activeStreamId||"")!=="")}}const Jn=Object.freeze({automaticDirectH264:!0,interactiveDirectFps:30,slowWallFps:5,fastWallFps:30,directPopulationThrottle:!1,adaptiveMinimumCurrentSampleMs:750,adaptiveDownshiftStableMs:6e3,adaptiveDownshiftConsecutiveSamples:3,missingDeliveryRatio:.72,recoveryDeliveryRatio:.88,recoveryByteRatio:.52,recoveryGapRatio:.7,controlWallReuseMaxFps:30,scalableAtlasMinInputFps:8,scalableAtlasMaxInputFps:20,scalableAtlasAggregateInputFps:120,atlasOutputFps:20,directDecodeAcceleration:"prefer-hardware",directLatencyMode:"interactive"});function fv(t){return t==="slow"?Jn.slowWallFps:Jn.fastWallFps}function nN({nowMs:t,nextPaintAtMs:n,targetFps:r,sourceFps:i,force:l=!1}){const u=Number.isFinite(Number(t))?Number(t):0,f=Number.isFinite(Number(n))?Math.max(0,Number(n)):0,h=Math.max(1,Number(r)||1),g=Math.max(1,Number(i)||1);if(h>=g)return{shouldPaint:!0,nextPaintAtMs:0,sourceCadencePassthrough:!0};const y=2;if(!l&&f>0&&u+y<f)return{shouldPaint:!1,nextPaintAtMs:f,sourceCadencePassthrough:!1};const w=1e3/h;let b=(l||f<=0?u:f)+w;for(;b<=u+y;)b+=w;return{shouldPaint:!0,nextPaintAtMs:b,sourceCadencePassthrough:!1}}function aN(t,n){const r=Number.isFinite(Number(n))?Math.max(0,Math.floor(Number(n))):Number.POSITIVE_INFINITY;if(r<=0)return[];const i=(Array.isArray(t)?t:[]).filter(f=>f&&String(f.deviceId||"").trim()).slice().sort((f,h)=>{const g=Number.isFinite(Number(f.slotNumber))?Number(f.slotNumber):Number.MAX_SAFE_INTEGER,y=Number.isFinite(Number(h.slotNumber))?Number(h.slotNumber):Number.MAX_SAFE_INTEGER;return g!==y?g-y:String(f.deviceId).localeCompare(String(h.deviceId))}),l=[],u=new Set;for(const f of i){const h=String(f.deviceId).trim();if(!u.has(h)&&(u.add(h),l.push(h),l.length>=r))break}return l}function rN(t,n){const r=Math.max(0,Math.floor(Number(n)||0));return t===!0&&r>0}function _f({mode4Enabled:t,directMode4WallEnabled:n,isMac:r}){return"direct"}function sN({mode4Enabled:t,directMode4WallEnabled:n,adaptiveFps:r,directDeviceCount:i,adaptive:l=!0}){return Math.max(1,Math.floor(Number(r)||1))}function iN({directDeviceCount:t,requestedFps:n,measuredFramesPerSecond:r,measuredPaintFramesPerSecond:i,measuredBytesPerSecond:l,maxBytesPerSecond:u,worstReceiveGapMs:f,worstPaintP95Ms:h,maxFrameGapMs:g}){const y=Math.max(1,Math.floor(Number(t)||1)),w=Math.max(1,Number(n)||1),b=Math.max(0,Number(r)||0),x=Math.max(0,Number(i)||0),M=Math.max(0,Number(l)||0),k=Math.max(1,Number(u)||1),N=Math.max(0,Number(f)||0),E=Math.max(0,Number(h)||0),I=Math.max(1,Number(g)||1),T=y*w,P=T>8&&b<T*Jn.missingDeliveryRatio,U=T>8&&x<T*Jn.missingDeliveryRatio,F=M>k||N>I||P||U,Y=b>=T*Jn.recoveryDeliveryRatio&&x>=T*Jn.recoveryDeliveryRatio&&M<k*Jn.recoveryByteRatio&&N<I*Jn.recoveryGapRatio&&E<I*Jn.recoveryGapRatio;return{expectedFramesPerSecond:T,estimatedMissingFrames:P,estimatedMissingPaints:U,overloaded:F,healthyForRecovery:Y}}function oN({receiveSampleMs:t,paintSampleMs:n,currentGenerationVerified:r,frameRequestedFps:i,adaptiveFps:l}){const u=Number(t),f=Number(n),h=Number(i),g=Number(l);return r===!0&&Number.isFinite(u)&&u>=Jn.adaptiveMinimumCurrentSampleMs&&Number.isFinite(f)&&f>=Jn.adaptiveMinimumCurrentSampleMs&&Number.isFinite(h)&&h>0&&h===g}function lN({deviceCount:t,targetFps:n,adaptive:r=!0}){const i=Math.max(1,Math.floor(Number(t)||1)),l=Math.max(1,Math.min(Jn.scalableAtlasMaxInputFps,Math.floor(Number(n)||Jn.scalableAtlasMaxInputFps)));if(!r)return l;const u=Math.max(Jn.scalableAtlasMinInputFps,Math.min(Jn.scalableAtlasMaxInputFps,Math.floor(Jn.scalableAtlasAggregateInputFps/i)));return Math.min(l,u)}function cN(t,n){return{acceleration:Jn.directDecodeAcceleration,latencyMode:Jn.directLatencyMode}}const md=999;function Jf(t){const n=Number(t);if(!Number.isFinite(n))return 0;const r=Math.floor(n);return r>=1&&r<=md?r:0}function uN(t){return String(t?.deviceName||t?.hostname||t?.deviceId||"Unknown Client").trim()||"Unknown Client"}function TS(t,n){return{deviceId:String(t?.deviceId||"").trim(),label:uN(t),platform:String(t?.platform||"").trim(),slotNumber:Jf(n)}}function ou(t){const n=Array.isArray(t)?t:[],r=new Map,i=new Set;for(const l of n){const u=String(l?.deviceId||"").trim(),f=Jf(l?.slotNumber);if(!u||!f||r.has(u)||i.has(f))continue;const h={deviceId:u,label:String(l?.label||u).trim()||u,platform:String(l?.platform||"").trim(),slotNumber:f};r.set(u,h),i.add(f)}return[...r.values()].sort((l,u)=>l.slotNumber-u.slotNumber||l.deviceId.localeCompare(u.deviceId))}function dN({connectedDevices:t,entries:n,minimumSlotCount:r=0}){const i=ou(n),l=(Array.isArray(t)?t:[]).filter(w=>w?.deviceId).slice().sort((w,b)=>{const x=Jf(w.slotNumber)||md+1,M=Jf(b.slotNumber)||md+1;return x-M||String(w.deviceId).localeCompare(String(b.deviceId))}),u=i.reduce((w,b)=>Math.max(w,b.slotNumber),0),f=Math.min(md,Math.max(0,Math.floor(Number(r)||0),u,l.length)),h=Array.from({length:f},(w,b)=>({slotNumber:b+1,device:null,saved:null,offline:!1,persisted:!1})),g=new Map(l.map(w=>[String(w.deviceId),w])),y=new Set;for(const w of i){for(;h.length<w.slotNumber&&h.length<md;)h.push({slotNumber:h.length+1,device:null,saved:null,offline:!1,persisted:!1});const b=h[w.slotNumber-1];if(!b)continue;const x=g.get(w.deviceId)||null;b.device=x,b.saved=w,b.offline=!x,b.persisted=!0,y.add(w.deviceId)}for(const w of l){const b=String(w.deviceId);if(y.has(b))continue;let x=h.find(M=>!M.device&&!M.saved);if(!x&&h.length<md&&(x={slotNumber:h.length+1,device:null,saved:null,offline:!1,persisted:!1},h.push(x)),!x)break;x.device=w,x.saved=TS(w,x.slotNumber),x.offline=!1,x.persisted=!1,y.add(b)}return h}function RS(t){return ou((Array.isArray(t)?t:[]).flatMap(n=>String(n?.saved?.deviceId||n?.device?.deviceId||"").trim()?[n.device?TS(n.device,n.slotNumber):{...n.saved,slotNumber:n.slotNumber}]:[]))}function fN(t,n,r){const i=String(n||"").trim(),l=Jf(r),u=RS(t);if(!i||!l)return u;const f=u.find(y=>y.deviceId===i);if(!f||f.slotNumber===l)return u;const h=u.find(y=>y.slotNumber===l),g=f.slotNumber;return f.slotNumber=l,h&&(h.slotNumber=g),ou(u)}const nu={revision:0,settings:{security:{accessMode:"trusted-only",allowLanConnections:!0,allowInternetConnections:!1,lockOnControlEnd:!0,idleControlMinutes:30},control:{allowKeyboardMouse:!0,allowRemoteRestart:!1},filesAudio:{allowFileTransfer:!0,allowRemoteAudio:!0,rollingBufferEnabled:!1,recordingQuality:"standard",timelapseIntervalSeconds:10,includeRemoteCursor:!0}}},mN=[{id:"connection",label:"Connection",icon:wd},{id:"remote-access",label:"Remote Access",icon:Na},{id:"capture-audio",label:"Capture & Audio",icon:zg},{id:"display",label:"Display",icon:Fp},{id:"agent",label:"Agent",icon:nc}];function Dp(t,n){return t?.settings?.[n]||nu.settings[n]||{}}function fw(t,n){return{...t,settings:{...t.settings,[n.section]:{...Dp(t,n.section),[n.key]:n.value}}}}function bg(t){return{revision:Number(t.revision||0),updatedAt:t.updatedAt,settings:t.settings}}function qs({icon:t,title:n,description:r,children:i,recommended:l=!1}){return o.jsxs("div",{className:"product-setting-row",children:[o.jsx("div",{className:"product-setting-control",children:i}),t&&o.jsx("span",{className:"product-setting-icon",children:o.jsx(t,{size:17})}),o.jsxs("div",{className:"product-setting-copy",children:[o.jsx("strong",{children:n}),l&&o.jsx("em",{children:"Recommended"}),o.jsx("small",{children:r})]})]})}function el({checked:t,onChange:n,label:r}){return o.jsxs("label",{className:"product-switch",children:[o.jsx("input",{"aria-label":r,type:"checkbox",checked:t,onChange:i=>n(i.target.checked)}),o.jsx("span",{})]})}function wg({value:t,onChange:n,options:r,label:i}){return o.jsx("select",{"aria-label":i,value:String(t),onChange:l=>n(l.target.value),children:r.map(([l,u])=>o.jsx("option",{value:l,children:u},l))})}function pN({hubUrl:t="",runtimeRole:n="hub",runtimeDeviceId:r="",sessionAccessToken:i="",initialTab:l="connection",pin:u,agent:f,captureGallery:h,advertisementsHidden:g=!1,onAdvertisementsHiddenChange:y=()=>{}}){const[w,b]=d.useState(l),[x,M]=d.useState(null),[k,N]=d.useState("loading"),[E,I]=d.useState(""),[T,P]=d.useState("idle"),[U,F]=d.useState(""),Y=d.useRef(null),D=d.useRef(null),K=d.useRef([]),ne=d.useRef(Promise.resolve()),q=d.useRef(0),O=d.useRef(0);d.useEffect(()=>{const Me=++O.current;let Ne=!0;return K.current=[],D.current=null,Y.current=null,ne.current=Promise.resolve(),N("loading"),tt("/api/settings",void 0,t).then(He=>{if(!Ne||Me!==O.current)return;const Ve=bg(He);D.current=Ve,Y.current=Ve,M(Ve),N("saved")}).catch(He=>{!Ne||Me!==O.current||(I(He instanceof Error?He.message:String(He)),D.current=nu,Y.current=nu,M(nu),N("failed"))}),()=>{Ne=!1}},[t]);const W=async(Me,Ne,He)=>{const Ve={id:++q.current,section:Me,key:Ne,value:He},ie=O.current;K.current.push(Ve);const Oe=fw(Y.current||D.current||nu,Ve);Y.current=Oe,M(Oe),N("saving"),I(""),ne.current=ne.current.then(async()=>{if(ie!==O.current)return;let $e=null,qe=null;for(let he=0;he<2&&!$e;he+=1){const pe=D.current||nu;try{const Ae=await tt("/api/settings",{method:"PATCH",body:JSON.stringify({revision:pe.revision,[Ve.section]:{[Ve.key]:Ve.value}})},t);$e=bg(Ae)}catch(Ae){if(qe=Ae,he!==0||!String(Ae instanceof Error?Ae.message:Ae).startsWith("409 "))break;try{const Se=await tt("/api/settings",void 0,t);if(ie!==O.current)return;D.current=bg(Se)}catch(Se){qe=Se;break}}}if(ie!==O.current)return;K.current=K.current.filter(he=>he.id!==Ve.id),$e&&(D.current=$e);const vt=D.current||nu,xe=K.current.reduce(fw,vt);Y.current=xe,M(xe),$e?(I(""),N(K.current.length>0?"saving":"saved")):(N(K.current.length>0?"saving":"failed"),I(qe instanceof Error?qe.message:String(qe||"Settings could not be saved.")))}),await ne.current},ce=(Me,Ne)=>He=>{W(Me,Ne,He)},$=async()=>{if(n!=="hub"||!r||!i){P("failed"),F("Sign in to this Hub before changing its runtime role.");return}P("changing"),F("");try{const Me=await tt("/api/runtime/status",void 0,t);await tt("/api/runtime/role",{method:"POST",headers:{Authorization:`Bearer ${i}`},body:JSON.stringify({role:"client"})},t),P("accepted"),await Wx({baseUrl:t,targetRole:"client",previousRuntimePid:Number(Me.runtimePid||0),allowedStates:["running","waiting-auth"]}),hM(5179)}catch(Me){P("failed"),F(Me instanceof Error?Me.message:String(Me))}},ee=Dp(x,"security"),B=Dp(x,"control"),L=Dp(x,"filesAudio"),oe=`settings-panel-${w}`,be=o.jsxs("div",{className:"settings-tab-content product-settings-content",children:[u,o.jsxs("section",{className:"settings-section-card runtime-role-settings",children:[o.jsxs("div",{className:"settings-section-heading",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Runtime role"}),o.jsx("h3",{children:"Use this computer as a Client"})]}),o.jsx(Fp,{size:20})]}),o.jsx("p",{className:"settings-help",children:"Stop hosting from this computer and reconnect it to the selected Hub."}),T==="accepted"?o.jsx("p",{className:"settings-help runtime-role-success",children:"LiveDesk is restarting as Client."}):U?o.jsx("p",{className:"settings-help runtime-role-error",role:"alert",children:U}):null,o.jsx("button",{className:"settings-reset",onClick:()=>{$()},disabled:T==="changing"||n!=="hub",type:"button",children:T==="changing"?"Switching role...":"Switch this computer to Client"})]})]}),H=o.jsxs("div",{className:"settings-tab-content product-settings-content",children:[o.jsxs("section",{className:"settings-section-card",children:[o.jsxs("div",{className:"settings-section-heading",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Remote access"}),o.jsx("h3",{children:"Who may connect?"})]}),o.jsx(Ci,{size:20})]}),o.jsx(qs,{icon:Na,title:"Access mode",description:"Choose the default permission boundary for remote sessions.",recommended:!0,children:o.jsx(wg,{value:String(ee.accessMode),onChange:ce("security","accessMode"),label:"Access mode",options:[["trusted-only","Trusted devices only"],["block-remote-access","Block remote access"]]})}),o.jsx(qs,{icon:wd,title:"Allow LAN connections",description:"Permit authenticated, encrypted Clients on private network addresses.",recommended:!0,children:o.jsx(el,{checked:!!ee.allowLanConnections,onChange:ce("security","allowLanConnections"),label:"Allow LAN connections"})}),o.jsx(qs,{icon:wd,title:"Allow internet connections",description:"Permit authenticated, end-to-end encrypted Direct or Relay connections from public networks.",children:o.jsx(el,{checked:!!ee.allowInternetConnections,onChange:ce("security","allowInternetConnections"),label:"Allow internet connections"})})]}),o.jsxs("section",{className:"settings-section-card",children:[o.jsxs("div",{className:"settings-section-heading",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Session permissions"}),o.jsx("h3",{children:"What may remote users do?"})]}),o.jsx(Ta,{size:20})]}),o.jsx(qs,{icon:Ta,title:"Keyboard and mouse control",description:"Allow Control to send keyboard and pointer input.",recommended:!0,children:o.jsx(el,{checked:!!B.allowKeyboardMouse,onChange:ce("control","allowKeyboardMouse"),label:"Keyboard and mouse control"})}),o.jsx(qs,{icon:_x,title:"Power actions",description:"Allow confirmed sleep, restart, and shut down commands from the Hub.",children:o.jsx(el,{checked:!!B.allowRemoteRestart,onChange:ce("control","allowRemoteRestart"),label:"Power actions"})}),o.jsx(qs,{icon:zg,title:"File transfer",description:"Allow files to be delivered to connected computers.",children:o.jsx(el,{checked:!!L.allowFileTransfer,onChange:ce("filesAudio","allowFileTransfer"),label:"File transfer"})}),o.jsx(qs,{icon:Zl,title:"Remote audio",description:"Allow sound capture from connected computers.",children:o.jsx(el,{checked:!!L.allowRemoteAudio,onChange:ce("filesAudio","allowRemoteAudio"),label:"Remote audio"})}),o.jsx(qs,{icon:Ci,title:"Lock after Control ends",description:"Release every remote key and button, then lock the controlled computer when the Control owner disconnects.",children:o.jsx(el,{checked:!!ee.lockOnControlEnd,onChange:ce("security","lockOnControlEnd"),label:"Lock after Control ends"})}),o.jsx(qs,{icon:Zl,title:"Control idle timeout",description:"End inactive Control ownership automatically. The visible local stop control is always enabled.",recommended:!0,children:o.jsx(wg,{value:Number(ee.idleControlMinutes),onChange:Me=>ce("security","idleControlMinutes")(Number(Me)),label:"Control idle timeout",options:[["5","5 minutes"],["15","15 minutes"],["30","30 minutes"],["60","1 hour"]]})})]})]}),me=o.jsxs("div",{className:"settings-tab-content product-settings-content",children:[o.jsxs("section",{className:"settings-section-card",children:[o.jsxs("div",{className:"settings-section-heading",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Capture"}),o.jsx("h3",{children:"Recording defaults"})]}),o.jsx(zg,{size:20})]}),o.jsx(qs,{icon:Zl,title:"Keep a Last 30s buffer",description:"Keep recent video in memory until you explicitly save it.",children:o.jsx(el,{checked:!!L.rollingBufferEnabled,onChange:ce("filesAudio","rollingBufferEnabled"),label:"Keep a Last 30s buffer"})}),o.jsx(qs,{icon:Zl,title:"Timelapse interval",description:"Choose how often a timelapse frame is captured.",children:o.jsx(wg,{value:Number(L.timelapseIntervalSeconds),onChange:Me=>ce("filesAudio","timelapseIntervalSeconds")(Number(Me)),label:"Timelapse interval",options:[["5","5 seconds"],["10","10 seconds"],["30","30 seconds"],["60","60 seconds"]]})})]}),h]}),Ce=w==="connection"?be:w==="remote-access"?H:w==="capture-audio"?me:w==="display"?o.jsx("div",{className:"settings-tab-content product-settings-content",children:o.jsxs("section",{className:"settings-section-card",children:[o.jsxs("div",{className:"settings-section-heading",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Display"}),o.jsx("h3",{children:"Wall appearance"})]}),o.jsx(Fp,{size:20})]}),o.jsx(qs,{icon:Ta,title:"Hide advertisements",description:"Remove the optional advertisement banner from the Wall on this computer.",children:o.jsx(el,{checked:g,onChange:y,label:"Hide advertisements"})})]})}):f;return o.jsxs("section",{className:"settings-page",children:[o.jsx("div",{className:"settings-page-tabs",role:"tablist","aria-label":"LiveDesk settings",children:mN.map(({id:Me,label:Ne,icon:He})=>o.jsxs("button",{className:w===Me?"active":"",id:`settings-tab-${Me}`,role:"tab","aria-selected":w===Me,"aria-controls":`settings-panel-${Me}`,tabIndex:w===Me?0:-1,onClick:()=>b(Me),type:"button",children:[o.jsx(He,{size:16}),Ne]},Me))}),k==="saving"&&o.jsx("div",{className:"product-save-state",role:"status",children:"Saving settings..."}),E&&o.jsx("div",{className:"agent-settings-alert error",role:"alert",children:E}),o.jsx("section",{className:"settings-page-panel",id:oe,role:"tabpanel","aria-labelledby":`settings-tab-${w}`,tabIndex:0,children:Ce})]})}function hN({children:t}){return o.jsx("div",{className:"settings-tab-content",children:t})}const mw={enabled:!1};function pw(t){return{enabled:t?.enabled===!0}}async function gN(t,n,r){let i=null;for(let l=0;l<2;l+=1){const u=await tt("/api/settings",{signal:r},n);if(u.settings.agent?.enabled===t)return;try{await tt("/api/settings",{method:"PATCH",signal:r,body:JSON.stringify({revision:u.revision,agent:{enabled:t}})},n);return}catch(f){if(i=f,l!==0||!String(f instanceof Error?f.message:f).startsWith("409 "))throw f}}throw i}function vN({hubUrl:t}){const[n,r]=d.useState(mw),[i,l]=d.useState(null),[u,f]=d.useState(""),[h,g]=d.useState(""),[y,w]=d.useState(""),b=d.useRef(0),x=d.useRef(null);d.useEffect(()=>{let F=!0;x.current?.abort();const Y=new AbortController;x.current=Y;const D=++b.current;return l(null),r(mw),f(""),w(""),g(""),tt("/api/settings/agent",{signal:Y.signal},t).then(K=>{!F||Y.signal.aborted||D!==b.current||(l(K.settings),r(pw(K.settings)))}).catch(K=>{F&&!Y.signal.aborted&&D===b.current&&w(K instanceof Error?K.message:String(K))}),()=>{F=!1,Y.abort(),x.current===Y&&(x.current=null)}},[t]);const M=(F,Y)=>r(D=>({...D,[F]:Y})),k=F=>{l(F),r(pw(F))},N=()=>({generation:b.current,controller:x.current}),E=F=>F.generation===b.current&&F.controller!==null&&F.controller===x.current&&!F.controller.signal.aborted,I=async()=>{if(!i){w("Agent settings are not available yet.");return}const F=N();if(E(F)){f("save"),w(""),g("");try{if(await gN(n.enabled,t,F.controller.signal),!E(F))return;const Y=await tt("/api/settings/agent",{signal:F.controller.signal},t);if(!E(F))return;k(Y.settings),g("Codex Agent settings saved.")}catch(Y){E(F)&&w(Y instanceof Error?Y.message:String(Y))}finally{E(F)&&f("")}}},T=async()=>{const F=N();if(E(F)){f("test"),w(""),g("");try{const Y=await tt("/api/settings/agent/test",{method:"POST",signal:F.controller.signal,body:JSON.stringify({})},t);if(!E(F))return;const D=await tt("/api/settings/agent",{signal:F.controller.signal},t);if(!E(F))return;k(D.settings);const K=Number.isFinite(Y.connection?.latencyMs)?Math.max(0,Math.round(Y.connection.latencyMs)):null;g(`Codex Agent connection verified${K!==null?` in ${K} ms.`:"."}`)}catch(Y){E(F)&&w(Y instanceof Error?Y.message:String(Y))}finally{E(F)&&f("")}}},P=i?.codexInstallation==="installed"&&i.codexAuth==="signed-in",U=i!==null;return o.jsxs("div",{className:"settings-tab-content agent-settings-content",children:[o.jsx("section",{className:"settings-section-card agent-enable-card",children:o.jsxs("label",{className:"settings-toggle agent-enable-toggle",children:[o.jsx("input",{type:"checkbox",checked:n.enabled,onChange:F=>M("enabled",F.target.checked),disabled:!U||u!==""}),o.jsx("span",{children:"Enable Codex Agent"})]})}),y&&o.jsx("div",{className:"agent-settings-alert error",role:"alert",children:y}),h&&o.jsx("div",{className:"agent-settings-alert success",role:"status",children:h}),o.jsxs("section",{className:"settings-section-card",children:[o.jsxs("div",{className:"settings-section-heading",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Connection"}),o.jsx("h3",{children:"Codex SDK / CLI"})]}),o.jsx(Na,{size:20})]}),o.jsxs("div",{className:"agent-connection-row",children:[o.jsx("span",{className:`agent-connection-dot ${P?"connected":i?.codexAuth==="not-signed-in"?"unavailable":""}`}),o.jsx("span",{children:i?.codexInstallation==="not-installed"?"Codex SDK not installed":i?.codexAuth==="signed-in"?"Codex CLI signed in":i?.codexAuth==="not-signed-in"?"Codex CLI sign-in required":"Codex status not tested"}),o.jsxs("button",{className:"settings-reset",onClick:()=>{T()},disabled:u!=="",type:"button",children:[o.jsx(YC,{size:15})," ",u==="test"?"Testing":"Test connection"]})]}),o.jsxs("p",{className:"settings-help",children:[o.jsx(XC,{size:12})," The Hub uses the installed Codex SDK / CLI to plan approved commands and run them through LiveDesk Agent tools on selected computers."]})]}),o.jsx("div",{className:"settings-action-row agent-settings-actions",children:o.jsxs("button",{className:"text-button primary",onClick:()=>{I()},disabled:!U||u!=="",type:"button",children:[o.jsx(ZC,{size:15})," ",u==="save"?"Saving":"Save Agent settings"]})})]})}new Date().valueOf();function po(t){const[n,r]=d.useState(t),i=d.useRef(t);return d.useEffect(()=>{if(i.current!==t){if(Array.isArray(i.current)&&Array.isArray(t)&&i.current.length===0&&t.length===0)return;i.current=t,r(t)}},[t]),[n,r]}function Pv(t,n){return typeof t=="function"?typeof n=="object"?t(n):t():t}function Sd(t,n="data-id"){let r=t;for(!r.tagName&&t.target&&(r=t.target);r;){if(r.getAttribute&&r.getAttribute(n))return r;r=r.parentNode}return null}function yN(t,n="data-id"){const r=Sd(t,n);return r?r.getAttribute(n):null}function em(t,n="data-id"){const r=Sd(t,n);return r?rh(r,n):null}function rh(t,n="data-id"){const r=t.getAttribute(n);return r?bN(r):null}function za(t){return typeof t=="string"?":"+t:t}function bN(t){if(t.startsWith(":"))return t.substring(1);const n=t*1;return isNaN(n)?t:n}function wN(){return{detect:()=>!0,addEvent:function(t,n,r){return t.addEventListener(n,r),()=>t.removeEventListener(n,r)},addGlobalEvent:function(t,n){return document.addEventListener(t,n),()=>document.removeEventListener(t,n)},getTopNode:function(){return window.document.body}}}var Yr=wN();function Fv(t){Object.assign(Yr,t)}function hw(t,n,r){function i(l){const u=Sd(l);if(!u)return;const f=rh(u);if(typeof n=="function")return n(f,l);let h,g=l.target;for(;g!=u;){if(h=g.dataset?g.dataset.action:null,h&&n[h]){n[h](f,l);return}g=g.parentNode}n[r]&&n[r](f,l)}Yr.addEvent(t,r,i)}function Cd(t,n){hw(t,n,"click"),n.dblclick&&hw(t,n.dblclick,"dblclick")}function xN(t,n){for(let r=t.length-1;r>=0;r--)if(t[r]===n){t.splice(r,1);break}}function SN(t,n,r){for(let i=0;i<al.length;i++){if(i===r)continue;const l=al[i],u=l.props.parent?.();if(u&&t.contains(u)&&l.node.contains(n))return!0}return!1}var jS=new Date,qp=!1,fp=[],al=[],gw=t=>{const n=t.target;if(qp||!n.isConnected){qp=!1;return}for(let r=al.length-1;r>=0;r--){const{node:i,date:l,props:u}=al[r];if(!(l>jS)&&!i.contains(n)&&i!==n&&(SN(i,n,r)||(u.callback&&u.callback(t),u.modal||t.defaultPrevented)))break}},CN=t=>{jS=new Date,qp=!0;for(let n=al.length-1;n>=0;n--){const{node:r}=al[n];if(!r.contains(t.target)&&r!==t.target){qp=!1;break}}};function go(t,n){fp.length||(fp=[Yr.addGlobalEvent("click",gw,t),Yr.addGlobalEvent("contextmenu",gw,t),Yr.addGlobalEvent("mousedown",CN,t)]),typeof n!="object"&&(n={callback:n});const r={node:t,date:new Date,props:n};return al.push(r),{destroy(){xN(al,r),al.length||(fp.forEach(i=>i()),fp=[])}}}var mp=t=>t.indexOf("bottom")!==-1,pp=t=>t.indexOf("left")!==-1,hp=t=>t.indexOf("right")!==-1,xg=t=>t.indexOf("top")!==-1,vw=t=>t.indexOf("fit")!==-1,Pf=t=>t.indexOf("overlap")!==-1,kN=t=>t.split("-").every(n=>["center","fit"].indexOf(n)>-1),MN=t=>{const n=t.match(/(start|center|end)/);return n?n[0]:null};function AN(t,n){let r=0;const i=Yr.getTopNode(t);for(;t&&t!==i;){const l=getComputedStyle(t).position;if((l==="absolute"||l==="relative"||l==="fixed")&&(r=parseInt(getComputedStyle(t).zIndex)||0),t=t.parentNode,t===n)break}return r}var ma,fr,Ff,Za;function ES(t,n,r="bottom",i=0,l=0){if(!t)return null;ma=i,fr=l,Ff="auto";let u=0,f=0,h=r;const g=DS(t),y=Pf(r)?Yr.getTopNode(t):g;if(!g)return null;const w=g.getBoundingClientRect(),b=t.getBoundingClientRect(),x=y.getBoundingClientRect(),M=window.getComputedStyle(y),k={left:0,top:0,bottom:0,right:0};for(const U in k){const F=`border-${U}-width`;k[U]=parseFloat(M.getPropertyValue(F))}if(n){const U=AN(n,g);u=Math.max(U+1,20)}if(n){if(Za=n.getBoundingClientRect(),vw(r)&&(Ff=Za.width+"px"),r!=="point")if(kN(r))vw(r)?ma=0:(ma=x.width/2,f=1),fr=(x.height-b.height)/2;else{const U=Pf(r)?0:1;ma=hp(r)?Za.right+U:Za.left-U,fr=mp(r)?Za.bottom+1:Za.top;const F=MN(r);F&&(hp(r)||pp(r)?F==="center"?fr-=(b.height-Za.height)/2:F==="end"&&(fr-=b.height-Za.height):(mp(r)||xg(r))&&(F==="center"?ma-=(b.width-Za.width)/2:F==="end"&&(ma-=b.width-Za.width),Pf(r)||(ma+=1)))}}else Za={left:i,right:i,top:l,bottom:l};const N=(pp(r)||hp(r))&&(mp(r)||xg(r));pp(r)&&(f=2);const E=ma-b.width-x.left;n&&pp(r)&&!N&&E<0&&(ma=Za.right,f=0,h=h.replace("left","right"));const I=ma+b.width*(1-f/2)-x.right;if(I>0)if(!hp(r))ma=x.right-k.right-b.width;else{const U=Za.left-x.x-b.width;n&&!N&&U>=0?(ma=Za.left-b.width,h=h.replace("right","left")):ma-=I+k.right}f&&(ma=Math.round(ma-b.width*f/2));const T=E<0||I>0||!N;xg(r)&&(fr=Za.top-b.height,n&&fr<x.y&&T&&(fr=Za.bottom,h=h.replace("top","bottom")));const P=fr+b.height-x.bottom;return P>0&&(n&&mp(r)&&T?(fr-=b.height+Za.height+1,h=h.replace("bottom","top")):fr-=P+k.bottom),ma-=w.left+k.left,fr-=w.top+k.top,ma=(Pf(r)?ma:Math.max(ma,0))+y.scrollLeft,fr=(Pf(r)?fr:Math.max(fr,0))+y.scrollTop,Ff=Ff||"auto",{at:h,x:ma,y:fr,z:u,width:Ff}}function DS(t){const n=Yr.getTopNode(t);for(t&&(t=t.parentElement);t;){const r=getComputedStyle(t).position;if(t===n||r==="relative"||r==="absolute"||r==="fixed")return t;t=t.parentNode}return null}function NN(t){const n=[];let r=t;const i=Yr.getTopNode(t);for(;r&&r!==i&&!r.getAttribute("data-wx-portal-root");)getComputedStyle(r).position==="absolute"&&n.push(r),r=r.parentNode;return n}var yw=new Date().valueOf();function Ov(){return yw+=1,yw}function pr(t){return t<10?"0"+t:t.toString()}function TN(t){const n=pr(t);return n.length==2?"0"+n:n}function IS(t){const n=Math.floor(t/11)*11;return{start:n,end:n+11}}function Sg(t){const n=(t.getDay()+6)%7,r=new Date(t.valueOf());r.setDate(t.getDate()+(3-n)),r.setHours(0,0,0,0);const i=new Date(r.getFullYear(),0,1),l=Math.round((r.getTime()-i.getTime())/864e5);return 1+Math.floor(l/7)}var bw=["",""];function RN(t,n,r){switch(t){case"%d":return pr(n.getDate());case"%m":return pr(n.getMonth()+1);case"%j":return n.getDate();case"%n":return n.getMonth()+1;case"%y":return pr(n.getFullYear()%100);case"%Y":return n.getFullYear();case"%D":return r.dayShort[n.getDay()];case"%l":return r.dayFull[n.getDay()];case"%M":return r.monthShort[n.getMonth()];case"%F":return r.monthFull[n.getMonth()];case"%h":return pr((n.getHours()+11)%12+1);case"%g":return(n.getHours()+11)%12+1;case"%G":return n.getHours();case"%H":return pr(n.getHours());case"%i":return pr(n.getMinutes());case"%a":return((n.getHours()>11?r.pm:r.am)||bw)[0];case"%A":return((n.getHours()>11?r.pm:r.am)||bw)[1];case"%s":return pr(n.getSeconds());case"%S":return TN(n.getMilliseconds());case"%W":return pr(Sg(n));case"%w":{const i=r.weekStart??1;if(i===1)return pr(Sg(n));const l=(n.getDay()-i+7)%7,u=(1-i+7)%7,f=new Date(n.valueOf());return f.setDate(n.getDate()+(u-l)),pr(Sg(f))}case"%c":{let i=n.getFullYear()+"";return i+="-"+pr(n.getMonth()+1),i+="-"+pr(n.getDate()),i+="T",i+=pr(n.getHours()),i+=":"+pr(n.getMinutes()),i+=":"+pr(n.getSeconds()),i}case"%Q":return Math.floor(n.getMonth()/3)+1;default:return t}}var jN=/%[a-zA-Z]/g;function gd(t,n){return typeof t=="function"?t:function(r){return r?(r.getMonth||(r=new Date(r)),t.replace(jN,i=>RN(i,r,n))):""}}function ww(t){return t&&typeof t=="object"&&!Array.isArray(t)}function mv(t,n){for(const r in n){const i=n[r];ww(t[r])&&ww(i)?t[r]=mv({...t[r]},n[r]):t[r]=n[r]}return t}function rm(t){return{getGroup(n){const r=t[n];return i=>r&&r[i]||i},getRaw(){return t},extend(n,r){if(!n)return this;let i;return r?i=mv({...n},t):i=mv({...t},n),rm(i)}}}var EN=$x();const DN="en-US",IN={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},LN={ok:"OK",cancel:"Cancel",select:"Select","No data":"No data","Rows per page":"Rows per page","Total pages":"Total pages"},_N={timeFormat:"%H:%i",dateFormat:"%m/%d/%Y",monthYearFormat:"%F %Y",yearFormat:"%Y"},LS={core:LN,calendar:IN,formats:_N,lang:DN},Hv=d.createContext(""),_S=d.createContext({}),Ai=d.createContext(null),PS=d.createContext(null),Ua=Object.freeze(Object.defineProperty({__proto__:null,fieldId:PS,helpers:_S,i18n:Ai,theme:Hv},Symbol.toStringTag,{value:"Module"}));function FS(t){const n=d.useContext(PS),[r]=d.useState(()=>t||n||Ov());return r}function Kf({type:t="",css:n="",icon:r="",disabled:i=!1,title:l="",tooltip:u,text:f="",children:h,onClick:g}){const y=d.useMemo(()=>{let b=t?t.split(" ").filter(x=>x!=="").map(x=>"wx-"+x).join(" "):"";return n+(n?" ":"")+b},[t,n]),w=b=>{g&&g(b)};return o.jsxs("button",{title:l,className:`wx-2ZWgb4 wx-button ${y} ${r&&!h?"wx-icon":""}`,disabled:i,onClick:w,"data-tooltip-text":u,children:[r&&o.jsx("i",{className:"wx-2ZWgb4 "+r}),h||f||" "]})}function PN({id:t,label:n="",inputValue:r="",value:i=!1,onChange:l,disabled:u=!1,css:f=""}){const h=FS(t),[g,y]=po(i),w=({target:b})=>{const x=b.checked;y(x),l&&l({value:x,inputValue:r})};return o.jsxs("div",{className:`wx-2IvefP wx-checkbox ${f}`,children:[o.jsx("input",{type:"checkbox",id:h,disabled:u,className:"wx-2IvefP wx-check",checked:g,value:r,onChange:w}),o.jsxs("label",{htmlFor:h,className:"wx-2IvefP wx-label",children:[o.jsx("span",{className:"wx-2IvefP wx-before"}),n&&o.jsx("span",{className:"wx-2IvefP wx-after",children:n})]})]})}function Bv({theme:t="",target:n,children:r}){const i=d.useRef(null),l=d.useRef(null),[u,f]=d.useState(null);i.current||(i.current=document.createElement("div"));const h=d.useContext(Hv);return d.useEffect(()=>{f(n||FN(l.current)||Yr.getTopNode(l.current))},[l.current]),o.jsxs(o.Fragment,{children:[o.jsx("span",{ref:l,style:{display:"none"}}),l.current&&u?EN.createPortal(o.jsx("div",{className:`wx-3ZWsT0 wx-${t||h}-theme`,children:r}),u):null]})}function FN(t){const n=Yr.getTopNode(t);for(;t&&t!==n&&!t.getAttribute("data-wx-portal-root");)t=t.parentNode;return t}function ON({left:t=0,top:n=0,at:r="bottom",parent:i=null,width:l="auto",css:u="",onCancel:f,children:h,trackScroll:g=!1}){const[y,w]=d.useState(0),[b,x]=d.useState(0),[M,k]=d.useState("auto"),[N,E]=d.useState(!1),I=d.useRef(null),T=d.useRef(null),P=d.useRef(f);d.useEffect(()=>{P.current=f},[f]);function U(Y){return i&&(l+"").indexOf("%")>-1?l.replace(/(\d+)%/,(D,K)=>(K=K*i.offsetWidth/100+"px",l.replace(D,K))):l&&l!=="auto"?l:Y}const F=d.useCallback(()=>{if(!I.current)return;const Y=ES(I.current,i,r,t,n);Y&&(w(Y.x),x(Y.y),k(U(Y.width)))},[I,i,r,t,n,l]);return d.useLayoutEffect(()=>{const Y=K=>{P.current&&K.target!==T.current&&I.current&&!I.current.contains(K.target)&&P.current(K)};let D;return requestAnimationFrame(()=>{F(),E(!0),g&&I.current&&(T.current=DS(I.current),T.current&&T.current.addEventListener("scroll",Y,!0)),i&&(D=new ResizeObserver(F),D.observe(i))}),()=>{g&&T.current&&T.current.removeEventListener("scroll",Y,!0),D?.disconnect()}},[]),d.useLayoutEffect(()=>{F()},[i,r,t,n]),d.useEffect(()=>{const Y=D=>{P.current&&P.current(D)};if(I.current)return go(I.current,{callback:Y,parent:()=>i}).destroy},[i]),o.jsx("div",{ref:I,className:["wx-37M6Fj","wx-popup",u].filter(Boolean).join(" "),style:{position:"absolute",visibility:N?"visible":"hidden",top:b+"px",left:y+"px",width:M},children:h})}function HN({position:t="bottom",align:n="start",autoFit:r=!0,onCancel:i=null,width:l="100%",css:u="",children:f}){const h=d.useRef(null),[g,y]=d.useState(t),[w,b]=d.useState(n),x=d.useRef(i);return d.useEffect(()=>{x.current=i},[i]),d.useEffect(()=>{if(r){const M=h.current;if(M){const k=M.getBoundingClientRect(),N=document.body.getBoundingClientRect();k.right>=N.right&&b("end"),k.bottom>=N.bottom&&y("top")}}},[]),d.useEffect(()=>{if(h.current){const M=k=>{x.current&&x.current(k)};return go(h.current,M).destroy}},[]),o.jsx("div",{ref:h,className:["wx-dropdown",`wx-${g}-${w}`,u||"","wx-aaaVytZW"].filter(Boolean).join(" "),style:{width:l},children:f})}function zv({position:t="bottom",align:n="start",autoFit:r=!0,inline:i=!1,onCancel:l,width:u="100%",children:f,...h}){const[g,y]=d.useState(void 0),w=d.useRef(null),b=d.useMemo(()=>`${t}-${n}`,[t,n]);return d.useLayoutEffect(()=>{w.current&&y(w.current.parentNode)},[]),o.jsxs(o.Fragment,{children:[g&&(i?o.jsx(HN,{onCancel:l,position:t,align:n,autoFit:r,width:u,...h,children:f}):o.jsx(Bv,{children:o.jsx(ON,{parent:g,at:b,onCancel:l,width:u,...h,children:f})})),o.jsx("span",{ref:w,className:"wx-portal-node wx-32GZ52"})]})}function sh(){return rm(LS)}function BN(){let t=null,n=!1,r=!1,i,l,u,f;const h=(b,x,M,k,N)=>{i=b,l=x,u=M,f=k,r=N},g=b=>{t=b,n=t!==null,u(t)},y=(b,x)=>{if(!r&&b!==null&&i){const M=i.querySelectorAll(".wx-list > .wx-item")[b];M&&(M.scrollIntoView({block:"nearest"}),x&&x.preventDefault())}},w=(b,x)=>{const M=b===null?null:Math.max(0,Math.min(t+b,l.length-1));M!==t&&(g(M),i?y(M,x):requestAnimationFrame(()=>y(M,x)))};return{move:b=>{const x=em(b),M=l.findIndex(k=>k.id===x);M!==t&&g(M)},keydown:(b,x)=>{switch(b.code){case"Enter":n?f():g(0);break;case"Space":n||g(0);break;case"Escape":u(t=null);break;case"Tab":u(t=null);break;case"ArrowDown":w(n?1:x||0,b);break;case"ArrowUp":w(n?-1:x||0,b);break}},init:h,navigate:w}}const xw=10,zN=d.memo(function({data:t,checkboxes:n,itemTemplate:r,value:i}){return o.jsxs(o.Fragment,{children:[n&&o.jsx(PN,{id:t.id,css:"wx-list-checkbox",value:i&&i.includes(t.id)}),r?Pv(r,{option:t}):t.label]})});function Sw({visibleItems:t,visibleRange:n,navIndex:r,checkboxes:i,itemTemplate:l,value:u,measureRefCallback:f}){return t.map((h,g)=>{const y=n.start+g;return o.jsx("div",{ref:g===0?f:void 0,className:`wx-233fr7 wx-item ${y===r?"wx-focus":""}`,"data-id":h.id,children:o.jsx(zN,{data:h,checkboxes:i,itemTemplate:l,value:u})},h.id)})}function ih({items:t=[],children:n,onSelect:r,onReady:i,virtualized:l=!1,checkboxes:u,multiselect:f,value:h,...g}){const y=d.useRef(),w=d.useRef(!1),b=d.useRef(BN()),[x,M]=d.useState(null),k=d.useRef(x),[N,E]=d.useState(0),[I,T]=d.useState(24),P=d.useRef(!1),U=(d.useContext(Ai)||sh()).getGroup("core"),F=d.useRef(t);d.useEffect(()=>{F.current=t},[t]);const Y=d.useRef(h);d.useEffect(()=>{Y.current=h},[h]);const D=d.useRef(0);d.useEffect(()=>{D.current=I},[I]);const K=d.useCallback(ue=>{ue&&ue.stopPropagation();const Ce=F.current,Me=Y.current,Ne=k.current;let He;const Ve=Ce[Ne]?.id;f?Me&&Me.includes(Ve)?He=Me.filter(ie=>ie!==Ve):He=[...Me||[],Ve]:He=Ve,r&&r({id:He})},[f,r]),ne=d.useRef(K);d.useEffect(()=>{ne.current=K},[K]);const q=d.useCallback(ue=>{if(y.current){let Ce=ue*D.current-y.current.clientHeight+D.current;E(Ce),y.current.scrollTop=Ce}},[D.current]),O=d.useCallback(ue=>{y.current=ue,l&&(ue&&!w.current&&k.current!==null&&requestAnimationFrame(()=>{y.current&&(q(k.current),w.current=!0)}),ue||(w.current=!1))},[q]),W=d.useCallback(ue=>{if(!ue||P.current)return;const Ce=ue.getBoundingClientRect().height;Ce&&(T(Ce),D.current=Ce,P.current=!0)},[]);d.useEffect(()=>{b.current.init(y.current,t,ue=>{M(ue),k.current=ue},ue=>ne.current(ue),l)},[t,y.current,l]),d.useEffect(()=>{const ue=(Me,Ne)=>{b.current.navigate(Me,Ne),q(k.current)},Ce=(Me,Ne)=>{const He=k.current,Ve=F.current;if(He!==0&&He!==Ve.length-1&&(Me.key==="ArrowDown"||Me.key==="ArrowUp")&&Me.preventDefault(),b.current.keydown(Me,Ne),y.current){const ie=y.current.scrollTop<=k.current*D.current,Oe=y.current.scrollTop+y.current.clientHeight>=k.current*D.current+D.current;ie?Oe||q(k.current):(y.current.scrollTop=k.current*D.current,E(y.current.scrollTop))}};i&&i({navigate:l?ue:b.current.navigate,keydown:l?Ce:b.current.keydown,move:b.current.move})},[]);const ce=d.useRef(0),$=d.useRef(t);$.current!==t&&($.current=t,ce.current+=1);const ee=d.useCallback(()=>{b.current.navigate(null)},[b]),B=d.useCallback(ue=>{l&&E(ue.target.scrollTop)},[l]),L=d.useMemo(()=>Math.ceil((y.current?.clientHeight||0)/I),[I,N]),oe=d.useMemo(()=>{if(!l)return{start:0,end:t.length};if(!t.length)return{start:0,end:0};const ue=Math.floor(N/I),Ce=ue+L;return{start:Math.max(0,ue-xw),end:Math.min(t.length,Ce+xw)}},[l,t,N,I,L]),be=d.useMemo(()=>{if(!l)return t;const{start:ue,end:Ce}=oe;return t.slice(ue,Ce).map(Me=>({...Me}))},[l,t,oe]),H=oe.start*I,me=t.length*I;return d.useEffect(()=>{l&&E(0)},[t,l]),d.useEffect(()=>{x===null&&(w.current=!1)},[x]),x===null?null:o.jsx(zv,{onCancel:ee,...g,children:o.jsx("div",{className:"wx-233fr7 wx-list",ref:O,onClick:K,onMouseMove:b.current.move,onScroll:B,children:t.length?l?o.jsx("div",{className:"wx-233fr7 wx-list-wrapper",style:{height:`${me}px`},children:o.jsx("div",{className:"wx-233fr7 wx-list-content",style:{transform:`translateY(${H}px)`},children:o.jsx(Sw,{visibleRange:oe,visibleItems:be,navIndex:x,measureRefCallback:W,checkboxes:u,itemTemplate:n,value:h})})}):o.jsx(Sw,{visibleRange:oe,visibleItems:be,navIndex:x,measureRefCallback:W,checkboxes:u,itemTemplate:n,value:h}):o.jsx("div",{className:"wx-233fr7 wx-no-data",children:U("No data")})})},ce.current)}function $v({value:t="",id:n,readonly:r=!1,focus:i=!1,select:l=!1,type:u="text",placeholder:f="",disabled:h=!1,error:g=!1,title:y="",tooltip:w,css:b="",icon:x="",clear:M=!1,onChange:k}){const N=FS(n),[E,I]=po(t),T=d.useRef(null),P=d.useMemo(()=>x&&b.indexOf("wx-icon-left")===-1?"wx-icon-right "+b:b,[x,b]),U=d.useMemo(()=>x&&b.indexOf("wx-icon-left")!==-1,[x,b]);d.useEffect(()=>{const ne=setTimeout(()=>{i&&T.current&&T.current.focus(),l&&T.current&&T.current.select()},1);return()=>clearTimeout(ne)},[i,l]);const F=d.useCallback(ne=>{const q=ne.target.value;I(q),k&&k({value:q,input:!0})},[k]),Y=d.useCallback(ne=>k&&k({value:ne.target.value}),[k]);function D(ne){ne.stopPropagation(),I(""),k&&k({value:""})}let K=u;return u!=="password"&&u!=="number"&&(K="text"),d.useEffect(()=>{const ne=Y,q=T.current;return q.addEventListener("change",ne),()=>{q&&q.removeEventListener("change",ne)}},[Y]),o.jsxs("div",{className:`wx-hQ64J4 wx-text ${P} ${g?"wx-error":""} ${h?"wx-disabled":""} ${M?"wx-clear":""}`,"data-tooltip-text":w,children:[o.jsx("input",{className:"wx-hQ64J4 wx-input",ref:T,id:N,readOnly:r,disabled:h,placeholder:f,type:K,title:y,value:E,onInput:F}),M&&!h&&E?o.jsxs(o.Fragment,{children:[o.jsx("i",{className:"wx-hQ64J4 wx-icon wxi-close",onClick:D}),U&&o.jsx("i",{className:`wx-hQ64J4 wx-icon ${x}`})]}):x?o.jsx("i",{className:`wx-hQ64J4 wx-icon ${x}`}):null]})}function $N({date:t,type:n,part:r,onShift:i}){const{calendar:l,formats:u}=d.useContext(Ai).getRaw(),f=t.getFullYear(),h=d.useMemo(()=>{switch(n){case"month":return gd(u.monthYearFormat,l)(t);case"year":return gd(u.yearFormat,l)(t);case"duodecade":{const{start:y,end:w}=IS(f),b=gd(u.yearFormat,l);return`${b(new Date(y,0,1))} - ${b(new Date(w,11,31))}`}default:return""}},[t,n,f,l,u]);function g(){i&&i({diff:0,type:n})}return o.jsxs("div",{className:"wx-8HQVQV wx-header",children:[r!=="right"?o.jsx("i",{className:"wx-8HQVQV wx-pager wxi-angle-left",onClick:()=>i&&i({diff:-1,type:n})}):o.jsx("span",{className:"wx-8HQVQV wx-spacer"}),o.jsx("span",{className:"wx-8HQVQV wx-label",onClick:g,children:h}),r!=="left"?o.jsx("i",{className:"wx-8HQVQV wx-pager wxi-angle-right",onClick:()=>i&&i({diff:1,type:n})}):o.jsx("span",{className:"wx-8HQVQV wx-spacer"})]})}function Uv({onClick:t,children:n}){return o.jsx("button",{className:"wx-3s8W4d wx-button",onClick:t,children:n})}function UN({value:t,current:n,part:r="",markers:i=null,css:l="",onCancel:u,onChange:f}){const h=(d.useContext(Ai)||sh()).getRaw().calendar,g=(h.weekStart||7)%7,y=h.dayShort.slice(g).concat(h.dayShort.slice(0,g)),w=(F,Y,D)=>new Date(F.getFullYear(),F.getMonth()+(Y||0),F.getDate()+(D||0));let b=r!=="normal";function x(F){const Y=F.getDay();return Y===0||Y===6}function M(){const F=w(n,0,1-n.getDate());return F.setDate(F.getDate()-(F.getDay()-(g-7))%7),F}function k(){const F=w(n,1,-n.getDate());return F.setDate(F.getDate()+(6-F.getDay()+g)%7),F}const N=d.useRef(0);function E(F,Y){Y.timeStamp!==N.current&&(N.current=Y.timeStamp,Y.stopPropagation(),f&&f(new Date(F)),u&&u())}const I=d.useMemo(()=>r=="normal"?[t?w(t).valueOf():0]:t?[t.start?w(t.start).valueOf():0,t.end?w(t.end).valueOf():0]:[0,0],[r,t]),T=d.useMemo(()=>{const F=M(),Y=k(),D=n.getMonth();let K=[];for(let ne=F;ne<=Y;ne.setDate(ne.getDate()+1)){const q={day:ne.getDate(),in:ne.getMonth()===D,date:ne.valueOf()};let O="";if(O+=q.in?"":" wx-inactive",O+=I.indexOf(q.date)>-1?" wx-selected":"",b){const W=q.date==I[0],ce=q.date==I[1];W&&!ce?O+=" wx-left":ce&&!W&&(O+=" wx-right"),q.date>I[0]&&q.date<I[1]&&(O+=" wx-inrange")}if(O+=x(ne)?" wx-weekend":"",i){const W=i(ne);W&&(O+=" "+W)}K.push({...q,css:O})}return K},[n,I,b,i]),P=d.useRef(null);let U=d.useRef({});return U.current.click=E,d.useEffect(()=>{Cd(P.current,U.current)},[]),o.jsxs("div",{className:`wx-398RBS wx-month ${l}`,children:[o.jsx("div",{className:"wx-398RBS wx-weekdays",children:y.map(F=>o.jsx("div",{className:"wx-398RBS wx-weekday",children:F},F))}),o.jsx("div",{className:"wx-398RBS wx-days",ref:P,children:T.map(F=>o.jsx("div",{className:`wx-398RBS wx-day ${F.css} ${F.in?"":"wx-out"}`,"data-id":F.date,children:F.day},F.date))})]})}function qN({value:t,current:n,part:r,onCancel:i,onChange:l,onShift:u}){const f=d.useRef(new Date),[h,g]=po(t||f.current),[y,w]=po(n||f.current),b=d.useContext(Ai).getRaw().calendar,x=b.monthShort||[],M=d.useMemo(()=>y.getMonth(),[y]),k=d.useCallback((I,T)=>{if(I!=null){T.stopPropagation();const P=new Date(y);P.setMonth(I),w(P),u&&u({current:P})}r==="normal"&&g(new Date(y)),i&&i()},[y,r,u,i]),N=d.useCallback(()=>{const I=new Date(OS(h,r)||y);I.setMonth(y.getMonth()),I.setFullYear(y.getFullYear()),l&&l(I)},[h,y,r,l]),E=d.useCallback(I=>{const T=I.target.closest("[data-id]");if(T){const P=parseInt(T.getAttribute("data-id"),10);k(P,I)}},[k]);return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"wx-34U8T8 wx-months",onClick:E,children:x.map((I,T)=>o.jsx("div",{className:"wx-34U8T8 wx-month"+(M===T?" wx-current":""),"data-id":T,children:I},T))}),o.jsx("div",{className:"wx-34U8T8 wx-buttons",children:o.jsx(Uv,{onClick:N,children:b.done})})]})}const Cg="wx-1XEF33",WN=({value:t,current:n,onCancel:r,onChange:i,onShift:l,part:u})=>{const f=d.useContext(Ai).getRaw().calendar,[h,g]=po(n),[y,w]=po(t),b=d.useMemo(()=>h.getFullYear(),[h]),x=d.useMemo(()=>{const{start:I,end:T}=IS(b),P=[];for(let U=I;U<=T;++U)P.push(U);return P},[b]),M={click:k};function k(I,T){if(I){T.stopPropagation();const P=new Date(h);P.setFullYear(I),g(P),l&&l({current:P})}u==="normal"&&w(new Date(h)),r&&r()}function N(){const I=new Date(OS(y,u)||h);I.setFullYear(h.getFullYear()),i&&i(I)}const E=d.useRef(null);return d.useEffect(()=>{E.current&&Cd(E.current,M)},[]),o.jsxs(o.Fragment,{children:[o.jsx("div",{className:Cg+" wx-years",ref:E,children:x.map((I,T)=>o.jsx("div",{className:Cg+` wx-year ${b==I?"wx-current":""} ${T===0?"wx-prev-decade":""} ${T===11?"wx-next-decade":""}`,"data-id":I,children:I},T))}),o.jsx("div",{className:Cg+" wx-buttons",children:o.jsx(Uv,{onClick:N,children:f.done})})]})},Cw={month:{component:UN,next:VN,prev:GN},year:{component:qN,next:QN,prev:KN},duodecade:{component:WN,next:XN,prev:YN}};function GN(t){return t=new Date(t),t.setMonth(t.getMonth()-1),t}function VN(t){return t=new Date(t),t.setMonth(t.getMonth()+1),t}function KN(t){return t=new Date(t),t.setFullYear(t.getFullYear()-1),t}function QN(t){return t=new Date(t),t.setFullYear(t.getFullYear()+1),t}function YN(t){return t=new Date(t),t.setFullYear(t.getFullYear()-10),t}function XN(t){return t=new Date(t),t.setFullYear(t.getFullYear()+10),t}function OS(t,n){let r;if(n==="normal")r=t;else{const{start:i,end:l}=t;n==="left"?r=i:n=="right"?r=l:r=i&&l}return r}const ZN=["clear","today"];function JN(t){if(t==="done")return-1;if(t==="clear")return null;if(t==="today")return new Date}function eT({value:t,current:n,onCurrentChange:r,part:i="normal",markers:l=null,buttons:u,css:f="",onShift:h,onChange:g}){const y=d.useContext(Ai).getGroup("calendar"),[w,b]=d.useState("month"),x=Array.isArray(u)?u:u?ZN:[],M=(T,P)=>{T.preventDefault(),g&&g({value:P})},k=()=>{w==="duodecade"?b("year"):w==="year"&&b("month")},N=T=>{const{diff:P,current:U}=T;if(P===0){w==="month"?b("year"):w==="year"&&b("duodecade");return}if(P){const F=Cw[w];r(P>0?F.next(n):F.prev(n))}else U&&r(U);h&&h()},E=T=>{b("month"),g&&g({select:!0,value:T})},I=d.useMemo(()=>Cw[w].component,[w]);return o.jsx("div",{className:`wx-2Gr4AS wx-calendar ${i!=="normal"&&i!=="both"?"wx-part":""} ${f}`,children:o.jsxs("div",{className:"wx-2Gr4AS wx-wrap",children:[o.jsx($N,{date:n,part:i,type:w,onShift:N}),o.jsxs("div",{children:[o.jsx(I,{value:t,current:n,onCurrentChange:r,part:i,markers:l,onCancel:k,onChange:E,onShift:N}),w==="month"&&x.length>0&&o.jsx("div",{className:"wx-2Gr4AS wx-buttons",children:x.map(T=>o.jsx("div",{className:"wx-2Gr4AS wx-button-item",children:o.jsx(Uv,{onClick:P=>M(P,JN(T)),children:y(T)})},T))})]})]})})}function qv(t){let{words:n=null,optional:r=!1,children:i}=t,l=d.useContext(Ai);const u=d.useMemo(()=>{let f=l;return(!f||!f.extend)&&(f=rm(LS)),n!==null&&(f=f.extend(n,r)),f},[n,r,l]);return o.jsx(Ai.Provider,{value:u,children:i})}function kw(t,n,r,i){if(!t||i){const l=n?new Date(n):new Date;l.setDate(1),r(l)}else if(t.getDate()!==1){const l=new Date(t);l.setDate(1),r(l)}}const tT=["clear","today"];function HS({value:t,current:n,markers:r=null,buttons:i=tT,css:l="",onChange:u}){const[f,h]=po(t),[g,y]=po(n);d.useEffect(()=>{kw(g,f,y,!1)},[f,g]);const w=d.useCallback(x=>{const M=x.value;M?(h(new Date(M)),kw(g,new Date(M),y,!0)):h(null),u&&u({value:M?new Date(M):null})},[u,g]),b=d.useCallback(x=>{y(x)},[y]);return g?o.jsx(qv,{children:o.jsx(eT,{value:f,current:g,markers:r,buttons:i,css:l,onChange:w,onCurrentChange:b})}):null}function nT(t){return t||(t={}),t.width||(t.width="unset"),t}const aT=["clear","today"];function rT({value:t,id:n,disabled:r=!1,error:i=!1,placeholder:l="",format:u="",buttons:f=aT,css:h="",title:g="",tooltip:y,editable:w=!1,clear:b=!1,onChange:x,dropdown:M={}}){const{calendar:k,formats:N}=(d.useContext(Ai)||sh()).getRaw(),E=u||N?.dateFormat;let I=typeof E=="function"?E:gd(E,k);const[T,P]=d.useState(t),[U,F]=d.useState(!1);d.useEffect(()=>{P(t)},[t]);function Y(){F(!1)}function D(q){const O=q===T||q&&T&&q.valueOf()===T.valueOf()||!q&&!T;P(q),O||x&&x({value:q}),setTimeout(Y,1)}const K=d.useMemo(()=>T?I(T):"",[T,I]);function ne({value:q,input:O}){if(!w&&!b||O)return;let W=typeof w=="function"?w(q):q?new Date(q):null;W=isNaN(W)?T||null:W||null,D(W)}return d.useEffect(()=>{const q=Y;return window.addEventListener("scroll",q),()=>window.removeEventListener("scroll",q)},[]),o.jsxs("div",{className:"wx-1lKOFG wx-datepicker",onClick:()=>F(!0),children:[o.jsx($v,{css:`wx-date-input ${h}`,title:g,tooltip:y,value:K,id:n,readonly:!w,disabled:r,error:i,placeholder:l,onInput:Y,onChange:ne,icon:"wxi-calendar",clear:b}),U&&!r&&o.jsx(zv,{onCancel:Y,...nT(M),children:o.jsx(HS,{buttons:f,value:T,onChange:q=>D(q.value)})})]})}function sT({value:t="",options:n=[],textOptions:r=null,placeholder:i="",disabled:l=!1,error:u=!1,title:f="",tooltip:h,textField:g="label",clear:y=!1,css:w="",children:b,onChange:x,dropdown:M={}}){const k=d.useRef(null),N=d.useRef(null);let[E,I]=po(t);function T(D){k.current=D.navigate,N.current=D.keydown}const P=d.useMemo(()=>E||E===0?(r||n).find(D=>D.id===E):null,[E,r,n]),U=d.useCallback(({id:D})=>{(D||D===0)&&(I(D),k.current(null),x&&x({value:D}))},[I,x]),F=d.useCallback(D=>{D.stopPropagation(),I(""),x&&x({value:""})},[I,x]),Y=d.useCallback(()=>n.findIndex(D=>D.id===E),[n,E]);return o.jsxs("div",{className:`wx-2YgblL wx-richselect ${w} ${u?"wx-2YgblL wx-error":""} ${l?"wx-2YgblL wx-disabled":""} ${b?"":"wx-2YgblL wx-nowrap"}`,title:f,onClick:()=>k.current(Y()),onKeyDown:D=>N.current(D,Y()),tabIndex:0,"data-tooltip-text":h,children:[o.jsx("div",{className:"wx-2YgblL wx-label",children:P?b?b(P):P[g]:i?o.jsx("span",{className:"wx-2YgblL wx-placeholder",children:i}):" "}),y&&!l&&E?o.jsx("i",{className:"wx-2YgblL wx-icon wxi-close",onClick:F}):o.jsx("i",{className:"wx-2YgblL wx-icon wxi-angle-down"}),!l&&o.jsx(ih,{items:n,onReady:T,onSelect:U,...M,children:({option:D})=>b?b(D):D[g]})]})}const iT=({options:t=[],value:n="",css:r="",children:i,onChange:l})=>{const[u,f]=d.useState(n),h=g=>{f(g),l&&l({value:g})};return d.useEffect(()=>{f(n)},[n]),o.jsx("div",{className:`wx-0hMO7P wx-segmented ${r}`,children:t.map(g=>o.jsx("button",{className:`wx-0hMO7P wx-segment ${g.css} ${g.id===u?"wx-selected":""}`,title:g.title,onClick:()=>h(g.id),"data-tooltip-text":g.tooltip,children:i?Pv(i,{option:g}):o.jsxs(o.Fragment,{children:[g.icon&&o.jsx("i",{className:`wx-0hMO7P wx-icon ${g.icon} ${g.label?"":"wx-only"}`}),g.label&&o.jsx("span",{className:"wx-0hMO7P wx-label",children:g.label})]})},g.id))})};function oT({notice:t={}}){function n(){t.remove&&t.remove()}return o.jsxs("div",{className:`wx-11sNg5 wx-notice wx-${t.type?t.type:""}`,role:"status","aria-live":"polite",children:[o.jsx("div",{className:"wx-11sNg5 wx-text",children:t.text}),o.jsx("div",{className:"wx-11sNg5 wx-button",children:o.jsx("i",{className:"wx-11sNg5 wxi-close",onClick:n})})]})}function lT({data:t=[]}){return o.jsx("div",{className:"wx-3nwoO9 wx-notices",children:t.map(n=>o.jsx(oT,{notice:n},n.id))})}function pv({title:t="",buttons:n=["cancel","ok"],header:r,children:i,footer:l,css:u="",onConfirm:f,onCancel:h}){const g=(d.useContext(Ai)||sh()).getGroup("core"),y=d.useRef(null);d.useEffect(()=>{y.current?.focus()},[]);function w(x){switch(x.code){case"Enter":{const M=x.target.tagName;if(M==="TEXTAREA"||M==="BUTTON")return;f&&f({event:x});break}case"Escape":h&&h({event:x});break}}function b(x,M){const k={event:x,button:M};M==="cancel"?h&&h(k):f&&f(k)}return o.jsx("div",{className:`wx-1FxkZa wx-modal ${u}`,ref:y,tabIndex:0,onKeyDown:w,children:o.jsxs("div",{className:"wx-1FxkZa wx-window",children:[r||(t?o.jsx("div",{className:"wx-1FxkZa wx-header",children:t}):null),o.jsx("div",{children:i}),l||n&&o.jsx("div",{className:"wx-1FxkZa wx-buttons",children:n.map(x=>o.jsx("div",{className:"wx-1FxkZa wx-button",children:o.jsx(Kf,{type:`block ${x==="ok"?"primary":"secondary"}`,onClick:M=>b(M,x),children:g(x)})},x))})]})})}function cT({children:t},n){const[r,i]=d.useState(null),[l,u]=d.useState([]);return d.useImperativeHandle(n,()=>({showModal:f=>{const h={...f};return i(h),new Promise((g,y)=>{h.resolve=w=>{i(null),g(w)},h.reject=w=>{i(null),y(w)}})},showNotice:f=>{f={...f},f.id=f.id||Ov(),f.remove=()=>u(h=>h.filter(g=>g.id!==f.id)),f.expire!=-1&&setTimeout(f.remove,f.expire||5100),u(h=>[...h,f])}}),[]),o.jsxs(o.Fragment,{children:[t,r&&o.jsx(pv,{title:r.title,buttons:r.buttons,onConfirm:r.resolve,onCancel:r.reject,children:r.message}),o.jsx(lT,{data:l})]})}const uT=d.forwardRef(cT);function dT(t){let{children:n}=t,r=d.useRef();const i=d.useMemo(()=>({showNotice:l=>r.current.showNotice(l),showModal:l=>r.current.showModal(l)}),[]);return o.jsx(_S.Provider,{value:i,children:o.jsx(uT,{ref:r,children:n})})}const fT=({value:t=!1,type:n="",icon:r="",disabled:i=!1,iconActive:l="",onClick:u,title:f="",tooltip:h,css:g="",text:y="",textActive:w="",children:b,active:x,onChange:M})=>{const[k,N]=po(t),E=d.useMemo(()=>(k?"pressed":"")+(n?" "+n:""),[k,n]),I=d.useCallback(T=>{let P=!k;u&&u(T),T.defaultPrevented||(N(P),M&&M({value:P}))},[k,u,M]);return k&&x?o.jsx(Kf,{title:f,tooltip:h,text:k&&w||y,css:g,type:E,icon:k&&l||r,onClick:I,disabled:i,children:Pv(x,{value:k})}):b?o.jsx(Kf,{title:f,tooltip:h,text:k&&w||y,css:g,type:E,icon:k&&l||r,onClick:I,disabled:i,children:b}):o.jsx(Kf,{title:f,tooltip:h,text:k&&w||y,css:g,type:E,icon:k&&l||r,onClick:I,disabled:i})};function mT(){return o.jsx(o.Fragment,{})}function Mw(t){const{fonts:n=!0,children:r}=t;return o.jsx(Hv.Provider,{value:"willow",children:o.jsxs(o.Fragment,{children:[r&&r&&o.jsx("div",{className:"wx-theme wx-willow-theme",children:r}),n&&o.jsxs(o.Fragment,{children:[o.jsx("link",{rel:"preconnect",href:"https://cdn.svar.dev",crossOrigin:"true"}),o.jsx(mT,{}),o.jsx("link",{rel:"stylesheet",href:"https://cdn.svar.dev/fonts/wxi/wx-icons.css"})]})]})})}Fv(Yr);const Wv={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 BS=class{constructor(t){this._nextHandler=null,this._dispatch=t,this.exec=this.exec.bind(this)}async exec(t,n){return this._dispatch(t,n),this._nextHandler&&await this._nextHandler.exec(t,n),n}setNext(t){return this._nextHandler=t}};new Date().valueOf();var pT=class{constructor(t){const n={id:0,$level:0,data:[],parent:null},r=new Map;r.set(0,n),this._pool=r,t&&t.length&&this.parse(t,0)}parse(t,n){const r=this._pool;for(let l=0;l<t.length;l++){const u=t[l];u.parent=u.parent||n,u.data=null,r.set(u.id,u)}for(let l=0;l<t.length;l++){const u=t[l],f=r.get(u.parent);f&&(f.data||(f.data=[]),f.data.push(u))}const i=r.get(n);this.setLevel(i,i.$level+1,!1)}add(t,n){const r=this._pool.get(t.parent||0);t.$level=r.$level+1,this._pool.set(t.id,t),r.data?n===-1?r.data=[...r.data,t]:Aw(r,n,t):r.data=[t]}addAfter(t,n){if(!n)return this.add(t,-1);const r=this.byId(n),i=this.byId(r.parent),l=gp(i,r.id)+1;t.parent=i.id,t.$level=i.$level+1,this.add(t,l)}remove(t){const n=this._pool.get(t);this._remove(n);const r=this._pool.get(n.parent);r.data=r.data.filter(i=>i.id!=t),this._clearBranch(r)}_remove(t){t.data&&t.data.forEach(n=>this._remove(n)),this._pool.delete(t.id)}update(t,n){let r=this._pool.get(t);const i=this._pool.get(r.parent),l=gp(i,r.id);r={...r,...n},i&&l>=0&&(i.data[l]=r,i.data=[...i.data]),this._pool.set(r.id,r)}move(t,n,r){const i=this._pool.get(t),l=n==="child",u=this._pool.get(r),f=u.$level+(l?1:0);if(!i||!u)return;const h=this._pool.get(i.parent),g=l?u:this._pool.get(u.parent);g.data||(g.data=[]);const y=gp(h,i.id);hT(h,y);const w=l?g.data.length:gp(g,u.id)+(n==="after"?1:0);if(Aw(g,w,i),h.id===g.id&&y===w)return null;i.parent=g.id,i.$level!==f&&(i.$level=f,this.setLevel(i,f+1,!0)),this.update(i.id,i),this._clearBranch(h)}_clearBranch(t){t.data&&!t.data.length&&(t.open&&delete t.open,this.update(t.id,{data:null}))}toArray(){const t=[],n=this._pool.get(0).data;return n&&zS(n,t),t}byId(t){return this._pool.get(t)}getBranch(t){return this._pool.get(t).data}forEach(t){this._pool.forEach((n,r)=>{r!==0&&t(n)})}eachChild(t,n){const r=this.byId(n);!r||!r.data||r.data.forEach((i,l)=>{t(this.byId(i.id),l),this.eachChild(t,i.id)})}setLevel(t,n,r){t.data&&(t.data=t.data.map(i=>(r&&(i={...i},this._pool.set(i.id,i)),i.$level=n,i.data&&this.setLevel(i,n+1,r),i)))}};function zS(t,n){t.forEach(r=>{n.push(r),r.open===!0&&zS(r.data,n)})}function hT(t,n){const r=[...t.data];r.splice(n,1),t.data=r}function Aw(t,n,r){const i=[...t.data];i.splice(n,0,r),t.data=i}function gp(t,n){return t?.data.findIndex(r=>r.id===n)}var $S=2,gT=class{constructor(n){n&&(this._writable=n.writable,this._async=n.async),this._values={},this._state={}}setState(n,r=0){const i={};return this._wrapProperties(n,this._state,this._values,"",i,r),i}getState(){return this._values}getReactive(){return this._state}_wrapProperties(n,r,i,l,u,f){for(const h in n){const g=r[h],y=i[h],w=n[h];if(g&&(y===w&&typeof w!="object"||w instanceof Date&&y instanceof Date&&y.getTime()===w.getTime()))continue;const b=l+(l?".":"")+h;g?(g.__parse(w,b,u,f)&&(i[h]=w),f&$S?u[b]=g.__trigger:g.__trigger()):(w&&w.__reactive?r[h]=this._wrapNested(w,w,b,u):r[h]=this._wrapWritable(w),i[h]=w),u[b]=u[b]||null}}_wrapNested(n,r,i,l){const u=this._wrapWritable(n);return this._wrapProperties(n,u,r,i,l,0),u.__parse=(f,h,g,y)=>(this._wrapProperties(f,u,r,h,g,y),!1),u}_wrapWritable(n){const r=[],i=function(){for(let l=0;l<r.length;l++)r[l](n)};return{subscribe:l=>(r.push(l),this._async?setTimeout(l,1,n):l(n),()=>{const u=r.indexOf(l);u>=0&&r.splice(u,1)}),__trigger:()=>{r.length&&(this._async?setTimeout(i,1):i())},__parse:function(l){return n=l,!0}}}};function Nw(t,n){return Object.defineProperty(t,"__reactive",{value:!0,enumerable:!1,writable:!1}),t}var vT=class{constructor(n,r,i,l){typeof n=="function"?this._setter=n:this._setter=n.setState.bind(n),this._routes=r,this._parsers=i,this._prev={},this._triggers=new Map,this._sources=new Map,this._routes.forEach(u=>{u.in.forEach(f=>{const h=this._triggers.get(f)||[];h.push(u),this._triggers.set(f,h)}),u.out.forEach(f=>{const h=this._sources.get(f)||{};u.in.forEach(g=>h[g]=!0),this._sources.set(f,h)})}),this._routes.forEach(u=>{u.length=Math.max(...u.in.map(f=>US(f,this._sources,1)))}),this._bus=l}init(n){const r={};for(const i in n)if(this._prev[i]!==n[i]){const l=this._parsers[i];r[i]=l?l(n[i]):n[i]}this._prev=this._prev?{...this._prev,...n}:{...n},this.setState(r),this._bus&&this._bus.exec("init-state",r)}setStateAsync(n){const r=this._setter(n,$S);return this._async?Object.assign(this._async.signals,r):this._async={signals:r,timer:setTimeout(this._applyState.bind(this),1)},r}_applyState(){const n=this._async;if(n){this._async=null,this._triggerUpdates(n.signals,[]);for(const r in n.signals){const i=n.signals[r];i&&i()}}}setState(n,r=[]){const i=this._setter(n);return this._triggerUpdates(i,r),i}_triggerUpdates(n,r){const i=Object.keys(n),l=!r.length;r=r||[];for(let u=0;u<i.length;u++){const f=i[u],h=this._triggers.get(f);h&&h.forEach(g=>{r.indexOf(g)==-1&&r.push(g)})}l&&this._execNext(r)}_execNext(n){for(;n.length;){n.sort((i,l)=>i.length<l.length?1:-1);const r=n[n.length-1];n.splice(n.length-1),r.exec(n)}}};function US(t,n,r){const i=n.get(t);if(!i)return r;const l=Object.keys(i).map(u=>US(u,n,r+1));return Math.max(...l)}var yT=class{constructor(){this._nextHandler=null,this._handlers={},this._tag=new WeakMap,this.exec=this.exec.bind(this)}on(n,r,i){let l=this._handlers[n];l?i&&i.intercept?l.unshift(r):l.push(r):l=this._handlers[n]=[r],i&&i.tag&&this._tag.set(r,i.tag)}intercept(n,r,i){this.on(n,r,{...i,intercept:!0})}detach(n){for(const r in this._handlers){const i=this._handlers[r];for(let l=i.length-1;l>=0;l--)this._tag.get(i[l])===n&&i.splice(l,1)}}async exec(n,r){const i=this._handlers[n];if(i)for(let l=0;l<i.length;l++){const u=i[l](r);if(u===!1||u&&u.then&&await u===!1)return}return this._nextHandler&&await this._nextHandler.exec(n,r),r}setNext(n){return this._nextHandler=n}};const cd=1024;function tm(t){return t<cd?`${t} B`:t<cd**2?`${(t/cd).toFixed(1)} KB`:t<cd**3?`${(t/cd**2).toFixed(1)} MB`:`${(t/cd**3).toFixed(1)} GB`}function Tw(t,n){n||(n={key:"name",order:"asc"});const r=t.filter(f=>f.type==="folder"),i=t.filter(f=>f.type!=="folder"),l=r.sort(Rw(n)),u=i.sort(Rw(n));return[...l,...u]}function bT(t,n){return typeof t=="string"?t.localeCompare(n,void 0,{numeric:!0}):typeof t=="object"?t.getTime()-n.getTime():(t??0)-(n??0)}function wT(t,n){return typeof t=="string"?-t.localeCompare(n,void 0,{numeric:!0}):typeof n=="object"?n.getTime()-t.getTime():(n??0)-(t??0)}function Rw({key:t,order:n}){const r=n==="asc"?bT:wT;return(i,l)=>r(i[t],l[t])}function Gv(t,n){const r=t==="/"?1:t.split("/").length;return r>=n.length?null:n[r].id}function xT(t){return t.length>1?t[t.length-2].id:null}let ST=class extends pT{constructor(n){const r={id:"/",name:"My files",open:!0,$level:1,parent:0,ext:"",type:"folder"};super([r]),this.parse(n,"/")}parse(n,r,i){!n||!n.length||(n.forEach(l=>this.parseId(l,i?r:void 0)),super.parse(n,r))}parseId(n,r){if(n.parent===0)return;const i=n.id,l=i.lastIndexOf("/");if(n.parent=r??(l===0?"/":i.slice(0,l)),n.name=i.slice(l+1),n.type=n.type||"file",n.type!=="folder"){const u=n.name.lastIndexOf("."),f=u!==-1?n.name.slice(u+1):"";n.ext=f!=="new"?f?.toLocaleLowerCase():""}}getParents(n){const r=[];let i=this.byId(n);if(!i)return r;for(;i.id!==0;)r.push(i),i=this.byId(i.parent);return r.reverse()}findFiles(n,r="/"){const i=[],l=n.toLocaleLowerCase();return this.eachChild(u=>{u.name.toLowerCase().indexOf(l)!==-1&&i.push(u)},r),i}add(n,r){const i=this.byId(n.parent||"/"),l=n.data?[...n.data]:null;n.data=null,super.add(n,r??i.data?i.data.length:0),l&&l.forEach(u=>this.add(u))}renameFiles(n,r,i){const l=this.byId(n),u=this.normalizeFile(l,r),f=[];return u.data?.forEach(h=>f.push(this.renameFiles(h.id,u.id,i))),f.length&&(u.data=f),i[n]=u.id,u}copyFiles(n,r,i){const l={};return n.forEach(u=>{const f=this.renameFiles(u,r,l);this.add(f),i&&this.remove(u),l[u]=f.id}),l}moveFiles(n,r){if(this.byId(n[0]).parent!==r)return this.copyFiles(n,r,!0)}serialize(n="/"){const r=[],i=this.byId(n);return i?(i.data?.forEach(l=>{const{id:u,date:f,type:h,size:g,lazy:y}=l,w={id:u,date:f,type:h??"file"};y&&(w.lazy=y),g&&(w.size=g),r.push(w);const b=this.serialize(u);b.length&&r.push(...b)}),r):null}normalizeFile(n,r){const i=n.name,l=i.lastIndexOf("."),u=l!==-1?i.slice(l+1):"",f=u?`.${u}`:"";let h=l!==-1?i.slice(0,l):i,g=r+(r==="/"?"":"/")+h;for(;this.byId(g+f);){const y=".new";g+=y,h+=y}return{...n,id:g+f,name:h+f,parent:r,ext:u.toLocaleLowerCase()}}},CT=class extends gT{in;_router;constructor(n){super({writable:n,async:!1});const r=[];for(let u=0;u<2;u++)r.push({in:["data",`panels.${u}.path`],out:[`panels.${u}._crumbs`],exec:f=>{const{data:h,panels:g}=this.getState(),y=[];y[u]={_crumbs:h.getParents(g[u].path)},this.setState({panels:y},f)}}),r.push({in:["data",`panels.${u}.path`,`panels.${u}._sorts`,"search"],out:[`panels.${u}._files`],exec:f=>{const{data:h,panels:g,search:y}=this.getState();let w;y?w=h.findFiles(y,g[u].path):w=h.byId(g[u].path)?.data||[];const{path:b,_sorts:x}=g[u];w=Tw(w,x[b]);const M=[];M[u]={_files:w},this.setState({panels:M},f)}}),r.push({in:["data",`panels.${u}.selected`,`panels.${u}._sorts`],out:[`panels.${u}._selected`],exec:f=>{const{data:h,panels:g}=this.getState(),y=[];g[u].selected.forEach(k=>{const N=h.byId(k);N&&y.push(N)});const{path:w,_sorts:b}=g[u],x=Tw(y,b[w]),M=[];M[u]={_selected:x},this.setState({panels:M},f)}});this._router=new vT(super.setState.bind(this),r,{data:u=>new ST(u)});const i=this.in=new yT;i.on("select-file",({id:u,toggle:f,range:h,panel:g,type:y})=>{const{panels:w,activePanel:b}=this.getState();typeof g>"u"&&(g=b),u||(f=h=!1);let x=[...w[g].selected];if(f){const k=x.indexOf(u);k===-1?x.push(u):x.splice(k,1)}else if(h&&w[g]._lastSelected){const k=w[g]._files;let N=k.findIndex(T=>T.id==w[g]._lastSelected),E=k.findIndex(T=>T.id==u);E<N&&([N,E]=[E,N]);const I=k.slice(N,E+1).map(T=>T.id);x=[...new Set([...x,...I])]}else x=u?[u]:[];const M=[];M[g]={selected:x,_lastSelected:u,_selectNavigation:y==="navigation"},this.setState({panels:M})}),i.on("set-path",({id:u,panel:f,selected:h})=>{const{data:g,activePanel:y}=this.getState(),w=g.byId(u);if(w){const b=[];typeof f>"u"&&(f=y),b[f]={path:u},this.setState({panels:b}),i.exec("select-file",{panel:f}),h&&h.forEach(x=>i.exec("select-file",{id:x,panel:f,toggle:!0})),w.lazy&&i.exec("request-data",{id:u})}}),i.on("provide-data",({id:u,data:f})=>{const{mode:h,data:g}=this.getState(),y=g.byId(u);y&&(y.lazy||(y.data=[]),y.lazy=!1,g.parse(f,u,h==="search"),this.setState({data:g}))}),i.on("open-tree-folder",({id:u,mode:f})=>{const{data:h}=this.getState();h.update(u,{open:f}),this.setState({data:h})}),i.on("show-preview",({mode:u})=>{this.setState({preview:u})}),i.on("rename-file",u=>{const{id:f,name:h}=u,{data:g,panels:y}=this.getState(),w=g.byId(f);if(w.name!==h){w.name=h;const b=g.normalizeFile(w,w.parent);u.newId=b.id,b.data=null,g.add(b);let x={[f]:b.id};w.data?.forEach(k=>x={...g.moveFiles([k.id],b.id),...x});const M=y.map(k=>({selected:k.selected,_crumbs:k._crumbs,_lastSelected:k._lastSelected,_sorts:k._sorts}));g.remove(f),this._updatePanels(M,x),this.setState({data:g,panels:M})}}),i.on("create-file",u=>{const{file:f,parent:h}=u,{data:g}=this.getState(),y=g.normalizeFile(f,h);y.type=f.type||"file",u.newId=y.id,g.add(y),this.setState({data:g}),i.exec("select-file",{id:y.id})}),i.on("delete-files",({ids:u})=>{const{data:f,panels:h}=this.getState(),g=h.map(y=>({selected:y.selected,_crumbs:y._crumbs,_lastSelected:y._lastSelected,_sorts:y._sorts}));u.forEach(y=>f.remove(y)),this._updatePanels(g,{}),this.setState({data:f,panels:g})}),i.on("copy-files",u=>{const{ids:f,target:h}=u;if(this._isPlacedIntoSelf(f,h)){console.error("You cannot copy a folder into itself"),u.skipProvider=!0;return}const{data:g,panels:y,activePanel:w}=this.getState(),b=g.copyFiles(f,h);u.newIds=f.map(x=>b[x]),this.setState({data:g}),y[w].path==h&&(i.exec("select-file",{}),f.forEach(x=>{i.exec("select-file",{id:b[x],toggle:!0})}))}),i.on("move-files",u=>{const{ids:f,target:h}=u;if(this._isPlacedIntoSelf(f,h)){console.error("You cannot move a folder into itself"),u.skipProvider=!0;return}const{data:g,panels:y,activePanel:w}=this.getState(),b=g.moveFiles(f,h);if(b){u.newIds=f.map(M=>b[M]);const x=y.map(M=>({selected:M.selected,_crumbs:M._crumbs,_lastSelected:M._lastSelected,_sorts:M._sorts}));this._updatePanels(x,b,!0),this.setState({data:g,panels:x}),y[w].path==h&&(i.exec("select-file",{}),f.forEach(M=>{i.exec("select-file",{id:b[M],toggle:!0})}))}});let l=null;i.on("filter-files",({text:u})=>{if(!u){l&&this.setState({...l});return}i.exec("select-file",{});const{panels:f,mode:h}=this.getState();l||(l={panels:f,mode:h,search:""}),this.setState({mode:"search",search:u})}),i.on("set-mode",({mode:u})=>{const{activePanel:f}=this.getState(),h=[];h[f]={_selectNavigation:!1};const g={mode:u,search:"",panels:h};l=null,this.setState(g)}),i.on("set-active-panel",({panel:u})=>{this.setState({activePanel:u})}),i.on("sort-files",({key:u,order:f,panel:h,path:g})=>{const{activePanel:y,panels:w}=this.getState();h=h??y,g=g??w[h].path;const b=[];b[h]={_sorts:{...w[h]._sorts,[g]:{key:u,order:f}}},this.setState({panels:b})}),this.initOnce()}initOnce(){const n=[];for(let i=0;i<2;i++)n[i]=Nw({_crumbs:[],_files:[],_selected:[],_sorts:{},path:"/",selected:[],...n[i]});const r={panels:Nw(n),data:[],search:""};this._router.init(r)}init(n){const r={...n};this._router.init(r)}setState(n,r){return this._router.setState(n,r)}getFile(n){const{data:r}=this.getState();return r.byId(n)||null}serialize(n){const{data:r}=this.getState();return r.serialize(n)}_updatePanels(n,r,i){const{data:l}=this.getState();n.forEach(u=>{const f=[];u.selected.forEach(y=>{l.byId(y)?f.push(y):!i&&r[y]&&f.push(r[y])}),u.selected=f,l.byId(u._lastSelected)||(u._lastSelected=i?null:r[u._lastSelected]||null);const h={};Object.keys(u._sorts).forEach(y=>{l.byId(y)?h[y]=u._sorts[y]:r[y]&&!i&&(h[r[y]]=u._sorts[y])}),u._sorts=h;const g=u._crumbs[u._crumbs.length-1];g?.id!=="/"&&(r[g.id]?u.path=r[g.id]:l.byId(g.id)||(u.path="/"))})}_isPlacedIntoSelf(n,r){return n.some(i=>i===r||this.getState().data.getParents(r).some(l=>l.id===i))}};function kT(t){switch(t){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[t==="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(n=>n!==null)}}function MT(t,n="data-id"){let r=t;for(!r.tagName&&t.target&&(r=t.target);r;){if(r.getAttribute&&r.getAttribute(n))return r;r=r.parentNode}return null}function AT(t,n="data-id"){const r=MT(t,n);return r?r.getAttribute(n):null}new Date().valueOf();function NT(t,n){const{api:r}=n;function i(u,f){const h=n.getPanel(),g=h.selected,y=f.ctrlKey||f.metaKey,w=f.shiftKey;let b;const x=g?.[0]?r.getFile(g[0]):null;g?.length?g.length>1?b=n.menuOptions("multiselect"):b=n.menuOptions(x.type,x):b=n.menuOptions("body");const M=`${y?"ctrl+":""}${w?"shift+":""}${u}`,k=b?b.find(E=>E.hotkey?.toLowerCase()===M):!1,N=n.performAction;if(k)switch(M){case"ctrl+c":N("copy");break;case"ctrl+x":N("move");break;case"ctrl+v":N("paste",x);break;case"delete":N("delete");break;case"ctrl+r":f.preventDefault(),N("rename",x);break;case"ctrl+d":f.preventDefault(),N("download",x);break;default:k.handler?.({context:x})}switch(u){case"enter":{if(y||w)break;const{_crumbs:E,_selectNavigation:I}=h;if(I){const T=xT(E);if(T){const P=Gv(T,E);r.exec("set-path",{id:T,selected:[P]})}}else if(g.length===1){const T=r.getFile(g[0]);T&&r.exec(T.type==="folder"?"set-path":"open-file",{id:T.id})}break}case"arrowup":case"arrowleft":{const{_files:E,_selected:I,path:T,_selectNavigation:P}=h;let U;if(I.length){const F=I.at(0).id,Y=E.findIndex(D=>D.id===F);if(Y!==-1){const D=Y-1;E[D]?U=E[D].id:T!=="/"&&!(y||w)&&r.exec("select-file",{type:"navigation"})}}else{if(P)break;if(T!=="/"){r.exec("select-file",{type:"navigation"});break}U=E.at(0)?.id}U&&r.exec("select-file",{id:U,toggle:y,range:w});break}case"arrowdown":case"arrowright":{const{_files:E,_selected:I,path:T,_selectNavigation:P}=h;let U;if(I.length){const F=I.at(-1).id,Y=E.findIndex(D=>D.id===F);if(Y!==-1){const D=Y+1;E[D]&&(U=E[D].id)}}else{if(T!=="/"&&!P){r.exec("select-file",{type:"navigation"});break}U=E.at(0)?.id}U&&r.exec("select-file",{id:U,toggle:y,range:w});break}}}function l(u){const f=u.code.replace("Key","").toLowerCase();i(f,u),f=="tab"&&setTimeout(()=>{const h=document.activeElement;h.className.indexOf("table")!=-1&&r.exec("set-active-panel",{panel:+AT(h,"data-panel")})})}return t.addEventListener("keydown",l),{destroy:()=>{t.removeEventListener("keydown",l)}}}function TT(t,n="data-id"){let r=t;for(!r.tagName&&t.target&&(r=t.target);r;){if(r.getAttribute&&r.getAttribute(n))return r;r=r.parentNode}return null}function RT(t,n="data-id"){const r=t.getAttribute(n);return r?jT(r):null}function jT(t){if(t.startsWith(":"))return t.substring(1);const n=t*1;return isNaN(n)?t:n}function ET(){return{detect:()=>!0,addEvent:function(t,n,r){return t.addEventListener(n,r),()=>t.removeEventListener(n,r)},addGlobalEvent:function(t,n){return document.addEventListener(t,n),()=>document.removeEventListener(t,n)},getTopNode:function(){return window.document.body}}}var DT=ET();new Date().valueOf();function qS(t){const[n,r]=d.useState(t),i=d.useRef(t);return d.useEffect(()=>{if(i.current!==t){if(Array.isArray(i.current)&&Array.isArray(t)&&i.current.length===0&&t.length===0)return;i.current=t,r(t)}},[t]),[n,r]}function IT(t,n,r){const[i,l]=d.useState(()=>n);return t||console.warn(`Writable ${r} is not defined`),d.useEffect(()=>t?t.subscribe(f=>{l(()=>f)}):void 0,[t]),i}function Lt(t,n){const r=t.getState(),i=t.getReactiveState();return IT(i[n],r[n],n)}function LT(t,n){const r=d.useRef(n);r.current=n;const[i,l]=d.useState(1);return d.useEffect(()=>t.subscribe(f=>{r.current=f,l(h=>h+1)}),[t]),[r.current,i]}function Vs(t,n){const r=t.getState(),i=t.getReactiveState();return LT(i[n],r[n])}function WS(t){const n={};return t.split(";").forEach(r=>{const[i,l]=r.split(":");if(l){let u=i.trim();u.indexOf("-")&&(u=u.replace(/-([a-z])/g,(f,h)=>h.toUpperCase())),n[u]=l.trim()}}),n}function GS(t){let n=t,r=[];return{subscribe:h=>{r.push(h),h(n)},unsubscribe:h=>{r=r.filter(g=>g!==h)},set:h=>{n=h,r.forEach(g=>g(n))},update:h=>{n=h(n),r.forEach(g=>g(n))}}}function jw(t,n,r){function i(l){const u=TT(l);if(!u)return;const f=RT(u);if(typeof n=="function")return n(f,l);let h,g=l.target;for(;g!=u;){if(h=g.dataset?g.dataset.action:null,h&&n[h]){n[h](f,l);return}g=g.parentNode}n[r]&&n[r](f,l)}return DT.addEvent(t,r,i)}function _T(t,n){const r=[jw(t,n,"click")];return n.dblclick&&r.push(jw(t,n.dblclick,"dblclick")),()=>{r.forEach(i=>i())}}function VS(t,n){return t.map((r,i)=>{const l=n(r,i);return r.data&&r.data.length&&(l.data=VS(r.data,n)),l}).filter(Boolean)}function KS(t,n){const r=[];return t.forEach(i=>{if(i.data){const l=KS(i.data,n);l.length&&r.push({...i,data:l})}else n(i)&&r.push(i)}),r}function PT(t){return VS(t,(n,r)=>{const i={...n,id:n.id||Ov()};return i.type&&(i.comp=i.type),i.comp==="separator"&&t[r-1]?.comp==="separator"?null:i})}const QS={};function FT(t){return QS[t]||t}function OT(t,n){QS[t]=n}function HT({onClick:t,onShow:n,option:r}){const i=d.useRef(null),l=d.useCallback(()=>{n(r.data?r.id:!1,i.current)},[n,r]),u=d.useCallback(h=>{if(r.data){h.stopPropagation(),n(r.id,i.current);return}t(h)},[t,n,r]),f=d.useMemo(()=>r&&r.comp?FT(r.comp):null,[r]);return o.jsxs("div",{ref:i,className:`wx-cDCz9rZQ wx-option ${r.css||""} ${r.disabled?"wx-disabled":""}`,"data-id":za(r.id),onMouseEnter:l,onClick:u,children:[r.icon?o.jsx("i",{className:`wx-cDCz9rZQ wx-icon ${r.icon}`}):null,r.comp?f?o.jsx(f,{item:r,option:r}):null:o.jsxs("span",{className:"wx-cDCz9rZQ wx-value",children:[" ",r.text," "]}),r.subtext?o.jsx("span",{className:"wx-cDCz9rZQ wx-subtext",children:r.subtext}):null,r.data?o.jsx("i",{className:"wx-cDCz9rZQ wx-sub-icon wxi-angle-right"}):null]})}function Vv({options:t,left:n=0,top:r=0,at:i="bottom",parent:l=null,mount:u=null,context:f=null,css:h="",onClick:g,onCancel:y}){const[w,b]=d.useState(-1e4),[x,M]=d.useState(-1e4),[k,N]=d.useState(20),[E,I]=d.useState(),T=d.useRef(null),[P,U]=d.useState(!1),[F,Y]=d.useState(null),D=d.useCallback(()=>{const $=ES(T.current,l,i,n,r);$&&(b($.x),M($.y),I($.width));let ee=$?.z??20;const B=l?NN(l):[];let L=0;for(const oe of B){const be=parseInt(getComputedStyle(oe).zIndex,10);be>L&&(L=be)}L>=ee&&(ee=L+1),N(ee)},[l,i,n,r]);d.useEffect(()=>{u&&u(D)},[]);const K=d.useCallback(()=>{U(!1)},[]),ne=d.useCallback(($,ee)=>{U($),Y(ee)},[]),q=d.useMemo(()=>PT(t),[t]);d.useEffect(()=>{D()},[l,D]);const O=d.useRef(g),W=d.useRef(y),ce=d.useRef(l);return d.useEffect(()=>{O.current=g},[g]),d.useEffect(()=>{W.current=y},[y]),d.useEffect(()=>{ce.current=l},[l]),d.useEffect(()=>{if(!T.current)return;function $(ee){W.current?W.current(ee):O.current&&O.current({action:null,option:null})}return go(T.current,{callback:$,modal:!0,parent:()=>ce.current}).destroy},[]),o.jsx("div",{ref:T,"data-wx-menu":"true",className:`wx-XMmAGqVx wx-menu ${h}`,style:{position:"absolute",top:x+"px",left:w+"px",width:E,zIndex:k},onMouseLeave:K,children:q.map($=>o.jsxs(d.Fragment,{children:[$.comp==="separator"?o.jsx("div",{className:"wx-XMmAGqVx wx-separator"}):o.jsx(HT,{option:$,onShow:ne,onClick:ee=>{if(!$.data&&!ee.defaultPrevented){const B={context:f,action:$,option:$,event:ee};$.handler&&$.handler(B),g&&g(B),ee.stopPropagation()}}}),$.data&&P===$.id?o.jsx(Vv,{css:h,options:$.data,at:"right-overlap",parent:F,context:f,onClick:g,onCancel:y}):null]},$.id))})}const YS=d.forwardRef(function(t,n){const{options:r,at:i="bottom",resolver:l=null,dataKey:u="contextId",filter:f=null,css:h="",children:g,onClick:y}=t,[w,b]=d.useState(null),[x,M]=d.useState(null),[k,N]=d.useState(0),[E,I]=d.useState(0),T=d.useRef(null),P=d.useMemo(()=>`data-${u.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}`,[u]),U=d.useMemo(()=>w!==null&&f?KS(r,K=>f(K,w)):r,[w,f,r]);function F(K){M(null),y&&y(K)}function Y(K){if(T.current===K){T.current=null;return}M(null),y&&y({action:null,option:null})}const D=d.useCallback((K,ne)=>{if(!K){M(null);return}if(K.defaultPrevented)return;const q=K.target;if(q&&q.dataset&&q.dataset.menuIgnore)return;if(x&&x===q){M(null),K.preventDefault();return}N(K.clientX+1),I(K.clientY+1);let O=typeof ne<"u"?ne:em(q,P);l&&(O=l(O,K),!O)||(b(O),M(q),T.current=K.nativeEvent||K,K.preventDefault())},[x,P,l]);return d.useImperativeHandle(n,()=>({show:D}),[D]),o.jsxs(o.Fragment,{children:[g?o.jsx("span",{onClick:D,"data-menu-ignore":"true",children:typeof g=="function"?g():g}):null,x?o.jsx(Bv,{children:o.jsx(Vv,{css:h,at:i,top:E,left:k,parent:x,context:w,onClick:F,onCancel:Y,options:U},x)}):null]})}),BT=d.forwardRef(function(t,n){const{options:r,at:i="bottom",css:l="",children:u,onClick:f}=t,[h,g]=d.useState(null),y=d.useRef(null);function w(k){g(null),f&&f(k)}function b(k){if(y.current===k){y.current=null;return}g(null),f&&f({action:null,option:null})}const x=d.useCallback(k=>{g(k.target),y.current=k.nativeEvent||k,k.preventDefault()},[]);d.useImperativeHandle(n,()=>({show:x}),[x]);function M(k){let N=k.target;for(;!N.dataset.menuIgnore;)g(N),N=N.parentNode}return o.jsxs(o.Fragment,{children:[o.jsx("span",{onClick:M,"data-menu-ignore":"true",children:u}),h?o.jsx(Bv,{children:o.jsx(Vv,{css:l,at:i,parent:h,options:r,onClick:w,onCancel:b})}):null]})}),zT=d.forwardRef(function(t,n){const{options:r,at:i="bottom",resolver:l=null,dataKey:u="contextId",filter:f=null,css:h="",children:g,onClick:y}=t,w=d.useRef(null),b=d.useCallback((x,M)=>{w.current.show(x,M)},[]);return d.useImperativeHandle(n,()=>({show:b}),[b]),o.jsxs(o.Fragment,{children:[g?o.jsx("span",{onContextMenu:b,"data-menu-ignore":"true",children:g}):null,o.jsx(YS,{css:h,at:i,options:r,resolver:l,dataKey:u,filter:f,ref:w,onClick:y})]})}),$T={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 UT=class{constructor(n,r,i,l,u){this.setFiles=n,this.setReady=r,this.setSignal=i,this.setDrag=l,u&&u.length&&this.setFiles(u)}open(n){this.setSignal(["click",n||{}])}getState(){let n="server";const r=this.files;for(let i=0;i<r.length;i++){if(r[i].status==="client")return"client";r[i].status==="error"&&(n="error")}return n}droparea(n,r){r=r||{};const i=()=>{r.dragEnter&&r.dragEnter(),this.setDrag(!0)},l=()=>{r.dragLeave&&r.dragLeave(),this.setDrag(!1)},u=h=>{h.preventDefault()},f=h=>{h.preventDefault(),this.setDrag(!1),this.setSignal(["drop",r,h]),r.dragLeave&&r.dragLeave(),r.drop&&r.drop()};return n.addEventListener("dragenter",i),n.addEventListener("dragleave",l),n.addEventListener("dragover",u,!0),n.addEventListener("drop",f,!0),()=>{n.removeEventListener("dragenter",i),n.removeEventListener("dragleave",l),n.removeEventListener("dragover",u,!0),n.removeEventListener("drop",f,!0)}}updateFile(n,r){const i=this.files.findIndex(u=>u.id===n);if(i===-1)return;const l=[...this.files];return l[i]={...l[i],...r},this.files=l,this.setFiles(this.files),this.files[i]}deleteFile(n){this.files=this.files.filter(r=>r.id!==n),this.setFiles(this.files)}addFile(n,r){r?this.files=[...this.files,n]:this.files=[n],this.setFiles(this.files)}deleteAll(){this.files=[],this.setFiles(this.files)}};function XS(t){const[n,r]=d.useState([]),[i,l]=d.useState(Promise.resolve(null)),[u,f]=d.useState(null),[h,g]=d.useState(!1),y=d.useRef();return y.current||(y.current=new UT(r,l,f,g,t)),y.current.files=n,y.current.ready=i,y.current.signal=u,y.current.drag=h,y.current}function qT(t,n){{if(t){const r=t.getGroup(n);if(r)return r}return rm($T).getGroup(n)}}const WT=()=>Math.random().toString(36).substr(2,9),GT=({data:t,accept:n="",multiple:r=!0,folder:i=!1,uploadURL:l="",apiOnly:u=!1,disabled:f=!1,children:h,onChange:g,onUpload:y})=>{const w=d.useRef(null),b=d.useRef(null),[x,M]=d.useState({}),k=XS(),N=t||k,E=d.useContext(Ua.i18n),I=qT(E,"uploader");d.useEffect(()=>{w.current&&i&&(w.current.webkitdirectory=!0)},[i]),d.useEffect(()=>{if(!u&&b.current&&!f)return N.droparea(b.current)},[u,f,b]);const T=q=>{const O=new FormData;return O.append("upload",q.file),fetch(l,{method:"POST",body:O}).then(W=>W.json()).then(W=>({id:q.id,...W}),()=>({id:q.id,status:"error"})).catch(W=>(console.log(W),{id:q.id,status:"error"}))},P=(q,O)=>{const W=N.updateFile(q,O),ce={...W,status:N.getState()};W&&W.uploaded&&W.uploaded(ce),y&&y(ce),W.temp&&N.deleteFile(W.id)},U=q=>{if(!q)return;const O=typeof l=="function"?l(q):T(q);N.setReady(O.then(W=>{W.status=W.status||"server",P(q.id,W)}).catch(W=>{P(q.id,{status:"error",error:W})}))},F=(q,O)=>{const W={...O||x,id:WT(),status:"client",name:q.name,file:q};W.selected&&W.selected(W),g&&g(W),N.addFile(W,r),U(W),w.current&&(w.current.value="")},Y=(q,O,W)=>{q.isFile?q.file(ce=>{F(ce,W)}):q.isDirectory&&q.createReader().readEntries(ce=>{ce.forEach($=>{Y($,O+$.name+"/",W)})})},D=q=>{Array.from(q.target.files).forEach(O=>F(O))},K=(q,O)=>{Array.from(q.dataTransfer.items).forEach(W=>{const ce=W.webkitGetAsEntry();ce&&Y(ce,"",O)})},ne=()=>{w.current&&w.current.click()};return d.useEffect(()=>{if(N.signal){const[q,O,W]=N.signal;M(O),q==="click"?ne():q==="drop"&&K(W,O),N.setSignal(null)}},[N.signal]),u?o.jsxs(o.Fragment,{children:[o.jsx("input",{type:"file",className:"wx-at1A8tb8 wx-input",ref:w,onChange:D,accept:n,multiple:r,disabled:f}),h]}):o.jsxs("div",{className:`wx-at1A8tb8 wx-label ${N.drag?"wx-active":""} ${f?"wx-disabled":""}`,ref:b,children:[o.jsx("input",{type:"file",className:"wx-at1A8tb8 wx-input",ref:w,onChange:D,accept:n,multiple:r,disabled:f}),h||o.jsx("div",{className:"wx-at1A8tb8 wx-dropzone",children:o.jsxs("span",{children:[I("Drop files here or")," ",o.jsx("span",{className:"wx-at1A8tb8 wx-action",onClick:ne,children:I("select files")})]})})]})};new Date().valueOf();function VT(t,n){if(Object.keys(t).length!==Object.keys(n).length)return!1;for(const r in n){const i=t[r],l=n[r];if(!oh(i,l))return!1}return!0}function oh(t,n){if(typeof t=="number"||typeof t=="string"||typeof t=="boolean"||t===null)return t===n;if(typeof t!=typeof n||(t===null||n===null)&&t!==n||t instanceof Date&&n instanceof Date&&t.getTime()!==n.getTime())return!1;if(typeof t=="object")if(Array.isArray(t)&&Array.isArray(n)){if(t.length!==n.length)return!1;for(let r=t.length-1;r>=0;r--)if(!oh(t[r],n[r]))return!1;return!0}else return VT(t,n);return t===n}function hv(t){if(typeof t!="object"||t===null)return t;if(t instanceof Date)return new Date(t);if(t instanceof Array)return t.map(hv);const n={};for(const r in t)n[r]=hv(t[r]);return n}var ZS=2,KT=class{constructor(t){t&&(this._writable=t.writable,this._async=t.async),this._values={},this._state={}}setState(t,n=0){const r={};return this._wrapProperties(t,this._state,this._values,"",r,n),r}getState(){return this._values}getReactive(){return this._state}_wrapProperties(t,n,r,i,l,u){for(const f in t){const h=n[f],g=r[f],y=t[f];if(h&&(g===y&&typeof y!="object"||y instanceof Date&&g instanceof Date&&g.getTime()===y.getTime()))continue;const w=i+(i?".":"")+f;h?(h.__parse(y,w,l,u)&&(r[f]=y),u&ZS?l[w]=h.__trigger:h.__trigger()):(y&&y.__reactive?n[f]=this._wrapNested(y,y,w,l):n[f]=this._wrapWritable(y),r[f]=y),l[w]=l[w]||null}}_wrapNested(t,n,r,i){const l=this._wrapWritable(t);return this._wrapProperties(t,l,n,r,i,0),l.__parse=(u,f,h,g)=>(this._wrapProperties(u,l,n,f,h,g),!1),l}_wrapWritable(t){const n=[],r=function(){for(let i=0;i<n.length;i++)n[i](t)};return{subscribe:i=>(n.push(i),this._async?setTimeout(i,1,t):i(t),()=>{const l=n.indexOf(i);l>=0&&n.splice(l,1)}),__trigger:()=>{n.length&&(this._async?setTimeout(r,1):r())},__parse:function(i){return t=i,!0}}}},QT=class{constructor(t,n,r,i){typeof t=="function"?this._setter=t:this._setter=t.setState.bind(t),this._routes=n,this._parsers=r,this._prev={},this._triggers=new Map,this._sources=new Map,this._routes.forEach(l=>{l.in.forEach(u=>{const f=this._triggers.get(u)||[];f.push(l),this._triggers.set(u,f)}),l.out.forEach(u=>{const f=this._sources.get(u)||{};l.in.forEach(h=>f[h]=!0),this._sources.set(u,f)})}),this._routes.forEach(l=>{l.length=Math.max(...l.in.map(u=>JS(u,this._sources,1)))}),this._bus=i}init(t){const n={};for(const r in t)if(this._prev[r]!==t[r]){const i=this._parsers[r];n[r]=i?i(t[r]):t[r]}this._prev=this._prev?{...this._prev,...t}:{...t},this.setState(n),this._bus&&this._bus.exec("init-state",n)}setStateAsync(t){const n=this._setter(t,ZS);return this._async?Object.assign(this._async.signals,n):this._async={signals:n,timer:setTimeout(this._applyState.bind(this),1)},n}_applyState(){const t=this._async;if(t){this._async=null,this._triggerUpdates(t.signals,[]);for(const n in t.signals){const r=t.signals[n];r&&r()}}}setState(t,n=[]){const r=this._setter(t);return this._triggerUpdates(r,n),r}_triggerUpdates(t,n){const r=Object.keys(t),i=!n.length;n=n||[];for(let l=0;l<r.length;l++){const u=r[l],f=this._triggers.get(u);f&&f.forEach(h=>{n.indexOf(h)==-1&&n.push(h)})}i&&this._execNext(n)}_execNext(t){for(;t.length;){t.sort((r,i)=>r.length<i.length?1:-1);const n=t[t.length-1];t.splice(t.length-1),n.exec(t)}}};function JS(t,n,r){const i=n.get(t);if(!i)return r;const l=Object.keys(i).map(u=>JS(u,n,r+1));return Math.max(...l)}var YT=class{constructor(){this._nextHandler=null,this._handlers={},this._tag=new WeakMap,this.exec=this.exec.bind(this)}on(t,n,r){let i=this._handlers[t];i?r&&r.intercept?i.unshift(n):i.push(n):i=this._handlers[t]=[n],r&&r.tag&&this._tag.set(n,r.tag)}intercept(t,n,r){this.on(t,n,{...r,intercept:!0})}detach(t){for(const n in this._handlers){const r=this._handlers[n];for(let i=r.length-1;i>=0;i--)this._tag.get(r[i])===t&&r.splice(i,1)}}async exec(t,n){const r=this._handlers[t];if(r)for(let i=0;i<r.length;i++){const l=r[i](n);if(l===!1||l&&l.then&&await l===!1)return}return this._nextHandler&&await this._nextHandler.exec(t,n),n}setNext(t){return this._nextHandler=t}};function XT(t){return n=>n[t]}function ZT(t){return(n,r)=>n[t]=r}function oc(t,n){return(n.getter||XT(n.id))(t)}function kg(t,n,r){return(n.setter||ZT(n.id))(t,r)}function JT(t,n){const r=document.createElement("a");r.href=URL.createObjectURL(t),r.download=n,document.body.appendChild(r),r.click(),document.body.removeChild(r)}function ac(t,n){let r=oc(t,n)??"";return n.template?r=n.template(r,t,n):n.optionsMap&&(Array.isArray(r)?r=r.map(i=>n.optionsMap.get(i)).join(", "):r=n.optionsMap.get(r)),typeof r>"u"?"":r+""}function eR(t,n){const r=/\n|"|;|,/;let i="";const l=n.rows||`
174
+ `,u=n.cols||" ",f=t._columns,h=t.flatData;n.header!==!1&&f[0].header&&(i=Ew("header",f,i,u,l));for(let g=0;g<h.length;g++){const y=[];for(let w=0;w<f.length;w++){let b=ac(h[g],f[w]);r.test(b)&&(b='"'+b.replace(/"/g,'""')+'"'),y.push(b)}i+=(i?l:"")+y.join(u)}return n.footer!==!1&&f[0].footer&&(i=Ew("footer",f,i,u,l)),i}function Ew(t,n,r,i,l){const u=/\n|"|;|,/;for(let f=0;f<n[0][t].length;f++){const h=[];for(let g=0;g<n.length;g++){let y=(n[g][t][f].text||"")+"";u.test(y)&&(y='"'+y.replace(/"/g,'""')+'"'),h.push(y)}r+=(r?l:"")+h.join(i)}return r}const tR="portrait",nR=100,aR="a4",rR={a3:{width:11.7,height:16.5},a4:{width:8.27,height:11.7},letter:{width:8.5,height:11}};function sR(t,n){const r=[];let i=[],l=0;const u=t.filter(h=>!h.hidden),f=iR(n);return u.forEach((h,g)=>{l+h.width<=f?(l+=h.width,i.push(h)):(i.length&&r.push(i),i=[h],l=h.width),g===u.length-1&&i.length&&r.push(i)}),r}function Dw(t,n,r){const i=[];return t.forEach((l,u)=>{const f=l[n];for(let h=0;h<r.length;h++){i[h]||(i[h]=[]);const g={...f[h]};if(i[h][u]!==null){if(!u&&!g.rowspan&&!g.colspan){let y=1,w=t[u+y][n][h],b=g.width;for(;!w.rowspan&&!w.colspan;)y++,w=t[u+y][n][h],b+=w.width;g.colspan=y,g.width=b,g.height=r[h]}if(i[h].push(g),!g.collapsed&&g.colspan>1){let y=g.colspan-1;if(g.colspan+u>t.length){const w=g.colspan-(g.colspan+u-t.length);g.colspan=w,g.width=t.slice(u,u+y+1).reduce((b,x)=>b+x.width,0),w>1&&(y=w-1)}for(let w=0;w<y;w++)i[h].push(null)}if(g.rowspan>1){const y=g.rowspan;for(let w=1;w<y;w++)i[h+w]||(i[h+w]=[]),i[h+w].push(null)}}}if(l.collapsed)for(let h=0;h<i.length;h++){const g=i[h],y=g[u];if(y&&y.collapsed){if(g[u]=null,!h)break}else{const w=y||g.findLast(b=>b?.colspan>=1);w&&(w.colspan=w.colspan-1,w.width=w.width-l.width)}}}),i.map(l=>l.filter(u=>u&&u.colspan!==0))}function iR(t){const{mode:n,ppi:r,paper:i}=t,{width:l,height:u}=rR[i];return oR(n==="portrait"?l:u,r)}function oR(t,n){return t*n}function lR(t={}){const{mode:n,ppi:r,paper:i}=t;return{mode:n||tR,ppi:r||nR,paper:i||aR}}function e0(t,n){return t.flexgrow?`min-width:${n}px;width:auto`:`width:${t.width}px; max-width:${t.width}px; height:${t.height}px`}function cR(t,n,r){let i=t[r.id];if(r.filter.type==="richselect"&&i){const l=r.filter.config?.options||n.find(({id:u})=>u==r.id).options;l&&(i=l.find(({id:u})=>u==i).label)}return i??""}const Iw=["resize-column","hide-column","update-cell"],uR=["delete-row","update-row","update-cell"],dR=["move-item"],fR=["resize-column","move-item"];class mR{undo=[];redo=[];progress={};in;getState;setState;_previousValues={};constructor(n,r,i){this.in=n,this.getState=r,this.setState=i,this.setHandlers(),this.resetStateHistory()}getHandlers(){return{"add-row":{handler:n=>({action:"delete-row",data:{id:n.id},source:{action:"add-row",data:n}})},"delete-row":{handler:n=>{const{id:r}=n,{data:i}=this.getPrev(),l=i.findIndex(u=>u.id===r);return{action:"add-row",data:{id:r,row:i[l],before:l<i.length-1?i[l+1].id:void 0},source:{action:"delete-row",data:n}}}},"update-cell":{handler:n=>{const{id:r,column:i}=n,l=this.getRow(r),u=this.getColumn(i),f=oc(l,u);return oh(f,n.value)?null:{action:"update-cell",data:{id:r,column:i,value:f},source:{action:"update-cell",data:n}}}},"update-row":{handler:n=>{const{id:r,row:i}=n,l=this.getRow(r);for(const u in i)Object.keys(l).includes(u)||(l[u]=void 0);return{action:"update-row",data:{id:r,row:l},source:{action:"update-row",data:n}}}},"copy-row":{handler:n=>{const{id:r}=n,{data:i}=this.getState(),l=i.findIndex(f=>f.id===r),u=i[l];return{action:"delete-row",data:{id:r},source:{action:"add-row",data:{id:r,row:u,before:l<i.length-1?i[l+1].id:void 0}}}}},"resize-column":{handler:n=>{const{id:r,width:i}=n,l=this.getColumn(r),{_sizes:u}=this.getState();return{action:"resize-column",data:{id:r,width:l.width??u.columnWidth},source:{action:"resize-column",data:{id:r,width:i}}}}},"hide-column":{handler:n=>{const{id:r}=n,i=this.getColumn(r);return{action:"hide-column",data:{id:r,mode:i.hidden},source:{action:"hide-column",data:n}}}},"collapse-column":{handler:n=>{const{id:r,row:i,mode:l}=n;return{action:"collapse-column",data:{id:r,row:i,mode:typeof l=="boolean"?!l:l},source:{action:"collapse-column",data:n}}}},"move-item":{handler:n=>{const{id:r,target:i,mode:l}=n,{flatData:u}=this.getPrev(),f=u.findIndex(h=>h.id===r);return{action:"move-item",data:{id:r,target:u[f+(f?-1:1)].id,mode:f?"after":"before"},source:{action:"move-item",data:{id:r,target:i,mode:l}}}}},"open-row":{handler:n=>{const{id:r,nested:i}=n;return{action:"close-row",data:{id:r,nested:i},source:{action:"open-row",data:n}}}},"close-row":{handler:n=>{const{id:r,nested:i}=n;return{action:"open-row",data:{id:r,nested:i},source:{action:"close-row",data:n}}}}}}resetHistory(){this.undo=[],this.redo=[],this.progress={},this.resetStateHistory()}getPrev(){return this._previousValues}setHandlers(){const n=this.getHandlers();for(const r in n)this.in.intercept(r,i=>{if(!(i.eventSource==="undo"||i.eventSource==="redo"||i.skipUndo)){if(fR.includes(r)){(i.inProgress&&!this.progress[r]||typeof i.inProgress!="boolean")&&(dR.includes(r)&&this.setPrev("flatData"),Iw.includes(r)&&this.setPrev("columns")),this.progress[r]=i.inProgress;return}uR.includes(r)&&this.setPrev("data"),Iw.includes(r)&&this.setPrev("columns")}}),this.in.on(r,i=>{if(i.eventSource==="undo"||i.eventSource==="redo"||i.skipUndo||i.inProgress)return;const l=n[r].handler(i);l&&this.addToHistory(l)})}setPrev(n){this._previousValues[n]=hv(this.getState()[n])}addToHistory(n){this.undo.push(n),this.redo=[],this.setStateHistory()}handleUndo(){if(!this.undo.length)return;const n=this.undo.pop();this.redo.push({...n.source,source:n}),this.in.exec(n.action,{...n.data,eventSource:"undo"}),this.setStateHistory()}handleRedo(){if(!this.redo.length)return;const n=this.redo.pop();this.undo.push({...n.source,source:n}),this.in.exec(n.action,{...n.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(n){const{data:r}=this.getPrev();return this.getState().tree?this.getTreeRow(r,n):r.find(i=>i.id===n)}getTreeRow(n,r){for(let i=0;i<n.length;i++){if(n[i].id===r)return n[i];if(n[i].data){const l=this.getTreeRow(n[i].data,r);if(l)return l}}return null}getColumn(n){const{columns:r}=this.getPrev();return r.find(i=>i.id===n)}}function t0(t,n){return typeof t>"u"||t===null?-1:typeof n>"u"||n===null?1:t===n?0:t>n?1:-1}function pR(t,n){return-t0(t,n)}function hR(t,n){if(typeof n.sort=="function")return function(i,l){const u=n.sort(i,l);return t==="asc"?u:-u};const r=t==="asc"?t0:pR;return function(i,l){return r(oc(i,n),oc(l,n))}}function gR(t,n){if(!t||!t.length)return;const r=t.map(i=>{const l=n.find(u=>u.id==i.key);return hR(i.order,l)});return t.length===1?r[0]:function(i,l){for(let u=0;u<r.length;u++){const f=r[u](i,l);if(f!==0)return f}return 0}}const vp=28,vR=20;function yR(){if(typeof document>"u")return"willow";const t=document.querySelector('[class^="wx"][class$="theme"]');return t?t.className.substring(3,t.className.length-6):"willow"}function Wp(t,n,r,i,l){const u=document.createElement("div"),f=document.createElement("div"),h=document.body;l=l?`${l}px`:"auto";let g,y;f.className=n,u.classList.add(`wx-${r}-theme`),u.style.cssText=`height:auto;position:absolute;top:0px;left:100px;overflow:hidden;width=${l};white-space:nowrap;`,u.appendChild(f),h.appendChild(u),typeof t!="object"&&(t=[t]);for(let w=0;w<t.length;w++){f.innerText=t[w]+"";const b=u.getBoundingClientRect(),x=Math.ceil(b.width)+(i&&i.length?i[w]:0),M=Math.ceil(b.height);g=Math.max(g||0,x),y=Math.max(y||0,M)}return u.remove(),{width:g,height:y}}function Lw(t,n,r,i,l){const u=[];for(let f=0;f<t.length;f++){const h=t[f][n],g=h.length;for(let y=0;y<g;y++){const{text:w,vertical:b,collapsed:x,rowspan:M,css:k}=h[y];if(!w){u[y]=Math.max(u[y]||0,i);continue}let N=0;if(b&&!x){let E=`wx-measure-cell-${n}`;if(E+=k?` ${k}`:"",N=Wp(w,E,l).width,(M>1||!h[y+1])&&r>y+1){const I=M||r-y,T=u.slice(y,y+I).reduce((P,U)=>P+U,0);if(T<N){const P=Math.ceil((N-T)/I);for(let U=y;U<y+I;U++)u[U]=(u[U]||i)+P}continue}}u[y]=Math.max(u[y]||i,N)}}return u}function bR(t,n,r){const i=[],l=[];let u="wx-measure-cell-body";u+=t.css?` ${t.css}`:"";for(let f=0;f<n.length;f++){const h=n[f],g=ac(h,t);g&&(i.push(g),t.treetoggle?l.push(n[f].$level*vp+(n[f].$count?vp:0)+(t.draggable?vp:0)):t.draggable&&l.push(vp))}return Wp(i,u,r,l).width}function wR(t,n){const r="wx-measure-cell-header",i=t.sort?vR:0;let l=t.header;if(typeof l=="string")return Wp(l,r,n).width+i;let u;Array.isArray(l)||(l=[l]);for(let f=0;f<l.length;f++){const h=l[f],g=typeof h=="string"?h:h.text,y=r+(typeof h=="string"?"":` ${h.css}`);let w=Wp(g,y,n).width;f===l.length-1&&(w+=i),u=Math.max(u||0,w)}return u}const xR={text:(t,n)=>t?t.toString().toLowerCase().indexOf(n.toLowerCase())!==-1:!n,richselect:(t,n)=>typeof n!="number"&&!n?!0:t==n,datepicker:(t,n)=>n?t&&CR(t,n):!0,multiselect:(t,n)=>!n||n?.length===0?!0:Array.isArray(t)?t?.some(r=>n.includes(r)):t&&n.includes(t)};function n0(t){return xR[t]}function SR(t,n){const r=[];for(const i in t){const l=n.find(g=>g.id==i),{config:u,type:f}=l.header.find(g=>g.filter).filter,h=t[i];r.push(g=>{const y=oc(g,l);return u?.handler?u.handler(y,h):n0(f)(y,h)})}return i=>{for(let l=0;l<r.length;l++)if(!r[l](i))return!1;return!0}}function CR(t,n){return t.getFullYear()===n.getFullYear()&&t.getMonth()===n.getMonth()&&t.getDate()===n.getDate()}let kR=class extends KT{in;_router;_branches;_xlsxWorker;_historyManager;constructor(n){super({writable:n,async:!1});const r={rowHeight:37,columnWidth:160,headerHeight:36,footerHeight:36};this._router=new QT(super.setState.bind(this),[{in:["columns","sizes","_skin"],out:["_columns","_sizes"],exec:l=>{const{columns:u,sizes:f,_skin:h}=this.getState(),g=this.copyColumns(u),y=g.reduce((x,M)=>Math.max(M.header.length,x),0),w=g.reduce((x,M)=>Math.max(M.footer.length,x),0);g.forEach(this.setCollapsibleColumns);const b=this.normalizeSizes(g,f,y,w,h);for(let x=0;x<g.length;x++)this.normalizeColumns(g,x,"header",y,b),this.normalizeColumns(g,x,"footer",w,b);this.setState({_columns:g,_sizes:b},l)}},{in:["data","tree","_filterIds"],out:["flatData","_rowHeightFromData"],exec:l=>{const{data:u,tree:f,dynamic:h,_filterIds:g}=this.getState(),y=g&&new Set(g),w=f?this.flattenRows(u,[],g):y?u.filter(x=>y.has(x.id)):u,b=!h&&w.some(x=>x.rowHeight);this.setState({flatData:w,_rowHeightFromData:b},l)}}],{sizes:l=>({...r,...l})});const i=this.in=new YT;i.on("close-editor",({ignore:l})=>{const{editor:u}=this.getState();u&&(l||i.exec("update-cell",u),this.setState({editor:null}))}),i.on("open-editor",({id:l,column:u})=>{let f=this.getState().editor;f&&i.exec("close-editor",{});const h=this.getRow(l),g=u?this.getColumn(u):this.getNextEditor(h);if(g?.editor){let y=g.editor;if(typeof y=="function"&&(y=y(h,g)),!y)return;f={column:g.id,id:l,value:oc(h,g)??"",renderedValue:ac(h,g),type:y.type||y},typeof y=="object"&&y.config&&(f.config=y.config,y.config.options&&(f.options=y.config.options)),g.options&&!f.options&&(f.options=g.options),this.setState({editor:f})}}),i.on("editor",({value:l})=>{let u=this.getState().editor;if(u){u={...u},u.value=l;const f=this.getColumn(u.column),h={...this.getRow(u.id)};kg(h,f,l),u.renderedValue=ac(h,f),this.setState({editor:u})}}),i.on("add-row",l=>{const u=this.getState();let{data:f}=u;const{select:h,_filterIds:g}=u,{row:y,before:w,after:b,select:x}=l;if(l.id=y.id=l.id||y.id||yp(),w||b){const k=w||b,N=f.findIndex(E=>E.id===k);f=[...f],f.splice(N+(b?1:0),0,l.row)}else f=[...f,l.row];const M={data:f};g&&(M._filterIds=[...g,l.id]),this.setState(M),!(typeof x=="boolean"&&!x)&&(x||h)&&i.exec("select-row",{id:y.id,show:!0})}),i.on("delete-row",l=>{const{data:u,selectedRows:f,focusCell:h,editor:g}=this.getState(),{id:y}=l,w={data:u.filter(b=>b.id!==y)};this.isSelected(y)&&(w.selectedRows=f.filter(b=>b!==y)),g?.id===y&&(w.editor=null),this.setState(w),h?.row===y&&this.in.exec("focus-cell",{eventSource:"delete-row"})}),i.on("update-cell",l=>{const u=this.getState();let{data:f}=u;f=[...f];const{tree:h}=u,{id:g,column:y,value:w}=l,b=this.getColumn(y);if(h){const x={...this._branches[g]};kg(x,b,w);const M=this.updateTreeRow(x);x.$parent===0&&(f=M)}else{const x=f.findIndex(k=>k.id===g),M={...f[x]};kg(M,b,w),f[x]=M}this.setState({data:f})}),i.on("update-row",l=>{let{data:u}=this.getState();const{id:f,row:h}=l,g=u.findIndex(y=>y.id===f);u=[...u],u[g]={...u[g],...h},this.setState({data:u})}),i.on("select-row",({id:l,toggle:u,range:f,mode:h,show:g,column:y})=>{const w=this.getState(),{focusCell:b}=w;let{selectedRows:x}=w;if(x.length||(f=u=!1),f){const{data:M}=this.getState();let k=M.findIndex(E=>E.id===x[x.length-1]),N=M.findIndex(E=>E.id===l);k>N&&([k,N]=[N,k]),M.slice(k,N+1).forEach(E=>{this.isSelected(E.id)||x.push(E.id)})}else if(u&&this.isSelected(l)){if(h===!0)return;x=x.filter(M=>M!==l)}else if(u){if(h===!1)return;x.push(l)}else x=[l];this.setState({selectedRows:[...x]}),b?.row!==l&&this.in.exec("focus-cell",{eventSource:"select-row"}),g&&this.in.exec("scroll",{row:l,column:y})}),this.in.on("focus-cell",l=>{const{row:u,column:f,eventSource:h}=l,{_columns:g,split:y}=this.getState();u&&f?(this.setState({focusCell:{row:u,column:f}}),h!=="click"&&((!y.left||g.findIndex(w=>w.id===l.column)>=y.left)&&(!y.right||g.findIndex(w=>w.id===l.column)<g.length-y.right)?this.in.exec("scroll",{row:u,column:f}):this.in.exec("scroll",{row:u}))):this.setState({focusCell:null})}),i.on("resize-column",l=>{const{id:u,auto:f,maxRows:h,inProgress:g}=l;if(g===!1)return;let y=l.width||0;const w=[...this.getState().columns],b=this.getColumn(u);if(f){if(f==="data"||f===!0){const{flatData:x,_skin:M}=this.getState();let k=x.length;h&&(k=Math.min(h,k));const N=x.slice(0,k);y=bR(b,N,M)}if(f==="header"||f===!0){const{_skin:x}=this.getState();y=Math.max(wR(b,x),y)}}b.width=Math.max(17,y),delete b.flexgrow,this.setState({columns:w})}),i.on("hide-column",l=>{const{id:u,mode:f}=l,h=[...this.getState().columns],g=this.getColumn(u),y=h.reduce((w,b)=>w+(b.hidden?0:1),0);!f||y>1?(g.hidden=!g.hidden,this.setState({columns:h})):l.skipUndo=!0}),i.on("sort-rows",l=>{const{key:u,add:f,sort:h}=l,g=this.getState(),{columns:y,data:w,tree:b}=g;if(h){const T=[...w];T.sort(h),this.setState({data:T});return}const{order:x="asc"}=l;let M=g.sortMarks;const k=Object.keys(M),N=k.length;!f||!N||N===1&&M[u]?M={[u]:{order:x}}:(N===1&&(M[k[0]]={...M[k[0]],index:0}),M={...M,[u]:{order:x,index:typeof f=="number"?f:M[u]?.index??N}});const E=Object.keys(M).sort((T,P)=>M[T].index-M[P].index).map(T=>({key:T,order:M[T].order}));this.setState({sortMarks:M});const I=gR(E,y);if(I){const T=[...w];b?this.sortTree(T,I):T.sort(I),this.setState({data:T})}}),i.on("filter-rows",l=>{const{value:u,key:f,filter:h}=l;if(!Object.keys(l).length){this.setState({filterValues:{},_filterIds:null});return}const g=this.getState(),{data:y,tree:w,_columns:b}=g;let x=g.filterValues;const M={};f&&(x={...x,[f]:u},M.filterValues=x);const k=h??SR(x,b);let N=[];w?N=this.filterTree(y,k,N):y.forEach(E=>{k(E)&&N.push(E.id)}),M._filterIds=N,this.setState(M)}),i.on("collapse-column",l=>{const{id:u,row:f,mode:h}=l,g=[...this.getState().columns],y=this.getColumn(u).header,w=Array.isArray(y)?y[f]:y;typeof w=="object"&&(w.collapsed=h??!w.collapsed,this.setState({columns:g}))}),i.on("move-item",l=>{const{id:u,inProgress:f}=l;let{target:h,mode:g="after"}=l;const{data:y,flatData:w,tree:b}=this.getState(),x=w.findIndex(N=>N.id===u);let M;if(g==="up"||g==="down"){if(g==="up"){if(x===0)return;M=x-1,g="before"}else if(g==="down"){if(x===w.length-1)return;M=x+1,g="after"}h=w[M]&&w[M].id}else M=w.findIndex(N=>N.id===h);if(x===-1||M===-1||f===!1)return;let k;b||(k=this.moveItem(u,h,y,g)),this.setState({data:b?this.normalizeTreeRows(k):k})}),i.on("copy-row",l=>{const{id:u,target:f,mode:h="after"}=l,g=this.getState(),{flatData:y,_filterIds:w}=g;let{data:b}=g;const x=this.getRow(u);if(!x)return;const M={...x,id:yp()};l.id=M.id;const k=y.findIndex(E=>E.id===f);if(k===-1)return;b.splice(k+(h==="after"?1:0),0,M),b=[...b];const N={data:b};w&&(N._filterIds=[...w,M.id]),this.setState(N)}),i.on("open-row",l=>{const{id:u,nested:f}=l;this.toggleBranch(u,!0,f)}),i.on("close-row",l=>{const{id:u,nested:f}=l;this.toggleBranch(u,!1,f)}),i.on("export-data",l=>new Promise((u,f)=>{const h=l.format||"csv",g=`${l.fileName||"data"}.${h}`;if(h==="csv"){const y=eR(this.getState(),l.csv||{});l.download!==!1?JT(new Blob(["\uFEFF"+y],{type:"text/csv"}),g):l.result=y,u(!0)}else f()})),i.on("hotkey",({key:l,event:u,isInput:f})=>{switch(l){case"arrowup":{const{flatData:h,focusCell:g,select:y}=this.getState();if(u.preventDefault(),f)return;const w=g?g.column:this._getFirstVisibleColumn()?.id,b=g?this.getPrevRow(g.row)?.id:h[h.length-1]?.id;w&&b&&(this.in.exec("focus-cell",{row:b,column:w,eventSource:"key"}),y&&this.in.exec("select-row",{id:b}));break}case"arrowdown":{const{flatData:h,focusCell:g,select:y}=this.getState();if(u.preventDefault(),f)return;const w=g?g.column:this._getFirstVisibleColumn()?.id,b=g?this.getNextRow(g.row)?.id:h[0]?.id;w&&b&&(this.in.exec("focus-cell",{row:b,column:w,eventSource:"key"}),y&&this.in.exec("select-row",{id:b}));break}case"arrowright":{const{focusCell:h}=this.getState();if(f)return;if(u.preventDefault(),h){const g=this.getNextColumn(h.column,!0)?.id;g&&this.in.exec("focus-cell",{row:h.row,column:g,eventSource:"key"})}break}case"arrowleft":{const{focusCell:h}=this.getState();if(f)return;if(u.preventDefault(),h){const g=this.getPrevColumn(h.column,!0)?.id;g&&this.in.exec("focus-cell",{row:h.row,column:g,eventSource:"key"})}break}case"tab":{const{editor:h,focusCell:g,select:y}=this.getState();if(h){u.preventDefault();const w=h.column;let b=h.id,x=this.getNextEditor(this.getRow(b),this.getColumn(w));if(!x){const M=this.getNextRow(b);M&&(b=M.id,x=this.getNextEditor(M))}x&&(this.in.exec("open-editor",{id:b,column:x.id}),this.in.exec("focus-cell",{row:b,column:x.id,eventSource:"key"}),y&&!this.isSelected(b)&&this.in.exec("select-row",{id:b}))}else g&&this.in.exec("focus-cell",{eventSource:"key"});break}case"shift+tab":{const{editor:h,focusCell:g,select:y}=this.getState();if(h){u.preventDefault();const w=h.column;let b=h.id,x=this.getPrevEditor(this.getRow(b),this.getColumn(w));if(!x){const M=this.getPrevRow(b);M&&(b=M.id,x=this.getPrevEditor(M))}x&&(this.in.exec("open-editor",{id:b,column:x.id}),this.in.exec("focus-cell",{row:b,column:x.id,eventSource:"key"}),y&&!this.isSelected(b)&&this.in.exec("select-row",{id:b}))}else g&&this.in.exec("focus-cell",{eventSource:"key"});break}case"escape":{const{editor:h}=this.getState();h&&(this.in.exec("close-editor",{ignore:h.type!="multiselect"}),this.in.exec("focus-cell",{row:h.id,column:h.column,eventSource:"key"}));break}case"f2":{const{editor:h,focusCell:g}=this.getState();!h&&g&&this.in.exec("open-editor",{id:g.row,column:g.column});break}case"enter":{const{focusCell:h,tree:g}=this.getState();if(!f&&g&&h&&this.getColumn(h.column).treetoggle){const y=this.getRow(h.row);if(!y.data)return;this.in.exec(y.open?"close-row":"open-row",{id:h.row,nested:!0})}break}case"home":{const{editor:h,focusCell:g}=this.getState();if(!h&&g){u.preventDefault();const y=this._getFirstVisibleColumn()?.id;this.in.exec("focus-cell",{row:g.row,column:y,eventSource:"key"})}break}case"ctrl+home":{const{editor:h,focusCell:g,flatData:y,select:w}=this.getState();if(!h&&g){u.preventDefault();const b=y[0]?.id,x=this._getFirstVisibleColumn()?.id;b&&x&&(this.in.exec("focus-cell",{row:b,column:x,eventSource:"key"}),w&&!this.isSelected(b)&&this.in.exec("select-row",{id:b}))}break}case"end":{const{editor:h,focusCell:g}=this.getState();if(!h&&g){u.preventDefault();const y=this._getLastVisibleColumn()?.id,w=g.row;this.in.exec("focus-cell",{row:w,column:y,eventSource:"key"})}break}case"ctrl+end":{const{editor:h,focusCell:g,flatData:y,select:w}=this.getState();if(!h&&g){u.preventDefault();const b=y.at(-1).id,x=this._getLastVisibleColumn()?.id;b&&x&&(this.in.exec("focus-cell",{row:b,column:x,eventSource:"key"}),w&&!this.isSelected(b)&&this.in.exec("select-row",{id:b}))}break}case"ctrl+z":{this.in.exec("undo",{});break}case"ctrl+y":{this.in.exec("redo",{});break}}}),i.on("scroll",l=>{const{_columns:u,split:f,_sizes:h,flatData:g,dynamic:y,_rowHeightFromData:w}=this.getState();let b=-1,x=-1,M=0,k=0;if(l.column){b=0;const N=u.findIndex(E=>E.id===l.column);M=u[N].width;for(let E=f.left??0;E<N;E++){const I=u[E];I.hidden||(b+=I.width)}}if(l.row&&!y){const N=g.findIndex(E=>E.id===l.row);N>=0&&(w?(x=g.slice(0,N).reduce((E,I)=>E+(I.rowHeight||h.rowHeight),0),k=g[N].rowHeight):x=h.rowHeight*N)}this.setState({scroll:{top:x,left:b,width:M,height:k||h.rowHeight}})}),i.on("scroll-to",l=>{const u={};l.top!==void 0&&(u.scrollTop=l.top),l.left!==void 0&&(u.scrollLeft=l.left),Object.keys(u).length&&this.setState(u)}),i.on("print",l=>{const u=lR(l);this.setState({_print:u}),this.setStateAsync({_print:null})}),i.on("undo",()=>{this._historyManager?.handleUndo()}),i.on("redo",()=>{this._historyManager?.handleRedo()}),this.initOnce()}getXlsxWorker(n){if(!this._xlsxWorker){const r=window.URL.createObjectURL(new Blob([`importScripts('${n}');`],{type:"text/javascript"}));this._xlsxWorker=new Promise(i=>{const l=new Worker(r);l.addEventListener("message",u=>{u.data.type==="init"&&i(l)})})}return this._xlsxWorker}initOnce(){const n={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(n)}init(n){n.hasOwnProperty("_skin")&&!n._skin&&(n._skin=yR()),n.columns&&n.columns.forEach(r=>{r.options&&(r.optionsMap=new Map(r.options.map(i=>[i.id,i.label])))}),oh(this.getState().data,n.data)||(n.tree?n.data=this.normalizeTreeRows(n.data):n.data=this.normalizeRows(n.data),this.setState({_filterIds:null,filterValues:{},sortMarks:{},search:null}),this._historyManager&&this._historyManager.resetHistory()),n.tree&&(n.undo=!1,n.reorder=!1),n.split?.right&&(n.split.right=0),n.undo&&!this._historyManager&&(this._historyManager=new mR(this.in,this.getState.bind(this),this.setState.bind(this))),this._router.init({...n})}setState(n,r){return this._router.setState(n,r)}setStateAsync(n){this._router.setStateAsync(n)}getRow(n){const{tree:r}=this.getState();return r?this._branches[n]:this.getState().data.find(i=>i.id===n)}getRowIndex(n,r){return r||(r=this.getState().flatData),r.findIndex(i=>i.id===n)}getNextRow(n){const r=this.getState().flatData,i=this.getRowIndex(n,r);return r[i+1]}getPrevRow(n){const r=this.getState().flatData,i=this.getRowIndex(n,r);return r[i-1]}getColumn(n){return this.getState().columns.find(r=>r.id===n)}getNextColumn(n,r){const i=this.getState()._columns,l=i.findIndex(u=>u.id===n);return r?this._getFirstVisibleColumn(l+1):i[l+1]}getPrevColumn(n,r){const i=this.getState()._columns,l=i.findIndex(u=>u.id===n);return r?this._getLastVisibleColumn(l-1):i[l-1]}_getFirstVisibleColumn(n){const r=this.getState()._columns;let i=n??0;for(;i<r.length&&(r[i]?.hidden||r[i]?.collapsed);)i++;return r[i]}_getLastVisibleColumn(n){const r=this.getState()._columns;let i=n??r.length-1;for(;i<r.length&&(r[i]?.hidden||r[i]?.collapsed);)i--;return r[i]}isCellEditable(n,r){const{editor:i,hidden:l}=r;return!i||l?!1:typeof i=="function"?i(n,r):!0}getNextEditor(n,r){let i=this.getState().columns;if(r){const l=i.findIndex(u=>u.id===r.id);i=i.slice(l+1)}return i.find(l=>this.isCellEditable(n,l))}getPrevEditor(n,r){let i=this.getState().columns;if(r){const l=i.findLastIndex(u=>u.id===r.id);i=i.slice(0,l)}return i.findLast(l=>this.isCellEditable(n,l))}toggleBranch(n,r,i){let l=this._branches[n],{data:u}=this.getState();if(u=[...u],n!==0){l={...l,open:r};const f=this.updateTreeRow(l);l.$parent===0&&(u=f)}i&&l.data?.length&&l.data.forEach(f=>{const h=this.toggleKids(f,r,i);n===0&&(u=h)}),this.setState({data:u})}toggleKids(n,r,i){n={...n,open:r};const l=this.updateTreeRow(n);return i&&n.data?.length&&n.data.forEach(u=>{this.toggleKids(u,r,i)}),l}updateTreeRow(n){const r=n.id;this._branches[r]=n;const i=this._branches[n.$parent],l=i.data.findIndex(u=>u.id===r);return i.data=[...i.data],i.data[l]=n,i.data}isSelected(n){return this.getState().selectedRows.indexOf(n)!==-1}findAndRemove(n,r){for(let i=0;i<n.length;i++){if(n[i].id===r)return n.splice(i,1)[0];if(n[i].data){const l=[...n[i].data],u=this.findAndRemove(l,r);if(u)return n[i]={...n[i],data:l},u}}return null}insertItem(n,r,i,l){for(let u=0;u<n.length;u++){if(n[u].id===r){const f=n[u],h=l==="before"?u:u+1;if(f.data){if(l==="before"){const g=u>0?n[u-1]:null;return g?.data&&g.open?n[u-1]={...g,data:[...g.data,i]}:n.splice(h,0,i),!0}else if(f.open)return n[u]={...f,data:[i,...f.data]},!0}return n.splice(h,0,i),!0}if(n[u].data&&(n[u]={...n[u],data:[...n[u].data]},this.insertItem(n[u].data,r,i,l)))return!0}return!1}moveItem(n,r,i,l){const u=[...i],f=this.findAndRemove(u,n);return this.insertItem(u,r,f,l),u}copyColumns(n){const r=[];for(let i=0;i<n.length;i++){const l={...n[i]};this.copyHeaderFooter(l,"header"),this.copyHeaderFooter(l,"footer"),r[i]=l}return r}copyHeaderFooter(n,r){let i=n[r];i=Array.isArray(i)?[...i]:[i],i.forEach((l,u)=>{i[u]=typeof l=="string"?{text:l}:{...l}}),n[r]=i}setCollapsibleColumns(n,r,i){let l=n.header;for(let u=0;u<l.length;u++){const f=l[u];if(f.collapsible&&f.collapsed){if(f.collapsible!=="first"){n.collapsed=!0,n.width=36,f.vertical=!0;const g=l.length-u;l=l.slice(0,u+1),l[u].rowspan=g}const h=f.colspan;if(h){const g=l[u+1];let y=1;g&&g.colspan&&!g.collapsed&&(y=g.colspan);for(let w=y;w<h;w++){const b=i[r+w];b&&(b.hidden=!0)}}}}}normalizeColumns(n,r,i,l,u){const f=n[r];f.width||(f.width=f.flexgrow?17:u.columnWidth),f._colindex=r+1;const h=f[i],g=u[`${i}RowHeights`];for(let y=0;y<l;y++){const w=h[y];w.id=f.id,y===h.length-1&&(w.rowspan=w.rowspan?Math.min(w.rowspan,l-y):l-y);for(let b=1;b<w.rowspan;b++){h.splice(y+b,0,{_hidden:!0});for(let x=1;x<w.colspan;x++)n[r+x][i].splice(y+b,0,{})}if(w.rowspan){const b=(w.rowspan===l?g:g.slice(y,w.rowspan+y)).reduce((x,M)=>x+M,0);w.height=b,y+w.rowspan!=l&&w.height--}if(w.colspan){let b=f.width,x=f.flexgrow||0;const M=w.colspan;for(let k=1;k<M;k++){const N=n[r+k];N&&(N.hidden?w.colspan-=1:N.flexgrow?x+=N.flexgrow:b+=N.width||u.columnWidth),x?w.flexgrow=x:w.width=b}}else w.width=f.width,w.flexgrow=f.flexgrow;i==="header"&&w.filter&&typeof w.filter=="string"&&(w.filter={type:w.filter})}h.length>l&&(h.length=l),f[i]=h}normalizeRows(n){for(let r=0;r<n.length;r++)n[r].id||(n[r].id=yp());return n}normalizeTreeRows(n,r,i){return!r&&!i&&(this._branches={0:{data:n}}),n.forEach(l=>{l.id||(l.id=yp()),l.$level=r||0,l.$parent=i||0,this._branches[l.id]=l,l.data&&(l.data.length?(l.$count=l.data.length,this.normalizeTreeRows(l.data,l.$level+1,l.id)):(delete l.data,delete l.$count,delete l.open))}),n}sortTree(n,r){n.sort(r),n.forEach(i=>{i.data&&this.sortTree(i.data,r)})}filterTree(n,r,i){return n.forEach(l=>{r(l)&&i.push(l.id),l.data&&this.filterTree(l.data,r,i)}),i}flattenRows(n,r,i){const l=r;return n.forEach(u=>{(!i||i.includes(u.id))&&l.push(u),u.data?.length&&u.open!==!1&&this.flattenRows(u.data,l,i)}),l}createFilter(n){const{_columns:r}=this.getState(),i=[];for(const l in n){const u=r.find(y=>y.id==l),{config:f,type:h}=u.header.find(y=>y.filter).filter,g=n[l];i.push(y=>{const w=oc(y,u);return f?.handler?f.handler(w,g):n0(h)(w,g)})}return l=>{for(let u=0;u<i.length;u++)if(!i[u](l))return!1;return!0}}searchRows(n,r){n=n.trim().toLowerCase();const i={};if(!n)return i;const{flatData:l,columns:u}=this.getState(),f=r?u.filter(h=>r[h.id]):u;return l.forEach(h=>{const g={};f.forEach(y=>{const w=ac(h,y);String(w).toLowerCase().includes(n)&&(g[y.id]=!0)}),Object.keys(g).length&&(i[h.id]=g)}),i}normalizeSizes(n,r,i,l,u){const f=Lw(n,"header",i,r.headerHeight,u),h=Lw(n,"footer",l,r.footerHeight,u),g=f.reduce((w,b)=>w+b,0),y=h.reduce((w,b)=>w+b,0);return{...r,headerRowHeights:f,footerRowHeights:h,headerHeight:g,footerHeight:y}}},MR=new Date().valueOf();function yp(){return"temp://"+MR++}function AR(t,n="data-id"){let r=t;for(!r.tagName&&t.target&&(r=t.target);r;){if(r.getAttribute&&r.getAttribute(n))return r;r=r.parentNode}return null}new Date().valueOf();var NR=class{constructor(){this.store=new Map}configure(t,n){this.node=n;for(const r in t)if(t[r]){const i=r.toLowerCase().replace(/[ ]/g,""),l=t[r];this.store.set(i,l)}}},vd=[],TR={subscribe:t=>{RR();const n=new NR;return vd.push(n),t(n),()=>{const r=vd.findIndex(i=>i===n);r>=0&&vd.splice(r,1)}}},_w=!1;function RR(){_w||(_w=!0,document.addEventListener("keydown",t=>{if(vd.length&&(t.ctrlKey||t.altKey||t.metaKey||t.shiftKey||t.key.length>1||t.key===" ")){const n=[];t.ctrlKey&&n.push("ctrl"),t.altKey&&n.push("alt"),t.metaKey&&n.push("meta"),t.shiftKey&&n.push("shift");let r=t.code.replace("Key","").toLocaleLowerCase();t.key===" "&&(r="space"),n.push(r);const i=n.join("+");for(let l=vd.length-1;l>=0;l--){const u=vd[l],f=u.store.get(i)||u.store.get(r);f&&u.node.contains(t.target)&&f(t,{key:i,evKey:r})}}}))}const jR={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 ER(t,{keys:n,exec:r}){if(!n)return;function i(f){const h=f.target;return h.tagName==="INPUT"||h.tagName==="TEXTAREA"||AR(h,"data-header-id")?.classList.contains("wx-filter")||!!h.closest(".wx-cell.wx-editor")}const l={};for(const f in n){const h=n[f];typeof h<"u"&&(typeof h=="function"?l[f]=h:h&&(l[f]=g=>{const y=i(g);r({key:f,event:g,isInput:y})}))}const u=TR.subscribe(f=>{f.configure(l,t)});return{destroy:()=>{u()}}}function DR(t,n){let r=null;n.scroll.subscribe(i=>{if(!i||i===r)return;r=i;const{left:l,top:u,height:f,width:h}=i,g=n.getHeight(),y=n.getWidth(),w=n.getScrollMargin();if(u>=0){const b=t.scrollTop;u<b?t.scrollTop=u:u+f>b+g&&(t.scrollTop=u-g+f)}if(l>=0){const b=t.scrollLeft;l<b?t.scrollLeft=l:l+h>b+y-w&&(t.scrollLeft=l-y+h+w)}}),n.scrollLeft?.subscribe?.(i=>{requestAnimationFrame(()=>{Math.abs(t.scrollLeft-i)>1&&(t.scrollLeft=i)})}),n.scrollTop?.subscribe?.(i=>{requestAnimationFrame(()=>{Math.abs(t.scrollTop-i)>1&&(t.scrollTop=i)})})}const ks=d.createContext(null);function IR(t,n){const r=new ResizeObserver(i=>{requestAnimationFrame(()=>n(i[0].contentRect))});return r.observe(t.parentNode),{destroy(){r.disconnect()}}}const Pw=5,LR=700;function Ip(t){const n=t.getBoundingClientRect(),r=document.body,i=n.top+r.scrollTop-r.clientTop||0,l=n.left+r.scrollLeft-r.clientLeft||0;return{y:Math.round(i),x:Math.round(l),width:t.offsetWidth,height:t.offsetHeight}}function gv(t,n){const r=Ip(n);return{x:t.clientX-r.x,y:t.clientY-r.y}}function _R(t,n){const r=n.current;let i=null,l,u,f=!1,h=!1;const g=document.createElement("DIV");g.className="wx-drag-zone",g.setAttribute("tabindex",-1);function y(){clearTimeout(l),l=null}function w(D){const K=Sd(D);K&&(i={container:g,sourceNode:D.target,from:rh(K),pos:gv(D,t)},u=i.pos,b(D))}function b(D){if(!i)return;const K=i.pos=gv(D,t);if(!f){if(!h&&!D?.target?.getAttribute("draggable-data")&&Math.abs(u.x-K.x)<Pw&&Math.abs(u.y-K.y)<Pw)return;if(F(D)===!1)return Y()}if(h){const ne=window.scrollX||document.documentElement.scrollLeft||document.body.scrollLeft,q=window.scrollY||document.documentElement.scrollTop||document.body.scrollTop;i.targetNode=document.elementFromPoint(D.pageX-ne,D.pageY-q)}else i.targetNode=D.target;r.move&&r.move(D,i),g.style.left=-(i.offset?i.offset.x:0)+"px",g.style.top=i.pos.y+(i.offset?i.offset.y:0)+"px"}function x(D){g.parentNode&&g.parentNode.removeChild(g),g.innerHTML="",f&&r.end&&r.end(D,i),i=u=null,Y()}function M(D){r.getReorder&&!r.getReorder()||D.button===0&&(U(D),window.addEventListener("mousemove",k),window.addEventListener("mouseup",N),w(D))}function k(D){b(D)}function N(D){x(D)}function E(D){if(r.getReorder&&!r.getReorder())return;l=setTimeout(()=>{h=!0,w(D.touches[0])},LR),U(D);function K(){l&&y(),D.target.removeEventListener("touchmove",I),D.target.removeEventListener("touchend",K),x(D)}D.target.addEventListener("touchmove",I),D.target.addEventListener("touchend",K),t.addEventListener("contextmenu",T)}function I(D){f?(D.preventDefault(),b(D.touches[0])):l&&y()}function T(D){if(f||l)return D.preventDefault(),!1}function P(D){D.preventDefault()}function U(D){if(!r.getDraggableInfo)return;const{hasDraggable:K}=r.getDraggableInfo();(!K||D.target.getAttribute("draggable-data"))&&(document.body.style.userSelect="none",document.body.style.webkitUserSelect="none")}function F(D){if(f=!0,r.start){if(r.start(D,i)===!1)return!1;t.appendChild(g),document.body.style.cursor="move"}}function Y(D){f=h=!1,document.body.style.cursor="",document.body.style.userSelect="",document.body.style.webkitUserSelect="",window.removeEventListener("mousemove",k),window.removeEventListener("mouseup",N),D&&(t.removeEventListener("mousedown",M),t.removeEventListener("touchstart",E),t.removeEventListener("dragstart",P))}return t.addEventListener("mousedown",M),t.addEventListener("touchstart",E),t.addEventListener("dragstart",P),{destroy(){Y(!0)}}}const PR=.004;function FR(){return{dirX:0,dirY:0,scrollSpeedFactor:1}}function OR(t,n,r,i){const{node:l,left:u,top:f,bottom:h,sense:g,xScroll:y,yScroll:w}=i,b=gv(t,l);r.scrollState||(r.scrollState=FR());let x=0,M=0;b.x<u+g?x=-1:b.x>n.width-g&&(x=1),b.y<f+Math.round(g/2)?M=-1:b.y>n.height-h-Math.round(g/2)&&(M=1),(r.scrollState.dirX!==x||r.scrollState.dirY!==M)&&(a0(r),r.scrollState.dirX=x,r.scrollState.dirY=M),(y&&r.scrollState.dirX!==0||w&&r.scrollState.dirY!==0)&&HR(r,i,{x:r.scrollState.dirX,y:r.scrollState.dirY})}function HR(t,n,r){t.autoScrollTimer||(t.autoScrollTimer=setTimeout(()=>{t.activeAutoScroll=setInterval(BR,15,t,n,r)},250))}function a0(t){t.scrollSpeedFactor=1,t.autoScrollTimer&&(t.autoScrollTimer=clearTimeout(t.autoScrollTimer),t.activeAutoScroll=clearInterval(t.activeAutoScroll))}function BR(t,n,r){const{x:i,y:l}=r;t.scrollSpeedFactor+=PR,i!==0&&$R(t,n,i),l!==0&&zR(t,n,l)}function zR(t,n,r){const i=n.node.scrollTop;r0(i+Math.round(n.sense/3)*t.scrollSpeedFactor*r,"scrollTop",n)}function $R(t,n,r){const i=n.node.scrollLeft;r0(i+Math.round(n.sense/3)*t.scrollSpeedFactor*r,"scrollLeft",n)}function r0(t,n,r){r.node[n]=t}function lh(t,n,r,i,l,u){const f={};return t&&(f.width=`${t}px`,f.minWidth=`${t}px`),n&&(f.flexGrow=n),u&&(f.height=`${u}px`),r&&(f.position="sticky",r.left&&(f.left=`${i}px`),r.right&&(f.right=`${l}px`)),f}function s0(t,n,r){let i="";if(t.fixed)for(const l in t.fixed){let u=t.fixed[l]===-1;!u&&t.fixed.leftSize&&n.colspan&&(u=n.colspan+t._colindex-1===t.fixed.leftSize),i+=u?"wx-shadow ":"wx-fixed "}return i+=n.rowspan>1?"wx-rowspan ":"",i+=n.colspan>1?"wx-colspan ":"",i+=n.vertical?"wx-vertical ":"",i+=r?r(t)+" ":"",i}function UR(t){const{row:n,column:r,cellStyle:i=null,columnStyle:l=null,children:u,focusable:f}=t,h=d.useContext(ks),g=Lt(h,"focusCell"),y=Lt(h,"search"),w=Lt(h,"reorder"),b=d.useMemo(()=>y?.rows[n.id]&&y.rows[n.id][r.id],[y,n.id,r.id]),x=d.useMemo(()=>lh(r.width,r.flexgrow,r.fixed,r.left,r.right),[r.width,r.flexgrow,r.fixed,r.left,r.right]);function M(F,Y){let D="wx-cell";return D+=r.fixed?" "+(r.fixed===-1?"wx-shadow":"wx-fixed"):"",D+=F?" "+F(r):"",D+=Y?" "+Y(n,r):"",D+=r.treetoggle?" wx-tree-cell":"",D}const k=d.useMemo(()=>M(l,i),[l,i,r,n]),N=d.useMemo(()=>typeof r.draggable=="function"?r.draggable(n,r)!==!1:r.draggable,[r,n]),E=d.useRef(null);d.useEffect(()=>{E.current&&f&&g?.row===n.id&&g?.column===r.id&&E.current.focus()},[g,f,n.id,r.id]);const I=d.useCallback(()=>{f&&!g&&h.exec("focus-cell",{row:n.id,column:r.id,eventSource:"focus"})},[h,f,g,n.id,r.id]);function T(F){const Y=new RegExp(`(${y.value.trim()})`,"gi");return String(F).split(Y).map(D=>({text:D,highlight:Y.test(D)}))}const P=d.useMemo(()=>{const F=r.fixed&&r.fixed.left===-1||r.fixed.right===-1,Y=r.fixed&&r.fixed.right;return[k,F?"wx-shadow":"",Y?"wx-fixed-right":""].filter(Boolean).join(" ")},[k,r]),U=r.cell;return o.jsxs("div",{className:"wx-TSCaXsGV "+P,ref:E,onFocus:I,style:x,"data-row-id":za(n.id),"data-col-id":za(r.id),tabIndex:f?"0":"-1",role:"gridcell","aria-colindex":r._colindex,"aria-readonly":r.editor?void 0:!0,children:[w&&r.draggable?N?o.jsx("i",{"draggable-data":"true",className:"wx-TSCaXsGV wx-draggable wxi-drag"}):o.jsx("i",{className:"wx-TSCaXsGV wx-draggable-stub"}):null,r.treetoggle?o.jsxs(o.Fragment,{children:[o.jsx("span",{style:{marginLeft:`${n.$level*28}px`}}),n.$count?o.jsx("i",{"data-action":"toggle-row",className:`wx-TSCaXsGV wx-table-tree-toggle wxi-menu-${n.open!==!1?"down":"right"}`}):null]}):null,U?o.jsx(U,{api:h,row:n,column:r,onAction:({action:F,data:Y})=>h.exec(F,Y)}):u?u():b?o.jsx("span",{children:T(ac(n,r)).map(({highlight:F,text:Y},D)=>F?o.jsx("mark",{className:"wx-TSCaXsGV wx-search",children:Y},D):o.jsx("span",{children:Y},D))}):ac(n,r)]})}function Fw(t,n){let r,i;function l(h){r=h.clientX,t.style.opacity=1,document.body.style.cursor="ew-resize",document.body.style.userSelect="none",window.addEventListener("mousemove",u),window.addEventListener("mouseup",f),n&&n.down&&n.down(t)}function u(h){i=h.clientX-r,n&&n.move&&n.move(i)}function f(){t.style.opacity="",document.body.style.cursor="",document.body.style.userSelect="",n&&n.up&&n.up(i),window.removeEventListener("mousemove",u),window.removeEventListener("mouseup",f)}return t.addEventListener("mousedown",l),{destroy(){t.removeEventListener("mousedown",l)}}}function qR({filter:t,column:n,action:r,filterValue:i}){function l({value:u}){r({value:u,key:n.id})}return o.jsx($v,{...t.config??{},value:i,onChange:l})}function WR({filter:t,column:n,action:r,filterValue:i}){const l=d.useContext(ks),u=Lt(l,"flatData"),f=d.useMemo(()=>t?.config?.options||n?.options||g(),[t,n,u]),h=d.useMemo(()=>t?.config?.template,[t]);function g(){const b=[];return u.forEach(x=>{const M=oc(x,n);b.includes(M)||b.push(M)}),b.map(x=>({id:x,label:x}))}function y({value:b}){r({value:b,key:n.id})}function w(b){b.key!=="Tab"&&b.preventDefault()}return o.jsx("div",{style:{width:"100%"},onKeyDown:w,children:o.jsx(sT,{placeholder:"",clear:!0,...t?.config??{},options:f,value:i,onChange:y,children:b=>h?h(b):b.label})})}function GR({filter:t,column:n,action:r,filterValue:i}){function l({value:u}){r({value:u,key:n.id})}return o.jsx("div",{className:"wx-aaaK5VYO",style:{width:"100%"},children:o.jsx(rT,{placeholder:"",clear:!0,...t?.config??{},value:i,onChange:l})})}function i0(t){const{value:n,options:r=[],placeholder:i="",clear:l=!1,text:u=null,template:f=null,cell:h=null,dropdown:g={},autoOpen:y=!1,onChange:w,onAction:b}=t,[x,M]=qS(n||[]),k=d.useMemo(()=>(x||[]).map(q=>r.find(O=>O.id===q)).filter(Boolean),[x,r]),N=d.useRef(null),E=d.useRef(null),[I,T]=d.useState(null),P=()=>{const q=x||[];if(!q.length)return 0;const O=r.find(W=>q.includes(W.id));return O?r.indexOf(O):0};function U(q){E.current=q.navigate,T(()=>q.keydown),y&&q.navigate(P())}d.useEffect(()=>{y&&(N.current?.focus(),typeof window<"u"&&window.getSelection&&window.getSelection().removeAllRanges())},[]);function F({id:q}){M(q),w&&w({value:q})}function Y(q){q.stopPropagation(),M([]),w&&w({value:[]})}function D(){E.current?.(P())}function K(){E.current?.(null)}function ne(q){I?.(q,P())}return o.jsxs("div",{ref:N,className:"wx-multiselect wx-aadNNOwy",onClick:D,onKeyDown:ne,tabIndex:0,children:[o.jsx("div",{className:"wx-label wx-aadNNOwy",children:f?f(k):h?o.jsx(h,{data:k,onAction:b}):u?o.jsx("span",{className:"wx-text wx-aadNNOwy",children:u}):k.length?o.jsx("span",{className:"wx-text wx-aadNNOwy",children:k.map(q=>q.label).join(", ")}):i?o.jsx("span",{className:"wx-placeholder wx-aadNNOwy",children:i}):" "}),l&&x?.length?o.jsx("i",{className:"wx-icon wxi-close wx-aadNNOwy",onClick:Y}):o.jsx("i",{className:"wx-icon wxi-angle-down wx-aadNNOwy"}),o.jsx(ih,{items:r,onReady:U,onSelect:F,multiselect:!0,checkboxes:!0,value:x||[],onCancel:K,...g,children:({option:q})=>o.jsx("div",{className:"wx-option wx-aadNNOwy",children:f?f(q):h?o.jsx(h,{data:q,onAction:b}):q.label})})]})}function VR({filter:t,column:n,action:r,filterValue:i}){const l=d.useContext(Ua.i18n)?.getGroup("grid")||rm(Wv).getGroup("grid"),u=d.useMemo(()=>({clear:!0,...t?.config||{}}),[t]),f=d.useMemo(()=>u.options||n.options,[u,n]),h=d.useMemo(()=>{const w=i?.length;return w?w<3?i.map(b=>n.optionsMap.get(b)).join(", "):w+" "+l("selected"):""},[i,n,l]);function g({value:w}){r({value:w,key:n.id})}function y(w){w.key!=="Tab"&&w.preventDefault()}return o.jsx("div",{style:{width:"100%"},onKeyDown:y,children:o.jsx(i0,{placeholder:"",...u,options:f,value:i||[],text:h,onChange:g})})}const KR={text:qR,richselect:WR,datepicker:GR,multiselect:VR};function QR({filter:t,column:n}){const r=d.useContext(ks),i=Lt(r,"filterValues");function l(f){r.exec("filter-rows",f)}const u=d.useMemo(()=>KR[t.type],[t.type]);return o.jsx(u,{filter:t,column:n,action:l,filterValue:i[n.id]})}function YR(t){const{cell:n,column:r,row:i,lastRow:l,sortRow:u,columnStyle:f,bodyHeight:h,hasSplit:g}=t,y=d.useContext(ks),w=Lt(y,"sortMarks"),b=d.useMemo(()=>w?w[r.id]:void 0,[w,r.id]),x=d.useRef(),M=d.useCallback($=>{x.current=n.flexgrow?$.parentNode.clientWidth:n.width},[n.flexgrow,n.width]),k=d.useCallback(($,ee)=>{y.exec("resize-column",{id:n.id,width:Math.max(1,(x.current||0)+$),inProgress:ee})},[y,n.id]),N=d.useCallback($=>k($,!0),[k]),E=d.useCallback($=>k($,!1),[k]),I=d.useCallback($=>{if(!r.sort||n.filter)return;let ee=b?.order;ee&&(ee=ee==="asc"?"desc":"asc"),y.exec("sort-rows",{key:n.id,add:$.ctrlKey||$.metaKey,order:ee})},[y,n.id,n.filter,r.sort,b?.order]),T=d.useCallback($=>{$&&$.stopPropagation(),y.exec("collapse-column",{id:n.id,row:i})},[y,n.id,i]),P=d.useCallback($=>{$.key==="Enter"&&T()},[T]),U=d.useCallback($=>{$.key==="Enter"&&!n.filter&&I($)},[I,n.filter]),F=d.useMemo(()=>n.collapsed&&r.collapsed,[n.collapsed,r.collapsed]),Y=d.useMemo(()=>F&&!g&&n.collapsible!=="header",[F,g,n.collapsible]),D=d.useMemo(()=>Y?{top:-h/2,position:"absolute"}:{},[Y,h]),K=d.useMemo(()=>lh(n.width,n.flexgrow,r.fixed,r.left,n.right??r.right,n.height+(F&&Y?h:0)),[n.width,n.flexgrow,r.fixed,r.left,n.right,r.right,n.height,F,Y,h]),ne=d.useMemo(()=>s0(r,n,f),[r,n,f]),q=d.useCallback(()=>Object.fromEntries(Object.entries(n).filter(([$])=>$!=="cell")),[n]),O=`wx-cell ${ne} ${n.css||""} wx-collapsed`,W=["wx-cell",ne,n.css||"",n.filter?"wx-filter":"",r.fixed&&r.fixed.right?"wx-fixed-right":""].filter(Boolean).join(" "),ce=d.useRef(null);return d.useEffect(()=>{const $=ce.current;if(!$)return;const ee=Fw($,{down:M,move:N,up:E});return()=>{typeof ee=="function"&&ee()}},[M,N,E,Fw]),F?o.jsx("div",{className:"wx-RsQD74qC "+O,style:K,role:"button","aria-label":`Expand column ${n.text||""}`,"aria-expanded":!n.collapsed,tabIndex:0,onKeyDown:P,onClick:T,"data-header-id":za(r.id),children:o.jsx("div",{className:"wx-RsQD74qC wx-text",style:D,children:n.text||""})}):o.jsxs("div",{className:"wx-RsQD74qC "+W,style:K,onClick:I,"data-header-id":za(r.id),tabIndex:!n._hidden&&r.sort&&!n.filter?0:void 0,role:"columnheader","aria-colindex":r._colindex,"aria-colspan":n.colspan>1?n.colspan:void 0,"aria-rowspan":n.rowspan>1?n.rowspan:void 0,"aria-sort":!b?.order||n.filter?"none":b?.order==="asc"?"ascending":"descending",onKeyDown:U,children:[n.collapsible?o.jsx("div",{className:"wx-RsQD74qC wx-collapse",role:"button","aria-label":n.collapsed?"Expand column":"Collapse column","aria-expanded":!n.collapsed,tabIndex:0,onKeyDown:P,onClick:T,children:o.jsx("i",{className:`wx-RsQD74qC wxi-angle-${n.collapsed?"down":"right"}`})}):null,n.cell?(()=>{const $=n.cell;return o.jsx($,{api:y,cell:q(),column:r,row:i,onAction:({action:ee,data:B})=>y.exec(ee,B)})})():n.filter?o.jsx(QR,{filter:n.filter,column:r}):o.jsx("div",{className:"wx-RsQD74qC wx-text",children:n.text||""}),r.resize&&l&&!n._hidden?o.jsx("div",{className:"wx-RsQD74qC wx-grip",role:"presentation","aria-label":"Resize column",ref:ce,onClick:$=>$.stopPropagation(),children:o.jsx("div",{})}):null,u?o.jsx("div",{className:"wx-RsQD74qC wx-sort",children:b?o.jsxs(o.Fragment,{children:[typeof b.index<"u"?o.jsx("div",{className:"wx-RsQD74qC wx-order",children:b.index+1}):null,o.jsx("i",{className:`wx-RsQD74qC wxi-arrow-${b.order==="asc"?"up":"down"}`})]}):null}):null]})}function XR({cell:t,column:n,row:r,columnStyle:i}){const l=d.useContext(ks),u=d.useMemo(()=>lh(t?.width,t?.flexgrow,n?.fixed,n?.left,t?.right??n?.right,t?.height),[t?.width,t?.flexgrow,n?.fixed,n?.left,t?.right,n?.right,t?.height]),f=d.useMemo(()=>s0(n,t,i),[n,t,i]),h=d.useCallback(()=>Object.fromEntries(Object.entries(t||{}).filter(([y])=>y!=="cell")),[t]),g=`wx-6Sdi3Dfd wx-cell ${f||""} ${t?.css||""}`+(n?.fixed&&n?.fixed.right?" wx-fixed-right":"");return o.jsx("div",{className:g,style:u,children:!n?.collapsed&&!t?.collapsed?t?.cell?kv.createElement(t.cell,{api:l,cell:h(),column:n,row:r,onAction:({action:y,data:w})=>l.exec(y,w)}):o.jsx("div",{className:"wx-6Sdi3Dfd wx-text",children:t?.text||""}):null})}function Ow({deltaLeft:t,contentWidth:n,columns:r,type:i="header",columnStyle:l,bodyHeight:u}){const f=d.useContext(ks),h=Lt(f,"_sizes"),g=Lt(f,"split"),y=d.useMemo(()=>h?.[`${i}RowHeights`],[h,i]),w=d.useMemo(()=>{let N=[];if(r&&r.length){const E=r[0][i].length;for(let I=0;I<E;I++){let T=0;N.push([]),r.forEach((P,U)=>{const F={...P[i][I]};T||N[I].push(F),F.colspan>1?T=F.colspan-1:T&&T--})}}return N},[r,i]),b=d.useMemo(()=>g?.left||g?.right,[g]);function x(N){return r.find(E=>E.id===N)}function M(N,E){let I=E;return N.rowspan&&(I+=N.rowspan-1),I===w.length-1}function k(N,E,I){if(!I.sort)return!1;for(let T=w.length-1;T>=0;T--){const P=I.header[T];if(!P.filter&&!P._hidden)return E===T}return M(N,E)}return o.jsx("div",{className:`wx-sAsPVaUK wx-${i}`,style:{paddingLeft:`${t}px`,width:`${n}px`},role:"rowgroup",children:w.map((N,E)=>o.jsx("div",{className:i==="header"?"wx-sAsPVaUK wx-h-row":"wx-sAsPVaUK wx-f-row",style:{height:`${y?.[E]}px`,display:"flex"},role:"row",children:N.map(I=>{const T=x(I.id);return i==="header"?o.jsx(YR,{cell:I,columnStyle:l,column:T,row:E,lastRow:M(I,E),bodyHeight:u,sortRow:k(I,E,T),hasSplit:b},I.id):o.jsx(XR,{cell:I,columnStyle:l,column:x(I.id),row:E},I.id)})},E))})}function ZR({overlay:t}){const n=d.useContext(ks);function r(l){return typeof l=="function"}const i=t;return o.jsx("div",{className:"wx-1ty666CQ wx-overlay",children:r(t)?o.jsx(i,{onAction:({action:l,data:u})=>n.exec(l,u)}):t})}function JR(t){const{editor:n,onSave:r,onApply:i}=t,[l,u]=d.useState(n?.value||""),{type:f="text"}=d.useMemo(()=>n?.config||{},[n]),h=d.useRef(null);d.useEffect(()=>{h.current&&h.current.focus()},[]),d.useEffect(()=>{if(!h.current)return;const w=go(h.current,()=>r(!0));return()=>w.destroy()},[r]);function g(){h.current&&(u(h.current.value),i(h.current.value))}function y({key:w}){w==="Enter"&&r()}return o.jsx("input",{className:"wx-e7Ao5ejY wx-text",onInput:g,onKeyDown:y,ref:h,type:f,value:l})}function ej({editor:t,onAction:n,onSave:r,onApply:i,onCancel:l}){const[u,f]=d.useState(t?.value),[h,g]=d.useState(t?.renderedValue),[y,w]=d.useState(t?.options||[]),b=d.useMemo(()=>t?.config?.template,[t]),x=d.useMemo(()=>t?.config?.cell,[t]),M=d.useMemo(()=>t?.config?.dropdown||{},[t]),k=d.useMemo(()=>({trackScroll:!0,...M}),[M]),N=d.useMemo(()=>(y||[]).findIndex(D=>D.id===u),[y,u]),E=d.useRef(null),I=d.useRef(null),T=d.useCallback(D=>{E.current=D.navigate,I.current=D.keydown,E.current(N)},[N,E]),P=d.useCallback(D=>{const K=D?.target?.value??"";g(K);const ne=K?(t?.options||[]).filter(q=>(q.label||"").toLowerCase().includes(K.toLowerCase())):t?.options||[];w(ne),ne.length?E.current(-1/0):E.current(null)},[t]),U=d.useRef(null);d.useEffect(()=>{U.current&&U.current.focus()},[]);const F=d.useRef(r);d.useEffect(()=>{F.current=r},[r]),d.useEffect(()=>{if(!U.current)return;const D=go(U.current,()=>F.current(!0));return()=>D.destroy()},[]),d.useEffect(()=>{f(t?.value),g(t?.renderedValue),w(t?.options||[])},[t]);const Y=d.useCallback(({id:D})=>{i(D),r()},[i,r]);return o.jsxs(o.Fragment,{children:[o.jsx("input",{className:"wx-0UYfSd1x wx-input",ref:U,value:h??"",onChange:P,onKeyDown:D=>I.current?I.current(D,N):void 0}),o.jsx(ih,{items:y,onReady:T,onSelect:Y,...k,onCancel:l,children:({option:D})=>b?b(D):x?o.jsx(x,{data:D,onAction:n}):D.label})]})}function tj({editor:t,onAction:n,onSave:r,onApply:i,onCancel:l}){const[u]=d.useState(()=>t.value||new Date),{template:f,cell:h,dropdown:g={}}=t?.config||{},y=d.useMemo(()=>({trackScroll:!0,width:"auto",...g}),[g]);function w({value:k}){i(k),r()}const b=d.useRef(null),[x,M]=d.useState(null);return d.useEffect(()=>{b.current&&b.current.focus(),typeof window<"u"&&window.getSelection&&window.getSelection().removeAllRanges()},[]),d.useEffect(()=>{if(!x)return;const k=go(x,()=>r(!0));return()=>k.destroy()},[x,r]),o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"wx-lNWNYUb6 wx-value",ref:b,tabIndex:0,onClick:l,onKeyDown:k=>k.preventDefault(),children:f?f(u):h?o.jsx(h,{data:t.value,onAction:n}):o.jsx("span",{className:"wx-lNWNYUb6 wx-text",children:t.renderedValue})}),o.jsx(zv,{...y,onCancel:l,children:o.jsx("div",{ref:M,className:"wx-lNWNYUb6",children:o.jsx(HS,{value:u,onChange:w,buttons:t.config?.buttons})})})]})}function nj(t){const{editor:n}=t,r=t.onAction??t.onaction,i=t.onSave??t.onsave,l=t.onApply??t.onapply,u=t.onCancel??t.oncancel,f=n.config||{},{dropdown:h={}}=f,g=d.useMemo(()=>({trackScroll:!0,...h}),[h]),[y]=d.useState(n.options.find(P=>P.id===n.value)),[w]=d.useState(n.value),[b]=d.useState(n.options),x=d.useMemo(()=>b.findIndex(P=>P.id===w),[b,w]);function M({id:P}){l(P),i()}let k;const[N,E]=d.useState();function I(P){k=P.navigate,E(()=>P.keydown),k(x)}const T=d.useRef(null);return d.useEffect(()=>{T.current&&T.current.focus(),typeof window<"u"&&window.getSelection&&window.getSelection().removeAllRanges()},[]),d.useEffect(()=>{if(!T.current)return;const P=go(T.current,()=>i(!0));return()=>P.destroy()},[i]),o.jsxs(o.Fragment,{children:[o.jsx("div",{ref:T,className:"wx-ywGRk611 wx-value",tabIndex:0,onClick:u,onKeyDown:P=>{N(P,x),P.preventDefault()},children:f.template?f.template(y):f.cell?(()=>{const P=f.cell;return o.jsx(P,{data:y,onAction:r})})():o.jsx("span",{className:"wx-ywGRk611 wx-text",children:n.renderedValue})}),o.jsx(ih,{items:b,onReady:I,onSelect:M,...g,onCancel:u,children:({option:P})=>f.template?f.template(P):f.cell?(()=>{const U=f.cell;return o.jsx(U,{data:P,onAction:r})})():P.label})]})}function aj(t){const{editor:n,onAction:r,onSave:i,onApply:l}=t,u=n?.config||{},f=n?.options??[],h=n?.value||[],g=n?.renderedValue,y=d.useMemo(()=>({trackScroll:!0,...u.dropdown||{}}),[u]);function w({value:x}){l(x)}const b=d.useRef(null);return d.useEffect(()=>{if(!b.current)return;const x=go(b.current,()=>i(!0));return()=>x.destroy()},[i]),o.jsx("div",{ref:b,className:"wx-value wx-aacZ4gNU",onClick:()=>i(!0),children:o.jsx(i0,{value:h,options:f,text:g,template:u.template,cell:u.cell,clear:u.clear,dropdown:y,autoOpen:!0,onChange:w,onAction:r})})}const rj={text:JR,combo:ej,datepicker:tj,richselect:nj,multiselect:aj};function sj({column:t,row:n}){const r=d.useContext(ks),i=Lt(r,"editor"),l=d.useCallback((k,N)=>{r.exec("close-editor",{ignore:k}),N&&r.exec("focus-cell",{...N,eventSource:"click"})},[r]),u=d.useCallback(k=>{const N=k?null:{row:i?.id,column:i?.column};l(!1,N)},[i,l]),f=d.useCallback(()=>{l(!0,{row:i?.id,column:i?.column})},[i,l]),h=d.useCallback(k=>{r.exec("editor",{value:k})},[r]),g=d.useCallback(k=>{k.key==="Enter"&&i&&(t.editor.type==="multiselect"?h(i.value):f())},[i,t.editor,f,h]),y=d.useMemo(()=>lh(t.width,t.flexgrow,t.fixed,t.left,t.right),[t.width,t.flexgrow,t.fixed,t.left,t.right]),w=d.useMemo(()=>{let k=t.editor;if(typeof k=="function"&&(k=k(n,t)),!k)return null;let N=typeof k=="string"?k:k.type;return rj[N]},[t,n]),b=d.useRef(null);d.useEffect(()=>{b.current&&typeof y=="string"&&b.current.setAttribute("style",y)},[y]);const x=typeof n.$parent<"u"?"gridcell":"cell",M=typeof n.$parent<"u"?!t.editor:void 0;return o.jsx("div",{className:"wx-8l724t2g wx-cell wx-editor",ref:b,style:typeof y=="object"&&y!==null?y:void 0,role:x,"aria-readonly":M,tabIndex:-1,onClick:k=>k.stopPropagation(),onDoubleClick:k=>k.stopPropagation(),onKeyDown:g,children:w?o.jsx(w,{editor:i,onSave:u,onApply:h,onCancel:f,onAction:({action:k,data:N})=>r.exec(k,N)}):null})}function Hw(t){const{columns:n,type:r,columnStyle:i}=t,l=d.useContext(ks),{filterValues:u,_columns:f,_sizes:h}=l.getState();function g(y){return i?" "+i(y):""}return o.jsx(o.Fragment,{children:n.map((y,w)=>o.jsx("tr",{children:y.map(b=>{const x=f.find(N=>N.id===b.id),M=`wx-print-cell-${r}${g(x)}${b.filter?" wx-print-cell-filter":""}${b.vertical?" wx-vertical":""}`,k=b.cell;return o.jsx("th",{style:WS(e0(b,h.columnWidth)),className:"wx-Gy81xq2u "+M,rowSpan:b.rowspan,colSpan:b.colspan,children:k?o.jsx(k,{api:l,cell:Object.fromEntries(Object.entries(b).filter(([N])=>N!=="cell")),column:x,row:w}):b.filter?o.jsx("div",{className:"wx-Gy81xq2u wx-print-filter",children:cR(u,f,b)}):o.jsx("div",{className:"wx-Gy81xq2u wx-text",children:b.text??""})},b.id)})},w))})}function ij(t){const{columns:n,rowStyle:r,columnStyle:i,cellStyle:l,header:u,footer:f,reorder:h}=t,g=d.useContext(ks),{flatData:y,_sizes:w}=g.getState(),b=u&&Dw(n,"header",w.headerRowHeights),x=f&&Dw(n,"footer",w.footerRowHeights);function M(N,E){let I="";return I+=i?" "+i(E):"",I+=l?" "+l(N,E):"",I}function k(N,E){return typeof E.draggable=="function"?E.draggable(N,E)!==!1:E.draggable}return o.jsxs("table",{className:`wx-8NTMLH0z wx-print-grid ${n.some(N=>N.flexgrow)?"wx-flex-columns":""}`,children:[u?o.jsx("thead",{children:o.jsx(Hw,{columns:b,type:"header",columnStyle:i})}):null,o.jsx("tbody",{children:y.map((N,E)=>o.jsx("tr",{className:"wx-8NTMLH0z wx-row"+(r?" "+r(N):""),style:{height:`${N.rowHeight||w.rowHeight}px`},children:n.map(I=>I.collapsed?null:o.jsxs("td",{className:`wx-8NTMLH0z wx-print-cell wx-cell ${M(N,I)}`,style:WS(e0(I,w.columnWidth)),children:[h&&I.draggable?o.jsx("span",{className:"wx-8NTMLH0z wx-print-draggable",children:k(N,I)?o.jsx("i",{className:"wx-8NTMLH0z wxi-drag"}):null}):null,I.treetoggle?o.jsxs(o.Fragment,{children:[o.jsx("span",{style:{marginLeft:N.$level*28+"px"}}),N.$count?o.jsx("i",{className:`wx-8NTMLH0z wx-print-grid-tree-toggle wxi-menu-${N.open!==!1?"down":"right"}`}):null]}):null,I.cell?(()=>{const T=I.cell;return o.jsx(T,{api:g,row:N,column:I})})():o.jsx("span",{children:ac(N,I)})]},I.id))},E))}),f?o.jsx("tfoot",{children:o.jsx(Hw,{columns:x,type:"footer",columnStyle:i})}):null]})}function oj(t){const{config:n,...r}=t,i=d.useContext(ks),{_skin:l,_columns:u}=i.getState(),f=d.useMemo(()=>sR(u,n),[]),h=d.useRef(null);return d.useEffect(()=>{const g=document.body;g.classList.add("wx-print");const y=h.current;if(!y)return;const w=y.cloneNode(!0);g.appendChild(w);const b=`@media print { @page { size: ${n.paper} ${n.mode}; }`,x=document.createElement("style");x.setAttribute("type","text/css"),x.setAttribute("media","print"),document.getElementsByTagName("head")[0].appendChild(x),x.appendChild(document.createTextNode(b)),window.print(),x.remove(),g.classList.remove("wx-print"),w.remove()},[]),o.jsx("div",{className:`wx-4zwCKA7C wx-${l}-theme wx-print-container`,ref:h,children:f.map((g,y)=>o.jsx("div",{className:"wx-4zwCKA7C wx-print-grid-wrapper",children:o.jsx(ij,{columns:g,...r})},y))})}function lj(t){const{header:n,footer:r,overlay:i,multiselect:l,onreorder:u,rowStyle:f,columnStyle:h,cellStyle:g,autoRowHeight:y,resize:w,clientWidth:b,clientHeight:x,responsiveLevel:M,hotkeys:k}=t,N=d.useContext(ks),E=Lt(N,"dynamic"),I=Lt(N,"_columns"),T=Lt(N,"flatData"),P=Lt(N,"split"),U=Lt(N,"_sizes"),[F,Y]=Vs(N,"selectedRows"),D=Lt(N,"select"),K=Lt(N,"editor"),ne=Lt(N,"scrollLeft"),q=Lt(N,"scrollTop"),O=Lt(N,"tree"),W=Lt(N,"focusCell"),ce=Lt(N,"_print"),$=Lt(N,"undo"),ee=Lt(N,"reorder"),B=Lt(N,"_rowHeightFromData"),[L,oe]=d.useState(0);d.useEffect(()=>{oe(Pn())},[]);const[be,H]=d.useState(0),me=d.useMemo(()=>(I||[]).some(fe=>!fe.hidden&&fe.flexgrow),[I]),ue=d.useMemo(()=>U?.rowHeight||0,[U]),Ce=d.useRef(null),[Me,Ne]=d.useState(null),[He,Ve]=d.useState(null),ie=d.useMemo(()=>{let fe=[],_e=0;return P&&P.left&&(fe=(I||[]).slice(0,P.left).filter(et=>!et.hidden).map(et=>({...et})),fe.forEach(et=>{et.fixed={left:1,leftSize:P.left},et.left=_e,_e+=et.width}),fe.length&&(fe[fe.length-1].fixed.left=-1)),{columns:fe,width:_e}},[P,I]),Oe=d.useMemo(()=>{let fe=[],_e=0;if(P&&P.right){fe=(I||[]).slice(P.right*-1).filter(et=>!et.hidden).map(et=>({...et}));for(let et=fe.length-1;et>=0;et--){const Rt=fe[et];Rt.fixed={right:1},Rt.right=_e,_e+=Rt.width}fe.length&&(fe[0].fixed={right:-1})}return{columns:fe,width:_e}},[P,I]),$e=d.useMemo(()=>{const fe=(I||[]).slice(P?.left||0,(I||[]).length-(P?.right??0)).filter(_e=>!_e.hidden);return fe.forEach(_e=>{_e.fixed=0}),fe},[I,P]),qe=d.useMemo(()=>(I||[]).reduce((fe,_e)=>(_e.hidden||(fe+=_e.width),fe),0),[I]),vt=1;function xe(fe,_e,et){let Rt=_e,An=fe;if($e.length){let Et=$e.length;for(let ct=fe;ct>=0;ct--)$e[ct][et].forEach(jt=>{jt.colspan>1&&ct>fe-jt.colspan&&ct<Et&&(Et=ct)});if(Et!==$e.length&&Et<fe){for(let ct=Et;ct<fe;ct++)Rt-=$e[ct].width;An=Et}}return{index:An,delta:Rt}}const he=d.useMemo(()=>{let fe,_e,et;const Rt=ne||0,An=(ne||0)+(b||0);let Et=0,ct=0,jt=0,mt=0;$e.forEach((Nn,Un)=>{Rt>jt&&(Et=Un,mt=jt),jt=jt+Nn.width,An>jt&&(ct=Un+vt)});const Yt={header:0,footer:0};for(let Nn=ct;Nn>=Et;Nn--)["header","footer"].forEach(Un=>{$e[Nn]&&$e[Nn][Un].forEach(Ni=>{const Ja=Ni.colspan;if(Ja&&Ja>1){const Er=Ja-(ct-Nn+1);Er>0&&(Yt[Un]=Math.max(Yt[Un],Er))}})});const fn=xe(Et,mt,"header"),Xt=xe(Et,mt,"footer"),Rn=fn.delta,Wt=fn.index,jr=Xt.delta,Ks=Xt.index;return me&&qe>(b||0)?fe=_e=et=[...ie.columns,...$e,...Oe.columns]:(fe=[...ie.columns,...$e.slice(Et,ct+1),...Oe.columns],_e=[...ie.columns,...$e.slice(Wt,ct+Yt.header+1),...Oe.columns],et=[...ie.columns,...$e.slice(Ks,ct+Yt.footer+1),...Oe.columns]),{data:fe||[],header:_e||[],footer:et||[],d:mt,df:jr,dh:Rn}},[$e,ie,Oe,ne,b,me,qe]),pe=d.useMemo(()=>n&&U?.headerHeight||0,[n,U]),Ae=d.useMemo(()=>r&&U?.footerHeight||0,[r,U]),Se=d.useMemo(()=>b&&x?qe>=b:!1,[b,x,qe]),[Pe,Qe]=d.useState(!1),Z=d.useMemo(()=>(x||0)-pe-Ae-(Se?L:0),[x,pe,Ae,Se,L]),$t=d.useMemo(()=>Math.ceil((Z||0)/(ue||1))+1,[Z,ue]),Ee=d.useRef([]),[Ge,ze]=d.useState(0),[Ft,Ze]=d.useState(void 0),nt=d.useMemo(()=>{let fe=0,_e=0;const et=2,Rt=q||0;if(y){let ct=Rt;for(;ct>0;)ct-=Ee.current[fe]||ue,fe++;_e=Rt-ct;for(let jt=Math.max(0,fe-et-1);jt<fe;jt++)_e-=Ee.current[fe-jt]||ue;fe=Math.max(0,fe-et)}else{if(B){let ct=0,jt=0;for(let Xt=0;Xt<(T||[]).length;Xt++){const Rn=T[Xt].rowHeight||ue;if(jt+Rn>Rt){ct=Xt;break}jt+=Rn}fe=Math.max(0,ct-et);for(let Xt=0;Xt<fe;Xt++)_e+=T[Xt].rowHeight||ue;let mt=0,Yt=0;for(let Xt=ct+1;Xt<(T||[]).length;Xt++){const Rn=T[Xt].rowHeight||ue;if(mt++,Yt+Rn>Z)break;Yt+=Rn}const fn=Math.min(E?E.rowCount:(T||[]).length,ct+mt+et);return{d:_e,start:fe,end:fn}}fe=Math.floor(Rt/(ue||1)),fe=Math.max(0,fe-et),_e=fe*(ue||0)}const An=E?E.rowCount:(T||[]).length,Et=Math.min(An,fe+($t||0)+et);return{d:_e,start:fe,end:Et}},[y,B,q,ue,E,T,$t,Z]),lt=d.useMemo(()=>{const fe=E?E.rowCount:(T||[]).length;if(y)return Ge+nt.d+(fe-(Ft||0))*(ue||0);if(!B)return fe*(ue||0);let _e=0;for(let et=0;et<fe;et++)_e+=T[et]?.rowHeight||ue;return _e},[E,T,ue,y,B,Ge,nt.d,Ft]),Tt=d.useRef({});Tt.current={clientWidth:b,clientHeight:x,fullHeight:lt,headerHeight:pe,footerHeight:Ae,fullWidth:qe,SCROLLSIZE:L};const Mt=d.useCallback(()=>{const fe=Tt.current;Qe(fe.clientWidth&&fe.clientHeight?fe.fullHeight+fe.headerHeight+fe.footerHeight>=fe.clientHeight-(fe.fullWidth>=fe.clientWidth?fe.SCROLLSIZE:0):!1)},[]);d.useEffect(()=>{const fe=requestAnimationFrame(Mt);return()=>window.cancelAnimationFrame(fe)},[be,Mt]),d.useEffect(()=>{Mt()},[x,Mt]);const rt=d.useMemo(()=>me&&qe<=(b||0)?(b||0)-0-(Pe?L:0):qe,[me,qe,b,Pe,L,Se]),dt=d.useMemo(()=>me&&qe<=(b||0)?b||0:rt<(b||0)?qe+(Pe?L:0):-1,[me,qe,b,rt,Pe,L]),G=d.useRef({});d.useEffect(()=>{if(E&&(G.current.start!==nt.start||G.current.end!==nt.end)){const{start:fe,end:_e}=nt;G.current={start:fe,end:_e},N&&N.exec&&N.exec("request-data",{row:{start:fe,end:_e}})}},[E,nt,N]);const ge=d.useMemo(()=>E?T||[]:(T||[]).slice(nt.start,nt.end),[E,T,nt]),De=d.useMemo(()=>(F||[]).filter(fe=>(ge||[]).some(_e=>_e.id===fe)),[Y,ge]),z=d.useMemo(()=>nt.start,[nt.start]),ae=d.useRef({top:q,left:ne});ae.current={top:q,left:ne};const Te=d.useCallback(fe=>{const _e=fe.target.scrollTop,et=fe.target.scrollLeft,Rt=ae.current;(_e!==Rt.top||et!==Rt.left)&&N.exec("scroll-to",{top:_e,left:et})},[N]),Ue=d.useCallback(fe=>{fe.shiftKey&&fe.preventDefault(),Ce.current&&Ce.current.focus&&Ce.current.focus()},[]),Xe=d.useCallback(()=>!!(I||[]).find(fe=>!!fe.draggable),[I]),at=d.useRef(null),kt=d.useRef(null),At=d.useRef({dblclick:(fe,_e)=>{const et={id:fe,column:em(_e,"data-col-id")};N.exec("open-editor",et)},click:(fe,_e)=>{if(_e.target.closest("input")||at.current)return;const et=em(_e,"data-col-id");if(W?.id!==fe&&N.exec("focus-cell",{row:fe,column:et,eventSource:"click"}),D===!1)return;const Rt=l&&(_e.ctrlKey||_e.metaKey),An=l&&_e.shiftKey;(Rt||F.length>1||!F.includes(fe))&&N.exec("select-row",{id:fe,toggle:Rt,range:An})},"toggle-row":fe=>{const _e=N.getRow(fe);N.exec(_e.open!==!1?"close-row":"open-row",{id:fe})},"ignore-click":()=>!1}),Ut=d.useMemo(()=>({top:pe,bottom:Ae,left:ie.width,xScroll:Se,yScroll:Pe,sense:y&&He?He.offsetHeight:Math.max(U?.rowHeight||0,40),node:Ce.current&&Ce.current.firstElementChild}),[pe,Ae,ie.width,Se,Pe,y,He,U]);function Qt(fe,_e){const{container:et,sourceNode:Rt,from:An}=_e;if(Xe()&&!Rt.getAttribute("draggable-data"))return!1;Ne(An),O&&N.getRow(An).open&&N.exec("close-row",{id:An,nested:!0});const Et=Sd(Rt),ct=Et.cloneNode(!0);ct.classList.remove("wx-selected"),ct.querySelectorAll("[tabindex]").forEach(fn=>fn.setAttribute("tabindex","-1")),et.appendChild(ct),Ve(ct);const jt=(ne||0)-he.d,mt=Pe?L:0;et.style.width=Math.min((b||0)-mt,me&&qe<=(b||0)?rt:rt-mt)+jt+"px";const Yt=Ip(Et);_e.offset={x:jt,y:-Math.round(Yt.height/2)},kt.current||(kt.current=fe.clientY)}function sa(fe,_e){const{from:et}=_e,Rt=_e.pos,An=Ip(Ce.current);Rt.x=An.x;const Et=Ut.top;if(Rt.y<Et)Rt.y=Et;else{const ct=An.height-(Se&&L>0?L:Math.round(Ut.sense/2))-Ut.bottom;Rt.y>ct&&(Rt.y=ct)}if(Ce.current.contains(_e.targetNode)){const ct=Sd(_e.targetNode),jt=ct&&rh(ct);if(jt&&jt!==et){_e.to=jt;const mt=y?He?.offsetHeight:U?.rowHeight;if(He&&((q||0)===0||Rt.y>Et+mt-1)){const Yt=ct.getBoundingClientRect(),fn=Ip(He).y,Xt=Yt.y,Rn=fn>Xt?-1:1,Wt=Rn===1?"after":"before",jr=N.getState().flatData,Ks=Math.abs(jr.findIndex(Un=>Un.id===et)-jr.findIndex(Un=>Un.id===jt)),Nn=Ks!==1?Wt==="before"?"after":"before":Wt;if(Ks===1&&(Rn===-1&&fe.clientY>kt.current||Rn===1&&fe.clientY<kt.current))return;kt.current=fe.clientY,N.exec("move-item",{id:et,target:jt,mode:Nn,inProgress:!0})}}u&&u({event:fe,context:_e})}OR(fe,An,_e,Ut)}function Ra(fe,_e){const{from:et,to:Rt}=_e;N.exec("move-item",{id:et,target:Rt,inProgress:!1}),at.current=setTimeout(()=>{at.current=0},1),Ne(null),Ve(null),kt.current=null,a0(_e)}function Pn(){const fe=document.createElement("div");fe.style.cssText="position:absolute;left:-1000px;width:100px;padding:0px;margin:0px;min-height:100px;overflow-y:scroll;",document.body.appendChild(fe);const _e=fe.offsetWidth-fe.clientWidth;return document.body.removeChild(fe),_e}const $n=d.useMemo(()=>dt>0?{width:`${dt}px`}:void 0,[dt]),ia=d.useRef(null);function Fe(){Promise.resolve().then(()=>{let fe=0,_e=z;const et=ia.current;et&&(Array.from(et.children).forEach((Rt,An)=>{Ee.current[z+An]=Rt.offsetHeight,fe+=Rt.offsetHeight,_e++}),ze(fe),Ze(_e))})}d.useEffect(()=>{ge&&y&&Fe()},[ge,y,z]);let[V,Je]=d.useState();d.useEffect(()=>{if(W&&(!D||!De.length||De.includes(W.row)))Je({...W});else if(ge.length&&he.data.length){if(!V||De.length&&!De.includes(V.row)||ge.findIndex(fe=>fe.id===V.row)===-1||he.data.findIndex(fe=>fe.id===V.column&&!fe.collapsed)===-1){const fe=De[0]||ge[0].id,_e=he.data.findIndex(et=>!et.collapsed);Je(_e!==-1?{row:fe,column:he.data[_e].id}:null)}}else Je(null)},[W]);const gt=d.useRef(null);d.useEffect(()=>{const fe=Ce.current;if(!fe)return;const _e=IR(fe,w);return()=>{typeof _e=="function"&&_e()}},[w]);const nn=d.useRef({});Object.assign(nn.current,{start:Qt,move:sa,end:Ra,getReorder:()=>ee,getDraggableInfo:()=>({hasDraggable:Xe()})}),d.useEffect(()=>{const fe=Ce.current;return fe?_R(fe,nn).destroy:void 0},[ee,Ce.current]),d.useEffect(()=>{const fe=Ce.current;return fe?ER(fe,{keys:k!==!1&&{...jR,"ctrl+z":$,"ctrl+y":$,...k},exec:_e=>N.exec("hotkey",_e)}).destroy:void 0},[N,$,k]);const Sn=d.useRef({scroll:N.getReactiveState().scroll,scrollLeft:N.getReactiveState().scrollLeft,scrollTop:N.getReactiveState().scrollTop});Sn.current.getWidth=()=>(b||0)-(Pe?L:0),Sn.current.getHeight=()=>Z,Sn.current.getScrollMargin=()=>ie.width+Oe.width,d.useEffect(()=>{DR(gt.current,Sn.current)},[]);const Ms=d.useRef(null);d.useEffect(()=>{const fe=Ms.current;if(!fe)return;const _e=[];_e.push(go(fe,()=>W&&N.exec("focus-cell",{eventSource:"click"})).destroy),_e.push(_T(fe,At.current)),H(fe.clientHeight);const et=new ResizeObserver(()=>{H(fe.clientHeight)});return et.observe(fe),_e.push(()=>et.disconnect()),()=>_e.forEach(Rt=>Rt())},[]);const qa=`wx-grid ${M?`wx-responsive-${M}`:""}`;return d.useEffect(()=>{W&&(ge.some(fe=>fe.id===W.row)&&he.data.some(fe=>fe.id===W.column&&!fe.collapsed)||N.exec("focus-cell",{eventSource:"destroy"}))},[W,ge,he.data,N]),o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"wx-4VuBwK2D "+qa,style:{"--header-height":`${pe}px`,"--footer-height":`${Ae}px`,"--split-left-width":`${ie.width}px`,"--split-right-width":`${Oe.width}px`},children:o.jsx("div",{ref:Ce,className:"wx-4VuBwK2D wx-table-box",style:$n,role:O?"treegrid":"grid","aria-colcount":he.data.length,"aria-rowcount":ge.length,"aria-multiselectable":O&&l?!0:void 0,tabIndex:-1,children:o.jsxs("div",{ref:gt,className:"wx-4VuBwK2D wx-scroll",style:{overflowX:Se?"scroll":"hidden",overflowY:Pe?"scroll":"hidden"},onScroll:Te,children:[n?o.jsx("div",{className:"wx-4VuBwK2D wx-header-wrapper",children:o.jsx(Ow,{contentWidth:rt,deltaLeft:he.dh,columns:he.header,columnStyle:h,bodyHeight:Z-+r})}):null,o.jsxs("div",{ref:Ms,className:"wx-4VuBwK2D wx-body",style:{width:`${rt}px`,height:`${lt}px`},onMouseDown:fe=>Ue(fe),children:[i?o.jsx(ZR,{overlay:i}):null,o.jsx("div",{ref:ia,className:"wx-4VuBwK2D wx-data",style:{paddingTop:`${nt.d}px`,paddingLeft:`${he.d}px`},children:ge.map((fe,_e)=>{const et=F.indexOf(fe.id)!==-1,Rt=Me===fe.id,An="wx-row"+(y?" wx-autoheight":"")+(f?" "+f(fe):"")+(et?" wx-selected":"")+(Rt?" wx-inactive":""),Et=y?{minHeight:`${fe.rowHeight||ue}px`}:{height:`${fe.rowHeight||ue}px`};return o.jsx("div",{className:"wx-4VuBwK2D "+An,"data-id":za(fe.id),"data-context-id":za(fe.id),style:Et,role:"row","aria-rowindex":_e,"aria-expanded":fe.open,"aria-level":O?fe.$level+1:void 0,"aria-selected":O?et:void 0,tabIndex:-1,children:he.data.map(ct=>ct.collapsed?o.jsx("div",{className:"wx-4VuBwK2D wx-cell wx-collapsed"},ct.id):K?.id===fe.id&&K.column===ct.id?o.jsx(sj,{row:fe,column:ct},ct.id):o.jsx(UR,{row:fe,column:ct,columnStyle:h,cellStyle:g,reorder:ee,focusable:V?.row===fe.id&&V?.column===ct.id},ct.id))},fe.id)})})]}),r&&(T||[]).length?o.jsx(Ow,{type:"footer",contentWidth:rt,deltaLeft:he.df,columns:he.footer,columnStyle:h}):null]})})}),ce?o.jsx(oj,{config:ce,rowStyle:f,columnStyle:h,cellStyle:g,header:n,footer:r,reorder:ee}):null]})}const cj=t=>t.split("-").map(n=>n?n.charAt(0).toUpperCase()+n.slice(1):"").join(""),uj=d.forwardRef(function({data:t=[],columns:n=[],rowStyle:r=null,columnStyle:i=null,cellStyle:l=null,selectedRows:u,select:f=!0,multiselect:h=!1,header:g=!0,footer:y=!1,dynamic:w=null,overlay:b=null,reorder:x=!1,onReorder:M=null,autoRowHeight:k=!1,sizes:N,split:E,tree:I=!1,autoConfig:T=!1,init:P=null,responsive:U=null,sortMarks:F,undo:Y=!1,hotkeys:D=null,filterValues:K,...ne},q){const O=d.useRef();O.current=ne;const W=d.useMemo(()=>new kR(GS),[]),ce=d.useMemo(()=>W.in,[W]),$=d.useRef(null);$.current===null&&($.current=new BS((Oe,$e)=>{const qe="on"+cj(Oe);O.current&&O.current[qe]&&O.current[qe]($e)}),ce.setNext($.current));const ee=d.useMemo(()=>({getState:W.getState.bind(W),getReactiveState:W.getReactive.bind(W),getStores:()=>({data:W}),exec:ce.exec,setNext:Oe=>($.current=$.current.setNext(Oe),$.current),intercept:ce.intercept.bind(ce),on:ce.on.bind(ce),detach:ce.detach.bind(ce),getRow:W.getRow.bind(W),getColumn:W.getColumn.bind(W)}),[W,ce]),[B,L]=d.useState(0),[oe,be]=d.useState(0),[H,me]=d.useState(null),[ue,Ce]=d.useState(null),Me=d.useMemo(()=>{if(T&&!n.length&&t.length){const Oe=t[0],$e=[];for(let qe in Oe)if(qe!=="id"&&qe[0]!=="$"){let vt={id:qe,header:qe[0].toUpperCase()+qe.slice(1)};typeof T=="object"&&(vt={...vt,...T}),$e.push(vt)}return $e}return(ue&&ue.columns)??n},[T,n,t,ue]),Ne=d.useMemo(()=>(ue&&ue.sizes)??N,[ue,N]),He=d.useCallback(Oe=>{if(L(Oe.width),be(Oe.height),U){const $e=Object.keys(U).map(Number).sort((qe,vt)=>qe-vt).find(qe=>Oe.width<=qe)??null;$e!==H&&(Ce(U[$e]),me($e))}},[U,H]),Ve=d.useContext(Ua.theme),ie=d.useRef(0);return d.useEffect(()=>{if(!ie.current)P&&P(ee);else{const Oe=W.getState();W.init({data:t,columns:Me,split:E||Oe.split,sizes:Ne||Oe.sizes,selectedRows:u||Oe.selectedRows,dynamic:w,tree:I,sortMarks:F||Oe.sortMarks,filterValues:K||Oe.filterValues,undo:Y,reorder:x,_skin:Ve,_select:f})}ie.current++},[W,t,Me,E,Ne,u,w,I,F,K,Y,x,Ve,f,P,ee]),ie.current===0&&W.init({data:t,columns:Me,split:E||{left:0},sizes:Ne||{},selectedRows:u||[],dynamic:w,tree:I,sortMarks:F||{},filterValues:K||{},undo:Y,reorder:x,_skin:Ve,select:f}),d.useImperativeHandle(q,()=>({...ee}),[ee]),o.jsx(ks.Provider,{value:ee,children:o.jsx(qv,{words:Wv,optional:!0,children:o.jsx(lj,{header:g,footer:y,overlay:b,rowStyle:r,columnStyle:i,cellStyle:l,onReorder:M,multiselect:h,autoRowHeight:k,clientWidth:B,clientHeight:oe,responsiveLevel:H,resize:He,hotkeys:D})})})});Fv(Yr);const $a=d.createContext(null),Kv=d.createContext(null),Qv=d.createContext(null);function dj({children:t}){const n=d.useContext(Ua.i18n),r=d.useMemo(()=>n.getGroup("filemanager"),[n]),i=d.useContext($a),[l]=Vs(i,"panels"),u=Lt(i,"activePanel"),f=l[u].path,[h,g]=d.useState(null),[y,w]=d.useState(null),[b,x]=d.useState(""),[M,k]=d.useState(""),[N,E]=d.useState(!1);function I(){const F=b.trim();if(!F){E(!0);return}h.add?i.exec("create-file",{file:{...h.item,name:F},parent:f}):M!==F&&i.exec("rename-file",{id:h.item.id,name:F}),T()}function T(){g(null),E(null),k(""),x("")}function P(){i.exec("delete-files",{ids:y.selected}),w(null)}const U=d.useMemo(()=>({showPrompt(F){const Y=F.item.name||(F.item.type==="folder"?r("New folder"):`${r("New file")}.txt`);k(Y),x(Y),g({...F})},showConfirm(F){w({...F})}}),[r]);return o.jsxs(Kv.Provider,{value:U,children:[o.jsx(dT,{children:t}),h?o.jsx(pv,{title:r(`Enter ${h.item.type} name`),onConfirm:I,onCancel:T,children:o.jsx($v,{error:N,select:!0,focus:!0,value:b,onChange:({value:F})=>x(F)})}):null,y?o.jsx(pv,{title:r("Are you sure you want to delete these items:"),onConfirm:P,onCancel:()=>w(null),children:y.selected?o.jsx("ul",{className:"wx-gq7BMzEP wx-list",children:y.selected.map((F,Y)=>o.jsx("li",{children:F},Y))}):null}):null]})}let Bw={"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 fj(t){const n=t.lastIndexOf("."),r=n>0&&n<t.length-1?Math.min(10,t.length-n):Math.min(5,t.length),i=t.slice(0,-r),l=t.slice(-r);return[i,l]}function mj({item:t}){const n=d.useContext($a),r=d.useContext(Ua.i18n).getGroup("filemanager"),i=d.useContext($a).templates,[l]=Vs(n,"panels"),u=Lt(n,"activePanel"),f=Lt(n,"mode"),h=l[u].selected,g=d.useMemo(()=>i.preview(t,214,163),[i,t]),y=d.useMemo(()=>i.icon(t,"big"),[i,t]),[w,b]=d.useMemo(()=>fj(t.name),[t.name]);return o.jsx(o.Fragment,{children:t.id==="/wx-filemanager-parent-link"?f!=="search"?o.jsx("div",{className:"wx-GAOa4kDV wx-back-item",children:o.jsxs("div",{className:`wx-GAOa4kDV wx-back ${t.navigation?"wx-selected":""}`,"data-id":za("/wx-filemanager-parent-link"),children:[o.jsx("i",{className:"wx-GAOa4kDV wxi-arrow-left"}),o.jsx("span",{children:r("Back to parent folder")})]})}):null:o.jsxs("div",{className:`wx-GAOa4kDV wx-item ${h?.length&&h.indexOf(t.id)>=0?"wx-selected":""}`,"data-id":za(t.id),children:[g?o.jsx("div",{className:"wx-GAOa4kDV wx-preview wx-file-preview",children:o.jsx("img",{className:"wx-GAOa4kDV wx-card-preview",alt:r("A miniature file preview"),src:g})}):y?o.jsx("div",{className:"wx-GAOa4kDV wx-preview wx-file-icon",children:o.jsx("img",{className:"wx-GAOa4kDV wx-card-preview",alt:"",src:y})}):o.jsx("div",{className:"wx-GAOa4kDV wx-preview",children:o.jsx("i",{className:`wx-GAOa4kDV wxi-${t.type}`})}),t.type==="folder"?o.jsxs("div",{className:"wx-GAOa4kDV wx-info",children:[o.jsxs("div",{className:"wx-GAOa4kDV wx-folder-name",children:[o.jsx("span",{className:"wx-GAOa4kDV wx-type",children:r("Folder")}),o.jsxs("span",{className:"wx-GAOa4kDV wx-name",children:[o.jsx("span",{children:w}),o.jsx("span",{children:b})]})]}),o.jsx("div",{"data-action-id":za(t.id),className:"wx-GAOa4kDV wx-more",children:o.jsx("i",{className:"wx-GAOa4kDV wxi-dots-v"})})]}):o.jsxs("div",{className:"wx-GAOa4kDV wx-info",children:[o.jsx("div",{className:"wx-GAOa4kDV wx-file-name",children:o.jsxs("span",{className:"wx-GAOa4kDV wx-name",children:[o.jsx("span",{children:w}),o.jsx("span",{children:b})]})}),o.jsx("div",{"data-action-id":za(t.id),className:"wx-GAOa4kDV wx-more",children:o.jsx("i",{className:"wx-GAOa4kDV wxi-dots-v"})})]})]})})}function o0(){const t=d.useContext($a),n=d.useContext(Ua.i18n),r=d.useMemo(()=>n.getGroup("filemanager"),[n]),[i]=Vs(t,"panels"),l=Lt(t,"activePanel"),u=Lt(t,"mode"),f=i[l]._files,h=i[l].selected,g=i[l].path,y=i[l]._crumbs,w=i[l]._selectNavigation,b=d.useCallback((T,P)=>{const U=P&&(P.ctrlKey||P.metaKey),F=P&&P.shiftKey;if(T==="/wx-filemanager-parent-link"){if(h.length&&(U||F))return;t.exec("select-file",{type:"navigation"});return}let Y=T==="body"&&P?null:T;const D=P.target.className.indexOf("wx-more")!==-1||P.target.className.indexOf("wxi-dots-v")!==-1;setTimeout(()=>{t.exec("select-file",{id:Y,toggle:U&&!D,range:F&&!D,panel:l})},1)},[t,h,l]),x=d.useCallback(()=>{y.length>1&&t.exec("set-path",{id:y[y.length-2].id,panel:l,selected:[y[y.length-1].id]})},[t,y,l]),M=d.useCallback(T=>{if(T==="/wx-filemanager-parent-link")return x();u==="search"&&t.exec("filter-files",{text:""});const P=f.find(U=>U.id===T);P&&(P.type=="folder"?t.exec("set-path",{id:P.id,panel:l}):t.exec("open-file",{id:P.id}))},[t,x,u,f,l]),k=d.useCallback((T,P)=>{(!h?.length||!h.filter(U=>U?.id===T).length>0)&&b(T,P)},[h,b]),N=d.useMemo(()=>g!=="/"?[{id:"/wx-filemanager-parent-link",name:r("Back to parent folder"),navigation:w},...f]:f,[g,r,w,f]),E=d.useRef(null),I=d.useRef();return d.useEffect(()=>{E.current&&(I.current?(I.current.click=b,I.current._dblclick=M,I.current.context=k):(I.current={click:b,dblclick:T=>I.current._dblclick(T),_dblclick:M,context:k},Cd(E.current,I.current)))},[b,M,k]),u=="search"&&!N.length?o.jsx("div",{className:"wx-iyjASZCY wx-not-found",children:o.jsx("div",{className:"wx-iyjASZCY wx-not-found-text",children:r("Looks like nothing is here")})}):o.jsx("div",{tabIndex:0,className:"wx-iyjASZCY "+("wx-cards"+(g!=="/"&&u!=="search"?" wx-has-back-link":"")),"data-id":za("body"),ref:E,children:N.map(T=>o.jsx(mj,{item:T},T.id))})}function du({name:t="",spin:n=!1,onClick:r}){return o.jsx("i",{"data-menu-ignore":"true",className:`wx-uwcvNSAG wx-icon wxi-${t} ${n?"wx-spin":""} ${r?"wx-clickable":""}`,onClick:()=>{r&&r()}})}function pj(){const t=d.useContext(Ua.i18n).getGroup("filemanager"),n=d.useContext($a),r=Lt(n,"activePanel"),[i]=Vs(n,"panels"),l=d.useMemo(()=>i[r]._crumbs,[i,r]);function u(){n.exec("filter-files",{text:""})}return o.jsxs("div",{className:"wx-GDJvtROw wx-search",children:[o.jsxs("div",{className:"wx-GDJvtROw wx-toolbar",children:[o.jsx("div",{className:"wx-GDJvtROw wx-back-icon",children:o.jsx(du,{name:"angle-left",onClick:u})}),o.jsxs("div",{className:"wx-GDJvtROw wx-text",children:[t("Search results in")," ",Array.isArray(l)&&l.map((f,h)=>o.jsxs(d.Fragment,{children:[h?"/":null,f.id=="/"?t(f.name):f.name]},h))]})]}),o.jsx(o0,{})]})}function Mg({narrowMode:t,extraInfo:n}){const r=d.useContext($a),{preview:i,icon:l}=r.templates,u=d.useContext(Ua.i18n),f=d.useMemo(()=>u.getGroup("filemanager"),[u]),h=d.useMemo(()=>gd("%D, %d %F %Y, %H:%i",u.getRaw().calendar),[u]),[g,y]=Vs(r,"panels"),w=Lt(r,"activePanel"),b=Lt(r,"preview"),x=Lt(r,"search"),M=d.useMemo(()=>{const D=g&&w!=null&&g[w]?._selected?.length||0;return x&&!D},[x,y,w]),k=d.useMemo(()=>{const D=g&&w!=null?g[w]:null;return D?M?D._files:D._selected:[]},[M,y,w]),N=d.useCallback((D,K)=>(D?`${D} ${f(D>1?"folders":"folder")} `:"")+(K?`${K} ${f(K>1?"files":"file")}`:""),[f]),E=d.useCallback(()=>{r.exec("show-preview",{mode:!b})},[r,b]),I=d.useCallback(D=>D.type==="folder"?f("Folder"):D.ext||f("Unknown file"),[f]),T=d.useMemo(()=>{let D,K,ne,q,O,W,ce,$;if(k.length===1&&!M){K=k[0],D=K.name;const ee=i(K,400,500);ee?(ne=ee,q=""):(q=l(K,"big"),ne=""),O=K.type!=="folder"}else{if(K=O=null,D="",k.length){let ee=0,B=0,L=0,oe=[],be;k.forEach(me=>{typeof me.size>"u"&&(be=!0,ee=void 0),be||(ee+=me.size),oe.push(I(me)),me.type==="folder"?B++:L++});const H=new Set(oe);W=H.size>1?f("multiple"):[...H][0],ce=N(B,L),$=ee,M||(D=f("Multiple files"))}q=l({type:M?"search":k.length?"multiple":"none"},"big"),ne=""}return{name:D,item:K,previewSrc:ne,iconSrc:q,showDownloadIcon:O,type:W,totalCount:ce,totalSize:$}},[k,M,i,l,f,I,N]),P=d.useCallback(()=>{r.exec("download-file",{id:k[0].id})},[r,k]),U=d.useCallback(async D=>{if(!n||!D)return null;try{return await n(D)}catch(K){return console.log(K),null}},[n]),[F,Y]=d.useState(null);return d.useEffect(()=>{let D=!1;return Y(null),Promise.resolve(U(T.item)).then(K=>{D||Y(K)}).catch(()=>{D||Y(null)}),()=>{D=!0}},[U,T.item]),o.jsx("div",{className:"wx-O0BTtRrH wx-wrapper",children:k&&k.length?o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"wx-O0BTtRrH wx-preview",children:[o.jsxs("div",{className:"wx-O0BTtRrH wx-toolbar",children:[o.jsx("div",{className:"wx-O0BTtRrH wx-name",children:T.name}),o.jsxs("div",{className:"wx-O0BTtRrH wx-icons",children:[T.showDownloadIcon?o.jsx(du,{name:"download",onClick:P}):null,t?o.jsx(du,{name:"close",onClick:E}):null]})]}),T.previewSrc?o.jsx("div",{className:"wx-O0BTtRrH wx-img-wrapper",children:o.jsx("img",{src:T.previewSrc,alt:f("A miniature file preview")})}):T.iconSrc?o.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:o.jsx("img",{src:T.iconSrc,alt:f("A miniature file preview")})}):o.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:T.item?o.jsx("i",{className:`wx-O0BTtRrH wx-icon wxi-${T.item.type}`}):o.jsx("i",{className:`wx-O0BTtRrH wx-icon wxi-${M?"search":"file-multiple-outline"}`})})]}),o.jsxs("div",{className:"wx-O0BTtRrH wx-info-panel",children:[o.jsx("div",{className:"wx-O0BTtRrH wx-title",children:f(M?"Found":"Information")}),o.jsxs("div",{className:"wx-O0BTtRrH wx-list",children:[T.item?o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"wx-O0BTtRrH wx-name",children:f("Type")}),o.jsx("span",{className:"wx-O0BTtRrH wx-value",children:I(T.item)}),typeof T.item.size<"u"?o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"wx-O0BTtRrH wx-name",children:f("Size")}),o.jsx("span",{className:"wx-O0BTtRrH wx-value",children:tm(T.item.size)})]}):null,o.jsx("span",{className:"wx-O0BTtRrH wx-name",children:f("Date")}),o.jsxs("span",{className:"wx-O0BTtRrH wx-value",children:[h(T.item.date)," "]})]}):o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"wx-O0BTtRrH wx-name",children:f("Count")}),o.jsx("span",{className:"wx-O0BTtRrH wx-value",children:T.totalCount}),o.jsx("span",{className:"wx-O0BTtRrH wx-name",children:f("Type")}),o.jsx("span",{className:"wx-O0BTtRrH wx-value",children:T.type}),typeof T.totalSize<"u"?o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"wx-O0BTtRrH wx-name",children:f("Size")}),o.jsx("span",{className:"wx-O0BTtRrH wx-value",children:tm(T.totalSize)})]}):null]}),F?Object.entries(F).map(([D,K])=>o.jsxs(kv.Fragment,{children:[o.jsx("span",{className:"wx-O0BTtRrH wx-name",children:D}),o.jsx("span",{className:"wx-O0BTtRrH wx-value",children:K})]},D)):null]})]})]}):o.jsxs("div",{className:"wx-O0BTtRrH wx-no-info-panel",children:[o.jsxs("div",{className:"wx-O0BTtRrH wx-toolbar",children:[o.jsx("div",{className:"wx-O0BTtRrH wx-name",children:T.name}),o.jsx("div",{className:"wx-O0BTtRrH wx-icons",children:t?o.jsx(du,{name:"close",onClick:E}):null})]}),o.jsx("div",{className:"wx-O0BTtRrH wx-no-info-wrapper",children:o.jsxs("div",{className:"wx-O0BTtRrH wx-no-info",children:[T.previewSrc?o.jsx("div",{className:"wx-O0BTtRrH wx-img-wrapper",children:o.jsx("img",{src:T.previewSrc,alt:f("A miniature file preview")})}):T.iconSrc?o.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:o.jsx("img",{src:T.iconSrc,alt:f("A miniature file preview")})}):o.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:o.jsx("i",{className:`wx-O0BTtRrH wx-icon wxi-${M?"search":"message-question-outline"}`})}),o.jsx("span",{className:"wx-O0BTtRrH wx-text",children:M?"":f("Select file or folder to view details")})]})})]})})}function l0({panel:t}){const n=d.useContext($a),r=d.useContext(Ua.i18n),i=d.useMemo(()=>r.getGroup("filemanager"),[r]),[l,u]=Vs(n,"panels"),f=d.useMemo(()=>l[t]._files,[u,t]),h=d.useMemo(()=>l[t]._crumbs||[],[u,t]);function g(k){const N=Gv(k,h);n.exec("set-path",{id:k,panel:t,...N&&{selected:[N]}})}const[y,w]=d.useState(null);d.useEffect(()=>{f&&w(null)},[f]);function b(){w(!0),n.exec("request-data",{id:h[h.length-1].id}),setTimeout(()=>{w(null)},5e3)}const x=d.useRef(null),M=d.useRef();return d.useEffect(()=>{M.current?M.current.click=g:(M.current={click:g},Cd(x.current,M.current))},[g]),o.jsxs("div",{className:"wx-SNY5LTYx wx-breadcrumbs","data-menu-ignore":"true",ref:x,children:[o.jsx("div",{className:"wx-SNY5LTYx wx-refresh-icon",children:o.jsx(du,{name:"refresh",spin:!!y,onClick:b})}),h.map((k,N)=>o.jsxs(kv.Fragment,{children:[N?o.jsx(du,{name:"angle-right"}):null,o.jsx("div",{className:"wx-SNY5LTYx wx-item","data-id":za(k.id),"data-menu-ignore":"true",children:k.id=="/"?i(k.name):k.name})]},N))]})}function hj({row:t}){const n=d.useContext(Ua.i18n),[r]=d.useState(()=>n.getGroup("filemanager")),i=d.useContext($a).templates,[l]=d.useState(()=>i.icon(t,"small"));return o.jsx("div",{className:"wx-qgAqG6sL wx-name-cell",children:t.id==="/wx-filemanager-parent-link"?o.jsxs(o.Fragment,{children:[o.jsx("i",{className:"wx-qgAqG6sL wxi-arrow-left"}),o.jsxs("span",{className:"wx-qgAqG6sL wx-name",children:[" ",r("Back to parent folder")]})]}):o.jsxs(o.Fragment,{children:[l?o.jsx("img",{className:"wx-qgAqG6sL wx-icon",alt:"",src:l,height:"24px",width:"24px"}):o.jsx("i",{className:`wx-qgAqG6sL wxi-${t.type}`}),o.jsxs("span",{className:"wx-qgAqG6sL wx-name",children:[" ",t.name," "]})]})})}function c0({children:t}){const n=d.useContext($a),r=Lt(n,"activePanel"),i=d.useContext(Qv),l=d.useRef(null);let u=d.useRef({});return u.current.drop=()=>{const f=l.current,h=yN(f,"data-panel");h&&h!=r&&n.exec("set-active-panel",{panel:h*1})},u.current.dragEnter=()=>{const f=l.current;f&&f.classList.toggle("wx-active")},u.current.dragLeave=()=>{const f=l.current;f&&f.classList.toggle("wx-active")},d.useEffect(()=>{const f=l.current;return i.droparea(f,u.current)},[]),o.jsx("div",{className:"wx-LT9X7tb7 wx-upload-area",ref:l,children:t})}function vv({panel:t,active:n=!1,onClick:r,onContextMenu:i}){const l=d.useContext($a),u=d.useContext(Ua.i18n),f=d.useMemo(()=>u.getGroup("filemanager"),[u]),h=d.useMemo(()=>gd("%d %M %Y",u.getRaw().calendar),[u]),[g]=Vs(l,"panels"),y=g[t].selected,w=g[t].path,b=g[t]._crumbs,x=g[t]._sorts,M=g[t]._selectNavigation,k=g[t]._files,N=d.useMemo(()=>[{id:"name",header:f("Name"),flexgrow:3,sort:!0,resize:!0,cell:hj},{id:"size",header:f("Size"),width:100,sort:!0,resize:!0,template:W=>typeof W=="number"?tm(W):""},{id:"date",header:f("Date"),width:120,sort:!0,resize:!0,template:W=>W?h(W):""}],[f,h]),E=d.useRef(null),I=d.useRef(null),T=d.useMemo(()=>M?["/wx-filemanager-parent-link"]:[...y],[M,y]);function P(W,ce){if(ce&&ce.target&&ce.target.className&&ce.target.className.indexOf("wx-grip")!==-1)return;const $=ce&&(ce.ctrlKey||ce.metaKey),ee=ce&&ce.shiftKey;if(W==="/wx-filemanager-parent-link"){if(y.length&&($||ee))return;l.exec("select-file",{type:"navigation"});return}let B=W==="body"&&ce?null:W;!E.current&&!I.current?l.exec("select-file",{id:B,toggle:$,range:ee,panel:t}):(E.current=null,I.current=null)}function U(){b.length>1&&l.exec("set-path",{id:b[b.length-2].id,panel:t,selected:[b[b.length-1].id]})}function F(W){if(W==="/wx-filemanager-parent-link")return U();const ce=k.find($=>$.id===W);ce&&(ce.type==="folder"?l.exec("set-path",{id:ce.id,panel:t}):l.exec("open-file",{id:ce.id}))}function Y(W){const ce=W.key,$=x[w];let ee=$?"asc":"desc";$&&$.key===ce&&(ee=$.order==="asc"?"desc":"asc"),l.exec("sort-files",{key:ce,order:ee,panel:t,path:w})}function D(W){W.intercept("sort-rows",ce=>(E.current=!0,Y(ce),!1)),W.intercept("select-row",()=>!1),W.on("resize-column",()=>I.current=!0),W.intercept("hotkey",()=>!1)}const K=d.useMemo(()=>w!=="/"?[{id:"/wx-filemanager-parent-link",name:f("Back to parent folder")},...k]:k,[w,k,f]),ne=d.useMemo(()=>{if(K&&x&&x[w]){const{key:W,order:ce}=x[w];return{[W]:{order:ce}}}},[K,x,w]),q=d.useRef(null),O=d.useRef();return d.useEffect(()=>{O.current?(O.current.click=P,O.current._dblclick=F):(O.current={click:P,dblclick:W=>O.current._dblclick(W),_dblclick:F},Cd(q.current,O.current))},[P,F]),o.jsxs("div",{onClick:r,onContextMenu:i,className:"wx-SSaVhET7 wx-wrapper",children:[o.jsx(l0,{panel:t}),o.jsx("div",{"data-id":za("body"),className:`wx-SSaVhET7 wx-list ${n?"wx-active":""}`,ref:q,children:o.jsx(c0,{children:o.jsx(uj,{init:D,data:K,columns:N,selectedRows:T,columnStyle:()=>"wx-SSaVhET7 wx-each-cell",sizes:{rowHeight:42,headerHeight:42},sortMarks:ne})})})]})}function gj(){const t=d.useContext($a),n=Lt(t,"activePanel");function r(i){t.exec("set-active-panel",{panel:i})}return o.jsxs("div",{className:"wx-L55BfJa2 wx-panels","data-id":za("body"),children:[o.jsx("div",{className:"wx-L55BfJa2 wx-item","data-panel":0,children:o.jsx(vv,{panel:0,active:n==0,onClick:()=>r(0),onContextMenu:()=>r(0)})}),o.jsx("div",{className:"wx-L55BfJa2 wx-item","data-panel":1,children:o.jsx(vv,{panel:1,active:n==1,onClick:()=>r(1),onContextMenu:()=>r(1)})})]})}function u0({folderIcon:t=!1,folder:n={}}){const r=d.useContext($a),[i,l]=Vs(r,"panels"),u=Lt(r,"activePanel"),f=d.useMemo(()=>i[u].path,[l,u]),h=d.useContext(Ua.i18n),g=d.useMemo(()=>h.getGroup("filemanager"),[h]),y=d.useMemo(()=>!!n.data?.find(M=>M.type==="folder"),[n]),w=d.useMemo(()=>n.id=="/"?g(n.name):n.name,[n,g]),b=d.useMemo(()=>n.$level>1?(n.$level-1)*20:0,[n]),x=n.open;return o.jsxs(o.Fragment,{children:[o.jsxs("li",{"data-id":za(n.id),className:`wx-NYfhvGIt wx-folder${f===n.id?" wx-selected":""}`,style:{paddingLeft:`${b}px`},children:[y?o.jsx("i",{className:`wx-NYfhvGIt wx-toggle wxi-${x?"angle-down":"angle-right"}`,"data-action":"toggle"}):o.jsx("span",{className:"wx-NYfhvGIt wx-toggle-placeholder"}),o.jsx("i",{className:"wx-NYfhvGIt "+(t||"wxi-folder")}),o.jsxs("span",{className:"wx-NYfhvGIt wx-name",children:[" ",w," "]})]}),x&&n.data&&n.data.length&&y?o.jsx(o.Fragment,{children:n.data.map(M=>M.type==="folder"?o.jsx(u0,{folder:M},M.id):null)}):null]})}function vj(){const t=d.useContext($a),[n,r]=Vs(t,"data"),[i,l]=Vs(t,"panels"),u=Lt(t,"activePanel"),f=d.useMemo(()=>i[u]._crumbs,[l,u]),h=d.useCallback(M=>{t.exec("open-tree-folder",{id:M,mode:!n.byId(M).open})},[t,r]),g=d.useCallback(M=>{const k=Gv(M,f);t.exec("set-path",{id:M,panel:u,...k&&{selected:[k]}})},[t,f,u]),[y,w]=d.useState([]);d.useEffect(()=>{w(n.byId(0).data)},[r]);const b=d.useRef(null),x=d.useRef();return d.useEffect(()=>{x.current?(x.current.click=g,x.current.toggle=h):(x.current={click:g,toggle:h},Cd(b.current,x.current))},[g,h]),o.jsx("ul",{ref:b,className:"wx-LyHJ6R6A",children:y.map(M=>M.type==="folder"?o.jsx(u0,{folder:M},M.id):null)})}function yj(){const t=d.useContext($a),n=d.useContext(Ua.i18n),r=d.useMemo(()=>n.getGroup("filemanager"),[n]),i=Lt(t,"drive"),l=i?i.used:"",u=i?i.total:"";return l&&u?o.jsxs("div",{className:"wx-DetSyKGG wx-drive",children:[o.jsx("progress",{value:l,max:u,className:"wx-DetSyKGG wx-progress"}),o.jsxs("p",{children:[tm(l)," ",r("of")," ",tm(u)," ",r("used")]})]}):null}function bj({option:t}){const n=d.useContext(Ua.i18n).getGroup("filemanager"),r=d.useContext(Qv),i=d.useCallback(()=>{r.open({})},[r]);return o.jsx("div",{className:"wx-9XiKcxq5 wx-upload-button",onClick:i,children:o.jsx("span",{children:n(t.text)})})}function wj({readonly:t,menuOptions:n}){const r=d.useContext(Ua.i18n).getGroup("filemanager"),{showPrompt:i}=d.useContext(Kv);d.useEffect(()=>{OT("upload",bj)},[]);function l({action:f}){f&&(f.id==="add-file"?i({item:{type:"file",size:0,date:new Date},add:!0}):f.id==="add-folder"&&i({item:{type:"folder",date:new Date},add:!0}))}const u=d.useMemo(()=>n("add").map(f=>(f.text=r(f.text),f)),[n,r]);return o.jsxs("div",{className:"wx-FlucfALM wx-wrapper",children:[!t&&o.jsx("div",{className:"wx-FlucfALM wx-button",children:o.jsx(BT,{options:u,at:"bottom-fit",onClick:l,children:o.jsx(Kf,{type:"primary block",children:r("Add New")})})}),o.jsx("div",{className:"wx-FlucfALM wx-tree",children:o.jsx(vj,{})}),o.jsx(yj,{})]})}function xj({value:t="",onSearch:n}){const[r,i]=qS(t),l=d.useContext(Ua.i18n).getGroup("filemanager"),u=d.useRef(null),f=d.useMemo(()=>r!==""?"wxi-close":"wxi-search",[r]);function h(y){const w=y.target.value;i(w),n&&n({value:w})}function g(){i(""),u.current&&u.current.focus(),n&&n({value:""})}return o.jsxs("div",{className:"wx-lUZMtgT1 wx-search-input",children:[o.jsx("i",{className:`wx-lUZMtgT1 wx-icon ${f}`,onClick:g}),o.jsx("input",{type:"text",className:"wx-lUZMtgT1 wx-text",ref:u,value:r,onInput:h,placeholder:l("Search")})]})}function Sj({narrowMode:t=!1,onShowTree:n}){const r=d.useContext($a),i=d.useContext(Ua.i18n).getGroup("filemanager"),l=Lt(r,"mode"),u=Lt(r,"preview"),f=Lt(r,"search"),h=[{icon:"wxi-view-sequential",id:"table"},{icon:"wxi-view-grid",id:"cards"},{icon:"wxi-view-column",id:"panels"}];function g({value:b}){r.exec("set-mode",{mode:b})}function y(b){b.preventDefault(),r.exec("show-preview",{mode:!u})}function w(b){r.exec("filter-files",{text:b.value})}return o.jsxs("div",{className:"wx-5PZQQztG wx-toolbar",children:[o.jsxs("div",{className:"wx-5PZQQztG wx-left "+(t?"wx-left-narrow":""),children:[t?l==="panels"||l==="search"?null:o.jsx("div",{className:"wx-5PZQQztG wx-sidebar-icon","data-id":za("toggle-tree"),children:o.jsx(du,{onClick:()=>n&&n(),name:"subtask"})}):o.jsx("div",{className:"wx-5PZQQztG wx-name",children:i("Files")}),o.jsx(xj,{onSearch:w,value:f})]}),o.jsxs("div",{className:"wx-5PZQQztG wx-right",children:[t?null:o.jsx("div",{className:"wx-5PZQQztG wx-preview-icon",children:o.jsx(fT,{onClick:y,value:u,children:o.jsx("i",{className:"wx-5PZQQztG wxi-eye"})})}),o.jsx("div",{className:"wx-5PZQQztG wx-modes",children:o.jsx(iT,{value:l,options:h,onChange:g})})]})]})}function Cj(){const t=d.useContext($a),n=Lt(t,"activePanel");return o.jsxs("div",{className:"wx-NwohNJzN wx-wrapper",children:[o.jsx(l0,{panel:n}),o.jsx(c0,{children:o.jsx(o0,{})})]})}function kj({readonly:t=!1,menuOptions:n,extraInfo:r}){const i=d.useRef(null),l=d.useRef(null),[u,f]=d.useState(void 0),[h,g]=d.useState(void 0),[y,w]=d.useState(!1),b=XS(),x=d.useContext($a),{showPrompt:M,showConfirm:k}=d.useContext(Kv),N=d.useContext(Ua.i18n),E=d.useMemo(()=>N.getGroup("filemanager"),[N]),I=Lt(x,"mode"),T=Lt(x,"preview"),P=Lt(x,"activePanel"),[U,F]=Vs(x,"panels"),Y=d.useMemo(()=>(U&&P!=null?U[P]:null)?.selected??[],[F,P]),D=d.useMemo(()=>(U&&P!=null?U[P]:null)?.path,[F,P]),[K,ne]=d.useState([]);d.useEffect(()=>{const H=i.current;if(!H)return;const me=new ResizeObserver(ue=>{const Ce=ue[0]?.borderBoxSize?.[0]?.inlineSize;typeof Ce=="number"&&g(Ce<768)});return me.observe(H),()=>{me.disconnect()}},[]);const q=d.useCallback(()=>{w(H=>!H)},[]),O=d.useCallback(H=>{h&&em(H)!=="toggle-tree"&&w(!1)},[h]);d.useEffect(()=>{const H=l.current;if(H)return go(H,O).destroy},[O]),d.useEffect(()=>{const H=l.current;if(!H)return;const me=new ResizeObserver(()=>{H&&f(H.clientWidth)});return me.observe(H),H&&f(H.clientWidth),()=>{me.disconnect()}},[]);const W=d.useMemo(()=>({icon:"wxi-eye",text:"Preview",id:"preview"}),[]),ce=d.useCallback(H=>{let me=h?[W]:[];return H==="file"&&(me=[...me,...n().filter(ue=>ue.id==="download")]),me},[h,W,n]),$=d.useRef(null),ee=d.useCallback((H,me,ue)=>{const Ce=ue?[me.id]:Y;switch(H){case"download":x.exec("download-file",{id:me.id});break;case"copy":case"move":$.current={action:H,ids:Ce};break;case"paste":$.current&&x.exec($.current.action==="copy"?"copy-files":"move-files",{ids:$.current.ids,target:me?.type==="folder"?me.id:D});break;case"rename":M({item:me});break;case"delete":k({selected:Ce});break;case"preview":x.exec("show-preview",{mode:!T});break}},[x,Y,D,M,k,T]),B=d.useCallback(()=>U?.[P],[U,P]);d.useEffect(()=>{const H=i.current;if(!H)return;const me=NT(H,{api:x,menuOptions:t?ce:n,performAction:ee,getPanel:B});return()=>{typeof me=="function"?me():me&&typeof me.destroy=="function"&&me.destroy()}},[x,t,ce,n,ee,B]);const L=d.useCallback((H,me)=>{const ue=H?x.getFile(H):null,Ce=me.target.closest(".tree-item.folder");let Me;if(t)Me=ce(ue?.type);else{switch(H){case"body":Me=n(H);break;default:if(ue)if(!Ce&&Y.length>1)Me=h?[W,...n("multiselect")]:n("multiselect");else if(H==="/")Me=n("folder",ue).filter(Ne=>Ne.id==="paste");else{const Ne=n(ue.type,ue);Ne&&(Me=h?[W,...Ne]:Ne)}}I==="search"&&(Me=Me?.filter(Ne=>Ne.id!=="paste"))}if(ue?.id&&(!Y.length||!Y.some(Ne=>Ne===ue.id))&&!Ce&&x.exec("select-file",{id:ue.id}),Me?.length)return Me.forEach(Ne=>{Ce&&(Ne.hotkey=""),Ne.text&&(Ne.text=E(Ne.text)),Ne.hotkey&&(Ne.subtext=Ne.hotkey)}),ne(Me),ue||{}},[x,t,ce,n,Y,h,W,I,E]),oe=d.useCallback(H=>{const{action:me,context:ue}=H;me&&ee(me.id,ue,!me.hotkey)},[ee]);async function be(H){await Promise.resolve();const{name:me,size:ue}=H.file;x.exec("create-file",{file:{name:me,size:ue,date:new Date,file:H.file},parent:D})}return o.jsx("div",{className:"wx-RJbNonjJ wx-filemanager wx-flex",ref:i,"data-menu-ignore":"false",children:h&&T?o.jsx("div",{className:"wx-RJbNonjJ wx-info-narrow",children:o.jsx(Mg,{narrowMode:h,extraInfo:r})}):o.jsxs(o.Fragment,{children:[o.jsx(Sj,{narrowMode:h,onShowTree:q}),o.jsx(zT,{dataKey:"id",at:"point",options:K,resolver:L,onClick:oe,children:o.jsxs(YS,{dataKey:"actionId",options:K,resolver:L,onClick:oe,children:[o.jsx(GT,{data:b,apiOnly:!0,uploadURL:be}),o.jsx(Qv.Provider,{value:b,children:o.jsx("div",{className:"wx-RJbNonjJ wx-content-wrapper wx-flex",children:I!=="panels"&&I!=="search"?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"wx-RJbNonjJ "+["wx-sidebar",h?"wx-sidebar-narrow":"",y?"wx-sidebar-visible":""].filter(Boolean).join(" "),ref:l,children:o.jsx(wj,{readonly:t,menuOptions:n})}),o.jsxs("div",{className:"wx-RJbNonjJ wx-content",style:{width:`calc(100% - ${u||0}px - 10px)`},children:[o.jsx("div",{className:`wx-RJbNonjJ wx-content-item${T?"":"-fit"}`,"data-id":za("body"),children:I==="table"?o.jsx(vv,{panel:P}):o.jsx(Cj,{})}),T?o.jsx("div",{className:"wx-RJbNonjJ wx-info",children:o.jsx(Mg,{extraInfo:r})}):null]})]}):o.jsxs(o.Fragment,{children:[o.jsx("div",{className:`wx-RJbNonjJ wx-content-item${T?"":"-fit"}`,children:I==="panels"?o.jsx(gj,{}):o.jsx(pj,{})}),T?o.jsx("div",{className:"wx-RJbNonjJ wx-info",children:o.jsx(Mg,{extraInfo:r})}):null]})})})]})})]})})}const Mj=t=>t.split("-").map(n=>n?n.charAt(0).toUpperCase()+n.slice(1):"").join("");function Aj(t,n){const{type:r,ext:i}=t;if(r==="folder")return!1;let l;return r&&r!=="file"&&Bw[r]?l=r:i?l=Bw[i]?i:"file":l="unknown",`https://cdn.svar.dev/icons/filemanager/vivid/${n}/${l}.svg`}const Nj=d.forwardRef(function(t,n){const{data:r=[],mode:i="cards",drive:l=null,preview:u=!1,panels:f=null,activePanel:h=0,readonly:g=!1,menuOptions:y=kT,extraInfo:w=null,init:b=null,icons:x=Aj,previews:M=null,...k}=t,N=d.useRef();N.current=k;const E=d.useMemo(()=>new CT(GS),[]),I=d.useMemo(()=>E.in,[E]),T=d.useRef(null);T.current===null&&(T.current=new BS((F,Y)=>{const D="on"+Mj(F);N.current&&N.current[D]&&N.current[D](Y)}),I.setNext(T.current));const P=d.useMemo(()=>({getState:E.getState.bind(E),getReactiveState:E.getReactive.bind(E),getStores:()=>({data:E}),exec:I.exec,setNext:F=>(T.current=T.current.setNext(F),T.current),intercept:I.intercept.bind(I),on:I.on.bind(I),detach:I.detach.bind(I),getFile:E.getFile.bind(E),serialize:E.serialize.bind(E),templates:{preview:M||(()=>null),icon:x==="simple"?(()=>null):x}}),[E,I]),U=d.useRef(0);return d.useEffect(()=>{if(!U.current)b&&b(P);else{const F=E.getState();E.init({data:r,mode:i,drive:l,preview:u,panels:f||F.panels||[],activePanel:h})}U.current++},[E,r,i,l,u,f,h,b,P]),U.current===0&&E.init({data:r,mode:i,drive:l,preview:u,panels:f||[],activePanel:h}),d.useImperativeHandle(n,()=>({...P}),[P]),o.jsx($a.Provider,{value:P,children:o.jsx(qv,{words:Wv,optional:!0,children:o.jsx(dj,{children:o.jsx(kj,{readonly:g,menuOptions:y,extraInfo:w})})})})});function Tj({fonts:t=!0,children:n}){return n?o.jsx(Mw,{fonts:t,children:n}):o.jsx(Mw,{fonts:t})}Fv(Yr);function Yv(t,n){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`Invalid Hub ${n} response.`);return t}function sm(t,n,r){const i=Yv(t,r);if(!Array.isArray(i[n]))throw new Error(`Invalid Hub ${r} response: ${n} must be an array.`);return i[n]}function Rj(t,n,r){const i=Yv(t,r);if(!i[n]||typeof i[n]!="object"||Array.isArray(i[n]))throw new Error(`Invalid Hub ${r} response: ${n} must be an object.`);return i[n]}async function jj(t,n=!1){return sm(await tt(`/api/remote/filesystem/roots${n?"?refresh=1":""}`,void 0,t),"roots","filesystem roots")}async function Ag(t,n){const r=await tt(`/api/remote/filesystem/entries?id=${encodeURIComponent(t)}`,void 0,n);return{folder:Rj(r,"folder","filesystem entries"),entries:sm(r,"entries","filesystem entries")}}async function Ej(t,n){return tt("/api/remote/filesystem/selection/scan",{method:"POST",body:JSON.stringify({itemIds:t})},n)}async function Dj(t,n,r,i){return tt("/api/remote/files/from-hub",{method:"POST",body:JSON.stringify({itemIds:t,deviceIds:n,remoteDirectory:r})},i)}async function Ij(t,n=!1){const r=await tt(`/api/remote/files/jobs?active=${n?"1":"0"}`,void 0,t);return{jobs:sm(r,"jobs","file transfer jobs")}}async function Lj(t,n){return tt(`/api/remote/files/jobs/${encodeURIComponent(t)}`,void 0,n)}async function _j(t,n){return tt(`/api/remote/files/jobs/${encodeURIComponent(t)}/cancel`,{method:"POST"},n)}async function zw(t){return sm(await tt("/api/remote/filesystem/shared-folders",void 0,t),"folders","shared folders")}async function Pj(t,n){return tt("/api/remote/filesystem/shared-folders",{method:"POST",body:JSON.stringify({sourceId:t})},n)}async function Fj(t,n,r){return tt(`/api/remote/filesystem/shared-folders/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)},r)}async function Oj(t,n){return tt(`/api/remote/filesystem/shared-folders/${encodeURIComponent(t)}`,{method:"DELETE"},n)}async function Hj(t,n,r,i){const l=await tt(`/api/remote/filesystem/shared-folders/${encodeURIComponent(t)}/sync`,{method:"POST",body:JSON.stringify({deviceIds:n,remoteDirectory:r})},i),u=Yv(l,"shared folder sync");return{ok:u.ok===!0,jobs:sm(l,"jobs","shared folder sync"),files:Number(u.files||0),totalBytes:Number(u.totalBytes||0)}}function Bj(t){return{id:String(t.id),parentId:t.parent,name:t.name,type:t.type==="file"?"file":"folder",size:Number(t.size||0),modifiedAt:t.date?.toISOString()||null,displayPath:String(t.displayPath||t.name),hasChildren:t.lazy===!0||!!t.data?.length,locked:t.locked===!0}}function $w(t){if(!Number.isFinite(t)||t<=0)return"0 B";const n=["B","KB","MB","GB","TB"];let r=t,i=0;for(;r>=1024&&i<n.length-1;)r/=1024,i+=1;return`${r.toFixed(i===0||r>=100?0:1)} ${n[i]}`}function Lp(t){return t.driveType==="network"?"network":t.driveType==="removable"?"removable":"local"}function zj(t){const n=t.filter(r=>Lp(r)==="local");return n.find(r=>/\bC:/i.test(`${r.name} ${r.displayPath||""}`))||n[0]||t[0]||null}function $j({hubUrl:t,roots:n,loading:r,error:i,onRefreshRoots:l,onImportFiles:u,onImportFolder:f,onSelectionChange:h,onShareItem:g,onAddSyncFolder:y,onNotice:w}){const b=d.useRef(null),x=d.useRef("/"),M=d.useRef(0),k=d.useRef([]),N=d.useRef(new Map),[E,I]=d.useState(null),[T,P]=d.useState([]),[U,F]=d.useState([]),[Y,D]=d.useState(0),[K,ne]=d.useState(null),[q,O]=d.useState(!1),[W,ce]=d.useState(""),[$,ee]=d.useState(new Set),B=n.find(xe=>xe.id===E)||null,L=T[T.length-1]||null,oe=B?L?.svarPath||`/${B.name}`:null,be=oe;d.useEffect(()=>{k.current=T,x.current=be||"/"},[be,T]);const H=d.useMemo(()=>(N.current.clear(),!B||!be||T.length===0?[]:(T.forEach(xe=>N.current.set(xe.svarPath,xe.hubId)),[...T.map((xe,he)=>({id:xe.svarPath,parent:he===0?"/":T[he-1].svarPath,type:"folder",name:xe.name,date:xe.modifiedAt?new Date(xe.modifiedAt):void 0,lazy:!1})),...U.map(xe=>{const he=`${be}/${xe.name}`;return N.current.set(he,xe.id),{id:he,parent:be,name:xe.name,type:xe.type==="file"?"file":"folder",...xe.type==="file"?{size:xe.size}:{},date:xe.modifiedAt?new Date(xe.modifiedAt):void 0,lazy:xe.type!=="file"&&xe.hasChildren===!0,displayPath:xe.displayPath,locked:xe.locked,driveType:xe.driveType,totalBytes:xe.totalBytes,freeBytes:xe.freeBytes}})])),[B,U,be,T]),me=xe=>N.current.get(String(xe))||String(xe),ue=xe=>Bj({...xe,id:me(String(xe.id)),parent:me(String(xe.parent))}),Ce=async(xe,he)=>{const pe=xe[xe.length-1];if(!pe)return;const Ae=++M.current;O(!0),ce("");try{const Se=await Ag(pe.hubId,t);if(Ae!==M.current)return;if(!Array.isArray(Se.entries))throw new Error("Invalid Hub filesystem entries response.");const Pe={...pe,displayPath:Se.folder.displayPath||pe.displayPath,modifiedAt:Se.folder.modifiedAt||pe.modifiedAt},Qe=[...xe.slice(0,-1),Pe];k.current=Qe,P(Qe),F(Se.entries),D(Z=>Z+1)}catch(Se){if(Ae!==M.current)return;console.error("[LiveDesk FS] folder navigation failed",{folderId:pe.hubId,error:Se}),ce(Se instanceof Error?`${he}: ${Se.message}`:`${he}: Unable to read this folder.`)}finally{Ae===M.current&&O(!1)}},Me=async xe=>{const he={svarPath:`/${xe.name}`,hubId:xe.id,name:xe.name,displayPath:xe.displayPath,modifiedAt:xe.modifiedAt},pe=++M.current;I(xe.id),k.current=[he],P([he]),x.current=he.svarPath,F([]),ce(""),O(!0),ne(xe.id),ee(Ae=>{const Se=new Set(Ae);return Se.delete(xe.id),Se});try{const Ae=await Ag(xe.id,t);if(pe!==M.current)return;if(!Array.isArray(Ae.entries))throw new Error("Invalid Hub filesystem entries response.");const Se={...he,displayPath:Ae.folder.displayPath||he.displayPath,modifiedAt:Ae.folder.modifiedAt||he.modifiedAt};k.current=[Se],P([Se]),F(Ae.entries),D(Pe=>Pe+1)}catch(Ae){if(pe!==M.current)return;console.error("[LiveDesk FS] getEntries failed",{rootId:xe.id,error:Ae}),ee(Se=>new Set(Se).add(xe.id)),ce(Ae instanceof Error?`${xe.name}: ${Ae.message}`:`${xe.name}: Unable to read this drive.`),w(Ae instanceof Error?`${xe.name}: ${Ae.message}`:`${xe.name}: Unable to read this drive.`)}finally{pe===M.current&&(ne(null),O(!1))}},Ne=xe=>{const he=k.current;xe<0||xe>=he.length||xe===he.length-1||Ce(he.slice(0,xe+1),he[xe].name)},He=(xe,he)=>{if(xe.type!=="folder")return;const pe=k.current,Ae=pe.findIndex(Pe=>Pe.svarPath===he);if(Ae<0)return;const Se={svarPath:`${he}/${xe.name}`,hubId:xe.id,name:xe.name,displayPath:xe.displayPath,modifiedAt:xe.modifiedAt};Ce([...pe.slice(0,Ae+1),Se],xe.name)},Ve=()=>Ne(k.current.length-2),ie=xe=>{if(xe.key!=="Enter"&&xe.code!=="Enter"&&xe.code!=="NumpadEnter"||xe.target?.closest('button, input, textarea, [contenteditable="true"]'))return;const pe=b.current;if(!pe)return;const Ae=pe.getState().panels?.flatMap(Pe=>Pe.selected||[])||[];if(Ae.length!==1)return;const Se=pe.getFile(String(Ae[0]));Se?.type==="folder"&&(xe.preventDefault(),xe.stopPropagation(),He(ue(Se),String(Se.parent||x.current)))};d.useEffect(()=>{const xe=n.find(he=>he.id===E)||zj(n);if(ee(he=>new Set([...he].filter(pe=>n.some(Ae=>Ae.id===pe)))),!xe){I(null),k.current=[],P([]),F([]);return}Me(xe)},[n]);const Oe=xe=>{b.current=xe,xe.on("request-data",async({id:he})=>{const pe=String(he),Ae=me(pe);try{const Se=await Ag(Ae,t);if(!Array.isArray(Se.entries))throw new Error("Invalid Hub filesystem entries response.");const Pe=Se.entries.map(Qe=>{const Z=`${pe}/${Qe.name}`;return N.current.set(Z,Qe.id),{id:Z,parent:pe,name:Qe.name,type:Qe.type==="file"?"file":"folder",...Qe.type==="file"?{size:Qe.size}:{},date:Qe.modifiedAt?new Date(Qe.modifiedAt):void 0,lazy:Qe.type!=="file"&&Qe.hasChildren===!0,displayPath:Qe.displayPath,locked:Qe.locked,driveType:Qe.driveType,totalBytes:Qe.totalBytes,freeBytes:Qe.freeBytes}});await xe.exec("provide-data",{id:pe,data:Pe})}catch(Se){console.error("[LiveDesk FS] nested getEntries failed",{id:Ae,error:Se}),w(Se instanceof Error?Se.message:"Unable to read this folder.")}}),xe.intercept("set-path",({id:he})=>{const pe=String(he),Ae=k.current.findIndex(Pe=>Pe.svarPath===pe);if(Ae>=0)return Ne(Ae),!1;const Se=xe.getFile(pe);if(Se?.type==="folder")return He(ue(Se),String(Se.parent||x.current)),!1}),xe.intercept("open-file",()=>!1),xe.on("select-file",()=>{window.setTimeout(()=>{const Ae=(xe.getState().panels?.flatMap(Se=>Se.selected||[])||[]).map(Se=>xe.getFile(Se)).filter(Boolean).map(Se=>ue(Se));h(Ae.map(Se=>Se.id),Ae)},0)})},$e=(xe,he)=>{const pe=he?ue(he):null,Ae=()=>{const Se=pe?.type==="file"?String(he?.parent||x.current):String(he?.id||x.current);b.current?.exec("request-data",{id:Se})};return xe==="body"?[{id:"refresh",text:"Refresh",icon:"mdi mdi-refresh",handler:Ae},{id:"properties",text:"Properties",icon:"mdi mdi-information-outline",handler:()=>w("Select a file or folder to view its properties.")}]:xe==="multiselect"?[{id:"share",text:"Share to Clients",icon:"mdi mdi-share-variant",handler:()=>{(b.current?.getState().panels?.flatMap(Pe=>Pe.selected||[])||[]).forEach(Pe=>{const Qe=b.current?.getFile(Pe);Qe&&g(ue(Qe))})}},{id:"refresh",text:"Refresh",icon:"mdi mdi-refresh",handler:Ae}]:pe?[{id:"share",text:"Share to Clients",icon:"mdi mdi-share-variant",handler:()=>g(pe)},...pe.type==="folder"?[{id:"sync",text:"Add folder to Sync",icon:"mdi mdi-folder-sync-outline",handler:()=>y(pe)}]:[],{id:"copy-path",text:"Copy path",icon:"mdi mdi-content-copy",handler:()=>{Rp(pe.displayPath||pe.name)}},{id:"refresh",text:"Refresh",icon:"mdi mdi-refresh",handler:Ae},{id:"properties",text:"Properties",icon:"mdi mdi-information-outline",handler:()=>w(`${pe.name}
175
+ ${pe.displayPath||""}`)}]:[]},qe=async()=>{try{await l()}catch(xe){w(xe instanceof Error?xe.message:"Unable to refresh Hub drives.")}},vt=[{id:"local",label:"Local drives",icon:su,roots:n.filter(xe=>Lp(xe)==="local")},{id:"removable",label:"Removable drives",icon:JC,roots:n.filter(xe=>Lp(xe)==="removable")},{id:"network",label:"Network drives",icon:Mv,roots:n.filter(xe=>Lp(xe)==="network")}];return o.jsxs("section",{className:"hub-file-explorer-panel","aria-label":"Hub file explorer",children:[o.jsxs("div",{className:"hub-file-explorer-heading",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Hub file explorer"}),o.jsxs("strong",{children:[o.jsx(su,{size:16})," Browse files on this Hub"]})]}),o.jsxs("div",{className:"hub-file-explorer-heading-actions",children:[o.jsx("button",{className:"icon-button",onClick:u,title:"Import files from this browser",type:"button",children:o.jsx(Px,{size:16})}),o.jsx("button",{className:"icon-button",onClick:f,title:"Import folder from this browser",type:"button",children:o.jsx(ek,{size:16})}),o.jsx("button",{className:"icon-button",onClick:()=>{qe()},title:"Refresh drives",type:"button",children:o.jsx(bd,{size:16})})]})]}),r?o.jsxs("div",{className:"hub-file-explorer-state",children:[o.jsx(su,{size:24}),o.jsx("strong",{children:"Connecting to LiveDesk Hub file system..."})]}):i?o.jsxs("div",{className:"hub-file-explorer-state error",role:"alert",children:[o.jsx(Ci,{size:24}),o.jsx("strong",{children:i})]}):o.jsxs("div",{className:"hub-file-explorer-content",children:[o.jsxs("aside",{className:"hub-file-explorer-drive-sidebar","aria-label":"Hub drives",children:[o.jsxs("div",{className:"hub-drive-sidebar-title",children:[o.jsx(su,{size:15}),o.jsx("strong",{children:"This PC"})]}),vt.map(xe=>xe.roots.length>0&&o.jsxs("section",{className:"hub-drive-group",children:[o.jsxs("h3",{children:[o.jsx(xe.icon,{size:13}),xe.label]}),o.jsx("div",{className:"hub-drive-list",children:xe.roots.map(he=>{const pe=xe.icon,Ae=$.has(he.id)||he.locked===!0;return o.jsxs("button",{className:`hub-drive-item ${E===he.id?"active":""} ${Ae?"unavailable":""}`,onClick:()=>{Me(he)},"aria-pressed":E===he.id,type:"button",children:[o.jsx("span",{className:"hub-drive-item-icon",children:o.jsx(pe,{size:16})}),o.jsxs("span",{className:"hub-drive-item-copy",children:[o.jsx("strong",{children:he.name}),o.jsx("small",{children:he.displayPath||he.name}),o.jsxs("em",{children:[$w(he.freeBytes||0)," free / ",$w(he.totalBytes||0)]})]}),K===he.id?o.jsx(Si,{className:"hub-drive-item-status spin",size:15}):Ae?o.jsx(vb,{className:"hub-drive-item-status",size:15}):null]},he.id)})})]},xe.id)),n.length===0&&o.jsxs("div",{className:"hub-drive-sidebar-empty",children:[o.jsx(Ci,{size:17}),o.jsx("span",{children:"No drives available."})]})]}),o.jsxs("div",{className:"hub-file-explorer-browser",children:[o.jsxs("div",{className:"hub-file-explorer-navigation",children:[o.jsx("nav",{className:"hub-file-explorer-breadcrumbs","aria-label":"Current Hub folder",children:T.map((xe,he)=>o.jsxs("span",{className:"hub-file-explorer-breadcrumb-item",children:[he>0&&o.jsx(Av,{size:13,"aria-hidden":"true"}),o.jsx("button",{className:`hub-file-explorer-breadcrumb ${he===T.length-1?"current":""}`,onClick:()=>Ne(he),"aria-current":he===T.length-1?"location":void 0,type:"button",children:xe.name})]},xe.svarPath))}),o.jsxs("div",{className:"hub-file-explorer-navigation-actions",children:[q&&o.jsx(Si,{className:"hub-file-explorer-loading-icon spin",size:15,"aria-label":"Loading folder"}),o.jsx("button",{className:"icon-button",onClick:Ve,disabled:T.length<=1||q,title:"Back to parent folder",type:"button",children:o.jsx(jx,{size:16})})]})]}),W&&o.jsxs("div",{className:"hub-file-explorer-folder-error",role:"alert",children:[o.jsx(vb,{size:15}),o.jsx("span",{children:W})]}),o.jsx("div",{className:"hub-file-explorer-svar",onKeyDownCapture:ie,children:o.jsx(Tj,{fonts:!1,children:o.jsx(Nj,{data:H,panels:oe?[{path:oe,selected:[]}]:void 0,readonly:!0,mode:"table",preview:!1,init:Oe,icons:"simple",menuOptions:$e},`${B?.id||"no-root"}:${Y}`)})})]})]})]})}class Uj extends d.Component{state={error:null};static getDerivedStateFromError(n){return{error:n}}componentDidCatch(n,r){console.error("[LiveDesk] Share Files runtime error",n,r.componentStack)}render(){return this.state.error?o.jsxs("section",{className:"file-share-error-boundary",role:"alert",children:[o.jsx(Qp,{size:24}),o.jsx("strong",{children:"Share Files could not be opened."}),o.jsx("span",{children:this.state.error.message||"An unexpected file explorer error occurred."}),o.jsxs("button",{className:"text-button",onClick:this.props.onRetry,type:"button",children:[o.jsx(bd,{size:15})," Retry"]})]}):this.props.children}}function qj(t){return t.deviceName||t.hostname||t.deviceId}function Wj({devices:t,mode:n,selectedIds:r,onModeChange:i,onToggle:l}){const u=new Set(r);return o.jsxs("section",{className:"distribution-targets",children:[o.jsxs("div",{className:"file-share-section-heading",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Target"}),o.jsx("strong",{children:n==="all"?`${t.length} connected`:`${r.length} selected`})]}),o.jsxs("div",{className:"file-share-tabs compact","aria-label":"File transfer targets",children:[o.jsxs("button",{className:n==="all"?"active":"",onClick:()=>i("all"),type:"button",children:[o.jsx(Xf,{size:14})," All connected"]}),o.jsxs("button",{className:n==="selected"?"active":"",onClick:()=>i("selected"),type:"button",children:[o.jsx(Ta,{size:14})," Selected"]})]})]}),o.jsx("div",{className:"file-share-device-list","aria-label":"Connected Client targets",children:t.length===0?o.jsx("div",{className:"file-share-empty-inline",children:"No connected Clients."}):t.map(f=>{const h=n==="all"||u.has(f.deviceId);return o.jsxs("label",{className:`file-share-device-option ${h?"selected":""}`,children:[o.jsx("input",{type:"checkbox",checked:h,disabled:n==="all",onChange:()=>l(f.deviceId)}),o.jsx(Ta,{size:20,"aria-hidden":"true"}),o.jsxs("span",{children:[o.jsx("strong",{children:qj(f)}),o.jsxs("small",{children:["Slot ",f.slotNumber?String(f.slotNumber).padStart(3,"0"):"-"," / ",f.platform||"unknown OS"]})]}),o.jsx(Ba,{size:17,"aria-hidden":"true"})]},f.deviceId)})})]})}function Gj(t){if(!Number.isFinite(t)||t<=0)return"0 B";const n=["B","KB","MB","GB","TB"];let r=t,i=0;for(;r>=1024&&i<n.length-1;)r/=1024,i+=1;return`${r.toFixed(i===0||r>=100?0:1)} ${n[i]}`}function Vj({folders:t,loading:n,busy:r,canSync:i,onSyncAll:l,onSync:u,onToggleAuto:f,onRemove:h,onAdd:g}){return o.jsxs("section",{className:"file-share-sync-panel",children:[o.jsxs("div",{className:"file-share-section-heading",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Hub folders"}),o.jsx("strong",{children:"Continuous sync"})]}),o.jsxs("button",{className:"text-button compact",onClick:l,disabled:r||!i||t.length===0,type:"button",children:[o.jsx(Np,{size:15})," ",r?"Syncing":"Sync all"]})]}),n?o.jsx("div",{className:"file-share-empty-state",children:"Loading Hub sync folders..."}):t.length===0?o.jsxs("button",{className:"file-share-empty-state interactive",onClick:g,type:"button",children:[o.jsx(Np,{size:28}),o.jsx("strong",{children:"Add a selected Hub folder"}),o.jsx("span",{children:"Hub keeps the manifest and can sync while this browser is closed."})]}):o.jsx("div",{className:"file-share-sync-list",children:t.map(y=>o.jsxs("article",{className:`file-share-sync-row state-${y.status}`,children:[o.jsx("div",{className:"file-share-sync-icon",children:o.jsx(Np,{size:19})}),o.jsxs("div",{className:"file-share-sync-info",children:[o.jsx("strong",{children:y.name}),o.jsx("span",{children:y.displayPath}),o.jsxs("small",{children:[y.fileCount," files / ",Gj(y.totalBytes)," · ",y.lastSyncedAt?`Last sync ${Gx(y.lastSyncedAt)} ago`:y.message||"Not synced yet"]})]}),o.jsxs("label",{className:"file-share-auto-sync",children:[o.jsx("input",{type:"checkbox",checked:y.autoSync,onChange:()=>f(y)}),o.jsx("span",{children:"Auto"})]}),o.jsxs("button",{className:"text-button compact",onClick:()=>u(y),disabled:r||!i||y.status==="syncing",type:"button",children:[o.jsx(bd,{size:14})," Sync now"]}),o.jsx("button",{className:"icon-button",onClick:()=>h(y),title:"Remove sync folder",type:"button",children:o.jsx(Fx,{size:15})})]},y.id))})]})}function Kj(t){const r=(t.targetMode==="all"?t.devices.map(i=>i.deviceId):t.selectedTargetIds).length>0;return o.jsxs("aside",{className:"file-share-distribution-panel",children:[o.jsxs("div",{className:"file-share-distribution-head",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Distribution"}),o.jsx("strong",{children:"Hub → Clients"})]}),o.jsx(Yf,{size:18})]}),o.jsxs("div",{className:"file-share-tabs",role:"tablist","aria-label":"Distribution mode",children:[o.jsx("button",{className:t.tab==="send"?"active":"",onClick:()=>t.onTabChange("send"),role:"tab","aria-selected":t.tab==="send",type:"button",children:"Send"}),o.jsx("button",{className:t.tab==="sync"?"active":"",onClick:()=>t.onTabChange("sync"),role:"tab","aria-selected":t.tab==="sync",type:"button",children:"Sync"})]}),t.tab==="send"?o.jsxs(o.Fragment,{children:[o.jsx(Wj,{devices:t.devices,mode:t.targetMode,selectedIds:t.selectedTargetIds,onModeChange:t.onTargetModeChange,onToggle:t.onTargetToggle}),o.jsxs("label",{className:"file-share-destination",children:[o.jsx("span",{children:"Destination folder"}),o.jsxs("div",{children:[o.jsx(pd,{size:15}),o.jsx("input",{value:t.remoteDirectory,onChange:i=>t.onRemoteDirectoryChange(i.target.value),placeholder:"Desktop/LiveDeskFiles"})]}),o.jsx("small",{children:"Blank uses Desktop/LiveDeskFiles."})]}),o.jsxs("div",{className:"file-share-selection-summary",children:[o.jsx("span",{children:"Selected"}),o.jsx("strong",{children:t.selectedSummary})]}),o.jsxs("button",{className:"file-share-share-button",onClick:t.onShare,disabled:!t.canShare,type:"button",children:[o.jsx(Yf,{size:17})," Share selected"]}),o.jsxs("button",{className:"file-share-secondary-button",onClick:t.onAddSync,disabled:!t.canAddSync,type:"button",children:[o.jsx(pd,{size:16})," Add selected folder to Sync"]})]}):o.jsx(Vj,{folders:t.folders,loading:t.foldersLoading,busy:t.syncBusy,canSync:r,onSyncAll:t.onSyncAll,onSync:t.onSync,onToggleAuto:t.onToggleAuto,onRemove:t.onRemove,onAdd:t.onAddFolder})]})}function Qj(t){if(!Number.isFinite(t)||t<=0)return"0 B";const n=["B","KB","MB","GB","TB"];let r=t,i=0;for(;r>=1024&&i<n.length-1;)r/=1024,i+=1;return`${r.toFixed(i===0||r>=100?0:1)} ${n[i]}`}function Uw(t){if(t.state==="completed")return 100;const n=t.totalBytes>0?Math.round(t.sentBytes/t.totalBytes*100):t.totalFiles>0?Math.round(t.completedFiles/t.totalFiles*100):0;return Math.max(0,Math.min(yv(t.state)?100:99,n))}function qw(t){return t.state==="scanning"?"Scanning selected Hub items":t.state==="queued"?"Preparing transfer":t.state==="sending"?`${t.completedFiles}/${t.totalFiles} · ${t.currentPath||"sending"}`:t.state==="completed"?`Sent ${t.totalFiles} file${t.totalFiles===1?"":"s"} to ${t.targetCount} Client${t.targetCount===1?"":"s"}`:t.state==="partially-failed"?`${t.failedTargets.length} Client${t.failedTargets.length===1?"":"s"} failed`:t.state==="cancelled"?"Transfer cancelled":t.error||"Transfer failed"}function yv(t){return["completed","partially-failed","failed","cancelled"].includes(t)}function Yj({hubUrl:t,devices:n,localFeatureAccess:r,upgradeNotice:i,remoteDirectory:l,onRemoteDirectoryChange:u,targetMode:f,selectedTargetIds:h,onTargetModeChange:g,onTargetToggle:y,filePickerRef:w,folderPickerRef:b,onBrowserFileImport:x,onBrowserFolderImport:M,onNotice:k,onTransferChange:N}){const E=Array.isArray(n)?n:[],[I,T]=d.useState([]),[P,U]=d.useState(!0),[F,Y]=d.useState(""),[D,K]=d.useState([]),[ne,q]=d.useState([]),[O,W]=d.useState(null),[ce,$]=d.useState(!1),[ee,B]=d.useState([]),[L,oe]=d.useState(!0),[be,H]=d.useState(!1),[me,ue]=d.useState("send"),[Ce,Me]=d.useState([]),Ne=d.useRef(new Set),He=d.useRef(!1),Ve=d.useMemo(()=>f==="all"?E.map(Ee=>Ee.deviceId):h.filter(Ee=>E.some(Ge=>Ge.deviceId===Ee)),[E,h,f]),ie=Ce.find(Ee=>!yv(Ee.state)),Oe=ne.length===1&&ne[0].type==="folder"?ne[0]:null,$e=ne.length===0?"Select files or folders from the Hub explorer.":ce?"Calculating selection size...":O?`${O.files} files, ${O.folders} folders · ${Qj(O.totalBytes)}`:`${ne.length} item${ne.length===1?"":"s"} selected`,qe=Ee=>{N({id:Ee.jobId,state:Ee.state,progress:Uw(Ee),message:qw(Ee)})},vt=d.useCallback(async()=>{const Ee=await jj(t,!0);return T(Ee),Y(""),Ee},[t]),xe=async()=>{if(!He.current){He.current=!0;try{const Ge=(await Ij(t,!0)).jobs||[],ze=await Promise.all([...Ne.current].map(async nt=>{try{return await Lj(nt,t)}catch{return null}})),Ft=[...Ge,...ze.filter(Boolean)],Ze=[...new Map(Ft.map(nt=>[nt.jobId,nt])).values()];Me(Ze),Ze.forEach(qe),Ze.filter(nt=>yv(nt.state)).forEach(nt=>Ne.current.delete(nt.jobId))}catch{}finally{He.current=!1}}};d.useEffect(()=>{let Ee=!0;U(!0),Y(""),Promise.all([vt(),zw(t).then(ze=>{Ee&&B(ze)})]).catch(ze=>{Ee&&(Y(ze instanceof Error?"Hub file system is unavailable. Make sure LiveDesk Hub is running on this computer.":"Hub file system is unavailable."),k(ze instanceof Error?ze.message:"Hub file system is unavailable."))}).finally(()=>{Ee&&(U(!1),oe(!1))}),xe();const Ge=window.setInterval(()=>{xe()},800);return()=>{Ee=!1,window.clearInterval(Ge)}},[t,vt]),d.useEffect(()=>{if(D.length===0){W(null);return}let Ee=!1;return $(!0),Ej(D,t).then(Ge=>{Ee||W(Ge)}).catch(Ge=>{Ee||k(Ge instanceof Error?Ge.message:"Unable to calculate selected size.")}).finally(()=>{Ee||$(!1)}),()=>{Ee=!0}},[t,D.join("|")]);const he=(Ee,Ge)=>{K(Ee),q(Ge)},pe=Ee=>{Ee.forEach(Ge=>Ne.current.add(Ge.jobId)),Me(Ge=>[...new Map([...Ge,...Ee].map(ze=>[ze.jobId,ze])).values()]),Ee.forEach(qe)},Ae=async()=>{if(!r){k(i);return}if(D.length===0){k("Select files or folders from the Hub explorer.");return}if(Ve.length===0){k("Choose at least one connected Client.");return}if(ie){k("A Hub transfer is already running.");return}try{const Ee=await Dj(D,Ve,l.trim(),t);Ne.current.add(Ee.jobId),k("Hub transfer queued."),await xe()}catch(Ee){k(Ee instanceof Error?Ee.message:"Unable to start Hub transfer.")}},Se=async Ee=>{const Ge=Ee||Oe;if(!Ge||Ge.type!=="folder"){k("Select one folder to add it to Sync.");return}try{const ze=await Pj(Ge.id,t);B(Ft=>[...Ft.filter(Ze=>Ze.id!==ze.folder.id),ze.folder]),ue("sync"),k(`${Ge.name} is ready for Hub sync.`)}catch(ze){k(ze instanceof Error?ze.message:"Unable to add the Hub folder to Sync.")}},Pe=async Ee=>{if(Ve.length===0){k("Choose at least one connected Client.");return}H(!0),B(Ge=>Ge.map(ze=>ze.id===Ee.id?{...ze,status:"syncing"}:ze));try{const Ge=await Hj(Ee.id,Ve,l.trim(),t);pe(Ge.jobs||[]),k(Ge.jobs?.length?"Hub sync queued.":"No changed files to sync.");const ze=await zw(t);B(ze)}catch(Ge){k(Ge instanceof Error?Ge.message:"Unable to sync the Hub folder."),B(ze=>ze.map(Ft=>Ft.id===Ee.id?{...Ft,status:"error",message:"Sync failed"}:Ft))}finally{H(!1)}},Qe=async()=>{H(!0);try{for(const Ee of ee)await Pe(Ee)}finally{H(!1)}},Z=async Ee=>{try{const Ge=await Fj(Ee.id,{autoSync:!Ee.autoSync},t);B(ze=>ze.map(Ft=>Ft.id===Ee.id?Ge.folder:Ft))}catch(Ge){k(Ge instanceof Error?Ge.message:"Unable to update auto sync.")}},$t=async Ee=>{try{await Oj(Ee.id,t),B(Ge=>Ge.filter(ze=>ze.id!==Ee.id))}catch(Ge){k(Ge instanceof Error?Ge.message:"Unable to remove the sync folder.")}};return o.jsxs("section",{className:"livedesk-file-explorer",children:[o.jsx("input",{ref:w,className:"hidden-file-input",type:"file",multiple:!0,onChange:Ee=>{Ee.currentTarget.files&&x(Ee.currentTarget.files),Ee.currentTarget.value=""}}),o.jsx("input",{ref:b,className:"hidden-file-input",type:"file",multiple:!0,webkitdirectory:"",directory:"",onChange:Ee=>{Ee.currentTarget.files&&M(Ee.currentTarget.files),Ee.currentTarget.value=""}}),o.jsx("div",{className:"file-share-workspace",children:o.jsxs(Uj,{onRetry:()=>window.location.reload(),children:[o.jsx($j,{hubUrl:t,roots:I,loading:P,error:F,onRefreshRoots:vt,onImportFiles:()=>w.current?.click(),onImportFolder:()=>b.current?.click(),onSelectionChange:he,onShareItem:Ee=>{K([Ee.id]),q([Ee]),ue("send")},onAddSyncFolder:Ee=>{K([Ee.id]),q([Ee]),Se(Ee)},onNotice:k}),o.jsx(Kj,{devices:E,targetMode:f,selectedTargetIds:h,onTargetModeChange:g,onTargetToggle:y,remoteDirectory:l,onRemoteDirectoryChange:u,selectedEntries:ne,selectedSummary:$e,canShare:r&&!ie&&D.length>0&&Ve.length>0&&!ce,onShare:()=>{Ae()},canAddSync:!!Oe,onAddSync:()=>{Se()},tab:me,onTabChange:ue,folders:ee,foldersLoading:L,syncBusy:be,onSyncAll:()=>{Qe()},onSync:Ee=>{Pe(Ee)},onToggleAuto:Ee=>{Z(Ee)},onRemove:Ee=>{$t(Ee)},onAddFolder:()=>{Se()}})]})}),ie&&o.jsx("footer",{className:"file-share-workspace-footer",children:o.jsxs("span",{children:[qw(ie)," · ",Uw(ie),"% ",o.jsx("button",{className:"icon-button",onClick:()=>{_j(ie.jobId,t).then(Ee=>{Me(Ge=>Ge.map(ze=>ze.jobId===Ee.jobId?Ee:ze)),qe(Ee)})},title:"Cancel transfer",type:"button",children:o.jsx(hr,{size:14})})]})})]})}const Xj=d.forwardRef(function({value:n,onChange:r,onSubmit:i,onOpenSuggestedTasks:l,suggestedOpen:u=!1,suggestedTaskCount:f,disabled:h=!1,placeholder:g="Ask LiveDesk to work across your machines...",compact:y=!1},w){return o.jsxs("form",{className:"agents-composer",onSubmit:b=>{b.preventDefault(),i()},children:[o.jsx("button",{className:`agents-suggested-trigger ${u?"active":""}`,type:"button","aria-label":f===void 0?"Open Suggested tasks":`Open Suggested tasks (${f} available)`,"aria-expanded":u,onClick:l,disabled:h,children:o.jsx(tk,{size:17})}),o.jsx("textarea",{ref:w,value:n,onChange:b=>r(b.target.value.slice(0,4e3)),placeholder:g,"aria-label":"Ask LiveDesk",rows:y?1:2,disabled:h}),o.jsxs("button",{className:"agents-run-button",type:"submit",disabled:h||!n.trim(),children:[h?o.jsx(Si,{className:"spin",size:16}):o.jsx(Yf,{size:16}),h?"Running":"Run"]})]})}),Zj=["read","processControl","serviceControl","applicationControl","fileRead","fileWrite","fileDelete","shell","script","softwareInstall","network","systemPower","systemConfiguration","userAccount"];function Gp(t){return t.deviceName?.trim()||t.hostname?.trim()||t.deviceId}function Vp(t){return t.connected!==!0?!1:t.synthetic===!0?!0:!t.channels||t.channels.control===!0}function Jj(t){return t==="running"||t==="completed"||t==="failed"||t==="cancelled"?t:"queued"}function eE(t){switch(t){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 tE(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function Cs(t){return typeof t=="number"&&Number.isFinite(t)?t:null}function bp(t){const n=Cs(t);return n===null?"":n<1024**2?`${Math.round(n/1024)}K`:n<1024**3?`${(n/1024**2).toFixed(0)}M`:`${(n/1024**3).toFixed(1)}G`}function nE(t){const n=Cs(t);return n===null?"":`${Math.round((n<=1?n:n/100)*100)}%`}function aE(t){return!t||/^(?:[\w .-]+ )?collected(?:\.)?$/i.test(t.trim())?"":t.trim()}function Kp(t,n){if(n.error)return n.error;const r=tE(n.data),i=aE(n.result||"");if(!r)return i||n.stage||n.status;if(t==="system.health"){const l=typeof r.machine=="string"?r.machine:"",u=bp(r.freeMemoryBytes),f=bp(r.totalMemoryBytes),h=Cs(r.totalMemoryBytes)&&Cs(r.freeMemoryBytes)!==null?`${Math.round(Cs(r.freeMemoryBytes)/Cs(r.totalMemoryBytes)*100)}% RAM free`:"";return[l,u&&f?`RAM ${u}/${f}`:"",h,typeof r.platform=="string"?r.platform:""].filter(Boolean).join(" · ")||i||n.status}if(t==="disk.status"){const l=typeof r.root=="string"?r.root:"",u=bp(r.freeBytes),f=Cs(r.totalBytes)&&Cs(r.freeBytes)!==null?`${Math.round(Cs(r.freeBytes)/Cs(r.totalBytes)*100)}% free`:"";return[l,u&&`${u} free`,f].filter(Boolean).join(" · ")||i||n.status}if(t==="gpu.status"){const l=typeof r.name=="string"&&r.name?r.name:"No GPU detected",u=nE(r.usageRatio),f=Cs(r.temperatureC)!==null?`${Math.round(Cs(r.temperatureC))}°C`:"",h=bp(r.freeMemoryBytes);return[l,u&&`GPU ${u}`,f,h&&`${h} free`].filter(Boolean).join(" · ")||i||n.status}if(t==="process.list"){const l=Cs(r.count);return l!==null?`${l} matching process${l===1?"":"es"}`:i||n.status}if(t==="network.status"){const l=Array.isArray(r.adapters)?r.adapters.length:null;return l!==null?`${l} active adapter${l===1?"":"s"}`:i||n.status}return i||n.stage||n.status}function Ww(t,n){const r=Kp(t,n);return n.status==="failed"||n.status==="cancelled"||/\b(?:warning|failed|error|offline|not running|low|timeout|timed out)\b/i.test(`${n.result||""} ${r}`)}function rE({state:t,operation:n}){const r=t.status==="completed"?fo:t.status==="failed"||t.status==="cancelled"?hr:t.status==="running"?Si:Ox,i=t.status==="running"?t.stage||"Working":t.status==="completed"?n?Kp(n,t):t.result||"Completed":t.status==="failed"?t.error||"Failed":t.status==="cancelled"?"Cancelled":"Queued";return o.jsxs("div",{className:`agent-target-row status-${t.status}`,"data-agent-target-id":t.deviceId,children:[o.jsx("span",{className:"agent-target-status","aria-hidden":"true",children:o.jsx(r,{size:15})}),o.jsx("strong",{children:t.deviceName}),o.jsx("span",{className:"agent-target-state",children:t.status[0].toUpperCase()+t.status.slice(1)}),o.jsx("small",{children:i})]})}function sE({operation:t,states:n,status:r,onCancel:i,onRetry:l,busy:u=!1}){const f=["running","queued"].includes(r),[h,g]=d.useState(!1),[y,w]=d.useState("all"),b=d.useMemo(()=>({total:n.length,completed:n.filter(P=>P.status==="completed").length,failed:n.filter(P=>P.status==="failed").length,running:n.filter(P=>P.status==="running").length,queued:n.filter(P=>P.status==="queued").length,cancelled:n.filter(P=>P.status==="cancelled").length}),[n]),x=n.filter(P=>Ww(t,P)),M=x.filter(P=>P.status==="completed").length,k=b.failed>0,N=x.length>0,E=n.filter(P=>y==="issues"?Ww(t,P):y==="running"?P.status==="running"||P.status==="queued":y==="completed"?P.status==="completed":y==="failed"?P.status==="failed":!0),I=N&&!f||r==="completed-with-failures"?"Completed with issues":r[0]?.toUpperCase()+r.slice(1),T=n.filter(P=>P.status==="completed").map(P=>Kp(t,P)).filter(Boolean).filter((P,U,F)=>F.indexOf(P)===U).slice(0,2);return o.jsxs("section",{className:"agent-task-block","aria-label":"Task execution",children:[o.jsxs("div",{className:"agent-task-head",children:[o.jsxs("div",{children:[o.jsx("span",{children:"LiveDesk Agent"}),o.jsx("strong",{children:eE(t)})]}),o.jsx("span",{className:`agent-task-status status-${N?"completed-with-failures":r}`,children:I})]}),o.jsxs("div",{className:"agent-task-summary","aria-label":"Task summary",children:[o.jsxs("strong",{children:[b.total," targets"]}),o.jsxs("span",{className:"summary-completed",children:[b.completed," completed"]}),b.running>0&&o.jsxs("span",{className:"summary-running",children:[b.running," running"]}),b.queued>0&&o.jsxs("span",{children:[b.queued," queued"]}),k&&o.jsxs("span",{className:"summary-failed",children:[b.failed," failed"]}),M>0&&o.jsxs("span",{className:"summary-cancelled",children:[M," warning"]}),b.cancelled>0&&o.jsxs("span",{className:"summary-cancelled",children:[b.cancelled," cancelled"]})]}),T.length>0&&o.jsxs("div",{className:"agent-task-result-preview",title:T.join(" · "),children:[o.jsx("span",{children:"Result"}),T.join(" · ")]}),o.jsx("div",{className:"agent-target-chips","aria-label":"Target status overview",children:n.map((P,U)=>{const F=P.status==="completed"?"✓":P.status==="failed"?"×":P.status==="cancelled"?"!":P.status==="running"?"…":"·";return o.jsxs("span",{className:`agent-target-chip status-${P.status}`,title:`${P.deviceName}: ${Kp(t,P)}`,"aria-label":`${U+1}. ${P.deviceName}: ${P.status}`,children:[o.jsx("b",{children:String(U+1).padStart(2,"0")}),o.jsx("span",{children:F})]},P.deviceId)})}),n.length>0&&o.jsx("div",{className:"agent-task-details-toggle",children:o.jsxs("button",{type:"button",onClick:()=>g(P=>!P),"aria-expanded":h,children:[h?o.jsx(nk,{size:14}):o.jsx(Hx,{size:14}),h?"Hide details":"Show details"]})}),h&&o.jsxs("div",{className:"agent-task-details",children:[o.jsx("div",{className:"agent-task-filters",role:"tablist","aria-label":"Task result filter",children:["all","issues","running","completed","failed"].map(P=>o.jsx("button",{className:y===P?"active":"",onClick:()=>w(P),role:"tab","aria-selected":y===P,type:"button",children:P==="all"?"All":P==="issues"?"Issues only":P[0].toUpperCase()+P.slice(1)},P))}),o.jsx("div",{className:"agent-task-rows",children:E.length>0?E.map(P=>o.jsx(rE,{operation:t,state:P},P.deviceId)):o.jsx("small",{className:"agent-task-no-results",children:"No targets match this filter."})})]}),(f||k)&&o.jsxs("div",{className:"agent-task-actions",children:[f&&i&&o.jsxs("button",{onClick:i,disabled:u,type:"button",children:[o.jsx(ak,{size:14})," Cancel"]}),!f&&k&&l&&o.jsxs("button",{onClick:l,disabled:u,type:"button",children:[o.jsx($g,{size:14})," Retry failed"]})]})]})}function iE(t){try{return JSON.stringify(t,null,2).slice(0,6e3)}catch{return"{}"}}function oE({approval:t,busy:n=!1,onApprove:r,onReject:i}){return o.jsxs("article",{className:"agent-approval-card","aria-label":"Agent approval required",children:[o.jsxs("div",{className:"agent-approval-head",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Approval required"}),o.jsx("strong",{children:t.toolName})]}),o.jsx("span",{className:`agent-approval-risk risk-${t.risk}`,children:t.risk})]}),o.jsx("p",{children:t.description}),o.jsx("pre",{children:iE(t.arguments)}),o.jsxs("small",{children:["Permission: ",t.permissionMode," · Scope: selected devices only · Expires in 5 minutes"]}),o.jsxs("div",{className:"agent-approval-actions",children:[o.jsxs("button",{className:"reject",disabled:n,onClick:i,type:"button",children:[o.jsx(hr,{size:14})," Reject"]}),o.jsxs("button",{disabled:n,onClick:()=>r("once"),type:"button",children:[o.jsx(fo,{size:14})," Once"]}),o.jsx("button",{disabled:n,onClick:()=>r("same-action-this-run"),type:"button",children:"Allow same action"}),o.jsx("button",{disabled:n,onClick:()=>r("category-this-run"),type:"button",children:"Allow category"})]}),o.jsxs("div",{className:"agent-approval-scope",children:[o.jsx(Qp,{size:13})," Approval is bound to this run, tool, arguments, selected devices, and policy hash."]})]})}function lE(t){return t==="queued"?"Request queued":t==="checking-codex"?"Checking Codex":t==="preparing-tools"?"Preparing tools":t==="thinking"?"Preparing answer":t==="tool-running"?"Working on computers":t==="recovering"?"Retrying safely":t==="waiting-approval"?"Waiting for approval":"Working"}function cE({items:t,onCancel:n,onRetry:r,busyBatchId:i,approvals:l,onApprove:u,onReject:f,busyApprovalId:h,progress:g,emptyTitle:y="Ask LiveDesk to work across your machines.",emptyBody:w="Start with a read-only request such as “현재 대상에서 CPU와 메모리 상태를 확인해줘”."}){const b=d.useRef(null),x=d.useRef(!0),M=d.useRef(""),k=t[t.length-1];return d.useLayoutEffect(()=>{const N=b.current;N&&(k?.type==="user"&&k.id!==M.current&&(x.current=!0),M.current=k?.id||"",x.current&&(N.scrollTop=N.scrollHeight))},[l,t,k?.id,k?.type,g?.message,g?.stage]),o.jsxs("section",{className:"agents-conversation","aria-live":"polite",ref:b,onScroll:N=>{const E=N.currentTarget;x.current=E.scrollHeight-E.scrollTop-E.clientHeight<72},children:[l.filter(N=>N.status==="pending").map(N=>o.jsx(oE,{approval:N,busy:h===N.approvalId,onApprove:E=>u(N,E),onReject:()=>f(N)},N.approvalId)),t.length===0&&o.jsxs("div",{className:"agents-empty-conversation",children:[o.jsx("strong",{children:y}),o.jsx("span",{children:w})]}),t.map(N=>{if(N.type==="task"){const E=N;return o.jsx(sE,{operation:E.operation,states:E.states,status:E.status,onCancel:()=>n(E.batchId,E.agentRunId),onRetry:()=>r(E.batchId),busy:i===E.batchId},E.id)}return o.jsxs("article",{className:`agents-message ${N.type}`,children:[o.jsx("span",{children:N.type==="user"?"You":"LiveDesk Agent"}),o.jsx("p",{children:N.text})]},N.id)}),g&&o.jsxs("article",{className:"agents-message agent agents-progress-message",role:"status",children:[o.jsxs("span",{children:[o.jsx(Si,{"aria-hidden":"true",size:15}),lE(g.stage)]}),o.jsx("p",{children:g.message})]})]})}const Gw=["Recommended","Health & capacity","Processes & services","Files & configuration","Software & automation","Network & connectivity","Power & maintenance","Troubleshooting & recovery"],ra=["windows","macos","linux"],ec={"system.health":{label:"system health",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:ra},"gpu.status":{label:"GPU status",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:ra},"disk.status":{label:"disk status",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:ra},"process.list":{label:"process inspection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:ra},"service.status":{label:"service inspection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:ra},"diagnostics.collect":{label:"diagnostics collection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:ra},"process.control":{label:"process control",permissionCategory:"processControl",readOnly:!1,risk:"high",supportedPlatforms:ra},"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:ra},"application.close":{label:"application close",permissionCategory:"applicationControl",readOnly:!1,risk:"medium",supportedPlatforms:ra},"file.read":{label:"file reading",permissionCategory:"fileRead",readOnly:!0,risk:"low",supportedPlatforms:ra},"file.write":{label:"file writing",permissionCategory:"fileWrite",readOnly:!1,risk:"high",supportedPlatforms:ra},"file.delete":{label:"file deletion",permissionCategory:"fileDelete",readOnly:!1,risk:"critical",supportedPlatforms:ra},"file.list":{label:"directory listing",permissionCategory:"fileRead",readOnly:!0,risk:"low",supportedPlatforms:ra},"command.run":{label:"command execution",permissionCategory:"shell",readOnly:!1,risk:"critical",supportedPlatforms:ra},"script.run":{label:"script execution",permissionCategory:"script",readOnly:!1,risk:"high",supportedPlatforms:ra},"software.install":{label:"software installation",permissionCategory:"softwareInstall",readOnly:!1,risk:"high",supportedPlatforms:ra},"network.status":{label:"network inspection",permissionCategory:"network",readOnly:!0,risk:"low",supportedPlatforms:ra},"system.power":{label:"power control",permissionCategory:"systemPower",readOnly:!1,risk:"critical",supportedPlatforms:ra},"system.configure":{label:"system configuration",permissionCategory:"systemConfiguration",readOnly:!1,risk:"critical",supportedPlatforms:ra},"logs.collect":{label:"log collection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:ra}};new Set(Object.keys(ec));const uE={Recommended:["recommended","overview","fleet","요약","추천"],"Health & capacity":["health","capacity","performance","상태","성능","용량"],"Processes & services":["process","service","application","프로세스","서비스","앱"],"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","문제해결","복구","장애"]},Vw=["low","medium","high","critical"];function dE(t){return t.reduce((n,r)=>{const i=ec[r].risk;return Vw.indexOf(i)>Vw.indexOf(n)?i:n},"low")}function fE(t){return ra.filter(n=>t.every(r=>ec[r].supportedPlatforms.includes(n)))}function ot(t,n,r,i,l,u,f={}){const h=f.description||i,g=l.flatMap(w=>w.split(".")),y=[...new Set([...uE[n],...u,...g])];return{id:t,category:n,title:r,prompt:i,description:h,requiredOperations:l,risk:f.risk||dE(l),targetSupport:f.targetSupport||"single-or-multiple",supportedPlatforms:f.supportedPlatforms||fE(l),keywords:y,recommended:f.recommended??!1,enabled:!0}}const d0=[ot("recommended-fleet-health","Recommended","Summarize current target health","Summarize system health, GPU, and disk capacity for the current target Clients.",["system.health","gpu.status","disk.status"],["summary","overview"],{recommended:!0}),ot("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}),ot("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}),ot("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}),ot("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}),ot("recommended-process-services","Recommended","Review processes and services","Review running processes and service state for warnings on the current targets.",["process.list","service.status"],["process","service","warning"],{recommended:!0}),ot("recommended-recover-application","Recommended","Recover a stopped application","Check a named application or service, relaunch its registered entry when stopped, and verify the result.",["process.list","application.launch","service.status"],["recover","start","application"],{targetSupport:"single",recommended:!0}),ot("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}),ot("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","높은 사용량"]),ot("health-uptime","Health & capacity","Review Client uptime","Show uptime, boot time, and current system health for the target Clients.",["system.health"],["uptime","boot","가동시간"]),ot("health-gpu-temperature","Health & capacity","Check GPU temperature","Check GPU temperature and thermal warnings on the current targets.",["gpu.status"],["thermal","temperature","발열"]),ot("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"]),ot("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","디스크"]),ot("health-gpu-compare","Health & capacity","Compare GPU capacity","Compare GPU model, memory, temperature, and utilization across the current targets.",["gpu.status"],["compare","graphics","capacity"]),ot("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","경고"]),ot("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"]),ot("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","실행 중"]),ot("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"]),ot("process-stop-named","Processes & services","Stop a named process","Stop process named [process name] on the target Client after checking its current state.",["process.list","process.control"],["stop","terminate","종료"],{targetSupport:"single"}),ot("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"}),ot("process-launch-app","Processes & services","Launch a registered application","Launch the registered application [application] on the target Client with [arguments].",["application.launch"],["launch","open","실행"],{targetSupport:"single"}),ot("process-close-app","Processes & services","Close an application","Close application [application] on the target Client and report whether it exited cleanly.",["application.close","process.list"],["close","exit","앱 종료"],{targetSupport:"single"}),ot("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","서비스 상태"]),ot("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"}),ot("files-list-directory","Files & configuration","List a directory","List files and folders under [path] on the target Client.",["file.list"],["directory","folder","list","목록"],{targetSupport:"single"}),ot("files-read-config","Files & configuration","Read a configuration file","Read the relevant settings from configuration file [path] on the target Client.",["file.read"],["config","settings","read","구성"]),ot("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"]),ot("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"}),ot("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"}),ot("files-compare-config","Files & configuration","Compare configuration files","Read configuration file [path] on the target Client and compare it with [reference path].",["file.read"],["compare","diff","configuration"]),ot("files-set-environment","Files & configuration","Set an environment variable","Set environment variable [name] to [value] for the target Client and verify the resulting configuration.",["system.configure","file.read"],["environment","variable","env","환경변수"],{targetSupport:"single"}),ot("files-archive-diagnostics","Files & configuration","Write a diagnostic manifest","Collect selected diagnostics and write a manifest file to [path] on the target Client.",["diagnostics.collect","file.write"],["manifest","export","diagnostic file"],{targetSupport:"single"}),ot("software-winget-install","Software & automation","Install software with winget","Install package [package name] with winget on the Windows target Client, then verify it.",["software.install","process.list"],["winget","windows","install","설치"],{targetSupport:"single",supportedPlatforms:["windows"]}),ot("software-apt-install","Software & automation","Install software with apt","Install package [package name] with apt on the Linux target Client, then verify it.",["software.install","process.list"],["apt","linux","package","설치"],{targetSupport:"single",supportedPlatforms:["linux"]}),ot("software-brew-install","Software & automation","Install software with Homebrew","Install package [package name] with brew on the macOS target Client, then verify it.",["software.install","process.list"],["brew","homebrew","macos","설치"],{targetSupport:"single",supportedPlatforms:["macos"]}),ot("software-npm-install","Software & automation","Install an npm package","Install npm package [package name] on the target Client and verify the installed version.",["software.install","command.run"],["npm","node","package"],{targetSupport:"single"}),ot("software-run-script","Software & automation","Run a registered script","Run the registered script [script path] on the target Client and report its result.",["script.run"],["script","automation","registered"],{targetSupport:"single"}),ot("software-run-command","Software & automation","Run a command on one target","Run command [command] on the target Client and return its exit status and output.",["command.run"],["command","shell","terminal"],{targetSupport:"single"}),ot("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"]),ot("software-toolchain-setup","Software & automation","Set up a toolchain","Install the requested package [package name], configure [change], and verify the toolchain on the target Client.",["software.install","system.configure","process.list"],["toolchain","setup","developer"],{targetSupport:"single"}),ot("network-adapter-status","Network & connectivity","Check network adapters","Show adapter state, address, and link information for the current targets.",["network.status"],["adapter","ethernet","wifi","네트워크 상태"]),ot("network-disconnected","Network & connectivity","Find disconnected targets","Find current targets with disconnected or degraded network adapters.",["network.status"],["disconnected","offline","연결 끊김"]),ot("network-link-speed","Network & connectivity","Check link speed","Report network link speed and duplex information for the current targets.",["network.status"],["speed","bandwidth","duplex"]),ot("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"]),ot("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"]),ot("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"]),ot("network-compare","Network & connectivity","Compare target connectivity","Compare adapter state, addresses, and link speed across the current targets.",["network.status"],["compare","inventory","connectivity"]),ot("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"]),ot("power-lock","Power & maintenance","Lock the Client","Lock the target Client and report the resulting power action status.",["system.power"],["lock","security","잠금"],{targetSupport:"single",risk:"critical"}),ot("power-logoff","Power & maintenance","Log off the Client","Log off the target Client after warning that interactive sessions will close.",["system.power"],["logoff","session","로그오프"],{targetSupport:"single",risk:"critical"}),ot("power-sleep","Power & maintenance","Put the Client to sleep","Put the target Client to sleep after confirming the requested delay of [delay].",["system.power"],["sleep","suspend","절전"],{targetSupport:"single",risk:"critical"}),ot("power-restart","Power & maintenance","Restart the Client","Restart the target Client after confirming that active work may be interrupted.",["system.power"],["restart","reboot","재부팅"],{targetSupport:"single",risk:"critical"}),ot("power-shutdown","Power & maintenance","Shut down the Client","Shut down the target Client after confirming that active work may be interrupted.",["system.power"],["shutdown","power off","종료"],{targetSupport:"single",risk:"critical"}),ot("power-maintenance-restart","Power & maintenance","Restart after maintenance","Check the target Client, restart it after maintenance, and verify that it returns online.",["system.health","system.power","network.status"],["maintenance","reboot","verify"],{targetSupport:"single",risk:"critical"}),ot("power-timezone","Power & maintenance","Set the Client timezone","Set the target Client timezone to [timezone] and verify the resulting system configuration.",["system.configure"],["timezone","clock","시간대"],{targetSupport:"single",risk:"critical"}),ot("power-persistent-environment","Power & maintenance","Persist an environment variable","Persist environment variable [name] with value [value] for the target Client and verify it.",["system.configure"],["environment","persistent","환경변수"],{targetSupport:"single",risk:"critical"}),ot("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"}),ot("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"}),ot("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"}),ot("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"}),ot("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"}),ot("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"}),ot("recovery-network-instability","Troubleshooting & recovery","Recover network instability","Collect network diagnostics, inspect network services, and report the safest recovery action for the target Client.",["network.status","service.status","diagnostics.collect"],["network","unstable","네트워크 복구"],{targetSupport:"single"}),ot("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","장애 보고서"])],Ng={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 mE(t,n){return t==="safe-auto"?Ng:t==="full-access"?{...Ng,processControl:"allow",serviceControl:"allow",applicationControl:"allow",fileDelete:"allow",shell:"allow",script:"allow",softwareInstall:"allow",systemPower:"allow",systemConfiguration:"allow"}:t==="custom"&&n?n:{...Ng,processControl:"ask",serviceControl:"ask",applicationControl:"ask",fileWrite:"ask",network:"ask"}}function pE(t,n,r){const i=mE(n,r),l=t.requiredOperations.map(u=>i[ec[u].permissionCategory]);if(l.includes("deny")){const u=t.requiredOperations.find(f=>i[ec[f].permissionCategory]==="deny");return{state:"blocked",label:"Blocked",reason:`This task requires ${ec[u].label}, which is blocked by the current permission policy.`}}return l.includes("ask")?{state:"approval",label:"Approval required",reason:"This task requires approval before the requested changes can reach a Client."}:t.requiredOperations.every(u=>ec[u].readOnly)?{state:"read-only",label:"Read only"}:n==="full-access"?{state:"full-access",label:"Full Access"}:{state:"auto",label:"Auto allowed"}}function hE(t){const n=String(t||"").trim().toLowerCase();return n==="windows"||n==="win32"||n==="win32nt"?"windows":n==="macos"||n==="macosx"||n==="darwin"||n==="osx"?"macos":n==="linux"?"linux":null}function gE(t,n,r){const i=new Set(r);return t.filter(l=>l.connected&&(n==="all"||n==="auto"||i.has(l.deviceId)))}function vE(t,n){const r=hE(t.platform);if(!r||!n.supportedPlatforms.includes(r))return!1;const i=t.capabilities?.agentTools;return!Array.isArray(i)||i.length===0?n.requiredOperations.every(l=>ec[l].readOnly):n.requiredOperations.every(l=>i.includes(l))}function f0(t,n,r,i,l,u){const f=pE(t,l,u),h=gE(n,r,i),g=h.map(M=>M.deviceId),y={...f,available:!1,availableDeviceIds:[],unsupportedDeviceIds:g,risk:t.risk,supportedPlatforms:t.supportedPlatforms};if(h.length===0)return{...y,reason:"Select at least one connected Client."};if(t.targetSupport==="single"&&h.length!==1)return{...y,reason:"This task supports one Client at a time."};if(f.state==="blocked")return y;const w=h.filter(M=>vE(M,t)),b=w.map(M=>M.deviceId),x=g.filter(M=>!b.includes(M));return w.length===0?{...y,unsupportedDeviceIds:x,reason:"No current target supports the required platform and client capabilities."}:{...y,available:!0,availableDeviceIds:b,unsupportedDeviceIds:x}}function yE(t,n,r,i,l,u){return t.filter(f=>f.enabled&&f0(f,n,r,i,l,u).available).length}const Tg="livedesk.agentPromptRecent",Rg="livedesk.agentPromptFavorites",bE={Recommended:nc,"Health & capacity":Zl,"Processes & services":ok,"Files & configuration":ik,"Software & automation":Fp,"Network & connectivity":Mv,"Power & maintenance":Na,"Troubleshooting & recovery":sk};function Kw(t){if(typeof window>"u")return[];try{const n=JSON.parse(window.localStorage.getItem(t)||"[]");return Array.isArray(n)?n.filter(r=>typeof r=="string"):[]}catch{return[]}}function wp(t,n){try{window.localStorage.setItem(t,JSON.stringify(n))}catch{}}function jg(t){return t==="all"?"All tasks":t==="recent"?"Recent":t==="favorites"?"Favorites":t==="read-only"?"Read only":t==="auto"?"Auto allowed":t==="approval"?"Approval required":t==="full-access"?"Full Access":t==="available"?"Available":t==="unavailable"?"Unavailable":t}function wE(t){return t==="all"?"All":t==="recent"?"Recent":t==="favorites"?"Favorites":t==="read-only"?"Read only":t==="auto"?"Auto":t==="approval"?"Approval":t==="full-access"?"Full access":t==="available"?"Available":t==="unavailable"?"Unavailable":{Recommended:"Recommended","Health & capacity":"Health","Processes & services":"Processes","Files & configuration":"Files","Software & automation":"Software","Network & connectivity":"Network","Power & maintenance":"Power","Troubleshooting & recovery":"Recovery"}[t]}function xE(t,n,r){if(!r.trim())return!0;const i=r.trim().toLowerCase();return[t.title,t.prompt,t.description,t.category,t.risk,n.label,...t.keywords,...t.requiredOperations,...t.supportedPlatforms].join(" ").toLowerCase().includes(i)}function SE(t){return`permission-${t}`}function CE(t){return t==="low"?"Low risk":t==="medium"?"Medium risk":t==="high"?"High risk":"Critical risk"}function kE(t){return t==="windows"?"Windows":t==="macos"?"macOS":"Linux"}function ME({devices:t,targetMode:n,selectedIds:r,permissionMode:i,customCategories:l,onSelectPrompt:u,onClose:f}){const[h,g]=d.useState(""),[y,w]=d.useState("all"),[b,x]=d.useState(()=>Kw(Tg)),[M,k]=d.useState(()=>Kw(Rg)),[N,E]=d.useState(0),[I,T]=d.useState(""),P=d.useRef(null),U=d.useRef(null),F=d.useMemo(()=>d0.filter(ee=>ee.enabled),[]),Y=d.useMemo(()=>new Map(F.map(ee=>[ee.id,f0(ee,t,n,r,i,l)])),[l,t,i,r,n,F]),D=d.useMemo(()=>[...Y.values()].filter(ee=>ee.available).length,[Y]),K=d.useMemo(()=>t.filter(ee=>ee.connected&&(n==="all"||n==="auto"||r.includes(ee.deviceId))).length,[t,r,n]),ne=d.useMemo(()=>{const ee=F.filter(B=>xE(B,Y.get(B.id),h));return y==="recent"?b.map(B=>ee.find(L=>L.id===B)).filter(B=>!!B):y==="favorites"?M.map(B=>ee.find(L=>L.id===B)).filter(B=>!!B):y==="all"?ee:ee.filter(B=>{const L=Y.get(B.id);return y==="read-only"?L.state==="read-only":y==="auto"?L.state==="auto":y==="approval"?L.state==="approval":y==="full-access"?L.state==="full-access":y==="available"?L.available:y==="unavailable"?!L.available:B.category===y})},[Y,M,y,b,h,F]),q=d.useMemo(()=>y!=="all"?[{category:jg(y),templates:ne}]:Gw.map(ee=>({category:ee,templates:ne.filter(B=>B.category===ee)})).filter(ee=>ee.templates.length>0),[y,ne]);d.useEffect(()=>{E(ee=>Math.min(ee,Math.max(0,ne.length-1)))},[ne.length]),d.useEffect(()=>{wp(Tg,b)},[b]),d.useEffect(()=>{wp(Rg,M)},[M]),d.useEffect(()=>{U.current?.focus();const ee=L=>{L.target instanceof Node&&!P.current?.contains(L.target)&&f()},B=L=>{L.key==="Escape"&&(L.preventDefault(),f())};return document.addEventListener("pointerdown",ee),document.addEventListener("keydown",B),()=>{document.removeEventListener("pointerdown",ee),document.removeEventListener("keydown",B)}},[f]);const O=ee=>{const B=Y.get(ee.id);if(!B.available){T(B.reason||"This task is not available for the current targets and permission policy.");return}const L=[ee.id,...b.filter(oe=>oe!==ee.id)].slice(0,10);x(L),wp(Tg,L),u(ee.prompt),f()},W=ee=>{k(B=>{const L=B.includes(ee)?B.filter(oe=>oe!==ee):[ee,...B];return wp(Rg,L),L})},ce=ee=>{ee.key==="ArrowDown"?(ee.preventDefault(),E(B=>Math.min(B+1,Math.max(0,ne.length-1)))):ee.key==="ArrowUp"?(ee.preventDefault(),E(B=>Math.max(B-1,0))):ee.key==="Enter"&&ne[N]&&(ee.preventDefault(),O(ne[N]))};let $=-1;return o.jsxs("section",{className:"agents-suggested-tasks",ref:P,"aria-label":"Suggested tasks",children:[o.jsxs("header",{className:"agents-suggested-header",children:[o.jsxs("div",{children:[o.jsxs("span",{className:"agents-suggested-title",children:[o.jsx(nc,{size:15})," Suggested tasks"]}),o.jsxs("small",{children:[D," available · ",F.length," total. Choose a task, edit it, then run it."]})]}),o.jsx("button",{className:"agents-suggested-close",type:"button","aria-label":"Close suggested tasks",onClick:f,children:o.jsx(hr,{size:16})})]}),o.jsxs("label",{className:"agents-suggested-search",children:[o.jsx(rk,{size:15,"aria-hidden":"true"}),o.jsx("input",{ref:U,value:h,onChange:ee=>g(ee.target.value),onKeyDown:ce,placeholder:"Search tasks...","aria-label":"Search suggested tasks"})]}),o.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",...Gw].map(ee=>{const B=ee==="recent"?Lx:ee==="favorites"?Ug:ee==="all"?nc:ee==="available"?Ba:ee==="unavailable"?Bx:ee==="read-only"||ee==="auto"||ee==="approval"||ee==="full-access"?Na:bE[ee];return o.jsxs("button",{className:y===ee?"active":"",type:"button",title:jg(ee),"aria-label":jg(ee),"aria-pressed":y===ee,onClick:()=>{w(ee),E(0),T("")},children:[o.jsx(B,{size:12})," ",wE(ee)]},ee)})}),I&&o.jsx("div",{className:"agents-suggested-notice",role:"status",children:I}),o.jsxs("div",{className:"agents-suggested-list",role:"listbox","aria-label":"Suggested tasks",children:[q.map(ee=>o.jsxs("div",{className:"agents-suggested-group",children:[o.jsx("strong",{children:ee.category}),ee.templates.map(B=>{$+=1;const L=$===N,oe=M.includes(B.id),be=Y.get(B.id),H=be.availableDeviceIds.length+be.unsupportedDeviceIds.length||K,me=be.available?`Available on ${be.availableDeviceIds.length} of ${H} target${H===1?"":"s"}`:`Unavailable: ${be.reason||"not supported by the current targets"}`;return o.jsxs("div",{className:`agents-suggested-item ${L?"active":""} ${be.available?"":"unavailable"}`,children:[o.jsxs("button",{className:"agents-suggested-prompt",type:"button",role:"option","aria-selected":L,"aria-disabled":!be.available,onClick:()=>O(B),children:[o.jsx("span",{children:B.title}),o.jsx("small",{className:"agents-suggested-description",children:B.description}),o.jsxs("span",{className:"agents-suggested-meta",children:[o.jsx("em",{children:B.category}),o.jsx("em",{className:SE(be.state),children:be.label}),o.jsx("em",{className:`risk-${B.risk}`,children:CE(B.risk)}),o.jsx("em",{children:B.supportedPlatforms.map(kE).join(" · ")}),o.jsx("em",{className:be.available?"availability-ok":"availability-unavailable",children:me}),be.available&&be.unsupportedDeviceIds.length>0&&o.jsxs("em",{className:"availability-warning",children:["Unsupported on ",be.unsupportedDeviceIds.length]})]})]}),o.jsx("button",{className:`agents-suggested-favorite ${oe?"favorite":""}`,type:"button","aria-label":oe?`Remove ${B.title} from favorites`:`Add ${B.title} to favorites`,"aria-pressed":oe,onClick:()=>W(B.id),children:o.jsx(Ug,{size:14,fill:oe?"currentColor":"none"})})]},B.id)})]},ee.category)),ne.length===0&&o.jsx("p",{className:"agents-suggested-empty",children:"No tasks match this search or current filter."})]})]})}function AE({devices:t,mode:n,selectedIds:r,onModeChange:i,onToggle:l,permissionMode:u,onPermissionModeChange:f}){const h=t.filter(Vp),g=r.filter(y=>h.some(w=>w.deviceId===y)).length;return o.jsxs("section",{className:"agents-target-picker","aria-label":"Agent targets",children:[o.jsxs("div",{className:"agents-target-toolbar",children:[o.jsx("span",{className:"agents-section-label",children:"Targets"}),o.jsxs("div",{className:"agents-target-modes",children:[o.jsxs("button",{className:n==="all"?"active":"",onClick:()=>i("all"),type:"button",children:[o.jsx(Xf,{size:14})," All connected ",o.jsx("small",{children:h.length})]}),o.jsxs("button",{className:n==="selected"?"active":"",onClick:()=>i("selected"),type:"button",children:[o.jsx(fo,{size:14})," Selected ",g]}),o.jsxs("button",{className:n==="auto"?"active":"",onClick:()=>i("auto"),type:"button",children:[o.jsx(nc,{size:14})," Auto"]}),o.jsxs("button",{type:"button",disabled:!0,title:"Saved Client groups are coming next.",children:[o.jsx(Xf,{size:14})," Group ",o.jsx("small",{children:"Soon"})]})]}),o.jsxs("label",{className:`agents-permission-picker permission-${u}`,children:[o.jsx(Qp,{size:14}),o.jsx("span",{children:"Permission"}),o.jsxs("select",{value:u,onChange:y=>f(y.target.value),"aria-label":"Agent permission mode",children:[o.jsx("option",{value:"ask",children:"Ask"}),o.jsx("option",{value:"safe-auto",children:"Safe Auto"}),o.jsx("option",{value:"full-access",children:"Full Access"}),o.jsx("option",{value:"custom",children:"Custom"})]}),o.jsx(Hx,{size:13,"aria-hidden":"true"})]})]}),o.jsx("div",{className:"agents-target-list",children:t.length===0?o.jsx("span",{className:"agents-target-empty",children:"No Clients discovered."}):t.map(y=>{const w=Vp(y),b=n==="all"||n==="auto"?w:r.includes(y.deviceId);return o.jsxs("label",{className:`agents-target-option ${b?"selected":""} ${w?"":"offline"}`,children:[o.jsx("input",{type:"checkbox",checked:b,disabled:!w||n!=="selected",onChange:()=>l(y.deviceId)}),o.jsx("span",{className:"agents-target-icon",children:o.jsx(Ta,{size:15})}),o.jsxs("span",{children:[o.jsx("strong",{children:Gp(y)}),o.jsx("small",{children:w?"Ready":y.connected?"Agent reconnecting":"Offline"})]}),b&&o.jsx(fo,{className:"agents-target-check",size:15,"aria-hidden":"true"})]},y.deviceId)})})]})}const NE=800,Qw=5e3;function TE(){return typeof document>"u"||document.visibilityState==="visible"}function RE(t){return typeof document>"u"?()=>{}:(document.addEventListener("visibilitychange",t),()=>document.removeEventListener("visibilitychange",t))}function Yw({poll:t,onResult:n,onError:r,intervalMs:i=NE,isVisible:l=TE,subscribeVisibility:u=RE,setTimeoutImpl:f=globalThis.setTimeout.bind(globalThis),clearTimeoutImpl:h=globalThis.clearTimeout.bind(globalThis),createAbortController:g=()=>new AbortController}){if(typeof t!="function")throw new TypeError("Agent polling requires a poll function.");const y={current:null};let w=!0,b=0,x=null,M=null;const k=()=>{x!==null&&(h(x),x=null)},N=()=>{!w||!l()||x!==null||y.current||(x=f(()=>{x=null,E()},i))},E=()=>{if(!w||!l()||y.current)return y.current;const U=++b,F=g();M=F;const Y=Op(y,()=>t(F.signal));return Y.then(D=>{w&&U===b&&!F.signal.aborted&&n?.(D)},D=>{w&&U===b&&!F.signal.aborted&&r?.(D)}).finally(()=>{M===F&&(M=null),w&&l()&&N()}).catch(()=>{}),Y},I=async()=>{if(!w)throw new Error("LiveDesk Agent polling owner is closed.");k(),b+=1;const U=y.current;if(M&&!M.signal.aborted&&M.abort(new Error("LiveDesk Agent polling was superseded by an explicit refresh.")),U)try{await U}catch{}if(!(!w||!l()))return k(),E()},P=u(()=>{if(k(),!l()){b+=1,M&&!M.signal.aborted&&M.abort(new Error("LiveDesk Agent polling paused while hidden."));return}E()});return E(),{refresh:I,stop(){w&&(w=!1,b+=1,k(),P?.(),M&&!M.signal.aborted&&M.abort(new Error("LiveDesk Agent polling owner closed.")))}}}async function jE(t,n){return tt("/api/settings/agent/run",{method:"POST",body:JSON.stringify(n)},t)}async function EE(t,n,r={}){return tt(`/api/settings/agent/runs/${encodeURIComponent(n)}`,r,t)}async function DE(t,n){return tt(`/api/settings/agent/runs/${encodeURIComponent(n)}/cancel`,{method:"POST",body:JSON.stringify({})},t)}async function IE(t){return tt("/api/settings/agent/runs/cancel-all",{method:"POST",body:JSON.stringify({})},t)}async function LE(t,n,r,i){return tt(`/api/settings/agent/runs/${encodeURIComponent(n)}/approvals/${encodeURIComponent(r)}/approve`,{method:"POST",body:JSON.stringify({scope:i})},t)}async function _E(t,n,r,i="User rejected this action."){return tt(`/api/settings/agent/runs/${encodeURIComponent(n)}/approvals/${encodeURIComponent(r)}/reject`,{method:"POST",body:JSON.stringify({reason:i})},t)}async function PE(t,n,r){return tt(`/api/settings/agent/policies/${encodeURIComponent(n)}`,{method:"PUT",body:JSON.stringify({categories:r})},t)}async function FE(t,n){return tt("/api/settings/agent/summary",{method:"POST",body:JSON.stringify(n)},t)}async function OE(t,n,r={}){return tt(`/api/remote/tasks/${encodeURIComponent(n)}`,r,t)}async function HE(t,n){return tt(`/api/remote/tasks/${encodeURIComponent(n)}/cancel`,{method:"POST",body:JSON.stringify({})},t)}async function BE(t,n){return tt(`/api/remote/tasks/${encodeURIComponent(n)}/retry`,{method:"POST",body:JSON.stringify({failedOnly:!0})},t)}function ud(t){return`${t}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function Eg(t,n){const r=new Map(n.map(i=>[i.deviceId,Gp(i)]));return t.results.map(i=>({deviceId:i.deviceId,deviceName:i.deviceName||r.get(i.deviceId)||i.deviceId,status:Jj(i.status),stage:i.stage||(i.status==="running"?"Checking processes":void 0),result:i.result,data:i.data,error:i.error,sequence:Number.isSafeInteger(i.sequence)?i.sequence:0}))}function zE(t,n){const r=new Map(n.map(i=>[i.deviceId,i]));return t.map(i=>{const l=r.get(i.deviceId);return!l||l.sequence<=i.sequence?i:l})}function $E(t,n){const r=n.filter(u=>u.status==="completed"),i=n.filter(u=>u.status==="failed");if(t.operation==="process.list"){const f=`${r.filter(h=>{const g=h.result||"";return!/not running|no process/i.test(g)&&/running|online|found/i.test(g)}).length}대에서 요청한 프로세스가 실행 중입니다.`;return i.length>0?`${f}
176
+ ${i.map(h=>`${h.deviceName}는 ${h.error||"응답하지 않았습니다."}`).join(`
177
+ `)}`:f}return i.length>0?`${r.length}대 완료, ${i.length}대 실패했습니다.`:`${r.length}대 작업이 완료되었습니다.`}const UE={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 qE(t){return t==="safe-auto"?"Safe Auto":t==="full-access"?"Full Access":t==="custom"?"Custom":"Ask"}function WE(t){return t.replace(/([A-Z])/g," $1").replace(/^./,n=>n.toUpperCase())}function GE(t){const n=t instanceof Error?t.message:String(t);return/agent-disabled/i.test(n)?"Enable Codex Agent in Settings before running commands.":/agent-no-target-devices|agent-target-not-connected|device-not-connected/i.test(n)?"The selected Client is reconnecting. Wait until its Agent status is Ready and try again.":/codex-auth-required/i.test(n)?"Codex sign-in is required on the Hub. Open Settings > Agent and test the Codex connection.":n}function Xw({hubUrl:t,devices:n,launchRequest:r,variant:i="page",selectedDeviceIds:l=[]}){const u=i==="dock",[f,h]=d.useState(u?l.length>0?"selected":"auto":"all"),[g,y]=d.useState(l),[w,b]=d.useState("auto"),[x,M]=d.useState(""),[k,N]=d.useState([]),[E,I]=d.useState(""),[T,P]=d.useState(""),[U,F]=d.useState(""),[Y,D]=d.useState("safe-auto"),[K]=d.useState("custom-default"),[ne,q]=d.useState(UE),[O,W]=d.useState([]),[ce,$]=d.useState(""),[ee,B]=d.useState(!1),[L,oe]=d.useState(null),[be,H]=d.useState(!1),[me,ue]=d.useState(""),[Ce,Me]=d.useState(!1),[Ne,He]=d.useState(null),Ve=d.useRef(null),ie=d.useRef(null),Oe=d.useRef(null),$e=d.useRef(new Set),qe=d.useRef(new Set),vt=d.useRef(new Set),xe=d.useMemo(()=>n.filter(Vp).map(G=>G.deviceId),[n]),he=d.useMemo(()=>yE(d0,n,f,g,Y,ne),[ne,n,Y,g,f]);d.useEffect(()=>{u&&y(l)},[u,l]),d.useEffect(()=>{r?.deviceId&&(h("selected"),y([r.deviceId]),M(r.instruction),Me(!1),window.requestAnimationFrame(()=>{Ve.current?.focus(),Ve.current?.setSelectionRange(r.instruction.length,r.instruction.length)}))},[r]);const pe=d.useCallback(G=>{const ge=Eg(G,n);if(N(De=>De.map(z=>z.type==="task"&&z.batchId===G.batchId?{...z,states:zE(z.states,ge),status:G.status}:z)),!["running","queued"].includes(G.status)&&!$e.current.has(G.batchId)){$e.current.add(G.batchId);const De=ud("agent-summary");N(z=>[...z,{type:"agent",id:De,text:$E(G,ge)}]),G.operation&&FE(t,{instruction:G.instructionPreview,operation:G.operation,total:ge.length,completed:ge.filter(z=>z.status==="completed").length,failed:ge.filter(z=>z.status==="failed").length,results:ge.map(z=>({deviceName:z.deviceName,status:z.status,result:z.result,error:z.error}))}).then(z=>{!z.ok||!z.summary||N(ae=>ae.map(Te=>Te.type==="agent"&&Te.id===De?{...Te,text:z.summary}:Te))}).catch(()=>{}),I(z=>z===G.batchId?"":z)}},[n,t]),Ae=d.useCallback((G,ge)=>{vt.current.has(G.batchId)||(vt.current.add(G.batchId),N(De=>[...De,{type:"task",id:ud("task"),batchId:G.batchId,agentRunId:ge,operation:G.operation||"diagnostics.collect",instruction:G.instructionPreview,states:Eg(G,n),status:G.status}])),pe(G)},[n,pe]),Se=d.useCallback((G,ge)=>{for(const z of ge.taskBatches||[])Ae(z,G);W(ge.approvals||[]);const De=["running","queued","waiting-approval"].includes(ge.status);if(He(De?{runId:G,stage:ge.stage||ge.status,message:ge.progressMessage||(ge.status==="waiting-approval"?"Review the requested action to continue.":"Codex is preparing the answer.")}:z=>z?.runId===G?null:z),!De&&!qe.current.has(G)){qe.current.add(G);const z=[ge.error,ge.errorMessage].filter(Boolean).join(" — "),ae=ge.finalResponse?.trim()||(ge.status==="cancelled"?"Codex 작업을 취소했습니다.":z?`Codex 작업이 완료되지 않았습니다: ${z}`:"Codex 작업이 완료되었습니다.");N(Te=>[...Te,{type:ge.status==="failed"?"error":"agent",id:ud("agent-run-result"),text:ae}])}},[Ae]),Pe=d.useCallback(async G=>{const ge=ie.current;if(!(!ge||ge.id!==G))try{return await ge.owner.refresh()}catch(De){if(ie.current!==ge)return;throw De}},[]);d.useEffect(()=>{if(!T){ie.current=null;return}const G=T,ge=Yw({poll:z=>EE(t,G,{signal:z,timeoutMs:Qw}),onResult:z=>{Se(G,z),["running","queued","waiting-approval"].includes(z.status)||(P(ae=>ae===G?"":ae),H(!1))},onError:z=>{ue(z instanceof Error?z.message:String(z))}}),De={id:G,owner:ge};return ie.current=De,()=>{ge.stop(),ie.current===De&&(ie.current=null)}},[T,t,Se]),d.useEffect(()=>{if(!E){Oe.current=null;return}const G=E,ge=Yw({poll:z=>OE(t,G,{signal:z,timeoutMs:Qw}),onResult:z=>{pe(z),["running","queued"].includes(z.status)||I(ae=>ae===G?"":ae)},onError:z=>{ue(z instanceof Error?z.message:String(z))}}),De={id:G,owner:ge};return Oe.current=De,()=>{ge.stop(),Oe.current===De&&(Oe.current=null)}},[E,t,pe]);const Qe=async(G="",ge,De=!1)=>{const z=(G||x).trim();if(!z||E||T)return;const ae=ge||(f==="all"||f==="auto"?xe:g.filter(at=>xe.includes(at)));if(ae.length===0){ue("Select at least one connected Client.");return}if(Y==="full-access"&&!be&&!De){oe({instruction:z,targetIds:ae});return}if(N(at=>[...at,{type:"user",id:ud("user"),text:z}]),M(""),Me(!1),ue(""),ae.length===0){N(at=>[...at,{type:"error",id:ud("no-targets"),text:"연결된 대상 장비를 하나 이상 선택해 주세요."}]);return}const Ue=w==="ask"?`Read-only request. Inspect and answer without changing Client state.
178
+
179
+ ${z}`:w==="plan"?`Plan only. Produce a safe execution plan, but do not change Client state.
180
+
181
+ ${z}`:w==="execute"?`Execute this request within the configured LiveDesk approval policy.
182
+
183
+ ${z}`:z,Xe=f==="auto"?`Auto target selection is enabled. Inspect the allowed Clients and use only the most suitable target or targets for this request.
184
+
185
+ ${Ue}`:Ue;try{if(Y==="custom"){const kt=await PE(t,K,ne);if(!kt.ok)throw new Error(kt.error||"Custom Agent policy could not be saved.")}const at=await jE(t,{instruction:Xe,deviceIds:ae,permissionMode:Y,customPolicyId:K});if(!at.ok||!at.runId)throw new Error(at.error||"Codex Agent run could not be started.");W(at.approvals||[]),He({runId:at.runId,stage:at.stage||at.status||"queued",message:at.progressMessage||"Codex request queued on the Hub."}),P(at.runId)}catch(at){N(kt=>[...kt,{type:"error",id:ud("codex-run-error"),text:GE(at)}])}},Z=async(G,ge)=>{$(G.approvalId);try{const De=await LE(t,G.runId,G.approvalId,ge);if(!De.ok)throw new Error(De.error||"Agent approval could not be applied.");await Pe(G.runId)}catch(De){ue(De instanceof Error?De.message:String(De))}finally{$("")}},$t=async G=>{$(G.approvalId);try{const ge=await _E(t,G.runId,G.approvalId);if(!ge.ok)throw new Error(ge.error||"Agent approval could not be rejected.");await Pe(G.runId)}catch(ge){ue(ge instanceof Error?ge.message:String(ge))}finally{$("")}},Ee=async(G,ge)=>{F(G);try{if(ge){const z=await DE(t,ge);for(const ae of z.taskBatches||[])pe(ae);P(ae=>ae===ge?"":ae),He(ae=>ae?.runId===ge?null:ae);return}const De=await HE(t,G);pe(De),I(z=>z===G?"":z)}catch(De){ue(De instanceof Error?De.message:String(De))}finally{F("")}},Ge=async()=>{if(!(ee||!E&&!T)){B(!0);try{const G=await IE(t);if(!G.ok)throw new Error(G.error||"모든 Agent 작업을 취소하지 못했습니다.");I(""),P(""),He(null),W([]),N(ge=>ge.map(De=>De.type==="task"&&["queued","running"].includes(De.status)?{...De,status:"cancelled",states:De.states.map(z=>["queued","running"].includes(z.status)?{...z,status:"cancelled",stage:"Cancelled",error:"Cancelled by user."}:z)}:De))}catch(G){ue(G instanceof Error?G.message:String(G))}finally{B(!1)}}},ze=async G=>{F(G);try{const ge=await BE(t,G);if(!ge.ok||!ge.batch||!ge.batchId)throw new Error(ge.error||"재시도하지 못했습니다.");$e.current.delete(ge.batchId),N(De=>De.map(z=>z.type==="task"&&z.batchId===G?{...z,batchId:ge.batchId,states:Eg(ge.batch,n),status:ge.batch.status}:z)),I(ge.batchId)}catch(ge){ue(ge instanceof Error?ge.message:String(ge))}finally{F("")}},Ft=G=>{M(G),Me(!1),window.requestAnimationFrame(()=>Ve.current?.focus())},Ze=d.useMemo(()=>n.filter(Vp),[n]),nt=d.useMemo(()=>Ze.filter(G=>g.includes(G.deviceId)),[Ze,g]),lt=f==="auto"?`Auto · ${Ze.length} available`:f==="all"?`All ${Ze.length} computers`:nt.length===1?Gp(nt[0]):`${nt.length} selected`,Tt=f==="auto"?"LiveDesk chooses the best computer for each task.":f==="all"?"The Agent may coordinate every connected computer.":nt.length>0?nt.map(Gp).join(" · "):"Select one or more computers on the Wall.",Mt=f==="selected"&&nt.length===1?["Diagnose this computer","Analyze recent errors","Summarize running applications","Check disk and GPU capacity"]:f==="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"],rt=f==="selected"?nt.length>0?"What should this computer do?":"Choose a computer or use Auto.":f==="all"?"Use all your computers together.":"What should LiveDesk handle?",dt=f==="auto"?"The Hub Codex Agent can inspect the available computers and choose the best target.":"Describe the outcome. The Hub Codex Agent will plan approved commands and show progress per computer.";return o.jsxs("section",{className:`agents-page ${u?"agents-dock-console":""}`,children:[u&&o.jsxs("header",{className:"agent-console-header",children:[o.jsxs("div",{className:"agent-console-title",children:[o.jsx("span",{className:"agent-console-mark",children:o.jsx(nc,{size:16})}),o.jsxs("div",{children:[o.jsx("small",{children:"Hub Codex Agent"}),o.jsx("strong",{children:"Command Console"})]}),o.jsx("i",{children:"Ready"})]}),o.jsxs("section",{className:"agent-console-target","aria-label":"Agent target scope",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Target"}),o.jsx("strong",{children:lt}),o.jsx("small",{children:Tt})]}),o.jsxs("div",{className:"agent-console-target-modes",children:[o.jsxs("button",{className:f==="selected"?"active":"",onClick:()=>h("selected"),type:"button",children:[o.jsx(fo,{size:12})," Selected"]}),o.jsxs("button",{className:f==="all"?"active":"",onClick:()=>h("all"),type:"button",children:[o.jsx(Xf,{size:12})," All"]}),o.jsxs("button",{type:"button",disabled:!0,title:"Saved Client groups are coming next.",children:[o.jsx(Xf,{size:12})," Group"]}),o.jsxs("button",{className:f==="auto"?"active":"",onClick:()=>h("auto"),type:"button",children:[o.jsx(nc,{size:12})," Auto"]})]})]}),o.jsx("div",{className:"agent-console-interaction-modes","aria-label":"Agent interaction mode",children:["auto","ask","plan","execute"].map(G=>o.jsxs("button",{className:w===G?"active":"",onClick:()=>b(G),type:"button",children:[G==="auto"?o.jsx(nc,{size:12}):G==="execute"?o.jsx(Ta,{size:12}):null,G[0].toUpperCase()+G.slice(1)]},G))})]}),o.jsxs("div",{className:"agents-workspace",children:[(E||T)&&o.jsxs("div",{className:"agents-page-status",children:[o.jsxs("span",{children:[xe.length," Clients · ",qE(Y)]}),o.jsx("button",{type:"button",className:"agents-stop-all",onClick:()=>{Ge()},disabled:ee,children:ee?"Stopping…":"Stop all"})]}),L&&o.jsx("div",{className:"agents-permission-modal-backdrop",role:"presentation",children:o.jsxs("section",{className:"agents-permission-modal",role:"dialog","aria-modal":"true","aria-labelledby":"full-access-title",children:[o.jsx("span",{className:"agents-permission-modal-icon",children:o.jsx(Qp,{size:20})}),o.jsx("h3",{id:"full-access-title",children:"Confirm Full Access"}),o.jsx("p",{children:"Codex may change files, run commands, manage applications, and modify system state on the selected Clients. This run is still limited to the selected devices, the fixed policy, and the tool budget."}),o.jsxs("div",{className:"agents-permission-modal-actions",children:[o.jsx("button",{type:"button",onClick:()=>oe(null),children:"Cancel"}),o.jsx("button",{type:"button",className:"danger",onClick:()=>{const G=L;oe(null),H(!0),Qe(G.instruction,G.targetIds,!0)},children:"Run with Full Access"})]})]})}),me&&o.jsx("div",{className:"agents-error",role:"alert",children:me}),o.jsx(cE,{items:k,onCancel:Ee,onRetry:ze,busyBatchId:U,approvals:O,onApprove:Z,onReject:$t,busyApprovalId:ce,progress:Ne,emptyTitle:u?rt:void 0,emptyBody:u?dt:void 0}),u&&k.length===0&&!Ne&&o.jsx("div",{className:"agent-console-suggestions","aria-label":"Suggested Agent commands",children:Mt.map(G=>o.jsx("button",{type:"button",onClick:()=>Ft(G),children:G},G))}),o.jsxs("div",{className:"agents-composer-shell",children:[Ce&&o.jsx(ME,{devices:n,targetMode:f,selectedIds:g,permissionMode:Y,customCategories:ne,onSelectPrompt:Ft,onClose:()=>Me(!1)}),o.jsx(Xj,{ref:Ve,value:x,onChange:M,onSubmit:()=>{Qe()},onOpenSuggestedTasks:()=>Me(G=>!G),suggestedOpen:Ce,suggestedTaskCount:he,disabled:!!E||!!T,placeholder:u?"Tell LiveDesk what outcome you want...":void 0,compact:u})]})]}),!u&&o.jsxs("aside",{className:"agents-target-sidebar","aria-label":"Agent targets and permissions",children:[o.jsx(AE,{devices:n,mode:f,selectedIds:g,onModeChange:h,onToggle:G=>y(ge=>ge.includes(G)?ge.filter(De=>De!==G):[...ge,G]),permissionMode:Y,onPermissionModeChange:G=>{D(G),G!=="full-access"&&H(!1)}}),Y==="custom"&&o.jsxs("section",{className:"agents-custom-policy","aria-label":"Custom Agent permissions",children:[o.jsxs("div",{className:"agents-custom-policy-head",children:[o.jsxs("div",{children:[o.jsx("span",{className:"agents-section-label",children:"Custom policy"}),o.jsx("strong",{children:"Choose what Codex may do automatically."})]}),o.jsx("span",{children:"Denied actions never reach a device."})]}),o.jsx("div",{className:"agents-custom-policy-grid",children:Zj.map(G=>o.jsxs("label",{children:[o.jsx("span",{children:WE(G)}),o.jsxs("select",{value:ne[G],onChange:ge=>q(De=>({...De,[G]:ge.target.value})),children:[o.jsx("option",{value:"allow",children:"Allow automatically"}),o.jsx("option",{value:"ask",children:"Ask every time"}),o.jsx("option",{value:"deny",children:"Deny"})]})]},G))})]})]})]})}function m0(t){return{type:t.type,deviceIds:t.deviceIds,monitorIndex:t.monitorIndex,label:t.label}}async function p0(t){try{return(await t.json()).error||`${t.status} ${t.statusText}`}catch{return`${t.status} ${t.statusText}`}}async function h0(t,n,r){const i=encodeURIComponent(JSON.stringify({kind:n.kind,fileName:n.fileName,mimeType:t.type||"application/octet-stream",durationMs:n.durationMs,target:m0(n.target)})),l=await fetch(`${ho(r)}/api/captures?metadata=${i}`,{method:"POST",headers:{"Content-Type":t.type||"application/octet-stream"},body:t,cache:"no-store"});if(!l.ok)throw new Error(await p0(l));return await l.json()}async function VE(t,n){return await tt("/api/capture-sessions",{method:"POST",body:JSON.stringify({...t,target:m0(t.target)})},n)}async function KE(t,n,r,i){const l=await fetch(`${ho(i)}/api/capture-sessions/${encodeURIComponent(t)}/chunks/${n}`,{method:"PUT",headers:{"Content-Type":r.type||"application/octet-stream"},body:r,cache:"no-store"});if(!l.ok)throw new Error(await p0(l));return await l.json()}async function QE(t,n,r){return await tt(`/api/capture-sessions/${encodeURIComponent(t)}/finalize`,{method:"POST",body:JSON.stringify({durationMs:n})},r)}async function Zw(t,n){await tt(`/api/capture-sessions/${encodeURIComponent(t)}`,{method:"DELETE"},n)}async function YE(t){return await tt("/api/captures",void 0,t)}function Jw(t,n){return`${ho(n)}/api/captures/${encodeURIComponent(t)}/content`}async function XE(t,n){return await tt(`/api/captures/${encodeURIComponent(t)}`,{method:"DELETE"},n)}function ZE({hubUrl:t,onToast:n}){const[r,i]=d.useState([]),[l,u]=d.useState(!0),f=d.useCallback(async()=>{u(!0);try{i((await YE(t)).captures||[])}catch(g){n(g instanceof Error?g.message:String(g))}finally{u(!1)}},[t,n]);d.useEffect(()=>{f()},[f]);const h=async g=>{const y=Jw(g.id,t);if(navigator.share)try{await navigator.share({title:g.fileName,url:y});return}catch{}window.open(y,"_blank","noopener,noreferrer")};return o.jsxs("section",{className:"capture-gallery",children:[o.jsxs("header",{children:[o.jsxs("div",{children:[o.jsx("span",{className:"settings-eyebrow",children:"Capture Gallery"}),o.jsx("h2",{children:"Saved captures"})]}),o.jsxs("button",{className:"text-button",onClick:()=>{f()},type:"button",children:[o.jsx(bd,{size:15})," Refresh"]})]}),l?o.jsx("p",{className:"settings-help",children:"Loading captures..."}):r.length===0?o.jsx("p",{className:"settings-help",children:"No captures saved yet."}):o.jsx("div",{className:"capture-gallery-grid",children:r.map(g=>{const y=Jw(g.id,t);return o.jsxs("article",{className:"capture-gallery-card",children:[g.mimeType.startsWith("image/")?o.jsx("img",{src:y,alt:g.target.label}):o.jsx("video",{src:y,controls:!0,preload:"metadata"}),o.jsxs("div",{className:"capture-gallery-card-body",children:[o.jsx("strong",{children:g.fileName}),o.jsxs("small",{children:[g.target.label," · ",new Date(g.createdAt).toLocaleString()," · ",Math.ceil(g.sizeBytes/1024)," KB"]}),o.jsxs("div",{children:[o.jsx("button",{className:"icon-button",title:"Open","aria-label":"Open",onClick:()=>window.open(y,"_blank","noopener,noreferrer"),type:"button",children:o.jsx(lk,{size:15})}),o.jsx("a",{className:"icon-button",title:"Download","aria-label":"Download",href:`${y}?download=1`,download:g.fileName,children:o.jsx(Sv,{size:15})}),o.jsx("button",{className:"icon-button",title:"Share","aria-label":"Share",onClick:()=>{h(g)},type:"button",children:o.jsx(ck,{size:15})}),o.jsx("button",{className:"icon-button danger",title:"Delete","aria-label":"Delete",onClick:()=>{window.confirm(`Delete ${g.fileName}?`)&&XE(g.id,t).then(()=>f()).catch(w=>n(w instanceof Error?w.message:String(w)))},type:"button",children:o.jsx(Fx,{size:15})})]})]})]},g.id)})})]})}function xp(t){if(!t)return"";const n=Math.max(0,Math.floor((Date.now()-t)/1e3)),r=Math.floor(n/3600),i=Math.floor(n%3600/60),l=n%60;return r>0?`${String(r).padStart(2,"0")}:${String(i).padStart(2,"0")}:${String(l).padStart(2,"0")}`:`${String(i).padStart(2,"0")}:${String(l).padStart(2,"0")}`}function ex({controller:t,compact:n=!1,onFirstRollingUse:r,onError:i}){const{state:l,settings:u,videoSupported:f}=t,h=async b=>{try{await b()}catch(x){i?.(x instanceof Error?x.message:String(x))}},g=async()=>{if(u.rollingEnabled){t.setRollingEnabled(!1);return}(r?await r():window.confirm(`Keep the most recent 30 seconds in memory temporarily?
186
+ Nothing is saved until you press Save Last 30s.`))&&t.setRollingEnabled(!0)},y=l.recording?`Stop recording · ${xp(l.recordingStartedAt)}`:`Start recording · ${l.targetLabel}`,w=l.timelapse?`Stop timelapse · ${xp(l.timelapseStartedAt)}`:`Start timelapse · ${u.timelapseIntervalSeconds}s interval`;return o.jsxs("div",{className:`capture-toolbar ${n?"compact":""} ${l.recording?"recording-active":""}`,"aria-label":"Capture actions",children:[o.jsx("button",{className:"capture-action","aria-label":`Take screenshot · ${l.targetLabel}`,title:`Take screenshot · ${l.targetLabel}`,disabled:l.busy,onClick:()=>{h(t.takeScreenshot)},type:"button",children:o.jsx(uk,{size:17})}),o.jsx("button",{className:`capture-action ${l.recording?"active":""}`,"aria-label":y,title:y,disabled:!f||l.busy||l.timelapse,onClick:()=>{h(l.recording?t.stopRecording:t.startRecording)},type:"button",children:l.recording?o.jsxs(o.Fragment,{children:[o.jsx(yb,{size:14,fill:"currentColor"}),o.jsx("span",{children:xp(l.recordingStartedAt)})]}):o.jsx(Ox,{size:18})}),o.jsxs("button",{className:"capture-action","aria-label":l.bufferEnabled?`Save last 30 seconds · ${l.bufferSeconds}s ready`:"Enable Last 30s memory buffer",title:l.bufferEnabled?`Save last 30 seconds · ${l.bufferSeconds}s ready`:"Enable Last 30s memory buffer",disabled:!f||l.recording||l.timelapse||l.busy||l.bufferEnabled&&l.bufferSeconds<1,onClick:()=>l.bufferEnabled?void h(t.saveLast30Seconds):void g(),type:"button",children:[o.jsx(dk,{size:17}),o.jsx("small",{children:"30s"})]}),o.jsx("button",{className:`capture-action ${l.timelapse?"timelapse-active":""}`,"aria-label":w,title:w,disabled:!f||l.busy||l.recording,onClick:()=>{h(l.timelapse?t.stopTimelapse:t.startTimelapse)},type:"button",children:l.timelapse?o.jsxs(o.Fragment,{children:[o.jsx(yb,{size:14,fill:"currentColor"}),o.jsx("span",{children:xp(l.timelapseStartedAt)})]}):o.jsx(fk,{size:17})})]})}function g0({state:t}){return t==="ok"?o.jsx(Ba,{size:15,"aria-hidden":"true"}):o.jsx(Bx,{size:15,"aria-hidden":"true"})}function tx({active:t,refreshing:n,onClick:r}){return o.jsx("button",{className:`remote-status-button ${t?"active":""}`,type:"button",title:"Check Remote Status","aria-label":"Check Remote Status","aria-pressed":t,"aria-busy":n,onClick:r,children:n?o.jsx("span",{className:"remote-status-spinner","aria-hidden":"true"}):o.jsx(mk,{size:18,"aria-hidden":"true"})})}function nx({active:t,refreshing:n,onClick:r}){return o.jsx("button",{className:`remote-status-button debug-status-button ${t?"active":""}`,type:"button",title:"Check Debug Status","aria-label":"Check Debug Status","aria-pressed":t,"aria-busy":n,onClick:r,children:n?o.jsx("span",{className:"remote-status-spinner","aria-hidden":"true"}):o.jsx(Ex,{size:18,"aria-hidden":"true"})})}function ax({active:t,refreshing:n,onClick:r}){return o.jsx("button",{className:`remote-status-button hub-status-button ${t?"active":""}`,type:"button",title:"Check Hub Status","aria-label":"Check Hub Status","aria-pressed":t,"aria-busy":n,onClick:r,children:n?o.jsx("span",{className:"remote-status-spinner","aria-hidden":"true"}):o.jsx(mo,{size:18,"aria-hidden":"true"})})}function v0({items:t,mode:n="remote"}){return o.jsx("span",{className:`remote-status-lines mode-${n}`,role:"status","aria-label":n==="debug"?"Debug status":"Remote status",children:t.map(r=>o.jsxs("span",{className:`remote-status-line state-${r.state}`,title:r.detail,children:[o.jsx(g0,{state:r.state}),o.jsxs("span",{children:[o.jsx("strong",{children:r.label}),o.jsx("small",{children:r.detail})]})]},r.id))})}function JE({items:t,collectedAt:n,onClose:r}){return o.jsxs("section",{className:"remote-status-dialog hub-status-dialog",role:"dialog","aria-modal":"false","aria-labelledby":"hub-status-dialog-title",children:[o.jsxs("header",{children:[o.jsx("span",{className:"remote-status-dialog-mark","aria-hidden":"true",children:o.jsx(mo,{size:19})}),o.jsxs("span",{children:[o.jsx("small",{children:"Hub measurements"}),o.jsx("h2",{id:"hub-status-dialog-title",children:"Hub Status"})]}),o.jsx("button",{type:"button",onClick:r,title:"Close Hub status","aria-label":"Close Hub status",children:o.jsx(hr,{size:17})})]}),o.jsx("p",{children:"LiveDesk collects these Hub and browser signals continuously. This check refreshed the latest snapshot instead of starting a one-time benchmark."}),o.jsx("div",{className:"remote-status-dialog-list",children:t.map(i=>o.jsxs("article",{className:`remote-status-dialog-row state-${i.state}`,children:[o.jsx(g0,{state:i.state}),o.jsxs("span",{children:[o.jsx("strong",{children:i.label}),o.jsx("small",{children:i.detail})]})]},i.id))}),o.jsxs("footer",{children:["Checked ",new Date(n).toLocaleTimeString()]})]})}const eD=/(nvenc|videotoolbox|qsv|quick\s*sync|amf|vaapi|v4l2m2m|mediafoundation|h264_mf)/i,tD=/(libx264|openh264|software|cpu)/i,bv=2,nD=256,Xc=new Map,Nt=Object.freeze({frameAgeWarningMs:2500,networkDelayWarningMs:120,receiveRatioWarning:.62,deliveryRatioWarning:.82,decoderInputRatioWarning:.82,decoderOutputRatioWarning:.62,captureBudgetMultiplier:2.5,minimumCaptureBudgetMs:80,cpuWarningRatio:.82,memoryWarningRatio:.86,gpuWarningRatio:.92,gpuMemoryWarningRatio:.92,gpuTemperatureWarningC:85,networkUsageWarningRatio:.85,networkLatencyWarningMs:80,nativeTelemetryStaleMs:3e3,minimumClientStatusFreshMs:15e3,clientStatusFreshMultiplier:3,runtimeProcessCpuWarningRatio:.65,runtimeProcessMemoryWarningBytes:1.5*1024**3,captureHelperCpuWarningRatio:.55,captureHelperMemoryWarningBytes:1024**3,hubMinimumTotalMemoryBytes:8*1024**3,hubMinimumBrowserMemoryGb:4});function cn(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Xv(t,n){let r=t;for(const i of String(n).split(".")){if(!r||typeof r!="object")return;r=r[i]}return r}function xt(t,...n){for(const r of n){const i=Xv(t,r);if(i==null||i==="")continue;const l=Number(i);if(Number.isFinite(l))return l}}function Bt(t,...n){for(const r of n){const i=Xv(t,r);if(typeof i=="string"&&i.trim())return i.trim()}return""}function y0(t,...n){for(const r of n){const i=Xv(t,r);if(typeof i=="boolean")return i;if(i===1||i==="1"||String(i).toLowerCase()==="true")return!0;if(i===0||i==="0"||String(i).toLowerCase()==="false")return!1}}function ki(t,...n){const r=xt(t,...n);if(r!==void 0)return Math.max(0,Math.min(1,r>1?r/100:r))}function Ke(t,n,r,i){return{id:t,state:n,label:r,detail:i}}function b0(t){const n=cn(t),r=xt(n,"helperCount"),i=xt(n,"helperOwnedIoTaskCount"),l=xt(n,"helperUndisposedProcessCount"),u=xt(n,"helperOwnedExitObserverCount"),f=xt(n,"helperQuarantineCount"),h=xt(n,"utilityQuarantineCount"),g=xt(n,"utilityOwnedIoTaskCount"),y=xt(n,"utilityUndisposedProcessCount"),w=Number(xt(n,"helperDisposeFailureCount")||0),b=Number(xt(n,"utilityDisposeFailureCount")||0),x=Math.max(0,Number(r||0)),M=Number(i||0),k=Number(l||0),N=Number(u||0),E=Math.max(0,Number(f||0)),I=Math.max(0,Number(h||0)),T=Number(g||0),P=Number(y||0),U=[i,l,u,f,h,g,y].every(D=>D!==void 0),F=U&&(M<0||k<0||N<0||k!==x||N!==0||x===0&&M!==0||x>0&&M===0),Y=U&&(T<0||P<0||P!==I||T!==I*2);return{telemetryAvailable:U,helperOwnedIoTaskCount:M,helperUndisposedProcessCount:k,helperOwnedExitObserverCount:N,helperQuarantineCount:E,helperDisposeFailureCount:w,helperLastDisposeFailure:Bt(n,"helperLastDisposeFailure"),helperLedgerMismatch:F,utilityQuarantineCount:I,utilityOwnedIoTaskCount:T,utilityUndisposedProcessCount:P,utilityQuarantinePids:Array.isArray(n.utilityQuarantinePids)?n.utilityQuarantinePids.map(D=>Number(D)).filter(D=>Number.isSafeInteger(D)&&D>0):[],utilityQuarantineProfiles:Array.isArray(n.utilityQuarantineProfiles)?n.utilityQuarantineProfiles.map(D=>String(D||"").trim()).filter(Boolean).slice(0,4):[],utilityQuarantineStartCount:Math.max(0,Number(xt(n,"utilityQuarantineStartCount")||0)),utilityQuarantineStopCount:Math.max(0,Number(xt(n,"utilityQuarantineStopCount")||0)),utilityDisposeFailureCount:b,utilityLastDisposeFailure:Bt(n,"utilityLastDisposeFailure"),utilityLedgerMismatch:Y,historicalCleanupFailure:w!==0||b!==0,currentProblem:E>0||I>0||F||Y}}function w0({key:t,sampleId:n,mismatch:r}){if(!t)return{count:0,confirmed:!1};if(!r)return Xc.delete(t),{count:0,confirmed:!1};const i=String(n||"").trim();if(!i)return{count:0,confirmed:!1};const l=Qf(i),u=Xc.get(t);if(u?.sampleId===i)return{count:u.count,confirmed:u.count>=bv};const f=u&&l!==void 0&&u.sampleEpochMs!==void 0&&l>u.sampleEpochMs,h=u&&f?u.count+1:1;return!Xc.has(t)&&Xc.size>=nD&&Xc.delete(Xc.keys().next().value),Xc.set(t,{sampleId:i,sampleEpochMs:l,count:h}),{count:h,confirmed:h>=bv}}function Qf(t){const n=Date.parse(String(t||""));return Number.isFinite(n)&&n>0?n:void 0}function rx(t){return`${(Math.max(0,Number(t||0))/1024**3).toFixed(1)} GB`}function Ql(t){const n=Number(t);return Number.isFinite(n)?`${(Math.max(0,n)/1024**2).toFixed(0)} MB`:"-"}function Yl(t){const n=Number(t);return Number.isFinite(n)?`${(Math.max(0,n)*100).toFixed(1)}%`:"-"}function Sp(t){const n=Number(t);return Number.isFinite(n)?`${Math.max(0,n).toFixed(1)}%`:"-"}function aD(t){const n=String(t||"").replace(/^::ffff:/,"").trim().toLowerCase();if(!n||n==="::1"||n==="localhost"||n==="127.0.0.1"||/^10\./.test(n)||/^192\.168\./.test(n))return!0;const r=n.match(/^172\.(\d{1,3})\./);return!!r&&Number(r[1])>=16&&Number(r[1])<=31||n.startsWith("fe80:")||n.startsWith("fc")||n.startsWith("fd")}function x0(t){const n=cn(t),r=Bt(n,"controlTransport").toLowerCase();return r==="encrypted-rendezvous-relay"||/relay/.test(r)?"encrypted-rendezvous-relay":r==="direct-tcp"||/direct|tcp/.test(r)?"direct-tcp":""}function sx(t){const n=String(t||"").trim();if(!n)return"";try{return new URL(n.includes("://")?n:`relay://${n}`).host}catch{return n.replace(/[?#].*$/,"").replace(/^[a-z][a-z0-9+.-]*:\/\//i,"").split("@").pop().split("/")[0].slice(0,256)}}function rD(t){const n=x0(t);return n==="encrypted-rendezvous-relay"?Ke("control-transport","ok","Control connection: Encrypted rendezvous relay","Commands and remote input use the end-to-end encrypted rendezvous relay."):n==="direct-tcp"?Ke("control-transport","ok","Control connection: Direct TCP","Commands and remote input use the direct Hub connection."):Ke("control-transport","warning","Control connection is not identified","Waiting for Direct TCP or encrypted rendezvous relay status.")}function sD(t,n){const r=cn(t),i=cn(n),l=x0(r);if(l==="encrypted-rendezvous-relay"){const u=Bt(i,"state")||(i.connected===!0?"registered":"unknown"),f=sx(Bt(i,"endpoint"))||sx(Bt(r,"relayEndpoint")),h=r.connected!==!0||i.connected===!1||/(connecting|reconnect|failed|error|degraded|unavailable|disabled)/.test(u);return Ke("debug-control-transport",h?"warning":"ok",`Encrypted rendezvous relay control · ${u}`,[`endpoint ${f||"-"}`,`state ${u}`,`reconnect ${Math.max(0,Number(i.reconnectCount||0))}`,`handshake ${Math.max(0,Number(i.handshakeCount||0))}`,`peers ${Math.max(0,Number(i.peerCount||0))}`,Bt(i,"lastError")].filter(Boolean).join(" · "))}if(l==="direct-tcp"){const u=Bt(r,"remoteAddress"),f=xt(r,"remotePort"),h=u?`${u}${f?`:${f}`:""}`:"-";return Ke("debug-control-transport",r.connected===!0?"ok":"warning","Direct TCP control",`peer ${h} · protocol ${Bt(r,"protocol")||"-"} v${xt(r,"protocolVersion")??"-"} · input ${cn(r.channels).input===!1?"shared control channel":"dedicated channel"}`)}return Ke("debug-control-transport","warning","Control transport is not identified","No Direct TCP or encrypted rendezvous relay metadata is available.")}function S0(t,n){const r=Number(t?.browserReceivedEpochMs);return Number.isFinite(r)&&r>0?Math.max(0,n-r):Number.POSITIVE_INFINITY}function C0(t,n,r){const i=cn(n?.frameTransport),l=Bt(t,"frameTransportChangedAt"),u=Bt(i,"changedAt"),f=Qf(l),h=Qf(u),g=h!==void 0&&(f===void 0||h>f),y=g?i:t,w=g?t:i,b=Bt(t,"transport").toLowerCase(),x=Bt(y,g?"active":"frameTransportActive")||Bt(w,g?"frameTransportActive":"active"),M=Bt(y,g?"protocol":"frameTransportProtocol")||Bt(w,g?"frameTransportProtocol":"protocol"),N=(g?Bt(i,"videoTransport","activeTransport")||[x,M].filter(Boolean).join("-")||Bt(t,"videoTransport"):Bt(t,"videoTransport")||Bt(i,"videoTransport","activeTransport")||[x,M].filter(Boolean).join("-")).toLowerCase(),E=/(?:^|[-_])ws(?:$|[-_])|websocket/.test(N)||/(?:^|[-_])ws(?:$|[-_])|websocket/.test(b),T=/relay/.test(N)||/relay/.test(b)?"encrypted-relay":/p2p|udp/.test(N)||b==="udp-p2p"?"p2p-udp":/direct|tcp|ws|websocket/.test(N)||b==="binary"||E?E?"direct-ws":"direct-tcp":"",P=(Bt(y,g?"state":"frameTransportState")||Bt(w,g?"frameTransportState":"state")||(T?"active":"")).toLowerCase(),U=Bt(y,g?"reason":"frameTransportReason")||Bt(w,g?"frameTransportReason":"reason"),F=g?u||l:l||u,Y=Qf(F),D=Y===void 0?void 0:Math.max(0,r-Y),K=D===void 0?"":D<1e3?"changed now":D<6e4?`changed ${Math.round(D/1e3)}s ago`:D<36e5?`changed ${Math.round(D/6e4)}m ago`:`changed ${F}`,ne=g?i.switchCount??t?.frameTransportSwitchCount:t?.frameTransportSwitchCount??i.switchCount,q=g?i.tcpFailureCount??t?.frameTransportTcpFailureCount:t?.frameTransportTcpFailureCount??i.tcpFailureCount,O=g?typeof i.p2pReady=="boolean"?i.p2pReady:t?.frameTransportP2pReady===!0:typeof t?.frameTransportP2pReady=="boolean"?t.frameTransportP2pReady:i.p2pReady===!0;return{rawTransport:b,videoTransport:T,state:P,reason:U,changedAt:F,changedLabel:K,switchCount:Math.max(0,Number(ne??0)||0),tcpFailureCount:Math.max(0,Number(q??0)||0),p2pReady:O}}function iD(t,n,r){const i=C0(t,n,r),l=/(connecting|recovering|failed|error|degraded|unavailable)/.test(i.state);if(i.videoTransport==="encrypted-relay")return Ke("transport",l?"warning":"ok",l?"Encrypted TCP relay fallback needs attention":"Encrypted TCP relay fallback",l?`End-to-end encrypted TCP relay is ${i.state||"not ready"}; open Debug Status for the technical reason${i.changedLabel?` · ${i.changedLabel}`:""}.`:`End-to-end encrypted TCP relay fallback is active${i.changedLabel?` · ${i.changedLabel}`:""}.`);if(i.videoTransport==="p2p-udp")return Ke("transport",l?"warning":"ok",l?"P2P video connection needs attention":"P2P video connection",l?`Encrypted UDP P2P is ${i.state||"not ready"}; open Debug Status for the technical reason${i.changedLabel?` · ${i.changedLabel}`:""}.`:`Encrypted UDP P2P fallback is active${i.changedLabel?` · ${i.changedLabel}`:""}.`);if(i.videoTransport==="direct-tcp"||i.videoTransport==="direct-ws"){const u=i.videoTransport==="direct-ws"?"WebSocket":"TCP";return Ke("transport",l?"warning":"ok",l?"Direct video connection needs attention":"Direct video connection",l?`Direct ${u} to Hub is ${i.state||"not ready"}; open Debug Status for the technical reason${i.changedLabel?` · ${i.changedLabel}`:""}.`:`Direct ${u} to Hub is active${i.changedLabel?` · ${i.changedLabel}`:""}.`)}return Ke("transport","warning","Video transport is not identified",i.reason||"Waiting for Direct TCP, encrypted UDP P2P, or encrypted TCP relay transport data.")}const oD=Object.freeze(["nativeEncodeFramesInFlight","nativeEncodePendingFrameCount","nativeEncodeTimestampOwnerCount","nativeEncodeTimestampOwnerHighWatermark","nativeBackpressureCoalescedFrameCount","nativeBackpressureSkippedFrameCount","nativeEncodePendingReplacedFrameCount","nativeIdleSkippedFrameCount","nativeVideoToolboxActiveSessionCount","nativeVideoToolboxSessionHighWatermark","nativeOutputQueueDepth","nativeOutputQueueBytes","nativeOutputQueueOldestAgeMs","nativeOutputQueueHighWatermark","nativeOutputQueueDroppedCount","nativeAnnexBAccessUnitAllocationCount","nativeAnnexBPayloadCopyCount","nativeAnnexBPayloadCopiedBytes","nativeAndPipeResidenceAgeMs","pipePayloadAllocationCount","pipePayloadCopyCount","pipePayloadCopiedBytes","handoffDroppedFrameCount","handoffRecoveryKeyFrameRequestCount","handoffOldestFrameAgeMs"]);function k0(t){const r=String(t?.platformProfile||"").toLowerCase().includes("macos-screencapturekit"),i=Number(t?.nativeCaptureTelemetryVersion)>=5&&oD.every(u=>xt(t,u)!==void 0)&&typeof t?.nativeOutputQueueAwaitingKeyFrame=="boolean"&&t?.nativeCopyTelemetryAvailable===!0,l=t?.nativeCaptureTelemetryAvailable===!0&&t?.nativeCaptureResourceTelemetryAvailable===!0&&i;return{required:r,available:l,pending:Math.max(0,Number(t?.nativeEncodePendingFrameCount||0)),timestampOwners:Math.max(0,Number(t?.nativeEncodeTimestampOwnerCount||0)),timestampOwnerHighWatermark:Math.max(0,Number(t?.nativeEncodeTimestampOwnerHighWatermark||0)),coalesced:Math.max(0,Number(t?.nativeBackpressureCoalescedFrameCount||0)),pendingReplaced:Math.max(0,Number(t?.nativeEncodePendingReplacedFrameCount||0)),vtActive:Math.max(0,Number(t?.nativeVideoToolboxActiveSessionCount||0)),vtHighWatermark:Math.max(0,Number(t?.nativeVideoToolboxSessionHighWatermark||0)),outputOldestAgeMs:Math.max(0,Number(t?.nativeOutputQueueOldestAgeMs||0)),nativeAndPipeResidenceAgeMs:Math.max(0,Number(t?.nativeAndPipeResidenceAgeMs||0)),handoffDropped:Math.max(0,Number(t?.handoffDroppedFrameCount||0)),handoffRecoveryRequests:Math.max(0,Number(t?.handoffRecoveryKeyFrameRequestCount||0)),handoffOldestAgeMs:Math.max(0,Number(t?.handoffOldestFrameAgeMs||0)),annexBAllocations:Math.max(0,Number(t?.nativeAnnexBAccessUnitAllocationCount||0)),annexBPayloadCopies:Math.max(0,Number(t?.nativeAnnexBPayloadCopyCount||0)),annexBPayloadCopiedBytes:Math.max(0,Number(t?.nativeAnnexBPayloadCopiedBytes||0)),pipePayloadAllocations:Math.max(0,Number(t?.pipePayloadAllocationCount||0)),pipePayloadCopies:Math.max(0,Number(t?.pipePayloadCopyCount||0)),pipePayloadCopiedBytes:Math.max(0,Number(t?.pipePayloadCopiedBytes||0))}}function lD(t){const n=String(t?.frameMode||t?.mode||t?.codec||"").toLowerCase(),r=[t?.hardwareEncoder,t?.platformProfile].filter(Boolean).join(" · "),i=y0(t,"nativeEncoderHardwareAccelerated"),l=t?.nativeEncoderHardwareAccelerationKnown===!0||i!==void 0,u=k0(t);return!t||!/h264/.test(n)?Ke("encoder","warning","Video encoder unavailable","Waiting for an H.264 frame."):u.required&&!u.available?Ke("encoder","warning","H.264 encoder resource status is unavailable",`${r||"Native encoder"} has not provided complete VideoToolbox v5 ownership, queue, and copy telemetry.`):u.required&&(u.vtActive!==1||u.vtHighWatermark>1||u.timestampOwners>2||u.timestampOwnerHighWatermark>2)?Ke("encoder","warning","VideoToolbox encoder ownership needs attention",`${u.vtActive} active session(s); high-water ${u.vtHighWatermark}; timestamp owners ${u.timestampOwners}/2 (HWM ${u.timestampOwnerHighWatermark})`):u.required&&u.coalesced>0?Ke("encoder","warning","Hardware H.264 encoding is under load",`${u.coalesced} current-window frame(s) were coalesced while the encoder was busy.`):l&&i===!1?Ke("encoder","warning","H.264 hardware acceleration is not active",`${r||"Native encoder"} is running without confirmed hardware acceleration.`):l&&i===!0?Ke("encoder","ok","Hardware H.264 encoding",`${r||"Native encoder"} · hardware acceleration confirmed`):eD.test(r)?Ke("encoder","ok","Hardware H.264 encoding",r):tD.test(r)?Ke("encoder","warning","Software H.264 encoding",`${r||"CPU encoder"} may limit frame rate.`):Ke("encoder","warning","H.264 encoder not identified",r||"The Client has not reported its active encoder profile.")}function cD({device:t,frame:n,receiveStat:r,paintStat:i,codec:l,selectedMonitorIndex:u=0,control:f=!1,controlInputReady:h=!1,controlBinding:g,hubRelay:y,capturePaused:w=!1,capturePauseConfirmed:b=!0,capturePauseError:x="",clientHeartbeatMs:M=5e3,now:k=Date.now()}={}){const N=cn(t),E=cn(N.status),I=cn(i?.lastInfo),T=[],P=S0(n,k);T.push(rD(N)),T.push(w?b?Ke("connection","ok","Video capture is paused","Client screen capture and video encoder shutdown were confirmed by the Client."):Ke("connection","warning","Video stop needs attention",String(x||"The Hub is blocking video restart, but the Client did not confirm screen capture and video encoder shutdown.")):N.connected===!0&&P<=Nt.frameAgeWarningMs?Ke("connection","ok","Video connection is current",`${Math.round(P)}ms since the latest frame.`):Ke("connection","warning",N.connected===!0?"Video frame is stale":"Client is offline",N.connected===!0&&Number.isFinite(P)?`${Math.round(P)}ms since the latest frame.`:String(N.lastDisconnectReason||"No current Client session."))),T.push(iD(n,E,k)),T.push(lD(n));const U=b0(E.capture),F=cn(E.capture),Y=w0({key:`${String(N.deviceId||N.id||"")}:capture-cleanup`,sampleId:Bt(F,"sampledAt"),mismatch:U.helperLedgerMismatch||U.utilityLedgerMismatch});(U.helperQuarantineCount>0||U.utilityQuarantineCount>0||Y.confirmed)&&T.push(Ke("capture-cleanup","warning","Video capture cleanup needs attention",`capture quarantine ${U.helperQuarantineCount} · utility quarantine ${U.utilityQuarantineCount} · owned I/O ${U.helperOwnedIoTaskCount+U.utilityOwnedIoTaskCount} · exit observers ${U.helperOwnedExitObserverCount} · undisposed processes ${U.helperUndisposedProcessCount+U.utilityUndisposedProcessCount}`));const D=Math.max(0,Number(n?.requestedFps||n?.effectiveFps||0)),K=Math.max(0,Number(r?.framesPerSecond||0));Math.max(0,Number(n?.sourceGapMs||0));const ne=Math.max(0,Number(n?.nativeCaptureFps||0)),q=Math.max(0,Number(n?.nativeEncodedFps||0)),O=Math.max(0,Number(n?.nativeCaptureSampleCount||0)),W=Math.max(0,Number(n?.nativeCaptureTelemetryVersion||0)),ce=xt(n,"nativeCaptureTelemetryAgeMs"),ee=Math.max(0,Number(ce||0))+(Number.isFinite(P)?P:0),B=W<2||ce!==void 0&&ee<=Nt.nativeTelemetryStaleMs,L=Math.max(0,Number(n?.nativeBackpressureSkippedFrameCount||0)),oe=Math.max(0,Number(n?.nativeIdleSkippedFrameCount||0)),be=n?.nativeCaptureTelemetryAvailable===!0&&O>0&&B,H=xt(n,"captureP95Ms","captureAverageMs","captureStageMs"),me=Math.max(0,Number(H||0)),ue=n?.captureTimingAvailable===!0&&D>0&&Number(r?.sampleMs||0)>0&&H!==void 0,Ce=ue||be,Me=Math.max(Nt.minimumCaptureBudgetMs,D>0?1e3/D*Nt.captureBudgetMultiplier:0),Ne=D>0?1e3/D:100,He=D>0&&ne>=D*Nt.receiveRatioWarning,Ve=q>0&&q<D*Nt.receiveRatioWarning,ie=be&&He&&Ve&&q>=1&&oe>=Math.max(10,ne*.6)&&L===0,Oe=be&&D>0&&(ne<D*Nt.receiveRatioWarning||!ie&&q>0&&q<D*Nt.receiveRatioWarning),$e=be?Oe:ue&&me>Me;T.push(Ce?$e?Ke("capture","warning","Screen capture cannot keep target speed",be?`${ne.toFixed(1)} native capture · ${q.toFixed(1)} encoded · ${D||"?"} requested fps`:`${me?`capture p95 ${Math.round(me)}ms`:"capture timing unavailable"} · ${K.toFixed(1)}/${D||"?"} fps`):Ke("capture","ok","Screen capture speed is healthy",be?`${ne.toFixed(1)} native capture · ${q.toFixed(1)} encoded · ${D||"?"} requested fps${ie?" · idle optimized":""}`:`${me?`capture p95 ${Math.round(me)}ms`:"no slow capture reported"}${D?` · ${K.toFixed(1)}/${D} fps`:""}`):Ke("capture","warning","Screen capture data is still collecting","A current frame-rate and capture-time sample is required."));const qe=xt(n,"hubPacketTransitAgeMs"),vt=Math.max(0,Number(qe||0)),xe=Math.max(0,Number(n?.agentSendGapMs||0)),he=Math.max(0,Number(n?.agentSendDurationMs||0)),pe=!aD(N.remoteAddress),Ae=ki(E,"network.usageRatio"),Se=xt(E,"network.latencyMs"),Pe=(Ae??0)>=Nt.networkUsageWarningRatio||(Se??0)>=Nt.networkLatencyWarningMs,Qe=n?.hubClientQueueTelemetryAvailable===!0||xt(n,"hubClientDropped")!==void 0&&xt(n,"hubClientQueueDepth")!==void 0&&xt(n,"hubClientQueueLimit")!==void 0&&xt(n,"hubClientBufferedBytes")!==void 0,Z=Qe?Math.max(0,Number(n?.hubClientQueueDepth||0)):0,$t=Qe?Math.max(0,Number(n?.hubClientQueueLimit||0)):0,Ee=Qe&&$t>0&&Z>=$t,Ge=qe!==void 0&&Number(r?.sampleMs||0)>0,ze=!ie&&D>0&&Number(r?.sampleMs||0)>0&&K<D*Nt.deliveryRatioWarning,Ft=!ie&&xe>Math.max(Nt.networkDelayWarningMs,Ne*3),Ze=vt>Nt.networkDelayWarningMs||Ft||he>Nt.networkDelayWarningMs||ze||P>Nt.frameAgeWarningMs||Pe||Ee;T.push(Ge?Ze||pe?Ke("network","warning",pe?"External network route may add delay":Pe?"Client network adapter needs attention":Ee?"Hub browser video queue needs attention":"Video delivery is uneven",[vt?`${Math.round(vt)}ms Hub-to-browser`:"",xe?`${Math.round(xe)}ms Client send gap`:"",he?`${Math.round(he)}ms Client send time`:"",ze?`${K.toFixed(1)} of ${D} requested fps`:"",Se!==void 0?`${Math.round(Se)}ms Client network latency`:"",Ae!==void 0?`${Math.round(Ae*100)}% Client link use`:"",Qe&&$t>0?`Hub queue ${Z}/${$t}`:"",pe?String(N.remoteAddress||"external route"):""].filter(Boolean).join(" · ")||"Frame delivery is not current."):Ke("network","ok","Network delivery is healthy",`${Math.round(vt)}ms Hub-to-browser · ${ie?`idle optimized at ${q.toFixed(1)} fps`:"the current video rate is on target."}`):Ke("network","warning","Network delivery data is still collecting","A calibrated Hub-to-browser transit sample is required."));const nt=ki(E,"cpu.usageRatio","cpu.usedRatio","cpu.percent"),lt=ki(E,"memory.usedRatio","usedMemRatio"),Tt=ki(E,"gpu.usageRatio"),Mt=ki(E,"gpu.memory.usedRatio"),rt=xt(E,"gpu.temperatureC","thermal.gpuC"),dt=nt!==void 0&&lt!==void 0,G=Qf(N.lastStatusAt),ge=G===void 0?Number.POSITIVE_INFINITY:Math.max(0,k-G),De=Math.max(Nt.minimumClientStatusFreshMs,Math.max(1e3,Number(M||0))*Nt.clientStatusFreshMultiplier),z=ge<=De,ae=(nt??0)>=Nt.cpuWarningRatio||(lt??0)>=Nt.memoryWarningRatio||(Tt??0)>=Nt.gpuWarningRatio||(Mt??0)>=Nt.gpuMemoryWarningRatio||(rt??0)>=Nt.gpuTemperatureWarningC;T.push(dt?z?ae?Ke("computer","warning",(Tt??0)>=Nt.gpuWarningRatio||(Mt??0)>=Nt.gpuMemoryWarningRatio||(rt??0)>=Nt.gpuTemperatureWarningC?"Client GPU is under load":"Client computer is under load",[`CPU ${Math.round(nt*100)}%`,`memory ${Math.round(lt*100)}%`,Tt!==void 0?`GPU ${Math.round(Tt*100)}%`:"",Mt!==void 0?`GPU memory ${Math.round(Mt*100)}%`:"",rt!==void 0?`GPU ${Math.round(rt)}C`:""].filter(Boolean).join(" · ")):Ke("computer","ok","Client computer has working capacity",[`CPU ${Math.round(nt*100)}%`,`memory ${Math.round(lt*100)}%`,Tt!==void 0?`GPU ${Math.round(Tt*100)}%`:""].filter(Boolean).join(" · ")):Ke("computer","warning","Client performance snapshot is stale",Number.isFinite(ge)?`The latest CPU and memory report is ${Math.round(ge/1e3)} seconds old.`:"No current Client performance heartbeat has been received."):Ke("computer","warning","Client performance data is unavailable","CPU and memory telemetry have not been reported yet."));const Te=Number(n?.monitorIndex),Ue=Number.isInteger(Te)&&Te===Number(u),Xe=cn(N.channels),at=cn(N.capabilities),kt=Xe.input!==!1&&at.remoteInput!==!1&&at.accessibilityPermission!==!1,At=at.screenRecordingPermission!==!1,Ut=cn(g),Qt=!f||String(n?.sessionId||"")&&String(n?.sessionId||"")===String(Ut.sessionId||"")&&String(n?.commandId||"")&&String(n?.commandId||"")===String(Ut.commandId||"")&&Number(n?.captureGeneration||0)>0&&Number(n?.captureGeneration||0)===Number(Ut.captureGeneration||0)&&Number(n?.monitorIndex)===Number(Ut.monitorIndex),sa=!f||h&&Qt;T.push(Ue&&sa&&kt&&At?Ke("display","ok",f?"Display and remote input are bound":"Display and remote input are available",`Display ${Number(u)+1} · generation ${Number(n?.captureGeneration||0)||"current"}.`):Ke("display","warning",At?kt?f?"Remote input is not bound to this display":"Waiting for the selected display":"Remote input permission is missing":"Screen capture permission is missing",`Selected display ${Number(u)+1}; latest frame ${Number.isInteger(Te)?Te+1:"not available"}.`));const Ra=cn(l),Pn=Array.isArray(Ra.canvases)?cn(Ra.canvases[0]):{},$n=Math.max(0,Number(i?.decoderInputFps||0)),ia=Math.max(0,Number(i?.decoderOutputFps||0)),Fe=$n>0&&Number(i?.sampleMs||r?.sampleMs||0)>0,Je=K>0&&Number(r?.sampleMs||0)>0&&Number(i?.sampleMs||0)>0&&$n<K*Nt.decoderInputRatioWarning,gt=$n>0?ia/$n:0,nn=Bt(Pn,"configuredAcceleration","requestedAcceleration")||Bt(I,"h264DecodeAcceleration"),Sn=Bt(Pn,"softwareFallbackReason"),Ms=!!Sn||nn==="prefer-software";return T.push(Je?Ke("decoder","warning","Browser decoder input is dropping frames",`${K.toFixed(1)} received / ${$n.toFixed(1)} decoder input / ${ia.toFixed(1)} output fps.`):Fe?Ms||gt<Nt.decoderOutputRatioWarning?Ke("decoder","warning",Ms?"Browser is using software H.264 fallback":"Browser decoder output is slow",`${Sn||String(I.decoderLabel||nn||"decoder")} · ${$n.toFixed(1)} in / ${ia.toFixed(1)} out fps.`):Ke("decoder","ok",nn==="prefer-hardware"?"Browser requests hardware H.264":"Browser H.264 path is responsive",`${$n.toFixed(1)} in / ${ia.toFixed(1)} out fps. Chrome does not expose definitive hardware acceptance.`):Ke("decoder","warning","Browser decoder data is still collecting","Decoder input and output samples are required before this path can be marked healthy.")),T}function lo(t){const n=String(t||"").trim();return n?n.length<=14?n:`${n.slice(0,6)}…${n.slice(-5)}`:"-"}function xn(t,n=1){const r=Number(t);return Number.isFinite(r)?r.toFixed(n):"-"}function uD({device:t,frame:n,receiveStat:r,paintStat:i,codec:l,selectedMonitorIndex:u=0,control:f=!1,controlInputReady:h=!1,controlBinding:g,hubRelay:y,now:w=Date.now()}={}){const b=cn(t),x=cn(b.status),M=cn(x.runtimeProcess),k=cn(x.capture),N=b0(k),E=cn(g),I=cn(i?.lastInfo),T=cn(l),P=Array.isArray(T.canvases)?cn(T.canvases[0]):{},U=[],F=Number(u),Y=Number(n?.monitorIndex),D=Number.isInteger(Y)&&Y===F,K=Number(n?.captureGeneration||0),ne=Number(E.captureGeneration||0),q=!f||D&&String(n?.sessionId||"")===String(E.sessionId||"")&&String(n?.commandId||"")===String(E.commandId||"")&&K>0&&K===ne,O=Math.max(0,Number(n?.requestedFps||n?.effectiveFps||0)),W=Math.max(0,Number(r?.framesPerSecond||0)),ce=Math.max(0,Number(i?.framesPerSecond||0)),$=Math.max(0,Number(i?.decoderInputFps||0)),ee=Math.max(0,Number(i?.decoderOutputFps||0)),B=Number(r?.sampleMs||0)>0&&Number(i?.sampleMs||0)>0,L=O>0&&B&&Math.min(W,ce||W,ee||W)<O*Nt.deliveryRatioWarning,oe=Math.max(0,Number(n?.sourceGapMs||0)),be=Math.max(0,Number(n?.agentSendGapMs||0)),H=Math.max(0,Number(n?.agentSendDurationMs||0)),me=Math.max(0,Number(n?.agentSendDurationFrameSeq||0)),ue=Math.max(0,Number(n?.agentQueueBeforePaceMs||0)),Ce=Math.max(0,Number(n?.agentFrameAgeMs||0)),Me=xt(n,"hubPacketTransitAgeMs"),Ne=Math.max(0,Number(n?.droppedByAgent||0)),He=Math.max(0,Number(n?.hubIngressDropped||0)),Ve=n?.hubClientQueueTelemetryAvailable===!0||xt(n,"hubClientDropped")!==void 0&&xt(n,"hubClientQueueDepth")!==void 0&&xt(n,"hubClientQueueLimit")!==void 0&&xt(n,"hubClientBufferedBytes")!==void 0,ie=Ve?Math.max(0,Number(n?.hubClientDropped||0)):0,Oe=Ve?Math.max(0,Number(n?.hubClientQueueDepth||0)):0,$e=Ve?Math.max(0,Number(n?.hubClientQueueLimit||0)):0,qe=Ve?Math.max(0,Number(n?.hubClientBufferedBytes||0)):0,vt=Math.max(0,Number(n?.udpIncompleteFrames||0)),xe=Ne+He+ie,he=S0(n,w),pe=Bt(P,"configuredAcceleration","requestedAcceleration")||Bt(I,"h264DecodeAcceleration"),Ae=Bt(P,"softwareFallbackReason"),Se=Math.max(0,Number(T.hardwareReleaseGeneration||0)),Pe=Math.max(0,Number(T.hardwareRecoveryProbeCount||0)),Qe=Number(T.lastHardwareRecoveryProbeAt),Z=Number.isFinite(Qe)&&Qe>0?Math.max(0,w-Qe):void 0,$t=`hardware releases ${Se} · recovery probes ${Pe} · last probe ${Z===void 0?"-":`${Math.round(Z)}ms ago`}`,Ee=B&&W>0&&$<W*Nt.decoderInputRatioWarning,Ge=C0(n,x,w),ze=Bt(b,"deviceId")||Bt(n,"deviceId"),Ft=Bt(n,"sessionId")||Bt(b,"sessionId"),Ze=Bt(b,"productVersion")||Bt(x,"productVersion","runtime.productVersion"),nt=Bt(b,"agentVersion")||Bt(x,"agentVersion","runtime.agentVersion"),lt=xt(b,"pid","runtimePid")??xt(x,"pid","runtimePid","process.pid"),Tt=xt(M,"pid"),Mt=ki(M,"cpuUsageRatio"),rt=xt(M,"cpuCorePercent"),dt=xt(M,"workingSetBytes"),G=xt(M,"privateMemoryBytes"),ge=Math.max(dt||0,G||0),De=(Tt??0)>0&&(dt??0)>0,z=De&&(lt??0)>0&&Tt!==lt,ae=(Mt??0)>=Nt.runtimeProcessCpuWarningRatio||ge>=Nt.runtimeProcessMemoryWarningBytes,Te=ki(x,"cpu.usageRatio"),Ue=ki(x,"memory.usedRatio","usedMemRatio"),Xe=Math.max(0,Number(xt(k,"videoStreamCount")||0)),at=Math.max(0,Number(xt(k,"audioStreamCount")||0)),kt=xt(k,"helperCount"),At=Math.max(0,Number(kt||0)),Ut=xt(k,"helperMaxConcurrent"),Qt=Math.max(At,Number(Ut||0)),sa=Array.isArray(k.helperPids)?k.helperPids.map(oa=>Number(oa)).filter(oa=>Number.isSafeInteger(oa)&&oa>0):[],Ra=Array.isArray(k.helperProfiles)?k.helperProfiles.map(oa=>String(oa||"").trim()).filter(Boolean).slice(0,4):[],Pn=ki(k,"helperCpuUsageRatio"),$n=xt(k,"helperCpuCorePercent"),ia=xt(k,"helperWorkingSetBytes"),Fe=xt(k,"helperPrivateMemoryBytes"),V=Math.max(ia||0,Fe||0),Je=Math.max(0,Number(xt(k,"helperStartCount")||0)),gt=Math.max(0,Number(xt(k,"helperStopCount")||0)),nn=kt!==void 0,Sn=nn&&Je>=gt&&Je-gt!==At,Ms=At>1||Qt>1||Xe>1||Sn||N.currentProblem,qa=nn&&(Xe>0&&At===0||Xe===0&&At>0),fe=w0({key:ze&&Ft?`${ze}:${Ft}`:"",sampleId:Bt(k,"sampledAt"),mismatch:qa}),_e=qa&&!fe.confirmed,et=Ms||fe.confirmed,Rt=(Pn??0)>=Nt.captureHelperCpuWarningRatio||V>=Nt.captureHelperMemoryWarningBytes,An=!!(ze&&Ft&&Ze&&nt&&(lt??0)>0),Et=n?.nativeCaptureTelemetryAvailable===!0,ct=Math.max(0,Number(n?.nativeCaptureTelemetryVersion||0)),jt=ct>=2,mt=k0(n),Yt=!mt.required||mt.available,fn=xt(n,"nativeCaptureTelemetryAgeMs"),Rn=Math.max(0,Number(fn||0))+(Number.isFinite(he)?he:0),Wt=fn===void 0?"-":`${Math.round(Rn)}ms`,jr=!jt||fn!==void 0&&Rn<=Nt.nativeTelemetryStaleMs,Ks=Et&&!jr,Nn=y0(n,"nativeEncoderHardwareAccelerated"),Un=n?.nativeEncoderHardwareAccelerationKnown===!0||Nn!==void 0,Ni=Bt(n,"nativeEncoderHardwareQueryStatus"),Ja=Ni==="0"?"confirmed":Ni,Er=Math.max(0,Number(n?.nativeCaptureDisplayId||0)),jn=Math.max(0,Number(n?.nativeCaptureFps||0)),Dr=Math.max(0,Number(n?.nativeCompressionOutputCount||0)),In=Math.max(0,Number(n?.nativeCompressionFps||0)),ea=Math.max(0,Number(n?.nativeEncodedFps||0)),en=jt||Dr>0?In:ea,Qs=Math.max(0,Number(n?.nativeCaptureSampleCount||0)),Ys=Math.max(0,Number(n?.nativeEncodableFrameCount||0)),As=Math.max(0,Number(n?.nativeSkippedFrameCount||0)),lc=Math.max(0,Number(n?.nativeEncodedFrameCount||0)),Xr=Math.max(0,Number(n?.nativeEncodeFramesInFlight||0)),Ir=mt.pending,Ln=mt.timestampOwners,vo=mt.timestampOwnerHighWatermark,Zr=mt.coalesced,Ti=Math.max(0,Number(n?.nativeBackpressureSkippedFrameCount||0)),Jr=mt.pendingReplaced,es=Math.max(0,Number(n?.nativeIdleSkippedFrameCount||0)),mu=mt.vtActive,Ri=mt.vtHighWatermark,Xs=Math.max(0,Number(n?.nativeOutputQueueDepth||0)),sl=Math.max(0,Number(n?.nativeOutputQueueBytes||0)),St=mt.outputOldestAgeMs,qn=Math.max(0,Number(n?.nativeOutputQueueHighWatermark||0)),il=Math.max(0,Number(n?.nativeOutputQueueDroppedCount||0)),rn=n?.nativeOutputQueueAwaitingKeyFrame===!0,Zs=mt.nativeAndPipeResidenceAgeMs,vr=mt.handoffDropped,Ns=mt.handoffRecoveryRequests,yo=mt.handoffOldestAgeMs,Ot=Xr>2||Ir>1||Ln>2||vo>2||Zr>0||Xr>=2&&Ti>0,Wn=mt.required&&mt.available&&(mu!==1||Ri>1||Ln>2||vo>2),bo=Xs>=3||sl>=6*1024*1024||St>120||il>0||rn||Zs>250||vr>0||Ns>0||yo>120,Js=`in-flight ${Xr}/2 · backpressure skipped ${Ti} · idle skipped ${es} · stdout queue ${Xs} AU/${Math.round(sl/1024)} KB/${Math.round(St)}ms · HWM ${qn} · dropped ${il} · awaiting key ${rn?"yes":"no"} · native+pipe ${Math.round(Zs)}ms · handoff ${Math.round(yo)}ms/drop ${vr}/recovery ${Ns}`,ta=`pending ${Ir}/1; timestamp owners ${Ln}/2 (HWM ${vo}); coalesced ${Zr}; pending replaced ${Jr}; VideoToolbox ${mu} active/HWM ${Ri}`,Ts=mt.available&&mt.annexBAllocations>0&&mt.annexBPayloadCopies>=mt.annexBAllocations&&mt.annexBPayloadCopiedBytes>0&&mt.pipePayloadAllocations>0&&mt.pipePayloadCopies>=mt.pipePayloadAllocations&&mt.pipePayloadCopiedBytes>0,ja=`Annex-B allocation/copy ${mt.annexBAllocations}/${mt.annexBPayloadCopies} (${Math.round(mt.annexBPayloadCopiedBytes/1024)} KB) · pipe allocation/read ${mt.pipePayloadAllocations}/${mt.pipePayloadCopies} (${Math.round(mt.pipePayloadCopiedBytes/1024)} KB)`,ts=Et&&Qs>0&&jr,wo=O>0?1e3/O:100,Rs=O>0&&jn>=O*Nt.receiveRatioWarning,cc=en>0&&en<O*Nt.receiveRatioWarning,Lr=ts&&Rs&&cc&&en>=1&&ea>=1&&es>=Math.max(10,jn*.6)&&Ti===0,pu=L&&!Lr,ol=!Lr&&be>Math.max(Nt.networkDelayWarningMs,wo*3),ji=ts&&O>0&&jn<O*Nt.receiveRatioWarning,ei=ts&&!Lr&&jn>0&&(jt&&en<=0||en>0&&en<jn*Nt.receiveRatioWarning),Ht=ts&&Dr>0&&en>0&&ea<en*Nt.receiveRatioWarning,Fn=Ks?"Native capture telemetry is stale":Yt?Wn?"VideoToolbox encoder ownership needs attention":ts?ji?"Native screen capture is below request":ei||Ot?"VideoToolbox compression is behind capture":Ht||bo?"Native stdout delivery is backpressured":Nn===!1?"Native hardware encoder is unavailable":"Native capture or encoder needs attention":"Native capture telemetry is unavailable":"Native encoder resource telemetry is unavailable";U.push(sD(b,y)),U.push(An?Ke("debug-runtime","ok",`LiveDesk ${Ze} · Agent ${nt}`,`pid ${lt} · session ${lo(Ft)} · device ${lo(ze)}`):Ke("debug-runtime","warning","Runtime identity is incomplete",`LiveDesk ${Ze||"-"} · Agent ${nt||"-"} · pid ${lt??"-"} · session ${lo(Ft)} · device ${lo(ze)}`)),U.push(De&&!z&&!ae?Ke("debug-process-load","ok","RemoteFast process load is healthy",`pid ${Tt} · CPU ${Yl(Mt)} machine / ${Sp(rt)} core · RSS ${Ql(dt)} · private ${Ql(G)} · system CPU ${Yl(Te)} · memory ${Yl(Ue)}`):Ke("debug-process-load","warning",De?z?"RemoteFast process identity does not match":"RemoteFast process load needs attention":"RemoteFast process telemetry is collecting",`runtime pid ${Tt??"-"} · reported pid ${lt??"-"} · CPU ${Yl(Mt)} machine / ${Sp(rt)} core · RSS ${Ql(dt)} · private ${Ql(G)} · system CPU ${Yl(Te)} · memory ${Yl(Ue)}`)),U.push(n?Ke("debug-frame","ok",`Frame #${Number(n.frameSeq||0)} · ${String(n.streamPurpose||(f?"control":"wall"))}`,`stream ${lo(n.streamId)} · ${n.width||0}x${n.height||0} · ${Math.round(Number(n.byteLength||0)/1024)} KB · age ${Number.isFinite(he)?Math.round(he):"-"}ms`):Ke("debug-frame","warning","No current frame",`Device ${lo(b.deviceId)} has not produced a frame.`));const er=/(connecting|recovering|failed|error|degraded|unavailable)/.test(Ge.state);U.push(Ge.videoTransport&&!er?Ke("debug-transport","ok",`${Ge.videoTransport==="encrypted-relay"?"Encrypted TCP relay fallback":Ge.videoTransport==="p2p-udp"?"P2P UDP":Ge.videoTransport==="direct-ws"?"Direct WebSocket":"Direct TCP"} · ${Ge.state||"active"}`,[`raw ${Ge.rawTransport||"-"}`,`P2P ${Ge.p2pReady?"ready":"standby unavailable"}`,`switch ${Ge.switchCount}`,`TCP failure ${Ge.tcpFailureCount}`,Ge.changedLabel,Ge.reason].filter(Boolean).join(" · ")):Ke("debug-transport","warning",Ge.videoTransport?`Video transport ${Ge.state||"needs attention"}`:"Video transport is not identified",[Ge.videoTransport||"no active path",`raw ${Ge.rawTransport||"-"}`,`P2P ${Ge.p2pReady?"ready":"not ready"}`,Ge.changedLabel,Ge.reason].filter(Boolean).join(" · "))),U.push(D?Ke("debug-monitor","ok",`Monitor selected ${F+1} · frame ${Y+1}`,`reported ${Number(n?.monitorCount||0)||"?"} displays · generation ${K||"-"}`):Ke("debug-monitor","warning",`Monitor mismatch: selected ${F+1} · frame ${Number.isInteger(Y)?Y+1:"-"}`,`reported ${Number(n?.monitorCount||0)||"?"} displays · generation ${K||"-"}`)),U.push(q&&(!f||h)?Ke("debug-binding","ok",f?"Control generation is bound":"Wall capture generation is current",`session ${lo(n?.sessionId)} · command ${lo(n?.commandId)} · generation ${K||"-"}`):Ke("debug-binding","warning",f?"Control generation is not bound":"Wall capture generation is unavailable",`frame ${lo(n?.commandId)}/${K||"-"} · expected ${lo(E.commandId)}/${ne||"-"} · input ${h?"ready":"waiting"}`)),U.push(B&&!pu?Ke("debug-cadence","ok",`Cadence ${xn(W)} rx · ${xn(ce)} paint · ${xn(ee)} decode`,`requested ${xn(O)} · decoder input ${xn($)} fps · receive p95 ${xn(r?.p95IntervalMs)}ms${Lr?" · idle optimized":""}`):Ke("debug-cadence","warning",B?"Frame cadence is below request":"Frame cadence sample is collecting",`requested ${xn(O)} · receive ${xn(W)} · paint ${xn(ce)} · decode ${xn(ee)} fps`)),U.push(ts&&Yt&&!ji&&!ei&&!Ht&&!Ot&&!Wn&&!bo&&Nn!==!1?Ke("debug-native-capture","ok",`Native capture ${xn(jn)} fps · compress ${xn(en)} fps · stdout ${xn(ea)} fps${Lr?" · idle optimized":""}`,`telemetry v${ct||1} · age ${Wt} · hardware ${Un?Nn?"yes":"no":"unknown"}${Ja?` (${Ja})`:""} · display ${Er||"-"} · capture samples ${Qs} · encodable ${Ys} · skipped ${As} · compression outputs ${Dr} · stdout written ${lc} · ${Js} · encoded AU output gap ${Math.round(oe)}ms`):Ke("debug-native-capture","warning",Fn,`telemetry ${Et?`v${ct||1}`:"no"} · age ${Wt} · hardware ${Un?Nn?"yes":"no":"unknown"}${Ja?` (${Ja})`:""} · display ${Er||"-"} · capture ${xn(jn)} fps · compress ${xn(en)} fps · stdout ${xn(ea)} fps · capture samples ${Qs} · encodable ${Ys} · skipped ${As} · compression outputs ${Dr} · stdout written ${lc} · ${Js} · encoded AU output gap ${Math.round(oe)}ms`)),mt.required&&(U.push(Yt&&!Ot&&!Wn?Ke("debug-native-resource","ok","VideoToolbox resource ownership is bounded",ta):Ke("debug-native-resource","warning",Yt?Wn?"VideoToolbox session ownership is not exclusive":"VideoToolbox encode lane is coalescing":"VideoToolbox resource telemetry is unavailable",ta)),U.push(Yt&&Ts?Ke("debug-native-copy","ok","Capture copy accounting is current",ja):Ke("debug-native-copy","warning",Yt?"Capture copy accounting needs attention":"Capture copy accounting is unavailable",ja))),U.push(nn&&!et&&!Rt?Ke("debug-capture-ownership","ok",_e?"Capture ownership transition is settling":At>0?"Capture helper ownership is exclusive":"Capture helpers are idle",`video ${Xe} · audio ${at} · helpers ${At} (max ${Qt||"-"}) · pid ${sa.join(",")||"-"} · profile ${Ra.join(", ")||"-"} · CPU ${Yl(Pn)} machine / ${Sp($n)} core · RSS ${Ql(ia)} · private ${Ql(Fe)} · starts ${Je} / stops ${gt}${_e?` · mismatch samples ${fe.count}/${bv}`:""}`):Ke("debug-capture-ownership","warning",nn?At>1||Qt>1?"Duplicate capture helpers detected":et?"Capture stream and helper ownership do not match":"Capture helper load needs attention":"Capture process telemetry is collecting",`video ${Xe} · audio ${at} · helpers ${At} (max ${Qt||"-"}) · pid ${sa.join(",")||"-"} · profile ${Ra.join(", ")||"-"} · CPU ${Yl(Pn)} machine / ${Sp($n)} core · RSS ${Ql(ia)} · private ${Ql(Fe)} · starts ${Je} / stops ${gt}`));const pn=`helper I/O ${N.helperOwnedIoTaskCount} | exit observers ${N.helperOwnedExitObserverCount} | undisposed ${N.helperUndisposedProcessCount} | quarantine ${N.helperQuarantineCount} | dispose failures ${N.helperDisposeFailureCount} | utility I/O ${N.utilityOwnedIoTaskCount} | undisposed ${N.utilityUndisposedProcessCount} | quarantine ${N.utilityQuarantineCount} | utility pid ${N.utilityQuarantinePids.join(",")||"-"} | profile ${N.utilityQuarantineProfiles.join(", ")||"-"} | utility starts ${N.utilityQuarantineStartCount} / stops ${N.utilityQuarantineStopCount} | dispose failures ${N.utilityDisposeFailureCount}${N.helperLastDisposeFailure?` | helper last ${N.helperLastDisposeFailure}`:""}${N.utilityLastDisposeFailure?` | utility last ${N.utilityLastDisposeFailure}`:""}`;U.push(N.telemetryAvailable&&!N.currentProblem&&!N.historicalCleanupFailure?Ke("debug-capture-cleanup","ok",At>0?"Capture cleanup ownership is exact":"Capture cleanup is idle",pn):Ke("debug-capture-cleanup","warning",N.telemetryAvailable?N.currentProblem?"Capture cleanup is quarantined or mismatched":"Capture cleanup recorded a disposal failure":"Capture cleanup telemetry is collecting",pn)),U.push(Ve?xe===0&&vt===0&&($e<=0||Oe<$e)&&!ol&&H<=Nt.networkDelayWarningMs&&Ce<=Nt.networkDelayWarningMs&&(Me===void 0||Me<=Nt.networkDelayWarningMs)?Ke("debug-delivery","ok","Delivery counters are clear",`encoded AU output gap ${Math.round(oe)}ms · Client send gap ${Math.round(be)}ms · Client send time ${Math.round(H)}ms (frame ${me||"-"}) · Agent queue ${Math.round(ue)}ms · Agent age ${Math.round(Ce)}ms · Agent drop ${Ne} · Hub transit ${Me===void 0?"-":Math.round(Me)}ms · Hub ingress drop ${He} · browser queue drop ${ie} (${Oe}/${$e||"-"}) · buffered ${Math.round(qe/1024)} KB · UDP incomplete ${vt}${Lr?" · idle optimized":""}`):Ke("debug-delivery","warning","Delivery counters show loss or delay",`encoded AU output gap ${Math.round(oe)}ms · Client send gap ${Math.round(be)}ms · Client send time ${Math.round(H)}ms (frame ${me||"-"}) · Agent queue ${Math.round(ue)}ms · Agent age ${Math.round(Ce)}ms · Agent drop ${Ne} · Hub transit ${Me===void 0?"-":Math.round(Me)}ms · Hub ingress drop ${He} · browser queue drop ${ie} (${Oe}/${$e||"-"}) · buffered ${Math.round(qe/1024)} KB · UDP incomplete ${vt}`):Ke("debug-delivery","warning","Browser queue counters are available in Hub Status",`encoded AU output gap ${Math.round(oe)}ms · Client send gap ${Math.round(be)}ms · Agent drop ${Ne} · Hub ingress drop ${He} · per-browser lane counters are intentionally collected outside video packets.`));const js=xt(n,"captureP95Ms");return U.push(n?.captureTimingAvailable===!0&&js!==void 0?Ke("debug-capture","ok",`Capture p95 ${xn(js)}ms · avg ${xn(n?.captureAverageMs)}ms`,`stage ${xn(n?.captureStageMs)}ms · slow ${Number(n?.slowFrameCount||0)} · helper restart ${Number(n?.captureHelperRestarts||0)} · source skip ${Number(n?.captureSourceSkipped||0)}`):ts&&jt?Ke("debug-capture","ok","Capture latency is not instrumented; native cadence is current",`ScreenCaptureKit ${xn(jn)} fps · VideoToolbox ${xn(en)} fps · stdout ${xn(ea)} fps · telemetry age ${Wt}`):Ke("debug-capture","warning","Capture timing sample is unavailable",`stage ${xn(n?.captureStageMs)}ms · helper restart ${Number(n?.captureHelperRestarts||0)} · source serial ${Number(n?.captureSourceSerial||0)}`)),U.push(!Ae&&pe!=="prefer-software"&&!Ee?Ke("debug-decoder","ok",`Decoder ${pe||"acceleration unknown"}`,`${String(n?.frameMode||n?.codec||"-")} · ${String(n?.hardwareEncoder||"-")} · ${String(n?.platformProfile||"-")} · ${$t}`):Ke("debug-decoder","warning",Ee?"Decoder input is losing received frames":"Decoder software fallback is active",Ee?`${xn(W)} received / ${xn($)} decoder input / ${xn(ee)} output fps · ${$t}`:`${Ae||pe||"software"} · ${xn($)} in / ${xn(ee)} out fps · ${$t}`)),U}function dD({status:t,deviceDiagnostics:n=[],codec:r,browser:i,frameStats:l}={}){const u=cn(t),f=cn(u.diagnostics),h=cn(f.system),g=cn(f.network),y=cn(r),w=cn(i),b=Array.isArray(n)?n:[],x=b.reduce((Ce,Me)=>Ce+(Array.isArray(Me)&&Me.some(Ne=>Ne?.state==="warning")?1:0),0),M=ki(h,"cpuUsageRatio","processCpuRatio"),k=ki(h,"memoryUsedRatio"),N=xt(h,"totalMemoryBytes"),E=xt(h,"cpuLogicalCores")??xt(w,"hardwareConcurrency"),I=xt(w,"deviceMemory"),T=(E??0)>0&&M!==void 0&&k!==void 0&&(N??0)>0,P=(N??0)>0&&N<Nt.hubMinimumTotalMemoryBytes,U=(I??0)>0&&I<Nt.hubMinimumBrowserMemoryGb,F=(E??0)>0&&E<4||(M??0)>=Nt.cpuWarningRatio||(k??0)>=Nt.memoryWarningRatio||P||U,Y=Math.max(0,Number(y.activeSoftwareFallbackCount??y.softwareFallbackCount??0)),D=Math.max(0,Number(y.activeDecoderCount||0)),K=Math.max(0,Number(l?.bytesPerSecond||0)*8/1e6),ne=xt(g,"externalDeviceCount"),q=Bt(g,"route"),O=ne!==void 0&&!!q,W=(ne??0)>0||q==="external",ce=cn(u.frameLanes),$=cn(ce.packetFanout),ee=["packetBuilds","metadataSerializations","payloadCopyOperations","fanoutEligibleSubscribers"].every(Ce=>xt($,Ce)!==void 0),B=Array.isArray(ce.clients)?ce.clients.map(cn):[],L=xt(ce,"clientCount")!==void 0&&Array.isArray(ce.clients)&&ee,oe=B.some(Ce=>{const Me=Math.max(0,Number(Ce.queueDepth||0)),Ne=Math.max(0,Number(Ce.queueLimit||0)),He=Math.max(0,Number(Ce.queuedBytes||0)),Ve=Math.max(0,Number(Ce.queueByteLimit||0));return Math.max(0,Number(Ce.droppedPackets||0))>0||Ne>0&&Me>=Ne||Ve>0&&He>=Ve||Array.isArray(Ce.backpressuredDeviceIds)&&Ce.backpressuredDeviceIds.length>0}),be=Math.max(0,Number($.packetBuilds||0)),H=Math.max(0,Number($.metadataSerializations||0)),me=Math.max(0,Number($.payloadCopyOperations||0)),ue=Math.max(0,Number($.fanoutEligibleSubscribers||0));return[u.started&&!u.lastError?Ke("hub-runtime","ok","Hub runtime is ready",`${u.connectedDeviceCount||0} Clients connected.`):Ke("hub-runtime","warning","Hub runtime needs attention",String(u.lastError||"Hub is not ready.")),T?F?Ke("hub-computer","warning",P?"Hub has limited system memory":U?"Browser reports limited memory capacity":"Hub computer may limit remote performance",[`${E||"?"} logical cores`,`${rx(N)} RAM`,I!==void 0?`${I} GB browser memory class`:"",`CPU ${M===void 0?"?":Math.round(M*100)}%`,`memory ${k===void 0?"?":Math.round(k*100)}%`].filter(Boolean).join(" · ")):Ke("hub-computer","ok","Hub computer capacity is healthy",`${E||"?"} logical cores · ${rx(N)} RAM · CPU ${M===void 0?"not reported":`${Math.round(M*100)}%`}.`):Ke("hub-computer","warning","Hub performance data is unavailable","Logical-core, CPU, used-memory, and total-memory telemetry are required."),D<=0?Ke("hub-codec","warning","No active browser H.264 decoder to check","Open Wall or Control and wait for a video frame."):Y>0?Ke("hub-codec","warning","Some browser decoders use software fallback",`${D} active H.264 decoders · ${Y} software fallbacks. Chrome does not expose definitive hardware acceptance.`):Ke("hub-codec","ok","All active streams request hardware H.264",`${D} active decoders. Chrome hardware acceptance is inferred from health, not directly exposed.`),L?oe?Ke("hub-frame-lanes","warning","A Hub browser video lane needs attention",`${B.length}/${ce.clientCount||0} lanes reported · packet builds ${be} · metadata serializations ${H} · payload copies ${me} · fanout deliveries ${ue}.`):Ke("hub-frame-lanes","ok","Hub browser video lanes are bounded",`${B.length}/${ce.clientCount||0} lanes reported · packet builds ${be} · metadata serializations ${H} · payload copies ${me} · fanout deliveries ${ue}.`):Ke("hub-frame-lanes","warning","Hub browser queue data is unavailable","Per-browser queue, drop, buffered-byte, and packet-allocation evidence is required."),x>0?Ke("hub-clients","warning",`${x} Clients need attention`,"Open the matching Wall slot lines for the exact cause."):Ke("hub-clients","ok","Connected Clients report healthy remote paths",`${b.length} Client reports checked.`),Ke("hub-network",!O||W||K>120?"warning":"ok",O?W?`${ne} Clients use an external network route`:K>120?"Hub receive load is high":"Hub receive load is within range":"Hub network route data is unavailable",O?`${q.toUpperCase()} route · ${K.toFixed(K>=10?0:1)} Mbps received by this browser.`:"The Hub has not reported LAN/external route classification yet.")]}async function fD(t,n={}){const r=t.filter(b=>b.canvas&&b.canvas.width>0&&b.canvas.height>0),i=Math.max(320,n.maxWidth||1920),l=Math.max(180,n.maxHeight||1080),u=r.length<=1?1:r.length<=4?2:r.length<=9?3:4,f=Math.max(1,Math.ceil(Math.max(1,r.length)/u)),h=Math.floor(i/u),g=Math.floor(l/f),y=document.createElement("canvas");y.width=Math.max(320,h*u),y.height=Math.max(180,g*f);const w=y.getContext("2d",{alpha:!1});if(!w)return y;w.fillStyle="#0b1220",w.fillRect(0,0,y.width,y.height),w.font="600 14px system-ui, sans-serif",w.textBaseline="bottom";for(let b=0;b<r.length;b+=1){const x=r[b],M=b%u,k=Math.floor(b/u),N=M*h,E=k*g,I=x.canvas,T=Math.min(h/I.width,g/I.height),P=Math.max(1,Math.floor(I.width*T)),U=Math.max(1,Math.floor(I.height*T)),F=N+Math.floor((h-P)/2),Y=E+Math.floor((g-U)/2);w.drawImage(I,F,Y,P,U),n.includeLabels!==!1&&(w.fillStyle="rgba(4, 10, 20, .74)",w.fillRect(N,E+g-28,h,28),w.fillStyle="#f8fafc",w.fillText(x.label,N+9,E+g-9))}return y}function mD(t){return t?.signature||"none"}function pD(t){return t?.label||"No capture target"}function ix(t){return{...t,deviceIds:[...t.deviceIds],sourceCanvas:t.sourceCanvas||null}}function hD(){const t=new Date,n=r=>String(r).padStart(2,"0");return`${t.getFullYear()}${n(t.getMonth()+1)}${n(t.getDate())}_${n(t.getHours())}${n(t.getMinutes())}${n(t.getSeconds())}`}function gD(t){return t.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"Wall"}function vD(t){return`LiveDesk_${t.type==="wall"||t.type==="selection"?"Wall":`${gD(t.label)}_Monitor-${Number(t.monitorIndex||0)+1}`}_${hD()}.png`}async function yD(t,n,r){const i=await new Promise((u,f)=>t.toBlob(h=>h?u(h):f(new Error("Screenshot could not be encoded.")),"image/png")),l=await h0(i,{kind:"screenshot",fileName:vD(n),target:n},r);try{await navigator.clipboard.write([new ClipboardItem({"image/png":i})])}catch{}return l.capture}function M0(){return["video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm"].find(n=>typeof MediaRecorder<"u"&&MediaRecorder.isTypeSupported(n))||""}function bD(t,n){const r=new Date().toISOString().replace(/[-:]/g,"").replace(/\.\d{3}Z$/,"").replace("T","_"),i=n.label.replace(/[^a-zA-Z0-9._-]+/g,"-").slice(0,70)||"Wall";return t==="timelapse"?`LiveDesk_Timelapse_${i}_${r}.webm`:`LiveDesk_Recording_${i}_${r}.webm`}async function A0(t){if(typeof MediaRecorder>"u"||typeof t.canvas.captureStream!="function")throw new Error("This browser does not support video recording.");const n=M0();if(!n)throw new Error("This browser does not support WebM recording.");const r=t.kind||"recording",i=await VE({kind:r,fileName:bD(r,t.target),mimeType:n,target:t.target},t.hubUrl),l=t.canvas.captureStream(t.frameRequests?0:t.fps),u=new MediaRecorder(l,{mimeType:n,videoBitsPerSecond:r==="timelapse"?2e6:4e6}),f=performance.now();let h=0,g=!1,y=null,w=Promise.resolve();return u.ondataavailable=b=>{if(!b.data||b.data.size===0)return;const x=h++;w=w.then(()=>KE(i.sessionId,x,b.data,t.hubUrl).then(()=>{})).catch(M=>{y=y||(M instanceof Error?M:new Error(String(M))),t.onError?.(y)})},u.onerror=()=>{y=new Error("Video recording stopped unexpectedly."),t.onError?.(y)},u.start(1e3),{requestFrame:()=>{l.getVideoTracks()[0]?.requestFrame?.()},stop:async()=>{if(!g){if(g=!0,await new Promise(b=>{u.addEventListener("stop",()=>b(),{once:!0}),u.stop()}),l.getTracks().forEach(b=>b.stop()),await w,y)throw await Zw(i.sessionId,t.hubUrl).catch(()=>{}),y;await QE(i.sessionId,Math.max(0,performance.now()-f),t.hubUrl)}},cancel:async()=>{g||(g=!0,u.stop(),l.getTracks().forEach(b=>b.stop()),await Zw(i.sessionId,t.hubUrl).catch(()=>{}))}}}class wD{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(n,r){if(this.recorder&&this.targetSignature===r.signature)return;if(this.stop(),typeof MediaRecorder>"u"||typeof n.captureStream!="function")throw new Error("This browser does not support Last 30s.");const i=M0();if(!i)throw new Error("This browser does not support WebM recording.");this.targetSignature=r.signature,this.stream=n.captureStream(20),this.recorder=new MediaRecorder(this.stream,{mimeType:i,videoBitsPerSecond:3e6}),this.startedAt=performance.now(),this.recorder.ondataavailable=l=>{if(!l.data.size)return;const u=performance.now();for(this.segments.push({blob:l.data,at:u}),this.totalBytes+=l.data.size;this.segments.length>1&&(u-this.segments[0].at>this.maxDurationMs||this.totalBytes>this.maxBytes);){const f=this.segments.shift();this.totalBytes-=f.blob.size}},this.recorder.start(1e3)}stop(){const n=this.recorder;this.recorder=null,n&&n.state!=="inactive"&&(n.ondataavailable=null,n.stop()),this.stream?.getTracks().forEach(r=>r.stop()),this.stream=null,this.segments=[],this.totalBytes=0,this.startedAt=0}async save(n,r){if(this.segments.length===0)throw new Error("The Last 30s buffer is not ready yet.");const i=new Blob(this.segments.map(f=>f.blob),{type:this.segments[0].blob.type||"video/webm"}),u=`LiveDesk_Last30s_${n.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 h0(i,{kind:"last-30s",fileName:u,target:n,durationMs:Math.min(3e4,this.segments.length*1e3)},r)}}async function xD(t,n,r,i,l){const u=await A0({canvas:t,target:n,kind:"timelapse",fps:30,frameRequests:!0,hubUrl:i,onError:l});u.requestFrame?.();const f=window.setInterval(()=>u.requestFrame?.(),Math.max(5,r)*1e3);return{stop:async()=>{window.clearInterval(f),await u.stop()},cancel:async()=>{window.clearInterval(f),await u.cancel()}}}const N0="livedesk.captureSettings";function SD(){const t={rollingEnabled:!1,recordingQuality:"standard",timelapseIntervalSeconds:10,includeRemoteCursor:!0};try{const n=JSON.parse(localStorage.getItem(N0)||"null");return{...t,...n&&typeof n=="object"?n:{}}}catch{return t}}function CD(t){const[n,r]=d.useState(SD),[i,l]=d.useState(0),[u,f]=d.useState(0),[h,g]=d.useState(0),[y,w]=d.useState(!1),b=d.useRef(void 0),x=d.useRef(!1),M=d.useRef(""),k=d.useRef(null),N=d.useRef(null),E=d.useRef(null),I=d.useRef(null),T=d.useRef(new wD),P=t.sourceRegistry.resolveCurrentTarget(),U=mD(P),F=pD(P),Y=typeof MediaRecorder<"u"&&typeof HTMLCanvasElement<"u"&&"captureStream"in HTMLCanvasElement.prototype;d.useEffect(()=>{if(localStorage.setItem(N0,JSON.stringify(n)),!x.current)return;const oe=JSON.stringify(n);oe!==M.current&&(M.current=oe,tt("/api/settings",{method:"PATCH",body:JSON.stringify({revision:b.current,filesAudio:{rollingBufferEnabled:n.rollingEnabled,recordingQuality:n.recordingQuality,timelapseIntervalSeconds:n.timelapseIntervalSeconds,includeRemoteCursor:n.includeRemoteCursor}})},t.hubUrl).then(be=>{b.current=Number(be.revision||b.current||0)}).catch(()=>{}))},[t.hubUrl,n]),d.useEffect(()=>{let oe=!0;return tt("/api/settings",void 0,t.hubUrl).then(be=>{if(!oe)return;const H=be.settings?.filesAudio||{},me=typeof H.rollingBufferEnabled=="boolean"?H.rollingBufferEnabled:n.rollingEnabled,ue=H.recordingQuality==="high"?"high":"standard",Ce=[5,10,30,60].includes(Number(H.timelapseIntervalSeconds))?Number(H.timelapseIntervalSeconds):n.timelapseIntervalSeconds,Me=typeof H.includeRemoteCursor=="boolean"?H.includeRemoteCursor:n.includeRemoteCursor,Ne={rollingEnabled:me,recordingQuality:ue,timelapseIntervalSeconds:Ce,includeRemoteCursor:Me};b.current=Number(be.revision||0),M.current=JSON.stringify(Ne),x.current=!0,r(Ne)}).catch(()=>{x.current=!0}),()=>{oe=!1}},[t.hubUrl]);const D=d.useCallback(async oe=>{if(oe.sourceCanvas&&oe.sourceCanvas.width>0&&oe.sourceCanvas.height>0)return{target:ix(oe),canvas:oe.sourceCanvas,cleanup:()=>{}};const be=await t.sourceRegistry.composeWall(oe.deviceIds,{maxWidth:1920,maxHeight:1080,includeLabels:!0});let H=!1;const me=window.setInterval(async()=>{if(H)return;const ue=await t.sourceRegistry.composeWall(oe.deviceIds,{maxWidth:1920,maxHeight:1080,includeLabels:!0}).catch(()=>null);!ue||H||((be.width!==ue.width||be.height!==ue.height)&&(be.width=ue.width,be.height=ue.height),be.getContext("2d")?.drawImage(ue,0,0))},100);return{target:ix(oe),canvas:be,cleanup:()=>{H=!0,window.clearInterval(me)}}},[t.sourceRegistry]);d.useEffect(()=>{const oe=T.current;if(!n.rollingEnabled||!P||!Y){oe.stop(),g(0);return}let be=!1,H=null;return(async()=>{try{if(H=await D(P),be)return;await oe.start(H.canvas,H.target);const ue=window.setInterval(()=>g(Math.round(oe.seconds)),500),Ce=()=>{window.clearInterval(ue),H?.cleanup()};oe.__cleanup=Ce}catch(ue){be||t.onToast(ue instanceof Error?ue.message:String(ue))}})(),()=>{be=!0,oe.stop(),oe.__cleanup?.(),oe.__cleanup=void 0,g(0)}},[D,t.onToast,n.rollingEnabled,U,Y]);const K=d.useCallback(oe=>r(be=>({...be,rollingEnabled:oe})),[]),ne=d.useCallback(oe=>r(be=>({...be,recordingQuality:oe})),[]),q=d.useCallback(oe=>r(be=>({...be,timelapseIntervalSeconds:oe})),[]),O=d.useCallback(async()=>{const oe=t.sourceRegistry.resolveCurrentTarget();if(!oe)throw new Error("화면이 준비된 후 다시 시도하세요.");w(!0);let be=null;try{be=await D(oe),await yD(be.canvas,be.target,t.hubUrl),t.onToast("Screenshot saved")}finally{be?.cleanup(),w(!1)}},[D,t.hubUrl,t.onToast,t.sourceRegistry]),W=d.useCallback(async()=>{if(E.current)throw new Error("Stop the timelapse before recording.");const oe=t.sourceRegistry.resolveCurrentTarget();if(!oe)throw new Error("화면이 준비된 후 다시 시도하세요.");const be=await D(oe),H=await A0({canvas:be.canvas,target:be.target,fps:oe.type==="control"?30:15,hubUrl:t.hubUrl,onError:me=>t.onToast(me.message)});N.current=be.cleanup,k.current=H,l(Date.now()),t.onToast("Recording started")},[D,t.hubUrl,t.onToast,t.sourceRegistry]),ce=d.useCallback(async()=>{const oe=k.current;if(oe){w(!0);try{await oe.stop(),t.onToast("Recording saved")}finally{k.current=null,N.current?.(),N.current=null,l(0),w(!1)}}},[t.onToast]),$=d.useCallback(async()=>{if(k.current||E.current)throw new Error("Last 30s is unavailable during a recording.");const oe=t.sourceRegistry.resolveCurrentTarget();if(!oe)throw new Error("화면이 준비된 후 다시 시도하세요.");w(!0);try{await T.current.save(oe,t.hubUrl),t.onToast("Last 30 seconds saved")}finally{w(!1)}},[t.hubUrl,t.onToast,t.sourceRegistry]),ee=d.useCallback(async()=>{if(k.current)throw new Error("Stop the recording before starting a timelapse.");const oe=t.sourceRegistry.resolveCurrentTarget();if(!oe)throw new Error("화면이 준비된 후 다시 시도하세요.");const be=await D(oe),H=await xD(be.canvas,be.target,n.timelapseIntervalSeconds,t.hubUrl,me=>t.onToast(me.message));I.current=be.cleanup,E.current=H,f(Date.now()),t.onToast("Timelapse started")},[D,t.hubUrl,t.onToast,t.sourceRegistry,n.timelapseIntervalSeconds]),B=d.useCallback(async()=>{const oe=E.current;if(oe){w(!0);try{await oe.stop(),t.onToast("Timelapse saved")}finally{E.current=null,I.current?.(),I.current=null,f(0),w(!1)}}},[t.onToast]);return d.useEffect(()=>{const oe=be=>{!k.current&&!E.current||(be.preventDefault(),be.returnValue="")};return window.addEventListener("beforeunload",oe),()=>window.removeEventListener("beforeunload",oe)},[]),d.useEffect(()=>()=>{T.current.stop(),k.current?.cancel(),E.current?.cancel(),N.current?.(),I.current?.()},[]),{state:d.useMemo(()=>({recording:!!k.current,recordingStartedAt:i,timelapse:!!E.current,timelapseStartedAt:u,bufferSeconds:h,bufferEnabled:n.rollingEnabled,busy:y,targetLabel:F}),[h,y,i,n.rollingEnabled,F,u]),settings:n,videoSupported:Y,targetKey:U,setRollingEnabled:K,setRecordingQuality:ne,setTimelapseInterval:q,takeScreenshot:O,startRecording:W,stopRecording:ce,saveLast30Seconds:$,startTimelapse:ee,stopTimelapse:B}}const kD=120,MD=999,Bf=5,zf=30,AD=Number.POSITIVE_INFINITY,T0="livedesk.remoteDirectory",wv="livedesk.localHubAccessEnabled",ND="livedesk.streamSettings",TD=18,RD="livedesk.controlStreamSettings",jD=10,R0="livedesk.wallCadence",ED=1e3,j0="livedesk.hideAdvertisements",E0="livedesk.wallMonitorSelections",D0=2,Dg=512*1024,xv="".trim(),I0="".trim(),ox="livedesk-adsense-script",Ig=!!xv&&!!I0,DD=Object.freeze([{code:"ShiftLeft",label:"Shift"},{code:"ControlLeft",label:"Ctrl"},{code:"AltLeft",label:"Alt"},{code:"MetaLeft",label:"Win"}]),ID=1e3/60,Lg=1500,LD=650,_D=1800,PD=650,FD=2500,_g=1500,lx=15e3,cx=120,ux=100,dx=20,OD=6e4,HD=6e4,fx=240,BD=1024,zD=640,$D=360,mx="Connected LiveDesk clients are updating in batches. Hub will restart after every target reconnects on the requested versions.",Cp="LiveDesk is replacing the Hub and verifying the requested version.",kp=5*6e4,UD=5e3,qD=8e3;function Zc({label:t,tooltip:n,disabled:r=!1,active:i=!1,danger:l=!1,pressed:u,onClick:f,children:h}){return o.jsx("span",{className:`manual-action-tooltip ${r?"disabled":""}`.trim(),"data-tooltip":n,children:o.jsx("button",{className:`manual-action ${i?"active":""} ${l?"danger":""}`.trim(),onClick:f,disabled:r,"aria-label":t,"aria-pressed":u,type:"button",children:h})})}function WD(t,n){if(n.deviceId!==t.deviceId)return!1;const r=Number(n.browserReceivedEpochMs);if(!Number.isFinite(r)||r<t.startedAtEpochMs)return!1;const i=Number(n.monitorIndex);if(Number.isFinite(i)&&Math.floor(i)!==t.monitorIndex)return!1;const l=String(n.frameMode||n.mode||"").trim().toLowerCase();return!l||l===t.frameMode}const Jc={free:{name:"Free",price:"$0",limit:Bf,audience:"Personal trial",note:"5 devices with a standard ad banner."},ltd:{name:"Plus",price:"$79 LTD",ltd:"$79 LTD",limit:zf,audience:"Creators and homelabs",note:"30 devices, no ads, personal use."},pro:{name:"Pro",price:"$199 LTD",ltd:"$199 LTD",limit:AD,audience:"Business and studios",note:"Commercial use and larger Client walls."}},GD={"mode3-h264-hw":30};function px(t,n){const r=f=>{const g=String(f||"").trim().replace(/^v/i,"").match(/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/);if(!g)return null;const y=g[4]?g[4].split(".").map(w=>/^\d+$/.test(w)?w.length>1&&w.startsWith("0")?Number.NaN:Number(w):w):[];return y.some(w=>typeof w=="number"&&!Number.isFinite(w))?null:{core:[Number(g[1]),Number(g[2]),Number(g[3])],prerelease:y}},i=r(t),l=r(n);if(!i||!l)return!1;for(let f=0;f<3;f+=1){if(i.core[f]>l.core[f])return!0;if(i.core[f]<l.core[f])return!1}if(i.prerelease.length===0||l.prerelease.length===0)return i.prerelease.length===0;const u=Math.max(i.prerelease.length,l.prerelease.length);for(let f=0;f<u;f+=1){const h=i.prerelease[f],g=l.prerelease[f];if(h===void 0||g===void 0)return g===void 0;if(h!==g){if(typeof h=="number"&&typeof g=="number")return h>g;if(typeof h=="number")return!1;if(typeof g=="number"||h>g)return!0;if(h<g)return!1}}return!0}const VD=512;function pa(t,n){return`${t}:${n}`}function co(t){return[t.deviceId,t.sessionId||"",t.streamId||"",t.commandId||"",Number(t.captureGeneration||0),Number(t.monitorIndex??-1),t.streamPurpose||""].join("|")}const KD={frameMode:"mode3-h264-hw",h264DecodeAcceleration:"prefer-hardware",fps:GD["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},QD={frameMode:"mode3-h264-hw",h264DecodeAcceleration:"prefer-hardware",fps:30,maxWidth:3840,maxHeight:2160,quality:90,showScreenStatus:!1},hx={maxWidth:3840,maxHeight:2160};function Of(t,n){if(t.length===0)return 0;const r=[...t].sort((l,u)=>l-u),i=Math.max(0,Math.min(r.length-1,Math.ceil(r.length*n)-1));return r[i]}function L0(t,n){t.push(n),t.length>fx&&t.splice(0,t.length-fx)}function Mp(t,n){t.sampleFrames=0,t.sampleStartedAt=n,t.intervalCount=0,t.intervalSumMs=0,t.minIntervalMs=Number.POSITIVE_INFINITY,t.maxIntervalMs=0,t.intervalSamplesMs.length=0,t.seqGapCount=0,t.maxSeqGap=0}function gx(t,n,r){if(t.lastAt!==void 0){const i=Math.max(0,n-t.lastAt);t.intervalCount+=1,t.intervalSumMs+=i,t.minIntervalMs=Math.min(t.minIntervalMs,i),t.maxIntervalMs=Math.max(t.maxIntervalMs,i),L0(t.intervalSamplesMs,i)}if(t.lastFrameSeq!==void 0){const i=r-t.lastFrameSeq;i!==1&&(t.seqGapCount+=1,t.maxSeqGap=Math.max(t.maxSeqGap,Math.abs(i)))}t.lastAt=n,t.lastFrameSeq=r}function vx(t){return!t||t.intervalCount<=0?"waiting":`${Math.round(t.averageIntervalMs)}ms avg / p95 ${Math.round(t.p95IntervalMs)}ms / max ${Math.round(t.maxIntervalMs)}ms`}function yx(t){return!t||t.seqGapCount<=0?"none":`${t.seqGapCount} gaps / max ${t.maxSeqGap}`}function YD(t){return Number.isFinite(t)?String(t):"30+"}const _0=[1,2,5,8,12,20,30],bx={large:{maxWidth:1920,maxHeight:1080},medium:{maxWidth:1280,maxHeight:720},list:{maxWidth:960,maxHeight:540}},xi={visibleRootMargin:"520px 0px 760px 0px",fallbackVisibleCounts:{large:12,medium:18,list:32},maxWallBytesPerSecond:80*1024*1024,maxFrameGapMs:280,downshiftCooldownMs:1800,downshiftStableSampleMs:Jn.adaptiveDownshiftStableMs,downshiftConsecutiveSamples:Jn.adaptiveDownshiftConsecutiveSamples,recoveryCooldownMs:14e3,minFps:5},wx=2200,XD=8e3,ZD=3500,JD=7e3,eI=2,tI=7e3,nI=2600,aI=4200,rI=750,sI=2,xx=4200;function Sx(t,n){return Math.min(3e4,t*2**Math.min(3,Math.max(0,n)))}function _p(t,n){const r=t.capabilities?.[n];return typeof r=="boolean"?r:/^(1|true|yes|on)$/i.test(String(r||"").trim())}function Rr(t){return t.deviceName||t.hostname||t.deviceId}function iI(){return"npx -y --prefer-online livedesk@latest client"}function oI(){return"npx -y --prefer-online livedesk@latest"}function lI(){try{return localStorage.getItem(T0)||""}catch{return""}}function cI(){try{return localStorage.getItem(wv)==="1"}catch{return!1}}function dd(t){try{t?localStorage.setItem(wv,"1"):localStorage.removeItem(wv)}catch{}}function Mi(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function ru(t){const n=Mi(t.status),r=Mi(n.screens),i=Mi(t.capabilities),l=Mi(t.latestLiveFrame),u=Mi(t.activeLiveStream),h=[n.monitorCount,n.screenCount,r.count,i.monitorCount,i.screenCount,l.monitorCount,u.monitorCount,Array.isArray(r.displays)?r.displays.length:0,Array.isArray(n.displays)?n.displays.length:0,Array.isArray(n.monitors)?n.monitors.length:0].map(Number).filter(g=>Number.isFinite(g)&&g>0).map(g=>Math.max(1,Math.min(64,Math.floor(g))));return h.length>0?Math.max(...h):1}function tc(t){const n=Number(t);return Number.isFinite(n)&&n>0?Math.floor(n):0}function P0(t){const n=Mi(t.status),i=[Mi(n.screens).displays,n.displays,n.monitors];for(const l of i)if(!(!Array.isArray(l)||l.length===0))return l.map(u=>Mi(u));return[]}function Zv(t,n){const r=P0(t),i=r.find(g=>Number(g.index)===n)||r[n]||r[0]||{},l=tc(i.width),u=tc(i.height),f=[i.name,i.displayName,i.deviceName,i.id].find(g=>typeof g=="string"&&g.trim()),h=typeof f=="string"?f.trim():`Display ${n+1}`;return{index:n,name:h,width:l,height:u,primary:i.primary===!0||i.isPrimary===!0}}function uI(t){const n=ru(t);return Array.from({length:n},(r,i)=>Zv(t,i))}function dI(t){const n=P0(t);if(n.length===0)return"";const r=n.map((i,l)=>{const u=Number(i.index),f=[i.name,i.displayName,i.deviceName,i.id].find(g=>typeof g=="string"&&g.trim()),h=g=>{const y=Number(g);return Number.isFinite(y)?y:null};return[Number.isFinite(u)?Math.floor(u):l,typeof f=="string"?f.trim().toLowerCase():"",h(i.left),h(i.top),h(i.width),h(i.height),i.primary===!0||i.isPrimary===!0]}).sort((i,l)=>i[0]-l[0]);return JSON.stringify(r)}function fI(t){const n=[t.name||`Display ${t.index+1}`];return t.width>0&&t.height>0&&n.push(`${t.width}x${t.height}`),t.primary&&n.push("Primary"),n.join(" - ")}function F0(t,n){const r=Zv(t,n);if(r.width>0&&r.height>0)return{width:r.width,height:r.height};const i=Mi(t.status),l=tc(i.screenWidth||i.width),u=tc(i.screenHeight||i.height);return l>0&&u>0?{width:l,height:u}:null}function O0(t){if(!t)return null;const n=tc(t.sourceWidth)||tc(t.width),r=tc(t.sourceHeight)||tc(t.height);return n>0&&r>0?{width:n,height:r}:null}function mI(t,n,r){const u=((typeof n?.monitorIndex=="number"?$f(n.monitorIndex,Math.max(1,n.monitorCount||1)):r)===r?O0(n):null)||F0(t,r);return u?Math.max(.25,Math.min(4,u.width/u.height)):16/9}const Ap=16/9;function $f(t,n){const r=Math.max(1,Math.min(64,Math.floor(Number(n)||1))),i=Math.floor(Number(t));return Number.isFinite(i)?Math.max(0,Math.min(r-1,i)):0}function Ws(t,n){return X1(n,ru(t),t.platform)}function pI(){try{const t=localStorage.getItem(E0);if(!t)return{selections:{},topologyFingerprints:{}};const n=JSON.parse(t),r=n&&typeof n=="object"&&!Array.isArray(n)?n.selections:void 0;if(Number(n?.version)!==D0||!r||typeof r!="object"||Array.isArray(r))return{selections:{},topologyFingerprints:{}};const i={},l={};for(const[u,f]of Object.entries(r)){const h=u.trim(),g=Mi(f),y=g.monitorIndex,w=Math.floor(Number(y));if(!h||!Number.isFinite(w))continue;i[h]=Math.max(0,Math.min(63,w));const b=typeof g.topologyFingerprint=="string"?g.topologyFingerprint.trim():"";b&&(l[h]=b)}return{selections:i,topologyFingerprints:l}}catch{return{selections:{},topologyFingerprints:{}}}}function hI(t,n){try{const r=Object.fromEntries(Object.entries(t).map(([i,l])=>[i,{monitorIndex:l,topologyFingerprint:n[i]||""}]));localStorage.setItem(E0,JSON.stringify({version:D0,selections:r}))}catch{}}function gI(){return{...KD}}function vI(t){try{localStorage.setItem(ND,JSON.stringify({...t,version:TD}))}catch{}}function yI(){return{...QD}}function bI(t){try{localStorage.setItem(RD,JSON.stringify({...t,version:jD}))}catch{}}function wI(){try{return localStorage.getItem(R0)==="slow"?"slow":"fast"}catch{return"fast"}}function xI(t){try{localStorage.setItem(R0,t)}catch{}}function SI(){try{return localStorage.getItem(j0)==="true"}catch{return!1}}function CI(t){try{localStorage.setItem(j0,t?"true":"false")}catch{}}function Pg(t,n){return t.length!==n.length?!1:t.every((r,i)=>r===n[i])}function Fg(t){return[...new Set(t.filter(Boolean))].sort()}function kI(t){return xi.fallbackVisibleCounts[t]||xi.fallbackVisibleCounts.large}function Cx(t,n,r){if(t.frameMode==="mode4-h264-atlas")return t.atlasTileSizeMode==="auto"?n==="large"?{maxWidth:640,maxHeight:360}:{maxWidth:320,maxHeight:180}:{maxWidth:t.atlasTileWidth,maxHeight:t.atlasTileHeight};if(!t.adaptiveSizeByWall)return{maxWidth:t.maxWidth,maxHeight:t.maxHeight};const i=bx[n]||bx.large;return{maxWidth:Math.min(t.maxWidth,i.maxWidth),maxHeight:Math.min(t.maxHeight,i.maxHeight)}}function MI(t,n=xi.minFps){const r=[..._0].sort((l,u)=>l-u),i=Math.max(n,Math.floor(t/2));return[...r].reverse().find(l=>l<t&&l>=n)||i}function AI(t,n){return[..._0].sort((i,l)=>i-l).find(i=>i>t&&i<=n)||n}function Uf(t){if(!Number.isFinite(t)||t<=0)return"0 B";const n=["B","KB","MB","GB","TB"];let r=t,i=0;for(;r>=1024&&i<n.length-1;)r/=1024,i+=1;const l=i===0||r>=100?0:1;return`${r.toFixed(l)} ${n[i]}`}function kx(t){if(!Number.isFinite(t)||!t||t<=0)return"0GB";const n=1024**4,r=1024**3;return t>=n?`${Math.max(1,Math.round(t/n))}TB`:`${Math.max(1,Math.round(t/r))}GB`}function Og(t,n){if(!Number.isFinite(t)||!t||t<=0)return"not reported";const r=Math.max(0,t-Math.max(0,Number(n||0)));return`${kx(r)} / ${kx(t)}`}function NI(t){const n=new Uint8Array(t),r=32768;let i="";for(let l=0;l<n.length;l+=r){const u=n.subarray(l,l+r);i+=String.fromCharCode(...u)}return btoa(i)}function Mx(t){return Array.from(t).filter(n=>n.size>=0).map(n=>{const r=n.webkitRelativePath||n.name;return{file:n,relativePath:r,fingerprint:`${n.size}:${n.lastModified}`}})}function Ax(t){return t===1?"middle":t===2?"right":"left"}function Nx(t,...n){for(const r of n){const i=t?.[r];if(typeof i=="string"&&i.trim())return i.trim()}return""}function Tx(t){const n=Number(t);return Number.isInteger(n)&&n>=1&&n<=MD?n:0}const TI={cpu:"CPU",memory:"MEM",disk:"Disk",gpu:"GPU",vram:"VRAM",npu:"NPU",temp:"Temp",network:"Net"};function RI(t,n,r){if(t==="online")return"Online";if(t==="busy")return"Busy";if(t==="stale")return"Stale";if(t==="offline")return"Offline";if(r==="failed")return"Task failed";const i=t==="critical"?"critical":"warn",l=n.find(f=>f.state===i)||n.find(f=>f.state==="critical"||f.state==="warn");if(!l)return t==="critical"?"Issue":"Check";const u=TI[l.id]||l.label;return l.value&&l.value!=="-"?`${u} ${l.value}`:u}function H0(t,n){const r=n.split(".");let i=t;for(const l of r){if(i==null)return;if(Array.isArray(i)){const u=Number(l);i=Number.isInteger(u)?i[u]:void 0;continue}if(typeof i=="object"){i=i[l];continue}return}return i}function Zn(t,...n){for(const r of n){const i=H0(t,r),l=Number(i);if(Number.isFinite(l))return l}}function uo(t,...n){for(const r of n){const i=H0(t,r);if(typeof i=="string"&&i.trim())return i.trim();if(typeof i=="number"&&Number.isFinite(i))return String(i)}return""}function tl(t){const n=Number(t);if(Number.isFinite(n))return Math.max(0,Math.min(1,n>1?n/100:n))}function Hg(t,n){if(!(typeof t!="number"||typeof n!="number"||!Number.isFinite(t)||!Number.isFinite(n)||t<=0))return tl((t-Math.max(0,n))/t)}function fd(t){return t===void 0?"-":`${Math.round(t*100)}%`}function Bg(t){return t===void 0||!Number.isFinite(t)?"":t>=1e3?`${(t/1e3).toFixed(t>=1e4?0:1)}Gb/s`:`${Math.round(t)}Mb/s`}function eu(t,n=.92,r=.78){return t===void 0?"unknown":t>=n?"critical":t>=r?"warn":"good"}function jI(t){return!Number.isFinite(t)||!t||t<=0?"-":t<3600?`${Math.round(t/60)}m`:t<86400?`${Math.round(t/3600)}h`:`${Math.round(t/86400)}d`}function B0(t){const n=t.status||{},r=Zn(n,"cpu.cores","cpuCores","processorCount"),i=Zn(n,"loadavg.0","cpu.load1"),l=tl(Zn(n,"cpu.usedRatio","cpu.usageRatio","cpu.ratio","cpu.usedPct","cpu.usagePct","cpu.percent")??(r&&i!==void 0?i/Math.max(1,r):void 0)),u=Zn(n,"memory.totalBytes","totalMem"),f=Zn(n,"memory.freeBytes","freeMem"),h=tl(Zn(n,"memory.usedRatio","memory.usedPct","usedMemRatio"))??Hg(u,f),g=Zn(n,"disk.totalBytes","rootDisk.totalBytes","storage.totalBytes"),y=Zn(n,"disk.freeBytes","rootDisk.freeBytes","storage.freeBytes"),w=tl(Zn(n,"disk.usedRatio","disk.usedPct","rootDisk.usedRatio","storage.usedRatio"))??Hg(g,y),b=Zn(n,"thermal.cpuC","temperatureC","cpu.temperatureC","gpu.temperatureC"),x=tl(Zn(n,"gpu.usedRatio","gpu.usageRatio","gpu.usedPct","gpu.usagePct","gpu.percent","accelerators.gpu.usageRatio")),M=uo(n,"gpu.name","gpu.model","accelerators.gpu.name"),k=Zn(n,"gpu.memory.totalBytes","gpu.totalMemoryBytes","gpu.vramTotalBytes"),N=Zn(n,"gpu.memory.freeBytes","gpu.freeMemoryBytes","gpu.vramFreeBytes"),E=tl(Zn(n,"gpu.memory.usedRatio","gpu.vramUsedRatio"))??Hg(k,N),I=Zn(n,"gpu.temperatureC","thermal.gpuC"),T=tl(Zn(n,"npu.usedRatio","npu.usageRatio","npu.usedPct","npu.usagePct","npu.percent","accelerators.npu.usageRatio")),P=uo(n,"npu.name","npu.model","accelerators.npu.name"),U=Zn(n,"npu.tops","npu.topsInt8","accelerators.npu.tops"),F=Zn(n,"network.rxMbps","network.receiveMbps","network.downMbps"),Y=Zn(n,"network.txMbps","network.transmitMbps","network.upMbps"),D=Zn(n,"network.latencyMs","network.rttMs"),K=tl(Zn(n,"network.usedRatio","network.usageRatio","network.saturationRatio")),ne=uo(n,"network.link","network.interface","network.name"),q=Math.max(b??Number.NEGATIVE_INFINITY,I??Number.NEGATIVE_INFINITY),O=Number.isFinite(q)?q:void 0,W=O===void 0?void 0:tl((O-35)/60),ce=b!==void 0&&I!==void 0?`CPU ${Math.round(b)}° · GPU ${Math.round(I)}°`:b!==void 0?`CPU ${Math.round(b)}°`:I!==void 0?`GPU ${Math.round(I)}°`:"-",$=uo(n,"workload.role","role","lane")||(_p(t,"taskDispatch")?"Command-ready Client":"Local machine"),ee=uo(t.latestTask,"status")||uo(n,"workload.status")||"idle",B=uo(t.latestTask,"title","instructionPreview")||uo(n,"workload.title"),L=uo(t.latestTask,"resultSummary","error","instructionPreview")||uo(n,"workload.summary"),oe=Date.parse(t.lastSeenAt||t.connectedAt||""),be=Number.isFinite(oe)?Date.now()-oe:0;let H="online";t.connected?be>5*6e4?H="stale":(b??0)>=86||(I??0)>=88||(l??0)>=.94||(x??0)>=.96||(E??0)>=.96||(T??0)>=.96||(h??0)>=.94||(w??0)>=.94||(D??0)>=200||ee==="failed"?H="critical":(b??0)>=78||(I??0)>=80||(l??0)>=.82||(x??0)>=.86||(E??0)>=.88||(T??0)>=.86||(h??0)>=.82||(w??0)>=.86||(D??0)>=80?H="warn":["queued","running","targeted"].includes(ee)&&(H="busy"):H="offline";const me=[{id:"cpu",label:"CPU",value:fd(l),detail:r?`${r} cores`:i!==void 0?`load ${i.toFixed(1)}`:"not reported",ratio:l,state:eu(l,.92,.78)},{id:"memory",label:"RAM",value:fd(h),detail:Og(u,f),ratio:h,state:eu(h,.92,.78)},{id:"disk",label:"DISK",value:fd(w),detail:Og(g,y),ratio:w,state:eu(w,.92,.82)},{id:"gpu",label:"GPU",value:fd(x),detail:M||(k&&N!==void 0?`${Uf(N)} VRAM free`:I!==void 0?`${Math.round(I)}C`:"not reported"),ratio:x,state:I!==void 0&&I>=88?"critical":I!==void 0&&I>=80?"warn":eu(x,.96,.86)},{id:"vram",label:"VRAM",value:fd(E),detail:Og(k,N),ratio:E,state:eu(E,.96,.88)},{id:"npu",label:"NPU",value:T!==void 0?fd(T):U!==void 0?`${Math.round(U)} TOPS`:"-",detail:P||(U!==void 0?"neural engine":"not reported"),ratio:T,state:eu(T,.96,.86)},{id:"temp",label:"TEMP",value:ce,detail:`uptime ${jI(Zn(n,"uptimeSec"))}`,ratio:W,state:O===void 0?"unknown":O>=86?"critical":O>=78?"warn":"good"},{id:"network",label:"NET",value:Bg(F)||(D!==void 0?`${Math.round(D)}ms`:ne||"-"),detail:Bg(Y)?`${Bg(Y)} up`:ne||"not reported",ratio:K,state:D!==void 0&&D>=200?"critical":D!==void 0&&D>=80?"warn":eu(K,.9,.75)}];return{state:H,label:RI(H,me,ee),role:$,taskLabel:B||(ee==="idle"?"idle":ee),taskStatus:ee,taskSummary:L,metrics:me}}const EI=[{id:"slow",label:"Slow",fps:fv("slow")},{id:"fast",label:"Fast",fps:fv("fast")}],DI=[{id:"list",label:"List"},{id:"medium",label:"Small"},{id:"large",label:"Large"}],II=[{id:"sync-server",label:"Hub",icon:mo,accent:"blue",tooltip:"hub"},{id:"wall",label:"Wall",icon:pk,accent:"blue",tooltip:"wall"},{id:"control",label:"Control",icon:qg,accent:"red",tooltip:"control"},{id:"share-files",label:"Share Files",icon:Np,accent:"green",tooltip:"share-files"},{id:"agents",label:"Agents",icon:Wg,accent:"violet",tooltip:"agents"}],LI=[{id:"doc",label:"Doc",icon:Pp,accent:"amber"},{id:"support",label:"Support",icon:qf,accent:"violet"},{id:"pricing",label:"Pricing",icon:Wf,accent:"green"}];function _I(t){return t.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 zn(t){return _I(t).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 tu(t){return t.map(n=>zn(n))}function mr(t){return{languageName:t.languageName,languageLabel:t.languageLabel,eyebrow:t.eyebrow,title:zn(t.title),intro:zn(t.intro),sections:[{title:zn(t.managerTitle),body:zn(t.managerBody),points:tu(t.managerPoints)},{title:zn(t.clientTitle),body:zn(t.clientBody),points:tu(t.clientPoints)},{title:zn(t.syncTitle),body:zn(t.syncBody),points:tu(t.syncPoints)},...t.agentTitle&&t.agentBody&&t.agentPoints?[{title:zn(t.agentTitle),body:zn(t.agentBody),points:tu(t.agentPoints)}]:[],{title:zn(t.platformTitle),body:zn(t.platformBody),points:tu(t.platformPoints)}],sync:{title:zn(t.syncTitle),body:zn(t.syncBody),points:tu(t.syncPoints)},firewall:{title:zn(t.firewallTitle),body:zn(t.firewallBody),points:tu(t.firewallPoints)},commands:{title:zn(t.commandsTitle),body:zn(t.commandsBody),manager:zn(t.managerCommandLabel),primary:zn(t.clientCommandLabel),slot:zn(t.slotCommandLabel),manual:zn(t.manualCommandLabel)}}}const yd={ko:mr({languageName:"한국어",languageLabel:"문서 언어",eyebrow:"LiveDesk Manual",title:"한 줄로 여는 로컬 Screen Wall",intro:"LiveDesk는 매니저 PC 한 대에서 여러 작업 PC, 미니 PC, 맥미니, 개발 장비를 한 화면에 모니터링하고 필요한 제어를 실행하는 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에는 일반적인 읽기·운영 명령 템플릿이 있으며, 검색과 권한·플랫폼·capability 조건으로 실행 가능 항목을 안내합니다.","Ask, Safe Auto, Full Access, Custom 권한 모드를 선택할 수 있습니다. 위험한 변경 작업은 승인 카드와 장비 capability 검사를 거칩니다.","All connected 또는 Selected로 대상 장비를 제한하고, 결과는 장비별 상태 칩과 실제 RAM·디스크·GPU·프로세스 요약으로 확인합니다.","Hub의 Codex Agent는 지시를 승인된 LiveDesk 도구로 변환하고 컴퓨터별 실행 상태와 결과를 표시합니다."],platformTitle:"5. 현재 플랫폼과 스트림 상태",platformBody:"Windows의 Wall, Control, 파일 전송, 원격 오디오와 RemoteFast 경로를 현재 기준으로 확인했습니다. macOS와 Linux는 같은 npm 명령 경로를 유지하면서 권한과 캡처 백엔드를 확장하고 있습니다.",platformPoints:["자동 Wall과 Control은 모든 Client에서 직접 H.264를 사용합니다. RGB565/LZO Atlas는 내부 진단 실험에만 남고 자동 전송 경로에는 사용되지 않습니다.","원격 오디오는 선택한 장비가 capability를 광고할 때 사용할 수 있으며, 브라우저는 queue·drop·resync·automatic restart 상태를 진단합니다.","macOS: 화면 캡처와 제어에는 Screen Recording/Accessibility 권한이 필요합니다. RemoteFast 로그는 필요한 상태 중심으로 제한됩니다.","Linux: linux-x64 runtime, X11/XTEST 입력과 PipeWire/PulseAudio 기본 출력 오디오 캡처를 지원합니다."],firewallTitle:"방화벽과 외부 장소 연결",firewallBody:"LiveDesk는 Direct TCP를 먼저 시도하고, 직접 연결이 안 되면 암호화된 rendezvous relay로 제어를 연결하며 가능한 경우 영상은 암호화된 UDP P2P로 전송합니다.",firewallPoints:["LAN Direct TCP의 기본 클라이언트 포트는 5197입니다.","클라이언트와 매니저는 설정된 rendezvous 서버로 나가는 연결이 가능해야 합니다.","Direct TCP가 실패하면 relay 제어와 UDP P2P 영상을 자동으로 시도합니다.","외부망에서도 Direct TCP를 원할 때만 TCP 5197 포트포워딩이나 VPN/IP allowlist를 설정합니다.","Screen Wall/API 포트 5179는 외부 브라우저가 Wall을 직접 열 때만 노출합니다."],commandsTitle:"현재 사용 명령",commandsBody:"웹사이트를 찾아가 설치 파일을 받는 방식보다 터미널 한 줄로 모든 운영체제에서 거의 같은 흐름을 쓰는 것이 LiveDesk의 기본 방향입니다.",managerCommandLabel:"매니저 시작",clientCommandLabel:"워크스테이션 연결",slotCommandLabel:"3번 슬롯에 고정",manualCommandLabel:"고급 수동 연결"}),en:mr({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 Clients, mini PCs, Mac minis, and development machines from one manager PC.",managerTitle:"1. Run the manager",managerBody:"Run LiveDesk on the computer that will watch the screens. The manager starts the UI and local server together, then opens http://127.0.0.1:5179.",managerPoints:["The command is npx -y livedesk.","The manager uses port 5179 for the Screen Wall/API and port 5197 for client connections.","If an old LiveDesk process still owns those ports, startup cleans it by default. Add --no-clean when you want to keep it."],clientTitle:"2. Connect a Client",clientBody:"On each monitored computer, connect with Google sign-in or the 6-digit PIN shown on the Hub screen. If no manager is online yet, the client waits for a live online signal and falls back to adaptive retries.",clientPoints:["Run npx -y livedesk client for first available placement.","Run npx -y livedesk client 3 to pin the machine to slot 3.","The browser connection page lets you choose Google or a 6-digit PIN."],syncTitle:"3. Sync Server and discovery",syncBody:"Sync Server publishes this manager as the active Screen Wall for the signed-in account. Clients read that Supabase record after Google sign-in and try the endpoint candidates in order.",syncPoints:["The record includes host instance, LAN/private addresses, public endpoint candidates, pair token, and a short lease.","LAN candidates are preferred first, then public candidates if needed.","Press Sync Server after manager moves, VPN/firewall/router changes, or when this development machine should take over as active manager.","Chrome Local Network Access on livedesk.pages.dev is no longer the default runtime path. The npm manager app is the real server."],agentTitle:"4. Run multi-Client tasks with Agent",agentBody:"The Agents page runs a Codex-based Agent in the Hub to inspect connected Clients and perform actions within the selected permission scope. Client PCs do not need the Codex app or Codex SDK installed.",agentPoints:["Suggested tasks provide generic read-only and operational command templates with search plus permission, platform, and capability 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.","The Hub-hosted Codex Agent turns instructions into approved LiveDesk tool calls and shows progress and results for each computer."],platformTitle:"5. Current platform and stream state",platformBody:"Windows Wall, Control, file transfer, remote audio, and the RemoteFast path are verified against the current implementation. macOS and Linux keep the same npm command path while capture and permission backends expand.",platformPoints:["Automatic Wall and Control use direct H.264 for every Client. The RGB565/LZO Atlas remains only for internal diagnostic experiments and is never selected automatically.","Remote audio is available when the selected Client advertises the capability, with queue, drop, resync, and automatic-restart diagnostics in the browser.","macOS requires Screen Recording and Accessibility permissions for capture and control. RemoteFast logs focus on actionable state.","Linux includes the linux-x64 runtime, X11/XTEST input, and default-output audio capture through PipeWire or PulseAudio."],firewallTitle:"Firewall and remote locations",firewallBody:"LiveDesk tries Direct TCP first; if direct access fails, control uses the encrypted rendezvous relay and video uses encrypted UDP P2P when available.",firewallPoints:["The default LAN Direct TCP client port is 5197.","Clients and the manager need outbound access to the configured rendezvous server.","Relay control and UDP P2P video are attempted automatically after Direct TCP fails.","Forward TCP 5197 or configure VPN/IP allowlists only when Direct TCP is required across networks.","Expose Screen Wall/API port 5179 only when a remote browser must open the Wall directly."],commandsTitle:"Current commands",commandsBody:"The product direction is one terminal command across operating systems instead of finding a website, downloading, and installing manually.",managerCommandLabel:"Start manager",clientCommandLabel:"Connect Client",slotCommandLabel:"Pin to slot 3",manualCommandLabel:"Advanced manual connection"}),ja:mr({languageName:"日本語",languageLabel:"ドキュメント言語",eyebrow:"LiveDesk Manual",title:"1行でローカル Screen Wall を開く",intro:"LiveDesk は、複数の作業 PC、mini PC、Mac mini、開発機を1台の manager PC から監視する npm-first のリモート作業デッキです。",managerTitle:"1. manager を実行",managerBody:"画面を集めて見るコンピューターで LiveDesk manager を実行します。UI とローカルサーバーが同時に起動し、http://127.0.0.1:5179 が開きます。",managerPoints:["コマンドは npx -y livedesk です。","Screen Wall/API は 5179、client 接続は 5197 を使います。","古い LiveDesk プロセスがポートを使っている場合は、基本的に自動で整理して起動します。"],clientTitle:"2. Client を接続",clientBody:"監視される PC で同じ Google アカウントにログインします。manager がまだ無い場合、client はオンライン通知を待ち、適応型の間隔で再確認します。",clientPoints:["空きスロットに入れるには npx -y livedesk client を実行します。","スロットを固定するには npx -y livedesk client 3 のように番号を付けます。","大量の PC でも再ログインなしで待ち続けます。"],syncTitle:"3. Sync Server と自動検出",syncBody:"Sync Server はこの manager を現在の Google アカウントの active Screen Wall として Supabase に登録します。",syncPoints:["host instance、LAN/private アドレス、public 候補、pair token、短い lease を登録します。","client は LAN 候補を優先し、必要なら public 候補も試します。","VPN、firewall、router、manager の場所が変わったら Sync Server を押します。","livedesk.pages.dev の Chrome Local Network Access は標準実行経路ではありません。npm manager アプリが実際のサーバーです。"],platformTitle:"4. 現在のプラットフォーム状態",platformBody:"Windows は live screen transfer まで確認済みです。macOS と Linux も同じ npm コマンド経路を目標に対応を広げています。",platformPoints:["Windows: 動作確認済み。","macOS: 画面取得と制御には Screen Recording/Accessibility 権限が必要です。","Linux: linux-x64 runtime、grim/gnome-screenshot/import/scrot capture、X11/XTEST input backend を追加済み。audio は未対応です。"],firewallTitle:"Firewall と外部拠点",firewallBody:"LiveDesk は Direct TCP を先に試し、失敗した場合は暗号化 rendezvous relay で制御し、可能なら映像に暗号化 UDP P2P を使います。",firewallPoints:["LAN の Direct TCP client 既定ポートは 5197 です。","client と manager は設定済み rendezvous server へ outbound 接続できる必要があります。","Direct TCP 失敗後は relay 制御と UDP P2P 映像を自動的に試します。","ネットワーク越しに Direct TCP が必要な場合だけ TCP 5197 の転送または VPN/IP allowlist を設定します。","5179 は外部ブラウザが Wall を直接開く場合だけ公開します。"],commandsTitle:"現在のコマンド",commandsBody:"Web サイトから installer を探すより、OS をまたいで terminal 1行で動かす方向です。",managerCommandLabel:"manager 起動",clientCommandLabel:"Client 接続",slotCommandLabel:"slot 3 に固定",manualCommandLabel:"高度な手動接続"}),"zh-CN":mr({languageName:"简体中文",languageLabel:"文档语言",eyebrow:"LiveDesk Manual",title:"用一条命令打开本地 Screen Wall",intro:"LiveDesk 是 npm-first 的远程工作台,用一台 manager PC 监控多台工作电脑、迷你主机、Mac mini 和开发机器。",managerTitle:"1. 运行 manager",managerBody:"在负责查看屏幕的电脑上运行 LiveDesk manager。它会同时启动 UI 和本地服务器,并打开 http://127.0.0.1:5179。",managerPoints:["命令是 npx -y livedesk。","Screen Wall/API 使用 5179,client 连接使用 5197。","如果旧的 LiveDesk 进程占用端口,默认会清理后重新启动。"],clientTitle:"2. 连接 Client",clientBody:"在被监控的电脑上使用同一个 Google 账号登录。如果 manager 尚未在线,client 会等待上线通知,并以自适应间隔重新检查。",clientPoints:["自动放入空位: npx -y livedesk client。","固定到 3 号位置: npx -y livedesk client 3。","大量电脑也可以持续等待,不需要反复登录。"],syncTitle:"3. Sync Server 和自动发现",syncBody:"Sync Server 会把当前 manager 作为该账号的 active Screen Wall 写入 Supabase。client 登录后读取记录并依次尝试连接候选地址。",syncPoints:["记录包括 host instance、LAN/private 地址、public 候选、pair token 和短 lease。","优先尝试同一 LAN 地址,需要时再尝试外部地址。","manager 位置、VPN、防火墙或路由变化后请点击 Sync Server。","livedesk.pages.dev 的 Chrome Local Network Access 不再是默认运行方式。npm manager app 才是真正服务器。"],platformTitle:"4. 当前平台状态",platformBody:"Windows 已确认可传输实时画面。macOS 和 Linux 正按同一 npm 命令路径扩展支持。",platformPoints:["Windows: 已确认可用。","macOS: 画面捕获和控制需要 Screen Recording/Accessibility 权限。","Linux: 已加入 linux-x64 runtime、grim/gnome-screenshot/import/scrot 捕获、X11/XTEST 输入后端。音频尚未启用。"],firewallTitle:"防火墙和外部地点",firewallBody:"LiveDesk 会先尝试 Direct TCP;直连失败时,控制改用加密 rendezvous relay,视频在可用时使用加密 UDP P2P。",firewallPoints:["LAN Direct TCP 的默认 client 端口是 5197。","client 和 manager 必须能向已配置的 rendezvous server 建立出站连接。","Direct TCP 失败后会自动尝试 relay 控制和 UDP P2P 视频。","只有跨网络需要 Direct TCP 时才转发 TCP 5197 或配置 VPN/IP 白名单。","只有远程浏览器需要直接打开 Wall 时才暴露 5179。"],commandsTitle:"当前命令",commandsBody:"产品方向是跨操作系统使用一条终端命令,而不是先找网站、下载、安装。",managerCommandLabel:"启动 manager",clientCommandLabel:"连接 Client",slotCommandLabel:"固定到 slot 3",manualCommandLabel:"高级手动连接"}),"zh-TW":mr({languageName:"繁體中文",languageLabel:"文件語言",eyebrow:"LiveDesk Manual",title:"用一行指令開啟本機 Screen Wall",intro:"LiveDesk 是 npm-first 的遠端工作台,用一台 manager PC 監看多台工作電腦、迷你主機、Mac mini 與開發機。",managerTitle:"1. 執行 manager",managerBody:"在負責看畫面的電腦上執行 LiveDesk manager。它會同時啟動 UI 與本機伺服器,並開啟 http://127.0.0.1:5179。",managerPoints:["指令是 npx -y livedesk。","Screen Wall/API 使用 5179,client 連線使用 5197。","若舊的 LiveDesk 程序占用連接埠,預設會清理後重新啟動。"],clientTitle:"2. 連接 Client",clientBody:"在被監看的電腦上使用同一個 Google 帳號登入。如果 manager 尚未上線,client 會等待上線通知,並以自適應間隔重新檢查。",clientPoints:["自動放入空位: npx -y livedesk client。","固定到 3 號位置: npx -y livedesk client 3。","大量電腦也能持續等待,不需要反覆登入。"],syncTitle:"3. Sync Server 與自動探索",syncBody:"Sync Server 會把目前 manager 登錄為此帳號的 active Screen Wall。client 登入後讀取 Supabase 記錄並依序嘗試連線候選地址。",syncPoints:["記錄包含 host instance、LAN/private 位址、public 候選、pair token 與短 lease。","優先嘗試 LAN 位址,需要時再嘗試外部位址。","manager 位置、VPN、防火牆或路由設定改變後請按 Sync Server。","livedesk.pages.dev 的 Chrome Local Network Access 不再是預設執行路徑。npm manager app 才是真正伺服器。"],platformTitle:"4. 目前平台狀態",platformBody:"Windows 已確認可傳輸即時畫面。macOS 與 Linux 也沿用相同 npm 指令路徑擴充支援。",platformPoints:["Windows: 已確認可用。","macOS: 畫面擷取與控制需要 Screen Recording/Accessibility 權限。","Linux: 已加入 linux-x64 runtime、grim/gnome-screenshot/import/scrot capture、X11/XTEST input backend。音訊尚未啟用。"],firewallTitle:"防火牆與外部地點",firewallBody:"LiveDesk 會先嘗試 Direct TCP;直連失敗時,控制改用加密 rendezvous relay,影像在可用時使用加密 UDP P2P。",firewallPoints:["LAN Direct TCP 的預設 client 連接埠是 5197。","client 與 manager 必須能向已設定的 rendezvous server 建立外送連線。","Direct TCP 失敗後會自動嘗試 relay 控制與 UDP P2P 影像。","只有跨網路需要 Direct TCP 時才轉送 TCP 5197 或設定 VPN/IP allowlist。","只有遠端瀏覽器需要直接開啟 Wall 時才公開 5179。"],commandsTitle:"目前指令",commandsBody:"產品方向是跨作業系統用一行 terminal 指令,而不是先找網站、下載、安裝。",managerCommandLabel:"啟動 manager",clientCommandLabel:"連接 Client",slotCommandLabel:"固定到 slot 3",manualCommandLabel:"進階手動連線"}),es:mr({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 equipos de trabajo, mini PC, Mac mini y equipos de desarrollo desde un PC manager.",managerTitle:"1. Ejecuta el manager",managerBody:"Ejecuta LiveDesk en el equipo que verá las pantallas. El manager inicia la UI y el servidor local juntos y abre http://127.0.0.1:5179.",managerPoints:["El comando es npx -y livedesk.","El manager usa 5179 para Screen Wall/API y 5197 para conexiones client.","Si un proceso antiguo ocupa los puertos, el arranque lo limpia por defecto."],clientTitle:"2. Conecta una Client",clientBody:"En cada equipo monitoreado, inicia sesión con la misma cuenta Google. Si el manager aún no está activo, el client espera una señal en tiempo real y vuelve a comprobar con intervalos adaptativos.",clientPoints:["Usa npx -y livedesk client para el primer slot libre.","Usa npx -y livedesk client 3 para fijar el equipo al slot 3.","Los clients siguen esperando para no repetir login en muchas máquinas."],syncTitle:"3. Sync Server y descubrimiento",syncBody:"Sync Server publica este manager como Screen Wall activo para la cuenta. Los clients leen el registro en Supabase y prueban los endpoints.",syncPoints:["Incluye host instance, direcciones LAN/private, candidatos public, pair token y lease corto.","Primero se prueban candidatos LAN, luego públicos si hace falta.","Pulsa Sync Server después de cambios de manager, VPN, firewall o router.","Chrome Local Network Access en livedesk.pages.dev ya no es el flujo principal. La app npm manager es el servidor real."],platformTitle:"4. Estado de plataformas",platformBody:"Windows ya fue verificado con transferencia de pantalla. macOS y Linux siguen el mismo camino npm.",platformPoints:["Windows: verificado.","macOS: captura y control requieren permisos Screen Recording/Accessibility.","Linux: runtime linux-x64, entrada X11/XTEST y audio de salida mediante PipeWire o PulseAudio."],firewallTitle:"Firewall y sedes remotas",firewallBody:"LiveDesk intenta primero Direct TCP; si falla, el control usa el rendezvous relay cifrado y el vídeo usa UDP P2P cifrado cuando está disponible.",firewallPoints:["El puerto client predeterminado para Direct TCP en LAN es 5197.","Clients y manager necesitan acceso saliente al servidor rendezvous configurado.","Tras fallar Direct TCP se intentan automáticamente control relay y vídeo UDP P2P.","Reenvía TCP 5197 o configura VPN/allowlist de IP solo si necesitas Direct TCP entre redes.","Expón 5179 solo si un navegador remoto debe abrir el Wall directamente."],commandsTitle:"Comandos actuales",commandsBody:"La dirección del producto es un comando de terminal común entre sistemas, no descargar e instalar desde una web.",managerCommandLabel:"Iniciar manager",clientCommandLabel:"Conectar Client",slotCommandLabel:"Fijar al slot 3",manualCommandLabel:"Conexión manual avanzada"}),fr:mr({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, mini PC, Mac mini et machines dev depuis un PC manager.",managerTitle:"1. Lancer le manager",managerBody:"Lancez LiveDesk sur l’ordinateur qui observe les écrans. Le manager démarre l’UI et le serveur local, puis ouvre http://127.0.0.1:5179.",managerPoints:["La commande est npx -y livedesk.","Le manager utilise 5179 pour Screen Wall/API et 5197 pour les connexions client.","Si un ancien processus utilise les ports, le démarrage le nettoie par défaut."],clientTitle:"2. Connecter une Client",clientBody:"Sur chaque ordinateur surveillé, connectez-vous avec le même compte Google. Si le manager n’est pas encore actif, le client réessaie toutes les 5 secondes.",clientPoints:["Utilisez npx -y livedesk client pour le premier slot libre.","Utilisez npx -y livedesk client 3 pour fixer la machine au slot 3.","Les clients continuent d’attendre pour éviter les reconnexions répétées."],syncTitle:"3. Sync Server et découverte",syncBody:"Sync Server publie ce manager comme Screen Wall actif du compte. Les clients lisent l’enregistrement Supabase et testent les endpoints.",syncPoints:["Il contient host instance, adresses LAN/private, candidats public, pair token et lease court.","Les candidats LAN sont essayés en premier, puis les candidats publics si besoin.","Cliquez Sync Server après un changement de manager, VPN, firewall ou routeur.","Chrome Local Network Access sur livedesk.pages.dev n’est plus le chemin par défaut. L’app npm manager est le vrai serveur."],platformTitle:"4. État des plateformes",platformBody:"Windows est vérifié avec transfert d’écran live. macOS et Linux suivent le même chemin npm.",platformPoints:["Windows: vérifié.","macOS: capture et contrôle nécessitent Screen Recording/Accessibility.","Linux: runtime linux-x64, entrée X11/XTEST et audio de sortie via PipeWire ou PulseAudio."],firewallTitle:"Firewall et sites distants",firewallBody:"LiveDesk tente d’abord Direct TCP ; en cas d’échec, le contrôle utilise le relais rendezvous chiffré et la vidéo UDP P2P chiffrée lorsqu’elle est disponible.",firewallPoints:["Le port client Direct TCP par défaut sur le LAN est 5197.","Clients et manager doivent avoir un accès sortant au serveur rendezvous configuré.","Après un échec Direct TCP, le contrôle relay et la vidéo UDP P2P sont tentés automatiquement.","Redirigez TCP 5197 ou configurez VPN/allowlist IP seulement si Direct TCP est requis entre réseaux.","Exposez 5179 uniquement si un navigateur distant doit ouvrir directement le Wall."],commandsTitle:"Commandes actuelles",commandsBody:"La direction produit est une commande terminal commune aux OS, plutôt qu’un téléchargement manuel depuis un site.",managerCommandLabel:"Démarrer manager",clientCommandLabel:"Connecter Client",slotCommandLabel:"Fixer au slot 3",manualCommandLabel:"Connexion manuelle avancée"}),de:mr({languageName:"Deutsch",languageLabel:"Dokumentsprache",eyebrow:"LiveDesk Manual",title:"Lokale Screen Wall mit einem Befehl öffnen",intro:"LiveDesk ist ein npm-first Arbeitsdeck, um viele Clients, Mini-PCs, Mac minis und Dev-Rechner von einem Manager-PC zu überwachen.",managerTitle:"1. Manager starten",managerBody:"Starte LiveDesk auf dem Computer, der die Screens sieht. Der Manager startet UI und lokalen Server zusammen und öffnet http://127.0.0.1:5179.",managerPoints:["Der Befehl ist npx -y livedesk.","Der Manager nutzt 5179 für Screen Wall/API und 5197 für Client-Verbindungen.","Wenn alte LiveDesk-Prozesse Ports belegen, werden sie beim Start standardmäßig bereinigt."],clientTitle:"2. Client verbinden",clientBody:"Melde dich auf jedem überwachten Computer mit demselben Google-Konto an. Wenn kein Manager online ist, wartet der Client auf ein Live-Signal und prüft mit adaptiven Intervallen erneut.",clientPoints:["npx -y livedesk client nutzt den ersten freien Slot.","npx -y livedesk client 3 fixiert den Rechner auf Slot 3.","Clients warten weiter, damit große Setups kein wiederholtes Login brauchen."],syncTitle:"3. Sync Server und Discovery",syncBody:"Sync Server veröffentlicht diesen Manager als aktive Screen Wall des Kontos. Clients lesen den Supabase-Eintrag und testen Endpoints der Reihe nach.",syncPoints:["Enthält host instance, LAN/private Adressen, public Kandidaten, pair token und kurze lease.","LAN-Kandidaten werden zuerst versucht, danach public Kandidaten.","Nach Änderungen an Manager, VPN, Firewall oder Router Sync Server drücken.","Chrome Local Network Access auf livedesk.pages.dev ist nicht mehr der Standardpfad. Die npm Manager App ist der echte Server."],platformTitle:"4. Plattformstatus",platformBody:"Windows wurde mit Live-Screen-Transfer geprüft. macOS und Linux folgen demselben npm-Pfad.",platformPoints:["Windows: verifiziert.","macOS: Capture und Control brauchen Screen Recording/Accessibility Rechte.","Linux: linux-x64 Runtime, X11/XTEST Eingabe und Ausgangsaudio über PipeWire oder PulseAudio."],firewallTitle:"Firewall und entfernte Standorte",firewallBody:"LiveDesk versucht zuerst Direct TCP; schlägt dies fehl, nutzt die Steuerung das verschlüsselte Rendezvous-Relay und Video nach Möglichkeit verschlüsseltes UDP P2P.",firewallPoints:["Der Standardport für LAN Direct TCP Clients ist 5197.","Clients und Manager benötigen ausgehenden Zugriff auf den konfigurierten Rendezvous-Server.","Nach einem Direct-TCP-Fehler werden Relay-Steuerung und UDP-P2P-Video automatisch versucht.","TCP 5197 nur weiterleiten oder VPN/IP-Allowlist einrichten, wenn Direct TCP netzübergreifend nötig ist.","5179 nur öffnen, wenn ein Remote-Browser die Wall direkt laden muss."],commandsTitle:"Aktuelle Befehle",commandsBody:"Die Produktlinie ist ein Terminalbefehl über Betriebssysteme hinweg, statt Website suchen, herunterladen und installieren.",managerCommandLabel:"Manager starten",clientCommandLabel:"Client verbinden",slotCommandLabel:"An Slot 3 fixieren",manualCommandLabel:"Erweiterte manuelle Verbindung"}),"pt-BR":mr({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, mini PCs, Mac minis e máquinas dev a partir de um PC manager.",managerTitle:"1. Execute o manager",managerBody:"Rode LiveDesk no computador que verá as telas. O manager inicia a UI e o servidor local juntos e abre http://127.0.0.1:5179.",managerPoints:["O comando é npx -y livedesk.","O manager usa 5179 para Screen Wall/API e 5197 para conexões client.","Se um processo antigo ocupa as portas, a inicialização limpa por padrão."],clientTitle:"2. Conecte uma Client",clientBody:"Em cada computador monitorado, entre com a mesma conta Google. Se o manager ainda não estiver online, o client aguarda um sinal em tempo real e verifica novamente em intervalos adaptativos.",clientPoints:["Use npx -y livedesk client para o primeiro slot livre.","Use npx -y livedesk client 3 para fixar no slot 3.","Clients continuam tentando para evitar login repetido em muitos PCs."],syncTitle:"3. Sync Server e descoberta",syncBody:"Sync Server publica este manager como Screen Wall ativo da conta. Clients leem o registro no Supabase e testam endpoints.",syncPoints:["Inclui host instance, endereços LAN/private, candidatos public, pair token e lease curto.","Candidatos LAN vêm primeiro; public depois se necessário.","Clique Sync Server após mudanças de manager, VPN, firewall ou roteador.","Chrome Local Network Access em livedesk.pages.dev não é mais o caminho padrão. O app npm manager é o servidor real."],platformTitle:"4. Estado das plataformas",platformBody:"Windows foi verificado com transferência de tela. macOS e Linux seguem o mesmo caminho npm.",platformPoints:["Windows: verificado.","macOS: captura e controle precisam de permissões Screen Recording/Accessibility.","Linux: runtime linux-x64, captura grim/gnome-screenshot/import/scrot e entrada X11/XTEST adicionados. Áudio ainda desativado."],firewallTitle:"Firewall e locais remotos",firewallBody:"LiveDesk tenta Direct TCP primeiro; se falhar, o controle usa o rendezvous relay criptografado e o vídeo usa UDP P2P criptografado quando disponível.",firewallPoints:["A porta client padrão para Direct TCP na LAN é 5197.","Clients e manager precisam de acesso de saída ao servidor rendezvous configurado.","Após falha no Direct TCP, controle relay e vídeo UDP P2P são tentados automaticamente.","Encaminhe TCP 5197 ou configure VPN/allowlist IP apenas se Direct TCP entre redes for necessário.","Exponha 5179 somente se um navegador remoto precisar abrir o Wall diretamente."],commandsTitle:"Comandos atuais",commandsBody:"A direção do produto é um comando de terminal comum entre sistemas, não baixar e instalar manualmente.",managerCommandLabel:"Iniciar manager",clientCommandLabel:"Conectar Client",slotCommandLabel:"Fixar no slot 3",manualCommandLabel:"Conexão manual avançada"}),it:mr({languageName:"Italiano",languageLabel:"Lingua documento",eyebrow:"LiveDesk Manual",title:"Apri uno Screen Wall locale con un comando",intro:"LiveDesk è un deck npm-first per monitorare Client, mini PC, Mac mini e macchine dev da un solo PC manager.",managerTitle:"1. Avvia il manager",managerBody:"Esegui LiveDesk sul computer che guarderà gli schermi. Il manager avvia UI e server locale e apre http://127.0.0.1:5179.",managerPoints:["Il comando è npx -y livedesk.","Il manager usa 5179 per Screen Wall/API e 5197 per connessioni client.","Se vecchi processi occupano le porte, l’avvio le pulisce di default."],clientTitle:"2. Connetti una Client",clientBody:"Su ogni computer monitorato, accedi con lo stesso account Google. Se il manager non è online, il client riprova ogni 5 secondi.",clientPoints:["npx -y livedesk client usa il primo slot libero.","npx -y livedesk client 3 fissa la macchina allo slot 3.","I client continuano a provare per evitare login ripetuti."],syncTitle:"3. Sync Server e discovery",syncBody:"Sync Server pubblica questo manager come Screen Wall attivo dell’account. I client leggono Supabase e provano gli endpoint.",syncPoints:["Include host instance, indirizzi LAN/private, candidati public, pair token e lease breve.","Prima LAN, poi public se necessario.","Premi Sync Server dopo cambi di manager, VPN, firewall o router.","Chrome Local Network Access su livedesk.pages.dev non è più il percorso principale. L’app npm manager è il server reale."],platformTitle:"4. Stato piattaforme",platformBody:"Windows è verificato con trasferimento schermo live. macOS e Linux seguono lo stesso percorso npm.",platformPoints:["Windows: verificato.","macOS: capture e control richiedono permessi Screen Recording/Accessibility.","Linux: aggiunti runtime linux-x64, capture grim/gnome-screenshot/import/scrot e input X11/XTEST. Audio disattivato."],firewallTitle:"Firewall e sedi remote",firewallBody:"LiveDesk prova prima Direct TCP; se fallisce, il controllo usa il rendezvous relay cifrato e il video usa UDP P2P cifrato quando disponibile.",firewallPoints:["La porta client predefinita per Direct TCP in LAN è 5197.","Client e manager devono avere accesso in uscita al server rendezvous configurato.","Dopo un errore Direct TCP, controllo relay e video UDP P2P vengono tentati automaticamente.","Inoltra TCP 5197 o configura VPN/allowlist IP solo se serve Direct TCP tra reti.","Esponi 5179 soltanto se un browser remoto deve aprire direttamente la Wall."],commandsTitle:"Comandi attuali",commandsBody:"La direzione è un comando terminale comune tra sistemi operativi, invece di download e install manuale.",managerCommandLabel:"Avvia manager",clientCommandLabel:"Connetti Client",slotCommandLabel:"Fissa allo slot 3",manualCommandLabel:"Connessione manuale avanzata"}),id:mr({languageName:"Bahasa Indonesia",languageLabel:"Bahasa dokumen",eyebrow:"LiveDesk Manual",title:"Buka Screen Wall lokal dengan satu perintah",intro:"LiveDesk adalah deck npm-first untuk memantau banyak Client, mini PC, Mac mini, dan mesin dev dari satu PC manager.",managerTitle:"1. Jalankan manager",managerBody:"Jalankan LiveDesk di komputer yang melihat layar. Manager membuka UI dan server lokal bersama, lalu membuka http://127.0.0.1:5179.",managerPoints:["Perintahnya npx -y livedesk.","Manager memakai 5179 untuk Screen Wall/API dan 5197 untuk koneksi client.","Jika proses lama memakai port itu, startup membersihkannya secara default."],clientTitle:"2. Hubungkan Client",clientBody:"Di komputer yang dipantau, masuk dengan akun Google yang sama. Jika manager belum online, client tetap mencoba tiap 5 detik.",clientPoints:["npx -y livedesk client memakai slot kosong pertama.","npx -y livedesk client 3 mengunci mesin ke slot 3.","Client terus mencoba agar banyak PC tidak perlu login berulang."],syncTitle:"3. Sync Server dan discovery",syncBody:"Sync Server menerbitkan manager ini sebagai Screen Wall aktif untuk akun. Client membaca Supabase dan mencoba endpoint.",syncPoints:["Berisi host instance, alamat LAN/private, kandidat public, pair token, dan lease pendek.","Kandidat LAN dicoba lebih dulu, lalu public jika perlu.","Tekan Sync Server setelah perubahan manager, VPN, firewall, atau router.","Chrome Local Network Access di livedesk.pages.dev bukan jalur utama lagi. App npm manager adalah server sebenarnya."],platformTitle:"4. Status platform",platformBody:"Windows sudah diverifikasi dengan live screen transfer. macOS dan Linux mengikuti jalur npm yang sama.",platformPoints:["Windows: terverifikasi.","macOS: capture dan control perlu izin Screen Recording/Accessibility.","Linux: runtime linux-x64, capture grim/gnome-screenshot/import/scrot, dan input X11/XTEST sudah ditambahkan. Audio belum aktif."],firewallTitle:"Firewall dan lokasi luar",firewallBody:"LiveDesk mencoba Direct TCP lebih dulu; jika gagal, kontrol memakai rendezvous relay terenkripsi dan video memakai UDP P2P terenkripsi bila tersedia.",firewallPoints:["Port client default untuk Direct TCP di LAN adalah 5197.","Client dan manager memerlukan akses keluar ke server rendezvous yang dikonfigurasi.","Setelah Direct TCP gagal, kontrol relay dan video UDP P2P dicoba otomatis.","Forward TCP 5197 atau atur VPN/IP allowlist hanya jika Direct TCP antarjaringan diperlukan.","Buka 5179 hanya jika browser jarak jauh harus membuka Wall secara langsung."],commandsTitle:"Perintah saat ini",commandsBody:"Arah produk adalah satu perintah terminal lintas OS, bukan download dan instal manual.",managerCommandLabel:"Mulai manager",clientCommandLabel:"Hubungkan Client",slotCommandLabel:"Kunci ke slot 3",manualCommandLabel:"Koneksi manual lanjutan"}),vi:mr({languageName:"Tiếng Việt",languageLabel:"Ngôn ngữ tài liệu",eyebrow:"LiveDesk Manual",title:"Mở Screen Wall cục bộ bằng một lệnh",intro:"LiveDesk là deck npm-first để giám sát nhiều Client, mini PC, Mac mini và máy dev từ một PC manager.",managerTitle:"1. Chạy manager",managerBody:"Chạy LiveDesk trên máy dùng để xem màn hình. Manager khởi động UI và server cục bộ cùng lúc, rồi mở http://127.0.0.1:5179.",managerPoints:["Lệnh là npx -y livedesk.","Manager dùng 5179 cho Screen Wall/API và 5197 cho kết nối client.","Nếu tiến trình cũ giữ port, startup mặc định sẽ dọn và khởi động lại."],clientTitle:"2. Kết nối Client",clientBody:"Trên mỗi máy được giám sát, đăng nhập cùng tài khoản Google. Nếu manager chưa online, client tiếp tục thử mỗi 5 giây.",clientPoints:["npx -y livedesk client dùng slot trống đầu tiên.","npx -y livedesk client 3 ghim máy vào slot 3.","Client tiếp tục chờ để nhiều máy không cần đăng nhập lại."],syncTitle:"3. Sync Server và tự phát hiện",syncBody:"Sync Server đăng manager này là Screen Wall đang hoạt động của tài khoản. Client đọc Supabase và thử các endpoint.",syncPoints:["Bao gồm host instance, địa chỉ LAN/private, public candidate, pair token và lease ngắn.","Ưu tiên LAN trước, sau đó thử public nếu cần.","Bấm Sync Server sau thay đổi manager, VPN, firewall hoặc router.","Chrome Local Network Access trên livedesk.pages.dev không còn là đường chạy chính. App npm manager mới là server thật."],platformTitle:"4. Trạng thái nền tảng",platformBody:"Windows đã được kiểm chứng với truyền màn hình live. macOS và Linux đi theo cùng đường npm.",platformPoints:["Windows: đã kiểm chứng.","macOS: capture và control cần quyền Screen Recording/Accessibility.","Linux: đã thêm runtime linux-x64, capture grim/gnome-screenshot/import/scrot và input X11/XTEST. Audio chưa bật."],firewallTitle:"Firewall và địa điểm ngoài",firewallBody:"LiveDesk thử Direct TCP trước; nếu thất bại, control dùng rendezvous relay mã hóa và video dùng UDP P2P mã hóa khi khả dụng.",firewallPoints:["Port client mặc định cho Direct TCP trong LAN là 5197.","Client và manager cần kết nối outbound tới rendezvous server đã cấu hình.","Sau khi Direct TCP thất bại, relay control và UDP P2P video được thử tự động.","Chỉ forward TCP 5197 hoặc cấu hình VPN/IP allowlist khi cần Direct TCP giữa các mạng.","Chỉ mở 5179 khi browser từ xa cần mở Wall trực tiếp."],commandsTitle:"Lệnh hiện tại",commandsBody:"Hướng sản phẩm là một lệnh terminal dùng chung giữa các OS, thay vì tải và cài thủ công.",managerCommandLabel:"Khởi động manager",clientCommandLabel:"Kết nối Client",slotCommandLabel:"Ghim vào slot 3",manualCommandLabel:"Kết nối thủ công nâng cao"}),th:mr({languageName:"ไทย",languageLabel:"ภาษาของเอกสาร",eyebrow:"LiveDesk Manual",title:"เปิด Screen Wall ภายในด้วยคำสั่งเดียว",intro:"LiveDesk คือ deck แบบ npm-first สำหรับดู Client, mini PC, Mac mini และเครื่อง dev หลายเครื่องจาก manager PC เครื่องเดียว",managerTitle:"1. รัน manager",managerBody:"รัน LiveDesk บนเครื่องที่ใช้ดูหน้าจอ Manager จะเปิด UI และ local server พร้อมกัน แล้วเปิด http://127.0.0.1:5179",managerPoints:["คำสั่งคือ npx -y livedesk","Manager ใช้ 5179 สำหรับ Screen Wall/API และ 5197 สำหรับ client connection","ถ้า process เก่ายังใช้ port อยู่ startup จะล้างให้โดย default"],clientTitle:"2. เชื่อม Client",clientBody:"บนเครื่องที่ต้อง monitor ให้ login ด้วย Google account เดียวกัน ถ้า manager ยังไม่ออนไลน์ client จะลองใหม่ทุก 5 วินาที",clientPoints:["npx -y livedesk client จะใช้ slot ว่างแรก","npx -y livedesk client 3 จะตรึงเครื่องไว้ที่ slot 3","Client จะรอต่อเนื่องเพื่อไม่ต้อง login ซ้ำเมื่อมีหลายเครื่อง"],syncTitle:"3. Sync Server และ discovery",syncBody:"Sync Server จะ publish manager นี้เป็น active Screen Wall ของ account แล้ว client อ่านข้อมูลจาก Supabase และลอง endpoint ต่างๆ",syncPoints:["มี host instance, LAN/private address, public candidate, pair token และ short lease","ลอง LAN ก่อน แล้วค่อยลอง public ถ้าจำเป็น","กด Sync Server หลังเปลี่ยน manager, VPN, firewall หรือ router","Chrome Local Network Access บน livedesk.pages.dev ไม่ใช่ runtime หลักแล้ว app npm manager คือ server จริง"],platformTitle:"4. สถานะ platform",platformBody:"Windows ตรวจสอบแล้วว่าส่งภาพ live ได้ macOS และ Linux ใช้เส้นทาง npm เดียวกัน",platformPoints:["Windows: verified","macOS: capture/control ต้องใช้สิทธิ์ Screen Recording/Accessibility","Linux: เพิ่ม linux-x64 runtime, grim/gnome-screenshot/import/scrot capture และ X11/XTEST input แล้ว audio ยังปิดอยู่"],firewallTitle:"Firewall และเครื่องต่างสถานที่",firewallBody:"LiveDesk จะลอง Direct TCP ก่อน หากล้มเหลว control จะใช้ rendezvous relay ที่เข้ารหัส และ video จะใช้ UDP P2P ที่เข้ารหัสเมื่อพร้อม",firewallPoints:["Port client เริ่มต้นสำหรับ Direct TCP ใน LAN คือ 5197","Client และ manager ต้องเชื่อมต่อ outbound ไปยัง rendezvous server ที่ตั้งค่าไว้ได้","หลัง Direct TCP ล้มเหลว ระบบจะลอง relay control และ UDP P2P video อัตโนมัติ","Forward TCP 5197 หรือตั้ง VPN/IP allowlist เฉพาะเมื่อต้องการ Direct TCP ข้าม network","เปิด 5179 เฉพาะเมื่อ browser ระยะไกลต้องเปิด Wall โดยตรง"],commandsTitle:"คำสั่งปัจจุบัน",commandsBody:"ทิศทาง product คือคำสั่ง terminal เดียวข้าม OS ไม่ใช่ download/install จากเว็บไซต์",managerCommandLabel:"เริ่ม manager",clientCommandLabel:"เชื่อม Client",slotCommandLabel:"ตรึง slot 3",manualCommandLabel:"manual connection ขั้นสูง"}),hi:mr({languageName:"हिन्दी",languageLabel:"दस्तावेज़ भाषा",eyebrow:"LiveDesk Manual",title:"एक कमांड से local Screen Wall खोलें",intro:"LiveDesk एक npm-first remote work deck है जिससे एक manager PC से कई Client, mini PC, Mac mini और dev machines देखे जा सकते हैं।",managerTitle:"1. manager चलाएं",managerBody:"जिस computer से screens देखनी हैं उस पर LiveDesk manager चलाएं। यह UI और local server साथ में शुरू करता है और http://127.0.0.1:5179 खोलता है।",managerPoints:["कमांड है npx -y livedesk।","Manager Screen Wall/API के लिए 5179 और client connections के लिए 5197 इस्तेमाल करता है।","अगर पुराने LiveDesk ports बचे हों तो startup default रूप से साफ करता है।"],clientTitle:"2. Client जोड़ें",clientBody:"हर monitored computer पर उसी Google account से sign in करें। Manager online न हो तब भी client बंद नहीं होता और हर 5 सेकंड retry करता है।",clientPoints:["npx -y livedesk client पहला खाली slot लेता है।","npx -y livedesk client 3 machine को slot 3 पर pin करता है।","बहुत सी machines हों तब भी बार-बार login की जरूरत नहीं रहती।"],syncTitle:"3. Sync Server और discovery",syncBody:"Sync Server इस manager को account का active Screen Wall बनाकर Supabase में publish करता है। Clients record पढ़कर endpoints try करते हैं।",syncPoints:["इसमें host instance, LAN/private addresses, public candidates, pair token और short lease होता है।","LAN candidates पहले try होते हैं, जरूरत हो तो public candidates।","Manager, VPN, firewall या router बदलने के बाद Sync Server दबाएं।","livedesk.pages.dev का Chrome Local Network Access अब default runtime नहीं है। npm manager app ही real server है।"],platformTitle:"4. Platform status",platformBody:"Windows live screen transfer के साथ verified है। macOS और Linux भी इसी npm path पर आगे बढ़ रहे हैं।",platformPoints:["Windows: verified.","macOS: capture/control के लिए Screen Recording/Accessibility permissions चाहिए।","Linux: linux-x64 runtime, X11/XTEST input और PipeWire/PulseAudio output audio capture उपलब्ध हैं।"],firewallTitle:"Firewall और remote locations",firewallBody:"LiveDesk पहले Direct TCP आज़माता है; विफल होने पर control encrypted rendezvous relay उपयोग करता है और उपलब्ध होने पर video encrypted UDP P2P उपयोग करता है।",firewallPoints:["LAN Direct TCP का default client port 5197 है।","Clients और manager को configured rendezvous server तक outbound access चाहिए।","Direct TCP विफल होने के बाद relay control और UDP P2P video अपने आप try होते हैं।","TCP 5197 forward या VPN/IP allowlist तभी सेट करें जब networks के बीच Direct TCP चाहिए।","5179 तभी expose करें जब remote browser को Wall सीधे खोलना हो।"],commandsTitle:"Current commands",commandsBody:"Product direction है OS के बीच एक terminal command, website से download/install नहीं।",managerCommandLabel:"Start manager",clientCommandLabel:"Connect Client",slotCommandLabel:"Pin to slot 3",manualCommandLabel:"Advanced manual connection"}),ar:mr({languageName:"العربية",languageLabel:"لغة المستند",eyebrow:"LiveDesk Manual",title:"افتح Screen Wall محلي بأمر واحد",intro:"LiveDesk هو deck بنمط npm-first لمراقبة عدة Clients وأجهزة mini PC وMac mini وأجهزة تطوير من كمبيوتر manager واحد.",managerTitle:"1. شغل manager",managerBody:"شغل LiveDesk على الكمبيوتر الذي سيعرض الشاشات. يبدأ manager الواجهة والخادم المحلي معا ويفتح http://127.0.0.1:5179.",managerPoints:["الأمر هو npx -y livedesk.","يستخدم manager المنفذ 5179 للواجهة/API والمنفذ 5197 لاتصالات client.","إذا بقيت عملية LiveDesk قديمة على المنافذ، يتم تنظيفها افتراضيا عند التشغيل."],clientTitle:"2. وصل Client",clientBody:"على كل كمبيوتر تتم مراقبته، سجل الدخول بنفس حساب Google. إذا لم يكن manager متاحا، يبقى client يعمل ويحاول كل 5 ثوان.",clientPoints:["npx -y livedesk client يختار أول slot فارغ.","npx -y livedesk client 3 يثبت الجهاز في slot 3.","clients تستمر بالمحاولة لتجنب تكرار تسجيل الدخول عند كثرة الأجهزة."],syncTitle:"3. Sync Server والاكتشاف",syncBody:"Sync Server ينشر هذا manager كـ active Screen Wall للحساب. يقرأ clients سجل Supabase ويجربون endpoints بالترتيب.",syncPoints:["السجل يتضمن host instance وعناوين LAN/private وpublic candidates وpair token وlease قصير.","يتم تفضيل LAN أولا، ثم public عند الحاجة.","اضغط Sync Server بعد تغيير manager أو VPN أو firewall أو router.","Chrome Local Network Access على livedesk.pages.dev لم يعد مسار التشغيل الافتراضي. تطبيق npm manager هو الخادم الحقيقي."],platformTitle:"4. حالة المنصات",platformBody:"Windows تم التحقق منه مع نقل شاشة live. macOS وLinux يتبعان نفس مسار npm.",platformPoints:["Windows: تم التحقق.","macOS: capture/control يحتاجان أذونات Screen Recording/Accessibility.","Linux: تمت إضافة linux-x64 runtime وgrim/gnome-screenshot/import/scrot capture وX11/XTEST input. الصوت ما زال معطلا."],firewallTitle:"Firewall والمواقع البعيدة",firewallBody:"يجرب LiveDesk اتصال Direct TCP أولا؛ وإذا فشل يستخدم التحكم rendezvous relay المشفر ويستخدم الفيديو UDP P2P المشفر عند توفره.",firewallPoints:["منفذ client الافتراضي لاتصال Direct TCP داخل LAN هو 5197.","يحتاج client وmanager إلى اتصال outbound بخادم rendezvous المهيأ.","بعد فشل Direct TCP تتم محاولة relay control وUDP P2P video تلقائيا.","وجه TCP 5197 أو اضبط VPN/IP allowlist فقط عند الحاجة إلى Direct TCP بين الشبكات.","اكشف 5179 فقط إذا كان browser بعيد يحتاج فتح Wall مباشرة."],commandsTitle:"الأوامر الحالية",commandsBody:"اتجاه المنتج هو أمر terminal واحد عبر الأنظمة، وليس تحميل وتثبيت يدوي من موقع.",managerCommandLabel:"Start manager",clientCommandLabel:"Connect Client",slotCommandLabel:"Pin to slot 3",manualCommandLabel:"Advanced manual connection"}),tr:mr({languageName:"Türkçe",languageLabel:"Belge dili",eyebrow:"LiveDesk Manual",title:"Yerel Screen Wall tek komutla açılsın",intro:"LiveDesk, tek bir manager PC üzerinden birçok Client, mini PC, Mac mini ve dev machine izlemek için npm-first bir çalışma deckidir.",managerTitle:"1. Manager çalıştır",managerBody:"Ekranları izleyecek bilgisayarda LiveDesk manager çalıştır. Manager UI ve local server birlikte başlar ve http://127.0.0.1:5179 açılır.",managerPoints:["Komut: npx -y livedesk.","Manager Screen Wall/API için 5179, client bağlantıları için 5197 kullanır.","Eski LiveDesk process portları tutuyorsa başlangıç varsayılan olarak temizler."],clientTitle:"2. Client bağla",clientBody:"İzlenecek bilgisayarda aynı Google hesabıyla giriş yap. Manager henüz online değilse client kapanmaz ve her 5 saniyede tekrar dener.",clientPoints:["npx -y livedesk client ilk boş slota yerleşir.","npx -y livedesk client 3 makineyi slot 3’e sabitler.","Çok makinede tekrar tekrar login gerekmesin diye client beklemeye devam eder."],syncTitle:"3. Sync Server ve discovery",syncBody:"Sync Server bu managerı hesabın active Screen Wall kaydı olarak Supabase’e yazar. Clients bu kaydı okuyup endpoint adaylarını dener.",syncPoints:["Host instance, LAN/private adresler, public adaylar, pair token ve kısa lease içerir.","Önce LAN adayları, gerekirse public adaylar denenir.","Manager, VPN, firewall veya router değişince Sync Server’a bas.","livedesk.pages.dev üzerindeki Chrome Local Network Access artık default runtime yolu değil. Gerçek server npm manager app."],platformTitle:"4. Platform durumu",platformBody:"Windows live screen transfer ile doğrulandı. macOS ve Linux aynı npm yolunu takip ediyor.",platformPoints:["Windows: doğrulandı.","macOS: capture/control için Screen Recording/Accessibility izinleri gerekir.","Linux: linux-x64 runtime, grim/gnome-screenshot/import/scrot capture ve X11/XTEST input backend eklendi. Audio kapalı."],firewallTitle:"Firewall ve uzak konumlar",firewallBody:"LiveDesk önce Direct TCP dener; başarısız olursa kontrol şifreli rendezvous relay kullanır ve video mümkün olduğunda şifreli UDP P2P kullanır.",firewallPoints:["LAN Direct TCP için varsayılan client portu 5197dir.","Client ve manager yapılandırılmış rendezvous servera outbound erişebilmelidir.","Direct TCP başarısız olduktan sonra relay control ve UDP P2P video otomatik denenir.","Ağlar arasında Direct TCP gerekiyorsa TCP 5197 forward et veya VPN/IP allowlist yapılandır.","5179u yalnız uzak browser Wallu doğrudan açacaksa expose et."],commandsTitle:"Güncel komutlar",commandsBody:"Ürün yönü, webden indirip kurmak yerine işletim sistemleri arasında ortak tek terminal komutu.",managerCommandLabel:"Manager başlat",clientCommandLabel:"Client bağla",slotCommandLabel:"Slot 3’e sabitle",manualCommandLabel:"Gelişmiş manuel bağlantı"})},PI=Object.entries(yd).map(([t,n])=>({id:t,label:n.languageName}));function FI(){if(typeof navigator>"u")return"en";const t=navigator.languages?.length?navigator.languages:[navigator.language];for(const n of t){const r=n.toLowerCase();if(yd[n])return n;if(r.startsWith("zh-tw")||r.startsWith("zh-hk"))return"zh-TW";if(r.startsWith("pt"))return"pt-BR";const i=r.split("-")[0];if(yd[i])return i}return"en"}function OI({index:t}){const n=t+1;return o.jsx("article",{className:"device-tile placeholder-tile","aria-label":`Empty slot ${n}`,children:o.jsxs("div",{className:"tile-screen","aria-hidden":"true",children:[o.jsx("span",{className:"slot-grid","aria-hidden":"true"}),o.jsxs("span",{className:"empty-screen",children:[o.jsx(Ta,{size:24}),o.jsxs("strong",{children:["Slot ",String(n).padStart(3,"0")]})]})]})})}function HI({entry:t,slotNumber:n}){return o.jsx("article",{className:"device-tile offline-wall-tile","aria-label":`${t.label} offline in slot ${n}`,children:o.jsxs("div",{className:"tile-screen","aria-hidden":"true",children:[o.jsx("span",{className:"slot-grid","aria-hidden":"true"}),o.jsxs("span",{className:"offline-screen",children:[o.jsx(Ta,{size:28}),o.jsx("strong",{children:t.label}),o.jsx("em",{children:"Offline"}),o.jsxs("small",{children:["Slot ",String(n).padStart(3,"0"),t.platform?` · ${t.platform}`:""]})]})]})})}const z0=["cpu","gpu","memory","vram","network","disk","temp"];function BI({entry:t,slotNumber:n}){return o.jsxs("div",{className:"wall-device-list-row offline-layout-row",role:"row","aria-label":`${t.label} offline`,children:[o.jsxs("span",{className:"wall-device-name",role:"gridcell",children:[o.jsx("span",{className:"wall-device-icon","aria-hidden":"true",children:o.jsx(Ta,{size:17})}),o.jsxs("span",{children:[o.jsx("strong",{children:t.label}),o.jsxs("small",{children:["Slot ",String(n).padStart(3,"0"),t.platform?` · ${t.platform}`:""]})]})]}),o.jsxs("span",{className:"wall-device-list-status state-offline",role:"gridcell",children:[o.jsx("i",{"aria-hidden":"true"}),o.jsx("strong",{children:"Offline"})]}),z0.map(r=>o.jsxs("span",{className:"wall-device-list-metric state-unknown",role:"gridcell",children:[o.jsx("strong",{children:"-"}),o.jsx("small",{children:"offline"})]},r))]})}function zI({device:t,slotNumber:n,selected:r,updateIndicator:i,remoteDiagnostics:l,diagnosticsMode:u="remote",onSelect:f,onOpenControl:h}){const g=B0(t),y=new Map(g.metrics.map(b=>[b.id,b])),w=i?.label||g.label;return o.jsxs("div",{className:`wall-device-list-row state-${g.state} ${r?"selected":""}`,role:"row","aria-selected":r,tabIndex:0,onClick:f,onDoubleClick:b=>{b.preventDefault(),h()},onKeyDown:b=>{(b.key==="Enter"||b.key===" ")&&(b.preventDefault(),f())},children:[o.jsxs("span",{className:"wall-device-name",role:"gridcell",children:[o.jsx("span",{className:"wall-device-icon","aria-hidden":"true",children:o.jsx(Ta,{size:17})}),o.jsxs("span",{children:[o.jsx("strong",{children:Rr(t)}),o.jsxs("small",{children:["Slot ",String(n).padStart(3,"0"),t.platform?` · ${t.platform}`:"",t.arch?` · ${t.arch}`:""]})]}),r&&o.jsx(fo,{size:16,strokeWidth:3,"aria-label":"Selected"})]}),o.jsxs("span",{className:`wall-device-list-status state-${g.state} ${i?`update-${i.state}`:""}`,role:"gridcell",title:i?.error||w,children:[o.jsx("i",{"aria-hidden":"true"}),o.jsx("strong",{children:w})]}),z0.map(b=>{const x=y.get(b);return o.jsxs("span",{className:`wall-device-list-metric state-${x?.state||"unknown"}`,role:"gridcell",title:x?`${x.label}: ${x.value} · ${x.detail}`:"Not reported",children:[o.jsx("strong",{children:x?.value||"-"}),o.jsx("small",{children:x?.detail||"not reported"}),x?.ratio!==void 0&&o.jsx("i",{style:{width:`${Math.round(x.ratio*100)}%`},"aria-hidden":"true"})]},b)}),l&&o.jsx("span",{className:"wall-device-list-diagnostics",role:"gridcell",children:o.jsx(v0,{items:l,mode:u})})]})}function $I(t){if(!t)return!1;const n=String(t.platform||"").trim().toLowerCase();return nl(n)&&t.capabilities?.screenRecordingPermission===!1}function nl(t){const n=String(t||"").trim().toLowerCase();return n==="macos"||n==="darwin"||n==="mac"||n==="macosx"}function UI(t){const n=String(t||"").trim().toLowerCase();return n==="linux"||n.startsWith("linux ")}function Rx({device:t,frame:n,selected:r,controlEnabled:i,showStatus:l,monitorIndex:u,monitorCount:f,onSelect:h,onFocusDevice:g,onOpenControl:y,onCycleMonitor:w,onCanvasReady:b,sendInput:x,remoteModifierState:M,updateIndicator:k,presentationReady:N,showPresentationSpinner:E=!1,remoteDiagnostics:I,diagnosticsMode:T="remote"}){const P=d.useRef(null),U=d.useRef(null),F=d.useRef(null),Y=d.useRef(0),D=d.useRef(null),K=B0(t),ne=["cpu","gpu","memory","vram"].map(ie=>K.metrics.find(Oe=>Oe.id===ie)).filter(ie=>!!ie),q=_v(u),O=f>1,W=N??!!n,ce=$I(t)&&!W,$=E&&t.connected&&!W&&!ce,ee=mI(t,n,q),B=ee>=Ap?100:ee/Ap*100,L=ee>=Ap?Ap/ee*100:100,oe={"--screen-aspect":ee.toFixed(5),"--screen-content-width":`${Math.max(1,Math.min(100,B)).toFixed(3)}%`,"--screen-content-height":`${Math.max(1,Math.min(100,L)).toFixed(3)}%`},be=d.useCallback(ie=>{P.current=ie,b(t.deviceId,ie)},[t.deviceId,b]),H=ie=>{const Oe=ie.currentTarget.getBoundingClientRect();return $1(ie.clientX,ie.clientY,Oe)},me=ie=>W1(ie,M),ue=d.useCallback(()=>{D.current!==null&&(window.cancelAnimationFrame(D.current),D.current=null)},[]),Ce=d.useCallback(()=>{const ie=U.current;if(!ie)return;U.current=null;const Oe=Number(ie.input.normalizedX),$e=Number(ie.input.normalizedY);if(!Number.isFinite(Oe)||!Number.isFinite($e))return;x(t.deviceId,{...ie.input,normalizedX:Oe,normalizedY:$e})&&(Y.current=performance.now())},[t.deviceId,x]),Me=d.useCallback(()=>{D.current===null&&(D.current=window.requestAnimationFrame(()=>{D.current=null,Ce()}))},[Ce]),Ne=d.useCallback((ie={},Oe="pointer-ownership-lost")=>{const $e=F.current;return $e?(F.current=null,ue(),Ce(),x(t.deviceId,{type:"pointerup",monitorIndex:q,...$e.input,...ie,button:$e.button,reason:Oe})):!1},[q,ue,t.deviceId,Ce,x]);d.useEffect(()=>{i||(ue(),U.current=null,Ne({},"pointer-control-disabled"))},[ue,i,Ne]),d.useEffect(()=>()=>{ue(),U.current=null,Ne({},"pointer-component-unmount")},[ue,Ne]);const He=(ie,Oe)=>{if(!i)return!1;const $e={type:Oe,monitorIndex:q,...H(ie),button:Ax(ie.button),...me(ie)},qe=F.current;if(qe&&qe.pointerId===ie.pointerId&&(qe.input={normalizedX:$e.normalizedX,normalizedY:$e.normalizedY,shiftKey:$e.shiftKey,ctrlKey:$e.ctrlKey,altKey:$e.altKey,metaKey:$e.metaKey}),Oe==="pointermove"){const vt=performance.now();return U.current={input:$e},vt-Y.current>=ID&&(ue(),Ce()),Me(),!0}return U.current&&(ue(),Ce()),x(t.deviceId,$e)},Ve=d.useCallback(ie=>{const Oe=document.activeElement;Oe instanceof HTMLElement&&ie.contains(Oe)&&Oe.classList.contains("monitor-cycle-button")&&Oe.blur()},[]);return o.jsx("article",{className:`device-tile ${r?"selected":""} ${t.connected?"online":"offline"}`,"data-live-device-id":t.deviceId,style:oe,children:o.jsxs("div",{className:`tile-screen ${W?"has-frame":"is-empty"}`,role:"button",tabIndex:i?-1:0,"aria-pressed":r,onClick:ie=>{ie.target instanceof Element&&ie.target.closest(".monitor-cycle")||i||h()},onKeyDown:ie=>{ie.target instanceof Element&&ie.target.closest(".monitor-cycle")||i||(ie.key==="Enter"||ie.key===" ")&&(ie.preventDefault(),h())},onDoubleClick:ie=>{ie.target instanceof Element&&ie.target.closest(".monitor-cycle")||(ie.preventDefault(),y())},onPointerLeave:ie=>Ve(ie.currentTarget),children:[o.jsx("span",{className:`screen-content ${W?"has-frame":"is-empty"}`,children:o.jsx("canvas",{ref:be,className:`remote-canvas ${W?"has-frame":"is-empty"}`,"data-monitor-index":q,tabIndex:i?0:-1,onPointerDown:ie=>{if(!i)return;ie.preventDefault(),ie.stopPropagation(),g(),ie.currentTarget.focus(),Ne({...H(ie),...me(ie)},"pointer-replaced");const Oe={...H(ie),...me(ie)};He(ie,"pointerdown")&&(F.current={pointerId:ie.pointerId,button:Ax(ie.button),input:Oe},ie.currentTarget.setPointerCapture(ie.pointerId))},onPointerMove:ie=>{i&&ie.preventDefault(),He(ie,"pointermove")},onPointerLeave:ie=>{i&&(He(ie,"pointermove"),ue(),Ce())},onPointerUp:ie=>{if(!i)return;ie.preventDefault(),ie.stopPropagation();const Oe={...H(ie),...me(ie)};Ne(Oe,"pointerup"),ie.currentTarget.hasPointerCapture(ie.pointerId)&&ie.currentTarget.releasePointerCapture(ie.pointerId)},onPointerCancel:ie=>{const Oe={...H(ie),...me(ie)};Ne(Oe,"pointercancel"),ie.currentTarget.hasPointerCapture(ie.pointerId)&&ie.currentTarget.releasePointerCapture(ie.pointerId)},onLostPointerCapture:ie=>{const Oe={...H(ie),...me(ie)};Ne(Oe,"lostpointercapture")},onWheel:ie=>{i&&(ie.preventDefault(),x(t.deviceId,{type:"wheel",monitorIndex:q,...H(ie),deltaX:ie.deltaX,deltaY:ie.deltaY,...me(ie)}))},onContextMenu:ie=>i&&ie.preventDefault()},`${t.deviceId}:monitor:${q}`)}),!W&&o.jsx("span",{className:"empty-screen",children:o.jsx(Ta,{size:26})}),o.jsx("span",{className:"wall-device-title",title:Rr(t),children:Rr(t)}),$&&o.jsxs("span",{className:"wall-presentation-loading",role:"status","aria-live":"polite",children:[o.jsx("span",{className:"wall-presentation-spinner","aria-hidden":"true"}),o.jsx("strong",{children:"Preparing video"})]}),ce&&o.jsxs("span",{className:"wall-presentation-loading permission-required",role:"status","aria-live":"polite",children:[o.jsx(Na,{size:24,"aria-hidden":"true"}),o.jsx("strong",{children:"Screen Recording permission required"}),o.jsx("small",{children:"Allow the terminal app on this Mac, then restart LiveDesk."})]}),k&&o.jsxs("span",{className:`wall-update-status state-${k.state}`,role:"status","aria-live":"polite",title:k.error||k.label,children:[k.state==="updated"?o.jsx(Ba,{size:20,"aria-hidden":"true"}):k.state==="failed"?o.jsx(hr,{size:22,"aria-hidden":"true"}):k.state==="offline"?o.jsx(wd,{size:22,"aria-hidden":"true"}):o.jsx("span",{className:"wall-update-spinner","aria-hidden":"true"}),o.jsx("strong",{children:k.label}),k.error?o.jsx("small",{children:k.error}):null]}),l&&o.jsxs(o.Fragment,{children:[o.jsx("span",{className:`tile-health-pill state-${K.state}`,children:K.label}),o.jsx("span",{className:"tile-metrics","aria-label":`${Rr(t)} status`,children:ne.map(ie=>o.jsxs("span",{className:`tile-metric state-${ie.state}`,children:[o.jsx("b",{children:ie.label}),o.jsx("em",{children:ie.value}),ie.ratio!==void 0&&o.jsx("i",{style:{width:`${Math.round(ie.ratio*100)}%`}})]},ie.id))})]}),I&&o.jsx(v0,{items:I,mode:T}),O&&o.jsxs("span",{className:"monitor-cycle","aria-label":`${Rr(t)} display ${q+1} of ${f}`,onPointerDown:ie=>ie.stopPropagation(),onClick:ie=>ie.stopPropagation(),onDoubleClick:ie=>ie.stopPropagation(),children:[o.jsx("button",{className:"monitor-cycle-button previous",onClick:ie=>{ie.preventDefault(),ie.stopPropagation(),w(-1),ie.currentTarget.blur()},title:"Previous display",type:"button",children:o.jsx(zx,{size:18})}),o.jsxs("span",{className:"monitor-cycle-count",children:["Screen ",q+1,"/",f]}),o.jsx("button",{className:"monitor-cycle-button next",onClick:ie=>{ie.preventDefault(),ie.stopPropagation(),w(1),ie.currentTarget.blur()},title:"Next display",type:"button",children:o.jsx(Av,{size:18})})]}),r&&o.jsx("span",{className:"device-selection-check","aria-hidden":"true",children:o.jsx(fo,{size:23,strokeWidth:3.5})})]})})}function qI({visible:t}){return d.useEffect(()=>{if(!t||!Ig)return;if(!document.getElementById(ox)){const r=document.createElement("script");r.id=ox,r.async=!0,r.crossOrigin="anonymous",r.src=`https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=${encodeURIComponent(xv)}`,document.head.appendChild(r)}const n=window.setTimeout(()=>{try{window.adsbygoogle=window.adsbygoogle||[],window.adsbygoogle.push({})}catch{}},120);return()=>window.clearTimeout(n)},[t]),t?o.jsxs("aside",{className:`free-ad-banner ${Ig?"adsense-ready":"house-ad"}`,"aria-label":"Advertisement",children:[o.jsx("span",{className:"ad-label",children:"Advertisement"}),Ig?o.jsx("ins",{className:"adsbygoogle livedesk-ad-unit",style:{display:"block"},"data-ad-client":xv,"data-ad-slot":I0,"data-ad-format":"auto","data-full-width-responsive":"true"}):o.jsxs("div",{className:"house-ad-copy",children:[o.jsx("strong",{children:"Sponsored placement"}),o.jsx("span",{children:"Mini PCs, GPUs, NAS, networking, and developer tools."})]})]}):null}function WI({runtimeBaseUrl:t=""}){const{session:n,loading:r}=y1(),{target:i,error:l,refresh:u}=w1(n),f=d.useMemo(()=>{if(!i?.active)return null;const p=i.expires_at?Date.parse(i.expires_at):Number.POSITIVE_INFINITY;return Number.isFinite(p)&&p<=Date.now()?null:i},[i]),h=d.useMemo(()=>Ib(f),[f]),g=t.trim().replace(/\/+$/,""),y=d.useMemo(()=>[...new Set([g,...h,Dn].filter(Boolean))],[h,g]),[w,b]=d.useState(cI),x=d.useMemo(()=>y.some(p=>!!hd(p)),[y]),M=!x||w,{status:k,devices:N,error:E,refresh:I,hubBaseUrl:T}=b1(y,M),{entitlement:P,licensed:U,loading:F,error:Y,refresh:D}=x1(n),[K,ne]=d.useState([]),[q,O]=d.useState(""),[W,ce]=d.useState(""),[$,ee]=d.useState(""),[B,L]=d.useState(""),[oe,be]=d.useState(""),[H,me]=d.useState("idle"),[ue,Ce]=d.useState(!1),[Me,Ne]=d.useState(null),He=d.useRef(null),[Ve,ie]=d.useState(""),Oe=d.useRef("");Oe.current=B;const[$e,qe]=d.useState(!1),[vt,xe]=d.useState([]),he=d.useRef(null),[pe,Ae]=d.useState(!1),Se=d.useRef(""),Pe=d.useRef(new Map),Qe=d.useRef(0),Z=d.useRef(!1),$t=d.useRef(""),Ee=d.useRef(null);Ee.current||(Ee.current=J1());const Ge=d.useRef(document.visibilityState==="visible"),[ze,Ft]=d.useState({}),Ze=d.useRef({}),nt=d.useRef(new Set),lt=d.useRef(new Map),Tt=d.useRef(new Map),[Mt,rt]=d.useState({}),dt=d.useMemo(()=>new Set(Object.keys(ze)),[ze]),G=d.useCallback((p,S)=>{if(!p)return;const C={...Ze.current};S?C[p]=S:delete C[p],Ze.current=C,Ft(C)},[]),ge=d.useCallback((p,S)=>{p&&rt(C=>{if(!!C[p]===S)return C;const R={...C};return S?R[p]=!0:delete R[p],R})},[]),De=d.useCallback((p,S)=>{p&&Tt.current.set(p,{paused:S,expiresAt:Date.now()+qD})},[]),[z,ae]=d.useState(""),[Te,Ue]=d.useState(""),[Xe,at]=d.useState(!1),kt=d.useRef(null),At=d.useRef(null);d.useEffect(()=>{z==="auth"&&n?.access_token&&ae("")},[z,n?.access_token]);const[Ut,Qt]=d.useState(""),[sa,Ra]=d.useState(null),Pn=d.useRef(null),$n=d.useRef(0),ia=d.useCallback((p,S,C)=>{const R=String(p||"").trim();if(Qt(R),Pn.current!==null&&(window.clearTimeout(Pn.current),Pn.current=null),!R){Ra(null);return}const j=++$n.current;if(Ra({id:j,message:R,tone:S}),!C)return;const Q=window.setTimeout(()=>{Ra(X=>X?.id===j?null:X),Pn.current===Q&&(Pn.current=null)},5e3);Pn.current=Q},[]),Fe=d.useCallback((p,S="info")=>{ia(p,S,!0)},[ia]),V=d.useCallback(p=>{ia(p,"progress",!1)},[ia]),Je=d.useCallback(async(p,S)=>{const C=String(n?.user?.id||"").trim();if(!C)throw new Error("Sign in before saving a Wall layout.");const R=++Er.current,j=ou(S);jr(!0);try{const{data:Q,error:X}=await Pt.from("livedesk_wall_layouts").upsert({user_id:C,is_locked:p,slots:j},{onConflict:"user_id"}).select("is_locked, slots, revision, updated_at").single();if(X)throw X;if(R===Er.current){const le=Q?.is_locked===!0;ct(le),mt(!1),fn(le?ou(Q?.slots):[])}return Q}finally{R===Er.current&&jr(!1)}},[n?.user?.id]);d.useEffect(()=>{const p=String(n?.user?.id||"").trim(),S=++Er.current;if(jr(!1),!p){ct(!1),mt(!1),fn([]),Rn(!1);return}let C=!1;return Rn(!0),(async()=>{const{data:R,error:j}=await Pt.from("livedesk_wall_layouts").select("is_locked, slots, revision, updated_at").eq("user_id",p).maybeSingle();if(!(C||S!==Er.current)){if(j)Fe(`Wall layout could not be loaded: ${j.message}`,"error"),ct(!1),mt(!1),fn([]);else{const Q=R?.is_locked===!0;ct(Q),mt(!1),fn(Q?ou(R?.slots):[])}Rn(!1)}})(),()=>{C=!0}},[n?.user?.id,Fe]),d.useEffect(()=>()=>{Pn.current!==null&&window.clearTimeout(Pn.current)},[]);const[gt,nn]=d.useState(()=>typeof window<"u"&&window.location.pathname.startsWith("/support")?"support":"wall");d.useEffect(()=>{const p=()=>{nn(window.location.pathname.startsWith("/support")?"support":S=>S==="support"?"wall":S)};return window.addEventListener("popstate",p),()=>window.removeEventListener("popstate",p)},[]);const[Sn,Ms]=d.useState("large"),[qa,fe]=d.useState(wI),_e=fv(qa),[et,Rt]=d.useState(SI),An=d.useCallback(p=>{Rt(p),CI(p)},[]),[Et,ct]=d.useState(!1),[jt,mt]=d.useState(!1),[Yt,fn]=d.useState([]),[Xt,Rn]=d.useState(!1),[Wt,jr]=d.useState(!1),[Ks,Nn]=d.useState(""),[Un,Ni]=d.useState(0),Ja=d.useRef(""),Er=d.useRef(0),[jn,Dr]=d.useState(!1),[In,ea]=d.useState(!1),[en,Qs]=d.useState(!1),[Ys,As]=d.useState(!1),[lc,Xr]=d.useState(Date.now),Ir=d.useRef(null);d.useEffect(()=>()=>{Ir.current!==null&&window.clearTimeout(Ir.current)},[]);const[Ln,vo]=d.useState(FI),[Zr,Ti]=d.useState(!1),[Jr,es]=d.useState(!1),[mu,Ri]=d.useState(!1),[Xs,sl]=d.useState(lI),[St]=d.useState(gI),[qn]=d.useState(yI),[il]=d.useState(pI),[rn,Zs]=d.useState(il.selections),vr=d.useRef({...il.topologyFingerprints}),Ns=d.useRef({}),yo=d.useRef({...il.selections}),[Ot,Wn]=d.useState(null),[bo,Js]=d.useState([]),[ta,Ts]=d.useState(_e),[ja,ts]=d.useState(""),[wo,Rs]=d.useState(0),[cc,Lr]=d.useState(0),[pu,ol]=d.useState(0),[ji,ei]=d.useState(()=>new Set),Ht=d.useRef(new Map),Fn=d.useRef(new Map),er=d.useRef(new Map),pn=d.useRef(new Map),js=d.useRef(new Map),oa=d.useRef(new Set),Ei=d.useRef(new Map),tr=d.useRef(new Map),xo=d.useRef(new WeakMap),uc=d.useRef(new WeakMap),So=d.useRef(""),nr=d.useRef(null),im=d.useRef(Promise.resolve()),ll=d.useRef(0),cl=d.useRef(null),yr=d.useRef(null),dc=d.useRef(""),br=d.useRef(new Map),ul=d.useRef(null),dl=d.useRef(0),ti=d.useRef(new Map),kd=d.useRef(typeof window<"u"&&new URLSearchParams(window.location.search).get("livedeskTransmissionProbe")==="1"),hu=d.useRef(new Map),Md=d.useRef([]),gu=d.useRef(0),[vu,Ad]=d.useState({}),Di=d.useRef(new Map),[fc,yu]=d.useState({}),bu=d.useRef(null),[Nd,Wa]=d.useState(!1),wu=d.useRef(null),ch=d.useRef(0),ni=d.useRef(null),om=d.useRef(new Map),ns=d.useRef(null),ar=d.useRef(null),va=d.useRef(null),mc=d.useRef(!1),Td=d.useRef(0),On=d.useRef(0),ya=d.useRef(""),Rd=d.useRef(Promise.resolve()),Co=d.useRef(""),pt=d.useRef(null),_r=d.useRef(""),ko=d.useRef(null),fl=d.useRef(0),ml=d.useRef(""),ai=d.useRef(new Map),as=d.useRef(new Map),Ii=d.useRef(performance.now()),pl=d.useRef(new Map),Es=d.useRef(new Map),Li=d.useRef(new Map),Mo=d.useRef(new Map),hl=d.useRef(new Map),rr=d.useRef(document.visibilityState==="visible"),_i=d.useRef(1),xu=d.useRef([]),[Ea,uh]=d.useState(document.visibilityState==="visible"),[dh,fh]=d.useState(0),pc=d.useRef(0),Su=d.useRef(0),Da=d.useRef(0),Pi=d.useRef(0),Cu=d.useRef(0),ku=d.useRef(new Map),hc=d.useRef([]),jd=d.useRef(new Map),Mu=d.useRef(new Map),ri=d.useRef(new Map),si=d.useRef(new Set),Fi=d.useCallback(p=>EA(xo.current,p),[]),Ds=d.useCallback(p=>Ev(uc.current,p),[]),ii=d.useCallback((p,S)=>Vb(uc.current,p,S),[]),Gn=d.useCallback(p=>{const S=Gb(xo.current,p);return Gb(uc.current,p),S},[]),Pr=d.useCallback((p,S)=>Vb(xo.current,p,S),[]),Ao=d.useCallback(p=>yr.current===p?!0:[Ht.current,Fn.current,er.current,pn.current,br.current].some(C=>Array.from(C.values()).some(R=>R===p)),[]),la=d.useCallback(p=>{p&&(Gn(p),si.current.add(p),LA(p,{isCurrent:Ao,dispose:id,schedule:S=>queueMicrotask(()=>{try{S()}finally{si.current.delete(p)}})}))},[Ao,Gn]),wr=d.useCallback(p=>(Gn(p),th(p,id)),[Gn]),Oi=d.useCallback(()=>{const p=yr.current,S=[...si.current];yr.current=null,si.current.clear(),xo.current=new WeakMap,uc.current=new WeakMap,tr.current.clear(),dc.current="",IA([Ht.current,Fn.current,er.current,pn.current,br.current],[p,...S],id),ul.current=null,dl.current=0,js.current.clear(),oa.current.clear(),Ei.current.clear(),ti.current.clear(),hu.current.clear(),Md.current.length=0,Di.current.clear(),nt.current.clear()},[]);d.useEffect(()=>()=>{Oi()},[Oi]);const ca=d.useCallback((p,S)=>{const C=pa(p,S),R=performance.now();ai.current.delete(C),as.current.delete(C),pl.current.delete(C),hl.current.delete(C),ri.current.delete(C),Di.current.delete(C),ti.current.delete(C),yu(j=>{if(!Object.prototype.hasOwnProperty.call(j,C))return j;const Q={...j};return delete Q[C],Q}),Ad(j=>{if(!Object.prototype.hasOwnProperty.call(j,C))return j;const Q={...j};return delete Q[C],Q}),p==="control"?(Es.current.delete(C),Li.current.set(C,R)):Mo.current.set(C,R)},[]),[Hi,oi]=d.useState(null),[mh,Ed]=d.useState(!1),[Jv,lm]=d.useState([]),[No,Dd]=d.useState("all"),[Ia,gl]=d.useState([]),[rs,gc]=d.useState(!1),[cm,Au]=d.useState(!0),vc=d.useRef(null),Nu=d.useRef(null),To=d.useRef(null),um=d.useRef(null),Tu=d.useRef(!1),Bi=d.useRef(!1),Id=d.useRef(!1),La=d.useRef(0),ss=d.useRef(0),ba=d.useRef(0),is=d.useRef(0),Ro=d.useRef(0),Is=d.useRef(""),vl=gt==="settings",Ld=gt==="pricing",Ru=gt==="doc",_d=gt==="support",_a=gt==="share-files",zi=gt==="agents",Ls=!vl&&!Ld&&!Ru&&!_d&&!_a&&!zi,wt=gt==="control",xr=Ea&&gt==="wall",Sr=d.useRef(xr);Sr.current=xr;const ua=Ea&&(gt==="wall"||wt),Fr=d.useRef(ua);Fr.current=ua;const wa=Ea&&(wt||xr),Cr=d.useRef({active:ua,epoch:_i.current});Cr.current.active!==ua&&(_i.current+=1,Cr.current={active:ua,epoch:_i.current}),d.useEffect(()=>{Ls||(Dr(!1),ea(!1),Qs(!1))},[Ls]);const Dt=St.frameMode==="mode4-h264-atlas",kr=oe||qn.frameMode,jo=kr!=="mode3-h264-hw"?Math.min(30,qn.fps):qn.fps,$i=N.find(p=>p.deviceId===W),dm=$i?.platform,xa=$i?Ws($i,rn[$i.deviceId]):0,mn=$i?Zv($i,xa):null,Gt=UI(dm)?{maxWidth:1280,maxHeight:720}:hx,li=kr!=="mode3-h264-hw"?{maxWidth:1920,maxHeight:1080}:hx,Ga={maxWidth:Math.min(li.maxWidth,Gt.maxWidth,qn.maxWidth),maxHeight:Math.min(li.maxHeight,Gt.maxHeight,qn.maxHeight)},Ui={maxWidth:mn?.width?Math.min(Ga.maxWidth,mn.width):Ga.maxWidth,maxHeight:mn?.height?Math.min(Ga.maxHeight,mn.height):Ga.maxHeight};d.useEffect(()=>{if(k?.started){if(!n?.access_token){tt("/api/remote/license",{method:"DELETE"},T).catch(()=>{});return}tt("/api/remote/license/sync",{method:"POST",headers:{Authorization:`Bearer ${n.access_token}`}},T).catch(p=>{console.warn("[LiveDesk] Hub license sync failed",p)})}},[P?.updated_at,T,n?.access_token,k?.started]),d.useEffect(()=>{!n?.access_token||!k?.started||k.runtimeRole!=="hub"||!k.deviceId||(async()=>{try{const{data:p,error:S}=await Pt.rpc("register_livedesk_device",{p_device_id:k.deviceId,p_device_name:k.deviceName||k.deviceId,p_role:"hub",p_assigned_hub_id:null,p_platform:navigator.platform||navigator.userAgent,p_os_version:navigator.userAgent,p_app_version:k.managerVersion||k.managerPackage||""}),C=Array.isArray(p)?p[0]:p;(S||C?.ok===!1)&&console.warn("[LiveDesk] Hub device role registration failed",S||C?.reason||"unknown-error")}catch(p){console.warn("[LiveDesk] Hub device role registration failed",p)}})()},[n?.access_token,k?.deviceId,k?.deviceName,k?.managerPackage,k?.managerVersion,k?.runtimeRole,k?.started]),d.useEffect(()=>{!n?.access_token||!n.refresh_token||!k?.started||k.runtimeRole!=="hub"||Id.current||(Id.current=!0,tt("/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}})},T||Dn).then(p=>{p.hostTarget?.ok===!1&&console.warn("[LiveDesk] Hub host target publish is waiting for a valid Hub role:",p.hostTarget.error||"unknown-error"),I()}).catch(p=>{console.warn("[LiveDesk] Hub session sync failed:",p)}).finally(()=>{Id.current=!1}))},[T,I,n?.access_token,n?.expires_at,n?.refresh_token,n?.user?.email,n?.user?.id,k?.runtimeRole,k?.started]);const ut=d.useMemo(()=>N.filter(p=>p.connected),[N]);d.useEffect(()=>{const p={...Ze.current},S=Date.now();let C=!1;rt(R=>{const j={...R};let Q=!1;for(const X of N){const le=String(X.liveCapturePause?.token||"").trim(),te=Tt.current.get(X.deviceId);if(te)if((te.paused?!!le:!le)||te.expiresAt<=S)Tt.current.delete(X.deviceId);else continue;const re=!!le&&(X.liveCapturePause?.captureStopConfirmed!==!0||X.liveCapturePause?.phase==="stop-unconfirmed");!!j[X.deviceId]!==re&&(Q=!0,re?j[X.deviceId]=!0:delete j[X.deviceId])}return Q?j:R});for(const R of N){const j=String(R.liveCapturePause?.token||"").trim(),Q=String(p[R.deviceId]||""),X=Tt.current.get(R.deviceId);if(X)if((X.paused?!!j:!j)||X.expiresAt<=S)Tt.current.delete(R.deviceId);else continue;j&&j!==Q?(p[R.deviceId]=j,C=!0):!j&&Q&&(delete p[R.deviceId],lt.current.delete(R.deviceId),C=!0)}C&&(Ze.current=p,Ft(p))},[N]);const Pd=No==="all"?ut.length:Ia.filter(p=>ut.some(S=>S.deviceId===p)).length,fm=d.useMemo(()=>ut.reduce((p,S)=>Math.max(p,Tx(S.slotNumber)),0),[ut]),os=Math.max(kD,ut.length,fm),qi=d.useMemo(()=>{const p=Array(os).fill(null),S=[];for(const C of ut){const R=Tx(C.slotNumber);R>0&&R<=os&&!p[R-1]?p[R-1]=C:S.push(C)}for(const C of S){const R=p.findIndex(j=>!j);R<0?p.push(C):p[R]=C}return p},[ut,os]),Or=d.useMemo(()=>Et||jt?dN({connectedDevices:ut,entries:Yt,minimumSlotCount:os}):qi.map((p,S)=>({slotNumber:S+1,device:p,saved:null,offline:!1,persisted:!1})),[ut,qi,os,jt,Yt,Et]),_s=d.useMemo(()=>RS(Or),[Or]),yc=d.useMemo(()=>JSON.stringify(_s)!==JSON.stringify(ou(Yt)),[_s,Yt]),ci=d.useMemo(()=>Or.map(p=>p.device),[Or]),Ps=d.useMemo(()=>Or.filter(p=>!!p.device||!!p.saved),[Or]),Wi=d.useCallback(async()=>{const p=Et,S=jt,C=Yt,R=_s;ct(!0),mt(!1),fn(R);try{await Je(!0,R),Fe("Current Wall layout is locked and saved to your account.","success")}catch(j){ct(p),mt(S),fn(C),Fe(`Wall layout could not be saved: ${j instanceof Error?j.message:String(j)}`,"error")}},[Je,Fe,_s,jt,Yt,Et]),ui=d.useCallback(async()=>{const p=Et,S=jt,C=Yt;if(ct(!1),mt(!1),fn([]),!p){Fe("Wall layout draft released. Client slot order is active again.","success");return}try{await Je(!1,[]),Fe("Saved Wall layout released. Client slot order is active again.","success")}catch(R){ct(p),mt(S),fn(C),Fe(`Wall layout could not be released: ${R instanceof Error?R.message:String(R)}`,"error")}},[Je,Fe,jt,Yt,Et]),Fd=d.useCallback((p,S)=>{!p||Xt||Wt||(Ja.current=p,Nn(p),S.dataTransfer.effectAllowed="move",S.dataTransfer.setData("text/plain",p))},[Xt,Wt]),yl=d.useCallback(()=>{Ja.current="",Nn(""),Ni(0)},[]),bl=d.useCallback(async p=>{const S=Ja.current;if(!S||p<=0||Xt||Wt){yl();return}const C=jt,R=Yt,j=fN(Or,S,p);if(yl(),JSON.stringify(j)!==JSON.stringify(_s)){if(fn(j),!Et){mt(!0);return}try{await Je(!0,j)}catch(Q){mt(C),fn(R),Fe(`Wall position could not be saved: ${Q instanceof Error?Q.message:String(Q)}`,"error")}}},[yl,Je,Fe,_s,jt,Yt,Xt,Et,Wt,Or]),Eo=d.useMemo(()=>ut.map(p=>p.deviceId),[ut]),Hr=d.useMemo(()=>new Set(K),[K]),tn=d.useMemo(()=>ut.filter(p=>Hr.has(p.deviceId)),[ut,Hr]),di=d.useMemo(()=>N.find(p=>p.deviceId===q)||tn[0]||null,[N,q,tn]),Pa=d.useMemo(()=>N.find(p=>p.deviceId===W)||null,[W,N]),Br=Pa?Ws(Pa,rn[Pa.deviceId]):0,Be=wt?Pa:di,mm=d.useMemo(()=>new Set(Ia),[Ia]),Vn=d.useMemo(()=>No==="all"?ut.map(p=>p.deviceId):ut.filter(p=>mm.has(p.deviceId)).map(p=>p.deviceId),[ut,mm,No]),Od=Be?_p(Be,"control"):!1,Do=nl(Be?.platform)&&(Be?.capabilities?.controlPermission===!1||Be?.capabilities?.accessibilityPermission===!1),Va=Be?_p(Be,"audio")||_p(Be,"remoteAudio"):!1,ls=(Array.isArray(Be?.capabilities?.agentTools)?Be.capabilities.agentTools.map(String):[]).includes("system.power"),Cn=U?P?.plan==="pro"?"pro":"ltd":"free",hm=Jc[Cn],ju=hm.limit,Fs=d.useMemo(()=>new Set(aN(ut,ju)),[ju,ut]),gm=!Be||Fs.has(Be.deviceId),Io=Cn==="free",an=gm,fi=Cn==="ltd"?`Plus includes up to ${zf} Clients. Upgrade to Pro for commercial use and larger walls.`:`Free includes up to ${Bf} Clients. Upgrade to Plus for ${zf} devices and an ad-free default.`,vm=Cn==="free"&&!et,sr=an&&!!Be&&Od,Eu=an&&!!Be&&Va,Gi=d.useMemo(()=>wt?Be?[Be]:[]:tn.length>0?tn:Be?[Be]:[],[Be,tn,wt]),Fa=d.useMemo(()=>Gi.filter(p=>Fs.has(p.deviceId)),[Fs,Gi]),bc=Fa.some(p=>String(ze[p.deviceId]||"").startsWith("pending:")||Mt[p.deviceId]===!0),cs=!(Fa.length>0&&Fa.every(p=>{const S=String(ze[p.deviceId]||"");return!!S&&!S.startsWith("pending:")&&Mt[p.deviceId]!==!0}))||bc,Os=d.useMemo(()=>ci.filter(p=>!!p?.connected).slice(0,kI(Sn)).map(p=>p.deviceId),[ci,Sn]),wc=d.useMemo(()=>ua?xr?Dt||Sn==="list"?Eo:St.visibleOnlyLive?bo.length>0?bo:Os:Eo:hc.current.length>0?hc.current:Eo:[],[Os,Dt,bo,St.visibleOnlyLive,Eo,ua,xr,Sn]),us=d.useMemo(()=>Fg(wc.filter(p=>Fs.has(p))),[Fs,wc]);hc.current=us;const Ka=d.useMemo(()=>us.filter(p=>p!==ja&&!dt.has(p)),[dt,us,ja]),Vi=d.useMemo(()=>new Map(ut.map(p=>[p.deviceId,p.platform])),[ut]),Ki=d.useMemo(()=>Object.fromEntries(ut.map(p=>[p.deviceId,String(p.sessionId||"").trim()])),[ut]),ir=rN(Dt,us.length),Sa=d.useMemo(()=>Dt?Ka.filter(p=>_f({mode4Enabled:Dt,directMode4WallEnabled:ir,isMac:nl(Vi.get(p))})==="atlas"):[],[ir,Dt,Vi,Ka]),or=d.useMemo(()=>Ka.filter(p=>_f({mode4Enabled:Dt,directMode4WallEnabled:ir,isMac:nl(Vi.get(p))})==="direct"),[ir,Dt,Vi,Ka]),Qi=d.useMemo(()=>{const p=St.autoStartLive?Ka.map(S=>pa("wall",S)):[];return wa&&an&&$&&Fs.has($)&&(H==="connecting"||H==="active"||H==="warm")&&p.push(pa("control",$)),[...new Set(p)].sort()},[wa,$,H,an,Fs,St.autoStartLive,Ka]);d.useEffect(()=>{const p=new Set(us);ei(S=>{let C=!1;const R=new Set;for(const j of S)p.has(j)?R.add(j):C=!0;return C?R:S})},[us]);const ym=d.useMemo(()=>{const p=j=>ut.find(Q=>Q.deviceId===j)||null,S=j=>{const Q=p(j);return Q?Ws(Q,rn[j]):0},C=(j,Q=S(j))=>j===$&&(H==="connecting"||H==="active"||H==="warm")?pn.current.get(j)||Fn.current.get(j)||null:Dt?br.current.get(j)||Ht.current.get(j)||null:Ht.current.get(j)||null,R=(j,Q=S(j))=>{const X=p(j);return`${X?Rr(X):j} · Monitor ${Q+1}`};return{resolveCurrentTarget(){if(wt&&Pa){const te=Br;return{type:"control",deviceIds:[Pa.deviceId],monitorIndex:te,label:`${Rr(Pa)} · Monitor ${te+1}`,sourceCanvas:C(Pa.deviceId,te),signature:`control:${Pa.deviceId}:${te}:${qn.frameMode}`}}const j=tn.map(te=>te.deviceId).filter(te=>Ka.includes(te)),Q=di&&Ka.includes(di.deviceId)?di.deviceId:"",X=j.length>0?j:Q?[Q]:Ka,le=j.length===0&&!Q;if(X.length===0)return null;if(X.length===1){const te=X[0],re=S(te);return{type:le?"wall":j.length>1?"selection":"device",deviceIds:X,monitorIndex:re,label:le?"Wall":R(te,re),sourceCanvas:le?null:C(te,re),signature:`${le?"wall":"device"}:${te}:${re}:${Dt?"atlas":"direct"}`}}return{type:j.length>1?"selection":"wall",deviceIds:X,label:j.length>1?`${X.length} selected Clients`:"Wall",sourceCanvas:null,signature:`${j.length>1?"selection":"wall"}:${X.join(",")}:${Sn}`}},getDeviceCanvas:C,composeWall(j,Q={}){return fD(j.map(X=>{const le=S(X);return{deviceId:X,label:R(X,le),canvas:C(X,le)}}),Q)}}},[ut,Pa,$,H,qn.frameMode,Ht,Dt,rn,Br,tn,wt,Ka,di,Sn]),mi=CD({hubUrl:T,sourceRegistry:ym,onToast:Fe}),Yi=d.useMemo(()=>wa&&an&&$&&Fs.has($)&&(H==="connecting"||H==="active"||H==="warm")?[$]:[],[wa,$,H,an,Fs]),xc=d.useMemo(()=>Fg([...us,...Yi]),[Yi,us]),ds=d.useMemo(()=>Cx(St,Sn),[St,Sn]),Oa=d.useMemo(()=>Cx(St,"large"),[St]),fs=sN({mode4Enabled:Dt,directMode4WallEnabled:ir,adaptiveFps:ta,directDeviceCount:or.length,adaptive:St.adaptiveLoadShedding}),Sc=lN({deviceCount:Sa.length,targetFps:ta,adaptive:St.adaptiveLoadShedding});Dt&&Sa.length>0;const ms=d.useCallback((p,S,C,R="low")=>{if(p.width<=0||p.height<=0)return!1;const j=C?Math.min(1,C.maxWidth/p.width,C.maxHeight/p.height):1,Q=Math.max(1,Math.round(p.width*j)),X=Math.max(1,Math.round(p.height*j));(S.width!==Q||S.height!==X)&&(S.width=Q,S.height=X);const le=S.getContext("2d",{alpha:!1});return le?(le.imageSmoothingEnabled=!0,le.imageSmoothingQuality=R,le.drawImage(p,0,0,p.width,p.height,0,0,S.width,S.height),!0):!1},[]),Xi=d.useCallback((p,S)=>{const C=Math.max(0,Number(S.clientWidth||0)),R=Math.max(0,Number(S.clientHeight||0)),j=Math.max(1,Number(window.devicePixelRatio||1)),Q=C>0&&R>0?{maxWidth:Math.ceil(C*j),maxHeight:Math.ceil(R*j)}:void 0;return ms(p,S,Q,"high")},[ms]),Zi=d.useCallback((p,S)=>{if(!kd.current)return;const C=`${p}:${S.deviceId}`,R=hu.current.get(C)||{bindingKey:"",totalPaints:0,lastPaintAt:0,lastFrameSeq:0};R.bindingKey=co(S),R.totalPaints+=1,R.lastPaintAt=performance.now(),R.lastFrameSeq=Number(S.frameSeq||0),hu.current.set(C,R);const j=++gu.current,Q={sequence:j,scope:p,deviceId:S.deviceId,bindingKey:R.bindingKey,frameSeq:R.lastFrameSeq,paintedAt:R.lastPaintAt};Md.current[(j-1)%VD]=Q},[]),ps=d.useCallback(p=>{p&&ei(S=>{if(S.has(p))return S;const C=new Set(S);return C.add(p),C})},[]),hs=d.useCallback(p=>{p&&ei(S=>{if(!S.has(p))return S;const C=new Set(S);return C.delete(p),C})},[]),zr=d.useCallback((p,S)=>{if(!S||S.width<=0||S.height<=0)return!1;const C=document.createElement("canvas");if(C.width=S.width,C.height=S.height,!ms(S,C))return la(C),!1;const R=er.current.get(p);return er.current.set(p,C),R&&R!==C&&wr(R),ps(p),!0},[ps,ms,wr,la]),Hn=d.useCallback(p=>{DA(er.current,p,id)},[]),Cc=d.useCallback((p,S)=>{const C=er.current.get(p),R=Ht.current.get(p)===S||br.current.get(p)===S;return Ze.current[p]?(Hn(p),!1):!C||!R||C.width<=0||C.height<=0?!1:ms(C,S)?!0:(Hn(p),!1)},[ms,Hn]),gs=d.useCallback((p,S=!1,C)=>{if(Ze.current[p]||!oa.current.has(p))return!1;const R=performance.now(),j=Math.max(1,Math.min(_e,Jn.controlWallReuseMaxFps,jo)),Q=Ei.current.get(p)||0,X=nN({nowMs:R,nextPaintAtMs:Q,targetFps:j,sourceFps:jo,force:S});if(!X.shouldPaint)return!1;const le=pn.current.get(p)||Fn.current.get(p),te=Ht.current.get(p)||br.current.get(p);if(!le||!te)return!1;const re=Math.max(0,Number(te.clientWidth||0)),Ye=Math.max(0,Number(te.clientHeight||0)),Le=Math.max(1,Number(window.devicePixelRatio||1)),st=re>0&&Ye>0?{maxWidth:Math.min(ds.maxWidth,Math.ceil(re*Le)),maxHeight:Math.min(ds.maxHeight,Math.ceil(Ye*Le))}:ds;return ms(le,te,st)?(X.sourceCadencePassthrough?Ei.current.delete(p):Ei.current.set(p,X.nextPaintAtMs),C&&te.isConnected&&Zi("wall-reuse-visible",C),ps(p),Hn(p),!0):!1},[jo,ds,ps,ms,Zi,Hn,_e]);d.useEffect(()=>{So.current=ja},[ja]);const wl=d.useCallback((p,S)=>{const C=ni.current;if(!C||C.deviceId!==p)return;const R=Date.now();om.current.set(p,{...C,source:S,completedAtEpochMs:R,durationMs:Math.max(0,performance.now()-C.startedAt)}),ni.current=null},[]),Mr=d.useCallback((p,S)=>{const C=Ht.current.get(p);if(S&&C&&C!==S&&zr(p,C),S){if(Ht.current.set(p,S),C&&C!==S&&la(C),Ze.current[p]){Hn(p),wr(S),hs(p);return}er.current.get(p)&&Cc(p,S)&&ps(p),gs(p,!0);return}if(C&&Fr.current&&hc.current.includes(p)){zr(p,C),Ht.current.delete(p),la(C);return}Ht.current.delete(p),Hn(p),la(C),hs(p)},[hs,ps,gs,Cc,zr,wr,Hn,la]),$r=d.useCallback((p,S)=>{const C=Fn.current.get(p);if(S){Fn.current.set(p,S),C&&C!==S&&la(C);const R=$===p&&ue?pn.current.get(p):null;R&&Xi(R,S)&&p===W&&(wl(p,"warm-reuse"),Wa(!0));return}Fn.current.delete(p),la(C)},[wl,W,$,ue,Xi,la]),vs=d.useCallback((p,S,C)=>{const R=performance.now(),j=pa(p,C.deviceId);let Q=C;if(p==="control"&&C.visualChanged){const te=String(S.inputFeedbackEventId||""),re=Number(S.inputFeedbackInputSeq||0),Ye=Number(S.inputFeedbackIssuedAtEpochMs||0),Le=Number(S.browserReceivedEpochMs||0),st=jd.current.get(C.deviceId)||"",qt=Ye>0?Math.max(0,Date.now()-Ye):Number.POSITIVE_INFINITY;if(te.length>0&&re>0&&te!==st&&qt<=_g){const It=Mu.current.get(C.deviceId)||[];It.push(qt),It.length>cx&&It.splice(0,It.length-cx),Mu.current.set(C.deviceId,It),Q={...C,inputFeedbackSeq:re,inputFeedbackMs:qt,inputFeedbackAt:R,inputFeedbackExact:!0,inputFeedbackEventId:te,inputFeedbackInputType:S.inputFeedbackInputType,inputFeedbackInputToFrameMs:Le>0?Math.max(0,Le-Ye):void 0,inputFeedbackFrameToPaintMs:Le>0?Math.max(0,Date.now()-Le):void 0,inputFeedbackAgentApplyMs:S.inputFeedbackAgentApplyMs,inputFeedbackApplyToCaptureMs:S.inputFeedbackApplyToCaptureMs,inputFeedbackSampleCount:It.length,inputFeedbackP50Ms:Of(It,.5),inputFeedbackP95Ms:Of(It,.95)},jd.current.set(C.deviceId,te),ku.current.set(C.deviceId,re)}else if(!te){const It=E1(C.deviceId),gn=ku.current.get(C.deviceId)||0,Ya=It?R-It.sentAt:Number.POSITIVE_INFINITY;It&&It.inputSeq>gn&&Ya<=_g&&(Q={...C,inputFeedbackSeq:It.inputSeq,inputFeedbackMs:Math.max(0,Ya),inputFeedbackAt:R,inputFeedbackExact:!1},ku.current.set(C.deviceId,It.inputSeq))}}as.current.set(j,R);const X=ti.current.get(j)||{totalFrames:0,totalChangedFrames:0,sampleFrames:0,sampleChangedFrames:0,sampleStartedAt:R,intervalCount:0,intervalSumMs:0,minIntervalMs:Number.POSITIVE_INFINITY,maxIntervalMs:0,intervalSamplesMs:[],seqGapCount:0,maxSeqGap:0,sampleDecoderInputBase:0,sampleDecoderOutputBase:0},le=co(S);X.bindingKey!==le&&(X.bindingKey=le,X.lastAt=void 0,X.lastFrameSeq=void 0,X.sampleChangedFrames=0,X.sampleDecoderInputBase=Number(C.decoderInputCount||0),X.sampleDecoderOutputBase=Number(C.decoderOutputCount||0),Mp(X,R)),p==="control"&&Q.inputFeedbackMs===void 0&&X.lastInfo?.inputFeedbackMs!==void 0&&X.lastInfo.inputFeedbackAt!==void 0&&R-X.lastInfo.inputFeedbackAt<=_g&&(Q={...Q,inputFeedbackSeq:X.lastInfo.inputFeedbackSeq,inputFeedbackMs:X.lastInfo.inputFeedbackMs,inputFeedbackAt:X.lastInfo.inputFeedbackAt,inputFeedbackExact:X.lastInfo.inputFeedbackExact,inputFeedbackEventId:X.lastInfo.inputFeedbackEventId,inputFeedbackInputType:X.lastInfo.inputFeedbackInputType,inputFeedbackInputToFrameMs:X.lastInfo.inputFeedbackInputToFrameMs,inputFeedbackFrameToPaintMs:X.lastInfo.inputFeedbackFrameToPaintMs,inputFeedbackAgentApplyMs:X.lastInfo.inputFeedbackAgentApplyMs,inputFeedbackApplyToCaptureMs:X.lastInfo.inputFeedbackApplyToCaptureMs,inputFeedbackSampleCount:X.lastInfo.inputFeedbackSampleCount,inputFeedbackP50Ms:X.lastInfo.inputFeedbackP50Ms,inputFeedbackP95Ms:X.lastInfo.inputFeedbackP95Ms}),X.totalFrames+=1,X.sampleFrames+=1,gx(X,R,Q.frameSeq),Q.visualChanged&&(X.totalChangedFrames+=1,X.sampleChangedFrames+=1),X.lastInfo=Q,ti.current.set(j,X)},[]),xl=d.useCallback((p,S)=>{if(Ze.current[p.deviceId]||So.current===p.deviceId)return;vs("wall",p,S),p.kind==="live"&&(ps(p.deviceId),Hn(p.deviceId));const C=ue&&$===p.deviceId;So.current!==p.deviceId&&!C&&(oa.current.delete(p.deviceId),Ei.current.delete(p.deviceId))},[$,ue,ps,vs,Hn]),Hd=d.useCallback((p,S)=>{if(Ze.current[p.deviceId]||Bn(va.current,pt.current)||!yg(p,pt.current))return;vs("control",p,S),ie(X=>X&&"");const C=pn.current.get(p.deviceId),R=Fn.current.get(p.deviceId);let j=!1;C&&C.width>0&&C.height>0&&(R&&wt&&p.deviceId===W&&(j=Xi(C,R),j&&Zi("control-visible",p)),js.current.set(p.deviceId,{...p,payload:new Uint8Array(0),byteLength:0}),oa.current.add(p.deviceId),p.deviceId===$&&(Ce(!0),me(X=>X==="connecting"?"active":X)),gs(p.deviceId,!1,p));const Q=wu.current;!Q||!WD(Q,p)||!j||(wl(p.deviceId,"fresh-frame"),Wa(!0))},[wl,W,$,gs,Xi,vs,Zi,wt]),Ar=d.useCallback((p,S)=>{const C=performance.now(),R=pa(p,S.deviceId);ai.current.set(R,C),ri.current.delete(R),p==="control"?Es.current.delete(R):Mo.current.delete(R);const j=Di.current.get(R)||{totalFrames:0,sampleFrames:0,sampleStartedAt:C,intervalCount:0,intervalSumMs:0,minIntervalMs:Number.POSITIVE_INFINITY,maxIntervalMs:0,intervalSamplesMs:[],seqGapCount:0,maxSeqGap:0,sampleBytes:0,sampleH264Frames:0,sampleTinyFrames:0,sampleRepeatedFrames:0,sourceSendIntervalsMs:[]},Q=co(S);if(j.bindingKey!==Q&&(j.bindingKey=Q,j.lastAt=void 0,j.lastFrameSeq=void 0,j.lastContentHash=void 0,j.sampleBytes=0,j.sampleH264Frames=0,j.sampleTinyFrames=0,j.sampleRepeatedFrames=0,j.sourceSendIntervalsMs.length=0,Mp(j,C)),j.totalFrames+=1,j.sampleFrames+=1,j.sampleBytes+=Math.max(0,Number(S.byteLength||0)),String(S.frameMode||S.mode||S.codec||S.mimeType||"").toLowerCase().includes("h264")){j.sampleH264Frames+=1,Number(S.byteLength||0)<=BD&&(j.sampleTinyFrames+=1);const re=String(S.contentHash||"");re&&j.lastContentHash===re&&(j.sampleRepeatedFrames+=1),j.lastContentHash=re}const te=Number(S.agentSendGapMs||0);te>0&&te<1e3&&L0(j.sourceSendIntervalsMs,te),j.lastFrame=au(S),gx(j,C,S.frameSeq),Di.current.set(R,j)},[]);d.useEffect(()=>{const p=new Set(Qi);for(const R of ti.current.keys())p.has(R)||ti.current.delete(R);for(const R of Di.current.keys())p.has(R)||Di.current.delete(R);const S=R=>{const j=Object.entries(R).filter(([Q])=>p.has(Q));return j.length===Object.keys(R).length?R:Object.fromEntries(j)};if(Ad(S),yu(S),p.size===0)return;const C=window.setInterval(()=>{const R=performance.now(),j={},Q={};for(const X of p){const le=ti.current.get(X);if(le){const Le=Math.max(1,R-le.sampleStartedAt);j[X]={bindingKey:le.bindingKey||"",totalFrames:le.totalFrames,totalChangedFrames:le.totalChangedFrames,framesPerSecond:le.sampleFrames*1e3/Le,changedFramesPerSecond:le.sampleChangedFrames*1e3/Le,averageIntervalMs:le.intervalCount>0?le.intervalSumMs/le.intervalCount:0,minIntervalMs:Number.isFinite(le.minIntervalMs)?le.minIntervalMs:0,maxIntervalMs:le.maxIntervalMs,p95IntervalMs:Of(le.intervalSamplesMs,.95),intervalCount:le.intervalCount,seqGapCount:le.seqGapCount,maxSeqGap:le.maxSeqGap,decoderInputFps:Math.max(0,(Number(le.lastInfo?.decoderInputCount||0)-le.sampleDecoderInputBase)*1e3/Le),decoderOutputFps:Math.max(0,(Number(le.lastInfo?.decoderOutputCount||0)-le.sampleDecoderOutputBase)*1e3/Le),sampleMs:Le,lastInfo:le.lastInfo},le.sampleDecoderInputBase=Number(le.lastInfo?.decoderInputCount||0),le.sampleDecoderOutputBase=Number(le.lastInfo?.decoderOutputCount||0),le.sampleChangedFrames=0,Mp(le,R)}const te=Di.current.get(X);if(!te)continue;const re=Math.max(1,R-te.sampleStartedAt),Ye=te.lastFrame?au(te.lastFrame):void 0;te.lastFrame=Ye,Q[X]={totalFrames:te.totalFrames,framesPerSecond:te.sampleFrames*1e3/re,averageIntervalMs:te.intervalCount>0?te.intervalSumMs/te.intervalCount:0,minIntervalMs:Number.isFinite(te.minIntervalMs)?te.minIntervalMs:0,maxIntervalMs:te.maxIntervalMs,p95IntervalMs:Of(te.intervalSamplesMs,.95),intervalCount:te.intervalCount,seqGapCount:te.seqGapCount,maxSeqGap:te.maxSeqGap,averageFrameBytes:te.sampleFrames>0?te.sampleBytes/te.sampleFrames:0,tinyFrameRatio:te.sampleH264Frames>0?te.sampleTinyFrames/te.sampleH264Frames:0,repeatedFrameRatio:te.sampleH264Frames>0?te.sampleRepeatedFrames/te.sampleH264Frames:0,sourceSendAverageMs:te.sourceSendIntervalsMs.length>0?te.sourceSendIntervalsMs.reduce((Le,st)=>Le+st,0)/te.sourceSendIntervalsMs.length:0,sourceSendP95Ms:Of(te.sourceSendIntervalsMs,.95),sourceSendSampleCount:te.sourceSendIntervalsMs.length,sampleMs:re,lastFrame:Ye},te.sampleBytes=0,te.sampleH264Frames=0,te.sampleTinyFrames=0,te.sampleRepeatedFrames=0,te.sourceSendIntervalsMs.length=0,Mp(te,R)}Ad(j),yu(Q)},1e3);return bu.current=C,()=>{window.clearInterval(C),bu.current===C&&(bu.current=null)}},[Qi]);const lr=d.useCallback(p=>{const S=p.deviceId,C=co(p);if(Ze.current[S]||So.current===S||p.currentGenerationVerified!==!0||tr.current.get(S)!==C||(Ar("wall",p),!rr.current))return;const R=Ht.current.get(S);if(!R)return;const j=Fi(R),Q=Ds(R),X=()=>Ht.current.get(S)!==R||!Pr(R,j)||!!Ze.current[S]||So.current===S||tr.current.get(S)!==C,le=()=>X()||!ii(R,Q),te=cN(Dt,St.h264DecodeAcceleration);hg(R,p,le,xl,te.acceleration,te.latencyMode,X).catch(()=>{})},[Fi,ii,Pr,Ds,xl,Dt,Ar,St.h264DecodeAcceleration]),_n=d.useCallback(p=>{const S=p.deviceId;if(Ze.current[S]||Bn(va.current,pt.current)||!yg(p,pt.current))return;Ar("control",p);let C=pn.current.get(S);C||(C=document.createElement("canvas"),C.setAttribute("aria-hidden","true"),pn.current.set(S,C));const R=C,j=au(p),Q=Fi(R),X=Ds(R),le=()=>pn.current.get(S)!==R||!Pr(R,Q)||!!Ze.current[S]||!yg(j,pt.current),te=()=>le()||!ii(R,X),re=Oe.current;hg(R,p,te,Hd,qn.h264DecodeAcceleration,"interactive",le).catch(Ye=>{Oe.current!==re||pn.current.get(S)!==R||!ii(R,X)||le()||$!==S||ie(Ye instanceof Error?Ye.message:String(Ye||"Control H.264 decode failed"))})},[Fi,ii,Pr,Ds,$,qn.h264DecodeAcceleration,Hd,Ar]),Du=d.useCallback(p=>{const S=yr.current;yr.current=p,S&&S!==p&&la(S),pc.current=0,Su.current=0,Da.current=0,Pi.current=0,Cu.current=0,dl.current=0},[la]),cr=d.useCallback(()=>{const p=new Set,S=yr.current,C=ul.current;if(!S||!C||S.width<=0||S.height<=0||dl.current!==C.layoutVersion)return p;for(const R of C.tiles){if(Ze.current[R.deviceId])continue;const j=br.current.get(R.deviceId);if(!j||R.width<=0||R.height<=0)continue;const Q=Math.max(1,Math.round(R.width)),X=Math.max(1,Math.round(R.height)),le=zD,te=$D;(j.width!==le||j.height!==te)&&(j.width=le,j.height=te);const re=j.getContext("2d",{alpha:!1});if(re){re.imageSmoothingEnabled=!0,re.imageSmoothingQuality="high";try{re.drawImage(S,Math.round(R.x),Math.round(R.y),Q,X,0,0,le,te),p.add(R.deviceId)}catch{}}}return p},[]),_t=d.useCallback((p,S)=>{const C=br.current.get(p);if(S&&C&&C!==S&&zr(p,C),S){if(br.current.set(p,S),C&&C!==S&&la(C),Ze.current[p]){Hn(p),wr(S),hs(p);return}er.current.get(p)&&Cc(p,S)&&ps(p),window.requestAnimationFrame(()=>{cr().has(p)&&Hn(p)}),window.requestAnimationFrame(()=>gs(p,!0));return}br.current.delete(p),Hn(p),la(C),hs(p)},[hs,ps,cr,gs,Cc,zr,wr,Hn,la]),un=d.useCallback((p,S)=>{Da.current=performance.now(),dl.current=Number(p.layoutVersion||0),cr();const C=ul.current?.tiles||[],R=C.length>0?Math.round(p.byteLength/C.length):p.byteLength;for(const j of C){if(Ze.current[j.deviceId])continue;const Q={...p,deviceId:j.deviceId,width:j.width,height:j.height,sourceWidth:j.width,sourceHeight:j.height,byteLength:R};xl(Q,{...S,deviceId:j.deviceId,width:j.width,height:j.height,byteLength:R}),So.current===j.deviceId&&gs(j.deviceId,!0)}},[xl,cr,gs]),Kn=d.useCallback(p=>{const S=performance.now();if(pc.current<=0&&(pc.current=S),Su.current=S,!rr.current)return;const C=yr.current;if(!C)return;const R=co(p);dc.current!==R&&(dc.current=R,Gn(C));const j=Fi(C),Q=Ds(C),X=()=>yr.current!==C||dc.current!==R||!Pr(C,j),le=()=>X()||!ii(C,Q),te=ul.current?.tiles||[],re=te.length>0?Math.round(p.byteLength/te.length):p.byteLength;for(const Ye of te)Ze.current[Ye.deviceId]||Ar("wall",{...p,deviceId:Ye.deviceId,width:Ye.width,height:Ye.height,sourceWidth:Ye.width,sourceHeight:Ye.height,byteLength:re});hg(C,p,le,un,void 0,"smooth",X).catch(()=>{})},[Fi,ii,Pr,Ds,un,Ar,Gn]),kc=d.useCallback(p=>{if(p.streamPurpose!=="wall"||Ze.current[p.deviceId])return;const S=co(p);tr.current.get(p.deviceId)!==S&&(tr.current.set(p.deviceId,S),Gn(Ht.current.get(p.deviceId)))},[Gn]),Sl=d.useMemo(()=>({fps:fs,maxWidth:Oa.maxWidth,maxHeight:Oa.maxHeight,quality:St.quality,mode:Dt?"mode3-h264-hw":St.frameMode,frameMode:Dt?"mode3-h264-hw":St.frameMode,streamPurpose:"wall",configurationRefreshMs:ED,connectionSessionIds:Ki,monitorSelections:rn,onFrame:lr,onStreamReady:kc}),[Ki,fs,lr,kc,Dt,rn,St,Oa]),Ji=d.useCallback(p=>{const S=pt.current;if(Ze.current[p.deviceId]||!S||Bn(va.current,S)||S.deviceId!==p.deviceId||p.deviceId!==$||p.streamPurpose!=="control"||p.monitorIndex!==Br)return;const C=ut.find(j=>j.deviceId===p.deviceId);if(!C?.sessionId||C.sessionId!==p.sessionId)return;const R=He.current;(!R||co(R)!==co(p))&&Gn(pn.current.get(p.deviceId)),pt.current=up(S.deviceId,S.transitionGeneration,p),He.current=p,Ne(p),me(j=>j==="connecting"?"active":j)},[ut,$,Gn,Br]);d.useEffect(()=>{Gn(pn.current.get($)),He.current=null;const p=pt.current;p&&p.deviceId===$&&(pt.current=up(p.deviceId,p.transitionGeneration,{sessionId:p.sessionId,monitorIndex:Br})),Ne(null)},[$,B,kr,Gn,Br]);const Lo=B?`${B}-monitor-${Br}`:"",Mc=d.useMemo(()=>({fps:jo,maxWidth:Ui.maxWidth,maxHeight:Ui.maxHeight,quality:qn.quality,mode:kr,frameMode:kr,streamPurpose:"control",forceRestart:Lo!=="",forceRestartToken:Lo,restartReason:Lo?"control-session-or-monitor-change":"",connectionSessionIds:Ki,monitorSelections:rn,onFrame:_n,onStreamReady:Ji}),[Ki,Lo,qn.quality,_n,jo,kr,Ui.maxHeight,Ui.maxWidth,Ji,rn]),{frames:_o,state:Ac,error:En,stats:pi,restartLive:Cl}=tw(or,St.autoStartLive&&or.length>0,T,Sl);d.useEffect(()=>{const p=new Set(or);for(const S of tr.current.keys())p.has(S)||(tr.current.delete(S),Gn(Ht.current.get(S)))},[or,Gn]);const{frame:Po,layout:eo,state:Bd,stats:zd,refreshInputs:Iu}=P1(Sa,Dt&&St.autoStartLive&&Sa.length>0,T,{fps:Jn.atlasOutputFps,inputFps:Sc,width:1920,height:1080,tileWidth:Oa.maxWidth,tileHeight:Oa.maxHeight,captureDeviceIds:Sa,connectionSessionIds:Ki,monitorSelections:rn,onFrame:Kn});d.useEffect(()=>{ul.current=eo,eo&&window.requestAnimationFrame(cr)},[eo,cr]),d.useEffect(()=>{if(!Dt||Bd!=="open"){pc.current=0,Su.current=0,Da.current=0;return}const p=window.setInterval(()=>{const S=yr.current,C=performance.now();if(!S||document.visibilityState!=="visible"||C-Ii.current<Lg)return;const R=Su.current,j=pc.current;if(R<=0||j<=0||C-R>500)return;const Q=Da.current||j,X=C-Q;if(X>=_D&&C-Cu.current>=FD){od(S)&&(Cu.current=C,Pi.current=C);return}X>=LD&&C-Pi.current>=PD&&MA(S)&&(Pi.current=C)},250);return()=>window.clearInterval(p)},[Bd,Dt]);const{frames:Fo,state:Ca,error:kn,stats:Lu,restartLive:to,reconnectLive:Nc}=tw(Yi,Yi.length>0,T,Mc);d.useEffect(()=>{const p=yo.current,S=new Set([...Object.keys(p),...Object.keys(rn)]);for(const C of S){const R=Math.max(0,Math.floor(Number(p[C])||0)),j=Math.max(0,Math.floor(Number(rn[C])||0));R!==j&&(tr.current.delete(C),Gn(Ht.current.get(C)),Gn(pn.current.get(C)),Gn(br.current.get(C)),ca("wall",C),ca("control",C),od(Ht.current.get(C)||null),od(pn.current.get(C)||null))}S.size>0&&(Gn(yr.current),od(yr.current)),yo.current={...rn}},[rn,ca,Gn]);const Oo=d.useMemo(()=>{const p=(C,R)=>{const j=ut.find(X=>X.deviceId===C),Q=j?Ws(j,rn[C]):0;return!Number.isFinite(Number(R.monitorIndex))||Number(R.monitorIndex)===Q},S=new Map;for(const[C,R]of _o.entries())p(C,R)&&S.set(C,R);if(Dt&&Po&&Sa.length>0){const C=new Map((eo?.tiles||[]).map(j=>[j.deviceId,j])),R=Math.max(1,C.size);for(const j of Sa){const Q=C.get(j);Q&&S.set(j,{...Po,deviceId:j,width:Q.width,height:Q.height,sourceWidth:Q.width,sourceHeight:Q.height,byteLength:Math.round(Po.byteLength/R)})}}for(const[C,R]of Fo.entries())p(C,R)&&S.set(C,R);for(const C of wc){if(!oa.current.has(C)||S.has(C))continue;const R=js.current.get(C);R&&p(C,R)&&S.set(C,R)}return S},[Po,eo,ut,Fo,Sa,Dt,rn,_o,wc,pu]),ys=wt&&Yi.length>0?Ca:Sa.length>0?Bd:Ac,Ho=wt&&Yi.length>0?Lu:Sa.length>0?zd:pi;d.useCallback((p,S="browser-stale")=>{const C=Cl(p,S),R=to(p,S);return C||R},[to,Cl]),d.useEffect(()=>{Dt&&Sa.length>0&&!wt&&Iu()},[Sa.length,Dt,Iu,wt]);const kl=d.useCallback((p,S,C)=>{const R=S==="control"?pn.current.get(p)||null:Ht.current.get(p)||null;if(!R||!od(R))return!1;const j=performance.now();return hl.current.set(pa(S,p),j),!0},[]),Ml=d.useCallback(p=>{if(kr!=="mode3-h264-hw"||!$||oe)return!1;const S=ut.find(le=>le.deviceId===$)||Pa,C=String(S?.platform||"").toLowerCase();if(!["win32","windows","win32nt"].includes(C))return!1;const R="mode5-lzo-delta",j=pa("control",$),Q=performance.now();Li.current.set(j,Q),ai.current.delete(j),as.current.delete(j),pl.current.delete(j),Es.current.delete(j),ri.current.delete(j),od(pn.current.get($)||null),Nc([$],"control-decode-fallback"),be(R),L(`control-${R}-fallback-${$}-${Date.now()}`),Ce(!1),Wa(!1);const X=p==="no first frame"||p==="control-first-frame-timeout";return ie(le=>le||(X?`Control frame transport timeout; retrying Control with Mode 5 (${p})`:`H.264 decode failed; retrying Control with Mode 5 (${p})`)),me("connecting"),!0},[ut,Pa,$,oe,kr,Nc]);d.useEffect(()=>{const p=wt?Pa:null;if(p){wu.current={deviceId:p.deviceId,monitorIndex:Br,frameMode:kr,startedAtEpochMs:Date.now()},Wa($===p.deviceId&&ue);return}wu.current=null,Wa(!1)},[Pa?.sessionId,W,$,ue,kr,Br,wt]);const $d=d.useCallback(async(p,S)=>{const C=String(S.streamId||"").trim(),R=String(S.streamPurpose||"").trim(),j=String(S.sessionId||"").trim(),Q=String(S.commandId||"").trim(),X=Number(S.captureGeneration||0),le=Number(S.monitorIndex??-1);if(!C||!["wall","atlas"].includes(R)||!j||!Q||!Number.isSafeInteger(X)||X<=0||!Number.isSafeInteger(le)||le<0)throw new Error("wall-start-owner-incomplete");const te=performance.now()+3e3;for(;;){const re=await tt(`/api/remote/devices/${encodeURIComponent(p)}/live/stop`,{method:"POST",body:JSON.stringify({streamId:C,streamPurpose:R,expectedSessionId:j,expectedCommandId:Q,expectedCaptureGeneration:X,expectedMonitorIndex:le,requireNoPresentationOwner:!0,reason:"wall-start-presentation-revoked"})},T);if(re?.ok===!1)throw new Error(re.error||"revoked-wall-start-stop-failed");if(re?.captureStopConfirmed===!0||re?.alreadyStopped===!0||re?.staleOwner===!0)return re;if(re?.presentationOwnerActive===!0||re?.retainedForPresentation===!0){if(rr.current&&Fr.current)return re;if(performance.now()<te){await new Promise(Ye=>window.setTimeout(Ye,50));continue}throw new Error("revoked-wall-start-presentation-owner-did-not-release")}throw new Error("revoked-wall-start-stop-unconfirmed")}},[T]),no=d.useCallback(async p=>{if(Ze.current[p])throw new Error("LIVE_CAPTURE_PAUSED");if(!Fr.current)return{ok:!0,skipped:!0,reason:"wall-capture-owner-inactive"};const S=Cr.current.epoch,C=N.find(X=>X.deviceId===p);_f({mode4Enabled:Dt,directMode4WallEnabled:ir,isMac:nl(C?.platform)});const R=C?Ws(C,rn[p]):0,j={fps:Dt?fs:ta,maxWidth:Oa.maxWidth,maxHeight:Oa.maxHeight,quality:St.quality,mode:Dt?"mode3-h264-hw":St.frameMode,frameMode:Dt?"mode3-h264-hw":St.frameMode,streamPurpose:"wall",monitorIndex:R},Q=await tt(`/api/remote/devices/${encodeURIComponent(p)}/live/start`,{method:"POST",body:JSON.stringify(j)},T);if(Q?.ok===!1)throw new Error(Q.error||"wall-stream-start-failed");return S!==Cr.current.epoch||!Fr.current?(await $d(p,Q),{...Q,skipped:!0,reason:"wall-presentation-owner-revoked",compensated:!0}):Q},[ta,Sc,N,ir,fs,T,Dt,rn,$d,St.frameMode,St.quality,Oa.maxHeight,Oa.maxWidth]),Ud=d.useCallback(async p=>{const S=N.find(R=>R.deviceId===p);_f({mode4Enabled:Dt,directMode4WallEnabled:ir,isMac:nl(S?.platform)});const C=await tt(`/api/remote/devices/${encodeURIComponent(p)}/live/stop`,{method:"POST",body:JSON.stringify({streamPurpose:"wall",reason:"control-active"})},T);if(C?.ok===!1)throw new Error(C.error||"wall-stream-stop-failed");return C},[N,ir,T,Dt]),qd=d.useCallback(async(p,S="control-session-stop")=>{const C=await tt(`/api/remote/devices/${encodeURIComponent(p)}/live/stop`,{method:"POST",body:JSON.stringify({streamPurpose:"control",reason:S})},T);if(C?.ok===!1)throw new Error(C.error||"control-stream-stop-failed");return C},[T]),Qa=d.useCallback((p,S={})=>{va.current?.deviceId===p&&(va.current=null);const C=pn.current.get(p);if(C){const j=er.current.has(p)||Ht.current.has(p)||br.current.has(p);S.preservePresentation!==!1&&!j&&zr(p,C),pn.current.delete(p),la(C)}const R=Fn.current.get(p);R&&id(R),js.current.delete(p),oa.current.delete(p),Ei.current.delete(p)},[zr,wr,la]),Tc=d.useCallback(p=>{const S=[pa("wall",p),pa("control",p)];for(const C of S){const R=Di.current.get(C);R?.lastFrame&&(R.lastFrame=au(R.lastFrame))}yu(C=>{let R=!1;const j={...C};for(const Q of S){const X=C[Q];!X?.lastFrame||X.lastFrame.payload.byteLength===0||(j[Q]={...X,lastFrame:au(X.lastFrame)},R=!0)}return R?j:C})},[]),Rc=d.useCallback(p=>{tr.current.delete(p),Hn(p),Qa(p,{preservePresentation:!1});const S=new Set;for(const C of[Fn.current.get(p),Ht.current.get(p),br.current.get(p)])C&&S.add(C);for(const C of S)wr(C);hs(p),$===p&&(wu.current=null,Wa(!1),Ce(!1)),nt.current.add(p),Tc(p)},[hs,$,wr,Qa,Tc,Hn]);d.useEffect(()=>{const p=new Set(Object.keys(ze));for(const S of p)nt.current.has(S)||Rc(S);for(const S of nt.current)p.has(S)||nt.current.delete(S)},[Rc,ze]);const Bo=d.useCallback(p=>{const S=dw(im.current,p);return im.current=S.tail,S.result},[]),Ur=d.useCallback(p=>{const S=dw(Rd.current,p);return Rd.current=S.tail,S.result},[]),Nr=d.useCallback(p=>{nr.current=p,ll.current=0;const S=p?.deviceId||"";So.current=S,ts(S),S&&oa.current.add(S)},[]),zo=d.useCallback(p=>Bo(async()=>{if(Ze.current[p.deviceId])return!1;const S=nr.current;return!Bn(S,p)||!dp(p.deviceId,p,pt.current)?!1:(await no(p.deviceId),Bn(nr.current,p)&&Nr(null),!0)}),[Nr,Bo,no]),Wd=d.useCallback((p,S,C)=>Bo(async()=>{const R=nr.current;if(Bn(R,p))return C.stoppedWallDeviceId=p.deviceId,!0;if(R)if(Ze.current[R.deviceId])Bn(nr.current,R)&&Nr(null);else{if(!dp(R.deviceId,R,pt.current))return!1;await no(R.deviceId),Bn(nr.current,R)&&Nr(null)}if(!S())return!1;if(await Ud(p.deviceId),C.stoppedWallDeviceId=p.deviceId,!S()){if(dp(C.stoppedWallDeviceId,p,pt.current))try{await no(C.stoppedWallDeviceId)}catch(j){throw Nr(p),j}finally{C.stoppedWallDeviceId=""}return!1}return id(Ht.current.get(p.deviceId)||null),Nr(p),!0}),[Nr,Bo,no,Ud]),Al=d.useCallback(async(p,S)=>{if(S.stoppedWallDeviceId){if(Bn(nr.current,p)){try{await zo(p)}catch(C){Fe(C instanceof Error?C.message:String(C))}finally{S.stoppedWallDeviceId=""}return}await Bo(async()=>{if(!S.stoppedWallDeviceId||!dp(S.stoppedWallDeviceId,p,pt.current))return;const C=S.stoppedWallDeviceId;try{await no(C)}catch(R){Nr(p),Fe(R instanceof Error?R.message:String(R))}finally{S.stoppedWallDeviceId=""}})}},[Nr,Bo,zo,Fe,no]),Tr=d.useCallback(async(p,S,C={})=>{const R=C.allowStopFailure===!0,j=C.resumeWall!==!1;try{await qd(p.deviceId,S)}catch(Q){if(!R)throw Q}if(!Bn(pt.current,p))return!1;if(pt.current=null,He.current=null,Ne(null),Qa(p.deviceId),Ce(!1),L(""),be(""),ie(""),ee(Q=>Q===p.deviceId?"":Q),!j)return Bn(nr.current,p)&&Nr(null),!0;try{await zo(p)}catch(Q){Fe(Q instanceof Error?Q.message:String(Q))}return!0},[Nr,Qa,zo,Fe,qd]),Gd=(Ea&&wt&&an&&W&&!dt.has(W)&&ut.find(p=>p.deviceId===W)||null)?.deviceId||"";d.useEffect(()=>{Co.current=Gd},[Gd]),d.useEffect(()=>{const p=W&&ut.find(Q=>Q.deviceId===W)||null;if(!Ea||!wt||!an||!p){ya.current&&(++On.current,ya.current="");return}if(Ze.current[p.deviceId]){ya.current&&(++On.current,ya.current=""),$===p.deviceId&&me("paused");return}if(_r.current){if(_r.current===p.deviceId)return;_r.current=""}if($===p.deviceId&&(H==="active"||H==="warm"||H==="connecting")){me(Q=>Q==="warm"?"active":Q);return}if(ya.current===p.deviceId)return;const S=++On.current,C=up(p.deviceId,S,{sessionId:p.sessionId,monitorIndex:Br});ya.current=p.deviceId;const R={stoppedWallDeviceId:""},j=()=>S===On.current&&Co.current===C.deviceId;Ur(async()=>{if(!j())return;const Q=pt.current;if(Q){me("stopping");try{await Tr(Q,"control-session-switch")}catch(te){j()&&(me("error"),Fe(te instanceof Error?te.message:String(te)));return}if(!j()){pt.current||me("idle");return}}try{if(!await Wd(C,j,R)||!j()){await Al(C,R),pt.current||me("idle");return}}catch(te){await Al(C,R),j()&&(me("error"),Fe(te instanceof Error?te.message:String(te)));return}if(!j()){await Al(C,R);return}pt.current=C,va.current=null,_r.current="",ko.current=null,fl.current=0,ml.current="",R.stoppedWallDeviceId="";const X=pa("control",C.deviceId),le=`control-session-${S}-${C.deviceId}`;Li.current.set(X,performance.now()),ai.current.delete(X),as.current.delete(X),ri.current.delete(X),Es.current.delete(X),be(""),ie(""),L(le),ee(C.deviceId),Ce(!1),me("connecting")}).catch(Q=>{j()&&(me("error"),Fe(Q instanceof Error?Q.message:String(Q)))}).finally(()=>{On.current===S&&ya.current===C.deviceId&&(ya.current="")})},[ut,W,$,H,Ea,Ur,an,Wd,Al,Br,Fe,wt,Tr,ze]),d.useEffect(()=>{if(!$||ut.some(C=>C.deviceId===$))return;const p=$;++On.current,ya.current="";const S=pt.current;me("stopping"),Ur(async()=>{S&&S.deviceId===p?await Tr(S,"control-device-disconnected",{allowStopFailure:!0}):(Qa(p),ee(C=>C===p?"":C)),pt.current||me("idle")})},[ut,$,Ur,Qa,Tr]),d.useEffect(()=>{if(ar.current!==null&&(window.clearTimeout(ar.current),ar.current=null),!xr||wt||!$||Ze.current[$]||H!=="connecting"&&H!=="active"&&H!=="warm")return;const p=$,S=pt.current;if(!S||S.deviceId!==p)return;const C=window.setTimeout(()=>{ar.current===C&&(ar.current=null);const R=pt.current;if(Co.current||Ze.current[p]||!Bn(R,S))return;va.current=S;const j=++On.current;ya.current="",me("stopping"),Ur(async()=>{if(j!==On.current||Co.current||!Bn(pt.current,S)){Bn(va.current,S)&&(va.current=null),Bn(pt.current,S)&&Co.current===p&&me("active");return}try{await Tr(S,"control-session-wall-downshift")}catch(Q){Bn(va.current,S)&&(va.current=null),j===On.current&&!Co.current&&Bn(pt.current,S)&&(me("active"),Fe(Q instanceof Error?Q.message:String(Q)));return}va.current=null,j===On.current&&!pt.current&&me("idle")})},HD);return ar.current=C,()=>{ar.current===C&&(window.clearTimeout(C),ar.current=null)}},[$,H,Ur,Fe,wt,Tr,ze,xr]);const jc=d.useCallback(p=>{if(Td.current===p)return;Td.current=p;const S=pt.current,C=S?.deviceId||$,R=++On.current;ya.current="",He.current=null,mc.current=!0,Ne(null),Ce(!1),Wa(!1),C&&(ca("control",C),Qa(C,{preservePresentation:!1}),me("stopping"),Ur(async()=>{if(S&&S.deviceId===C)try{await Tr(S,"control-session-document-hidden",{resumeWall:!1})}catch(j){!rr.current&&_i.current===p&&(me("error"),Fe(j instanceof Error?j.message:String(j)));return}else Qa(C,{preservePresentation:!1}),ee(j=>j===C?"":j);!pt.current&&On.current===R&&me("idle")}))},[$,Ur,Qa,ca,Fe,Tr]);d.useEffect(()=>{if(ns.current!==null&&(window.clearTimeout(ns.current),ns.current=null),!$||H==="idle"||H==="paused"||H==="error")return;if(!Ea){jc(_i.current);return}if(H==="stopping"||wa){$&&wa&&H==="connecting"&&(mc.current=!1),$&&wa&&mc.current&&(H==="warm"||H==="active")&&(mc.current=!1,He.current=null,Ne(null),Ce(!1),Wa(!1),ca("control",$),L(`control-presentation-resume-${Date.now()}-${$}`),me("connecting"));return}He.current=null,mc.current=!0,Ne(null),Ce(!1),Wa(!1),me(S=>S==="idle"||S==="stopping"?S:"warm");const p=$;return Qa(p,{preservePresentation:!1}),ns.current=window.setTimeout(()=>{ns.current=null,++On.current,ya.current="";const S=pt.current;me("stopping"),Ur(async()=>{if(S&&S.deviceId===p)try{await Tr(S,"control-session-warm-timeout")}catch(C){me("error"),Fe(C instanceof Error?C.message:String(C));return}else Qa(p),ee(C=>C===p?"":C);pt.current||me("idle")})},OD),()=>{ns.current!==null&&(window.clearTimeout(ns.current),ns.current=null)}},[wa,$,H,Ea,Ur,Qa,jc,ca,Fe,Tr]),d.useEffect(()=>()=>{ns.current!==null&&window.clearTimeout(ns.current),ar.current!==null&&(window.clearTimeout(ar.current),ar.current=null),va.current=null},[]);const _u=d.useCallback(()=>{const p=new Set(xu.current),S=pt.current?.deviceId||"";$&&p.add($),S&&p.add(S),xu.current=[];for(const R of p){tr.current.delete(R),Hn(R),Qa(R,{preservePresentation:!1});for(const j of[Ht.current.get(R),Fn.current.get(R),br.current.get(R)])j&&wr(j);hs(R),ca("wall",R),ca("control",R),Tc(R)}const C=yr.current;C&&wr(C),dc.current="",ul.current=null,dl.current=0},[hs,$,wr,Qa,Tc,Hn,ca]);d.useEffect(()=>{Ea&&(xu.current=[...xc])},[Ea,xc]),d.useEffect(()=>{const p=nr.current,S=pt.current;if(!xr||!p||Ze.current[p.deviceId]||S&&S.deviceId===p.deviceId){ll.current=0;return}const C=ll.current,R=Math.min(5e3,500*2**Math.min(C,4)),j=window.setTimeout(()=>{cl.current===j&&(cl.current=null);const Q=nr.current;!Sr.current||!Q||Ze.current[Q.deviceId]||!Bn(Q,p)||(ll.current=C+1,zo(Q).catch(X=>{Fe(X instanceof Error?X.message:String(X)),Bn(nr.current,Q)&&!pt.current&&Rs(le=>le+1)}))},R);return cl.current=j,()=>{window.clearTimeout(j),cl.current===j&&(cl.current=null)}},[H,zo,Fe,xr,wo,ja]);const Ec=$&&ut.find(p=>p.deviceId===$)||null,Nl=!!(wt&&$e&&H==="active"&&ue&&Ec?.sessionId&&Me?.deviceId===Ec.deviceId&&Me.sessionId===Ec.sessionId&&Me.streamPurpose==="control"&&Me.commandId&&Me.captureGeneration>0&&Me.monitorIndex===Br),hi=Ec?.deviceId||"",Tl=Ec?.sessionId||"",$o=Me?.commandId||"",Uo=Number(Me?.captureGeneration||0),Pu=Number(Me?.monitorIndex||0),Vd=Nl?[hi,Tl,$o,Uo,Pu].join(":"):"",{state:Fu,sendInput:Kd,stats:bs,error:Qd}=F1(Ea&&sr&&wt&&$e&&!!Tl,T,Vd),Dc=d.useCallback((p,S)=>!rr.current||!Nl||!hi||!Tl||!$o||Uo<=0||p!==hi?!1:Kd(p,{...S,monitorIndex:Pu,controlSessionId:Tl,controlCommandId:$o,captureGeneration:Uo}),[Nl,Uo,$o,hi,Pu,Tl,Kd]),Ou=Ea&&rr.current&&Nl&&Fu==="open",Hs=Ea&&rr.current&&Nl&&Fu!=="idle",Yd={shiftKey:vt.includes("ShiftLeft"),ctrlKey:vt.includes("ControlLeft"),altKey:vt.includes("AltLeft"),metaKey:vt.includes("MetaLeft")},qr=d.useCallback(p=>Ee.current.enqueueStop(p),[]),gi=d.useCallback(p=>Ee.current.enqueueStart(p),[]),ka=d.useCallback((p,S=$t.current)=>(Z.current=p,$t.current=p?String(S||""):"",Qe.current+=1,Qe.current),[]),Wr=d.useCallback((p,S,C)=>eN({generation:p,currentGeneration:Qe.current,enabled:Z.current,deviceId:S,currentDeviceId:$t.current,documentVisible:rr.current,presentationVisible:Ge.current,streamId:C,currentStreamId:Pe.current.get(S)||""}),[]),Gr=d.useCallback(async(p,S,C)=>{if(!S)return{ok:!0,alreadyStopped:!0,captureStopConfirmed:!0,noExactOwner:!0};const j=await(X=>tt(`/api/remote/devices/${encodeURIComponent(p)}/audio/stop`,{method:"POST",body:JSON.stringify({...X?{streamId:X}:{},reason:C})},T))(S),Q=tN(j);if(Q.staleOwner)return j;if(!Q.confirmed)throw new Error(j?.error||"Remote audio capture stop was not confirmed.");return j},[T]),Ic=d.useCallback(async(p,S)=>{const C=await tt(`/api/remote/devices/${encodeURIComponent(p)}/audio/stop`,{method:"POST",body:JSON.stringify({reason:S})},T);if(C?.ok===!1||C?.captureStopConfirmed!==!0&&C?.alreadyStopped!==!0)throw new Error(C?.error||"Remote audio stop-all was not confirmed.");return C},[T]),bm=d.useCallback(p=>{const S=Qe.current,C=Pe.current.get(p)||"";return qr(()=>Gr(p,C,"remote-audio-automatic-restart")).then(()=>gi(async()=>{if(S!==Qe.current||!Z.current||$t.current!==p||!rr.current||!Ge.current||!an||!Va||(Se.current||Be?.deviceId||"")!==p)return"";const R=`audio-restart-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;if(Pe.current.set(p,R),!Wr(S,p,R))return Pe.current.delete(p),"";const j=await tt(`/api/remote/devices/${encodeURIComponent(p)}/audio/start`,{method:"POST",body:JSON.stringify({streamId:R,mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},T);if(j?.ok===!1)throw Pe.current.get(p)===R&&Pe.current.delete(p),new Error(j.error||"Remote audio restart failed.");return Wr(S,p,R)?R:(await Gr(p,R,"remote-audio-stale-restart-compensation"),Pe.current.get(p)===R&&Pe.current.delete(p),"")}))},[gi,qr,an,T,Wr,Va,Be?.deviceId,Gr]),Xd=Be?.deviceId&&Pe.current.get(Be.deviceId)||"",Zd=d.useCallback(async(p,S,C)=>{ka(!1),Ae(!1),await qr(()=>Gr(p,S,C)),Pe.current.get(p)===S&&Pe.current.delete(p)},[qr,ka,Gr]),{state:Hu,lastFrame:Bu,stats:Tn,error:Jd}=B1(Be?.deviceId||"",Ea&&Eu&&pe,T,dh,jn||In||kd.current,Xd,bm,Zd),Lc=d.useRef(new Map);d.useEffect(()=>{const p=[["hub",E],["registry",l],["license",Y],["wall-stream",En],["control-stream",kn],["control-decode",Ve],["remote-input",Qd],["remote-audio",Jd]];for(const[S,C]of p){const R=String(C||"").trim();if(S==="hub"&&Ot?.requiresHubRestart&&Ot.stage==="updating"){Lc.current.delete(S);continue}if(!R){Lc.current.delete(S);continue}Lc.current.get(S)!==R&&(Lc.current.set(S,R),Fe(R))}},[Jd,Ve,kn,E,Qd,Y,l,Fe,En,Ot]);const ao=Be?.deviceId||"",zu=Be?Ws(Be,rn[ao]):0;d.useEffect(()=>{if(!$e||!sr||!Hs||!ao)return;const p=V1(),S=ao,C=zu,R=Le=>{if(!Le)return!1;const st=Dc(S,{...Le,monitorIndex:C});return!st&&Le.type!=="keyboard.reset"&&(p.reset("browser-input-send-rejected"),xe([])),st},j=(Le,st)=>{const qt=Le.target,sn=qt?.tagName?.toLowerCase(),It=qt?.isContentEditable||sn==="input"||sn==="textarea"||sn==="select",gn=p.isPressed(Le);if(It&&(st==="keydown"||!gn))return;const Ya=p.event(Le,st);Ya&&(Le.preventDefault(),Le.stopPropagation(),R(Ya))},Q=Le=>j(Le,"keydown"),X=Le=>j(Le,"keyup"),le=(Le,st=!1)=>{const qt=p.reset(Le,st);qt&&(R(qt),xe([]))};he.current=Le=>{const st=p.snapshot().latchedCodes.includes(Le),qt=p.modifier(Le,!st);qt&&(R(qt),xe(sn=>st?sn.filter(It=>It!==Le):[...sn.filter(It=>It!==Le),Le]))};const te=()=>le("browser-window-blur"),re=()=>le("browser-page-hidden"),Ye=()=>{document.visibilityState==="hidden"&&le("browser-document-hidden")};return window.addEventListener("keydown",Q,!0),window.addEventListener("keyup",X,!0),window.addEventListener("blur",te),window.addEventListener("pagehide",re),document.addEventListener("visibilitychange",Ye),()=>{window.removeEventListener("keydown",Q,!0),window.removeEventListener("keyup",X,!0),window.removeEventListener("blur",te),window.removeEventListener("pagehide",re),document.removeEventListener("visibilitychange",Ye),he.current=null,le("control-keyboard-owner-changed",!0)}},[sr,Hs,ao,zu,$e,Dc]);const _c=d.useCallback(p=>{Ge.current=p;const S=Se.current||Be?.deviceId||"";if(!pe||!S)return;const C=ka(Z.current,S);if(!p){const j=Pe.current.get(S)||"";qr(async()=>{await Gr(S,j,"remote-audio-document-hidden")}).catch(Q=>{(Se.current||Be?.deviceId||"")===S&&(ka(!1),Pe.current.delete(S),Ae(!1),Fe(Q instanceof Error?Q.message:String(Q)))});return}const R=`audio-presentation-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;Pe.current.set(S,R),gi(async()=>{if(!Wr(C,S,R)||!an||!Va||(Se.current||Be?.deviceId||"")!==S)return;const j=await tt(`/api/remote/devices/${encodeURIComponent(S)}/audio/start`,{method:"POST",body:JSON.stringify({streamId:R,mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},T);if(j?.ok===!1)throw new Error(j.error||"Remote audio presentation resume failed.");Wr(C,S,R)||(await Gr(S,R,"remote-audio-stale-presentation-compensation"),Pe.current.get(S)===R&&Pe.current.delete(S))}).catch(j=>{rr.current&&C===Qe.current&&(ka(!1),Pe.current.delete(S),Ae(!1),Fe(j instanceof Error?j.message:String(j)))})},[pe,gi,qr,ka,an,T,Wr,Va,Be?.deviceId,Fe,Gr]);d.useEffect(()=>{const p=j=>{const Q=rr.current;j!==Q&&(rr.current=j,_i.current+=1,j||(jc(_i.current),_u()),_c(j),uh(j),j&&!Q&&(fh(X=>X+1),Ii.current=performance.now()))},S=()=>{p(document.visibilityState==="visible")},C=j=>{p(!1),j.persisted||_u()},R=()=>S();return document.addEventListener("visibilitychange",S),window.addEventListener("pagehide",C),window.addEventListener("pageshow",R),()=>{document.removeEventListener("visibilitychange",S),window.removeEventListener("pagehide",C),window.removeEventListener("pageshow",R)}},[_u,jc,_c]),d.useEffect(()=>{if(!$||H!=="connecting"&&H!=="active"&&H!=="warm"||Ca!=="open")return;const p=$,S=pa("control",p),C=window.setInterval(()=>{const R=performance.now();if(document.visibilityState!=="visible"||R-Ii.current<Lg)return;const j=ai.current.get(S)||0,Q=as.current.get(S)||0,X=pl.current.get(S)||0,le=Li.current.get(S)||R;Li.current.has(S)||Li.current.set(S,le);const te=j<=0,re=te?R-le>XD:R-j>wx,Ye=j>0&&(Q<=0||R-Q>wx);if(!re&&Ye){const sn=hl.current.get(S)||0;R-sn>=xx&&kl(p,"control","decoder-paint-stale");return}if(!re)return;const Le=Es.current.get(S)||0;if(Le>0){if(R-Le<JD)return;Es.current.delete(S)}const st=ri.current.get(S)||0;if(st>=eI){if(Ml(te?"no first frame":"stale stream"))return;Ce(!1),Wa(!1),_r.current=p,me("error");return}if(R-X<Sx(ZD,st))return;to([p],te?"control-first-frame-timeout":"control-receive-stale")&&(pl.current.set(S,R),Es.current.set(S,R),Li.current.set(S,R),ri.current.set(S,st+1))},650);return()=>window.clearInterval(C)},[Ca,$,H,Ml,kl,to]),d.useEffect(()=>{!Ve||$&&Ze.current[$]||kr!=="mode3-h264-hw"||Ml(Ve)||(Ce(!1),Wa(!1),_r.current=pt.current?.deviceId||"",me("error"))},[Ve,$,kr,Ml]),d.useEffect(()=>{!wt||!$||Ze.current[$]||!kn||(_r.current=$,me(p=>p==="error"?p:"error"))},[kn,$,wt]),d.useEffect(()=>{if(H!=="error")return;const p=pt.current;if(!p)return;_r.current=p.deviceId,Bn(ko.current,p)||(ko.current=p,fl.current=0);const S=fl.current,C=S===0?0:Math.min(5e3,500*2**Math.min(S-1,4)),R=window.setTimeout(()=>{Bn(pt.current,p)&&(++On.current,ya.current="",me("stopping"),Ur(async()=>{if(Bn(pt.current,p))try{if(!await Tr(p,"control-session-terminal-error"))return;ko.current=null,fl.current=0,ml.current===p.deviceId?(ml.current="",_r.current="",me("idle")):me("error")}catch(j){if(!Bn(pt.current,p))return;fl.current+=1,Fe(j instanceof Error?j.message:String(j)),me("error"),Lr(Q=>Q+1)}}))},C);return()=>window.clearTimeout(R)},[H,cc,Ur,Fe,Tr]);const Rl=d.useCallback(p=>{if(!p||_r.current!==p)return!1;const S=pt.current;return++On.current,ya.current="",fl.current=0,S&&S.deviceId===p?(ml.current=p,ko.current=null,me("error"),Lr(C=>C+1),!0):(ml.current="",_r.current="",ko.current=null,me("idle"),!0)},[]);d.useEffect(()=>{if(Ac!=="open"||!St.autoStartLive||or.length===0)return;const p=window.setInterval(()=>{const S=performance.now();if(document.visibilityState!=="visible"||S-Ii.current<Lg)return;const C=1e3/Math.max(1,fs||_e||1),R=Math.max(nI,Math.ceil(C*4)),j=[];for(const Q of or){if(j.length>=sI)break;const X=pa("wall",Q),le=ai.current.get(X)||0,te=le<=0,re=Mo.current.get(X)||S;if(Mo.current.has(X)||Mo.current.set(X,re),te&&S-re<=tI)continue;const Ye=pl.current.get(X)||0,Le=as.current.get(X)||0,st=te||S-le>R,qt=!te&&(Le<=0||S-Le>R);if(!st&&qt){const It=hl.current.get(X)||0;S-It>=xx&&kl(Q,"wall","decoder-paint-stale");continue}if(!st)continue;const sn=ri.current.get(X)||0;S-Ye>=Sx(aI,sn)&&j.push(Q)}if(j.length>0&&Cl(j,j.some(Q=>(ai.current.get(pa("wall",Q))||0)<=0)?"wall-first-frame-timeout":"wall-frame-stale"))for(const Q of j){const X=pa("wall",Q);pl.current.set(X,S),Mo.current.set(X,S),ai.current.delete(X),as.current.delete(X),ri.current.set(X,(ri.current.get(X)||0)+1)}},rI);return()=>window.clearInterval(p)},[fs,or,kl,Cl,St.autoStartLive,_e,Ac]),d.useEffect(()=>{Ts(_e),La.current=Date.now(),ss.current=0,ba.current=0,is.current=0,Ro.current=0,Is.current=""},[_e,St.frameMode,St.adaptiveLoadShedding]),d.useEffect(()=>{lA({h264DecodeAcceleration:St.h264DecodeAcceleration})},[St.h264DecodeAcceleration]),d.useEffect(()=>{if(!an||wt||Sn==="list"||!St.visibleOnlyLive){Js([]);return}const p=vc.current;if(!p||typeof IntersectionObserver>"u"){Js(Os);return}const S=Array.from(p.querySelectorAll("[data-live-device-id]"));if(S.length===0){Js([]);return}const C=new Map,R=()=>{const Q=Fg(S.map(X=>String(X.dataset.liveDeviceId||"")).filter(X=>(C.get(X)||0)>0));Js(X=>Pg(X,Q)?X:Q)},j=new IntersectionObserver(Q=>{for(const X of Q){const le=String(X.target.dataset.liveDeviceId||"");le&&C.set(le,X.isIntersecting?X.intersectionRatio||.01:0)}R()},{root:null,rootMargin:xi.visibleRootMargin,threshold:[0,.01,.2,.6,1]});return S.forEach(Q=>j.observe(Q)),R(),()=>j.disconnect()},[Os,an,wt,ci,St.visibleOnlyLive,Sn]),d.useEffect(()=>{if(!St.adaptiveLoadShedding||!St.autoStartLive||or.length===0){ba.current=0,is.current=0,Ro.current=0,Is.current="";return}const p=_e;if(Ac!=="open"||pi.sampleMs<500||pi.lastUpdatedAt<=0||Ro.current===pi.lastUpdatedAt)return;Ro.current=pi.lastUpdatedAt;const S=Date.now(),C=or.map(Le=>({deviceId:Le,receive:fc[pa("wall",Le)],paint:vu[pa("wall",Le)]}));if(!C.every(({receive:Le,paint:st})=>{const qt=Le?.lastFrame,sn=Math.max(0,Number(qt?.requestedFps||0)),It=qt?co(qt):"";return oN({receiveSampleMs:Number(Le?.sampleMs||0),paintSampleMs:Number(st?.sampleMs||0),currentGenerationVerified:qt?.currentGenerationVerified===!0,frameRequestedFps:sn,adaptiveFps:ta})&&st?.bindingKey===It})){ba.current=0,is.current=0,ss.current=0;return}const j=[ta,...C.map(({deviceId:Le,receive:st})=>`${Le}:${co(st.lastFrame)}`).sort()].join("|");if(Is.current!==j){Is.current=j,ba.current=S,is.current=0,ss.current=0;return}if(!ba.current){ba.current=S,is.current=0;return}if(S-ba.current<xi.downshiftStableSampleMs)return;const Q=C.reduce((Le,{receive:st})=>Le+Math.max(0,Number(st?.framesPerSecond||0)),0),X=C.reduce((Le,{receive:st})=>Le+Math.max(0,Number(st?.framesPerSecond||0))*Math.max(0,Number(st?.averageFrameBytes||0)),0),le=C.reduce((Le,{paint:st})=>Le+Math.max(0,Number(st?.framesPerSecond||0)),0),te=Math.max(0,...C.map(({receive:Le})=>Number(Le?.maxIntervalMs||0))),re=Math.max(0,...C.map(({paint:Le})=>Number(Le?.p95IntervalMs||0))),Ye=iN({directDeviceCount:or.length,requestedFps:ta,measuredFramesPerSecond:Q,measuredPaintFramesPerSecond:le,measuredBytesPerSecond:X,maxBytesPerSecond:xi.maxWallBytesPerSecond,worstReceiveGapMs:te,worstPaintP95Ms:re,maxFrameGapMs:xi.maxFrameGapMs});if(Ye.overloaded){if(ss.current=0,is.current+=1,is.current<xi.downshiftConsecutiveSamples)return;const Le=xi.minFps;if(S-La.current>=xi.downshiftCooldownMs&&ta>Le){const st=Math.max(Le,MI(ta,Le));st<ta&&(Ts(st),La.current=S,ba.current=0,is.current=0)}return}if(is.current=0,!Ye.healthyForRecovery||ta>=p){Ye.healthyForRecovery||(ss.current=0);return}if(!ss.current){ss.current=S;return}if(S-ss.current>=xi.recoveryCooldownMs){const Le=Math.min(p,AI(ta,p));Le>ta&&(Ts(Le),La.current=S,ss.current=0,ba.current=0,is.current=0)}},[ta,or.length,or,vu,fc,Ac,pi.lastUpdatedAt,pi.sampleMs,St.adaptiveLoadShedding,St.autoStartLive,St.frameMode,_e]),d.useEffect(()=>{const p=new URLSearchParams(window.location.search).get("checkout");if(p==="success"){Fe("Checkout returned. Waiting for Dodo confirmation."),D();const S=window.setInterval(()=>{D()},4e3),C=window.setTimeout(()=>{window.clearInterval(S)},45e3);return()=>{window.clearInterval(S),window.clearTimeout(C)}}p==="cancelled"&&Fe("Checkout cancelled.")},[D]),d.useEffect(()=>{!an&&$e&&qe(!1),!an&&pe&&(ka(!1),Ae(!1))},[pe,$e,ka,an]),d.useEffect(()=>{pe&&(!Be||!Va)&&(ka(!1),Ae(!1))},[pe,ka,Va,Be]),d.useEffect(()=>{const p=Be?.deviceId||"",S=Se.current;if(Se.current=p,!S||S===p)return;const C=ka(pe,p),R=p?`audio-${Date.now()}-${Math.random().toString(36).slice(2,8)}`:"";p&&pe&&Pe.current.set(p,R);let j=!0;const Q=Pe.current.get(S)||"";return(async()=>{try{await qr(async()=>{await Gr(S,Q,"remote-audio-device-switch"),Pe.current.delete(S)}),await gi(async()=>{if(!j||!Wr(C,p,R)||!p||!an||!Va)return;const X=await tt(`/api/remote/devices/${encodeURIComponent(p)}/audio/start`,{method:"POST",body:JSON.stringify({streamId:R,mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},T);if(X.ok===!1)throw new Error(X.error||"Remote audio start failed.");Wr(C,p,R)||(await Gr(p,R,"remote-audio-stale-device-switch-compensation"),Pe.current.get(p)===R&&Pe.current.delete(p))})}catch(X){j&&(ka(!1),Pe.current.delete(p),Ae(!1),Fe(X instanceof Error?X.message:String(X)))}})(),()=>{j=!1}},[pe,gi,qr,ka,an,T,Wr,Va,Be?.deviceId,Gr]),d.useEffect(()=>{const p=ut.map(j=>j.deviceId),S=new Set(p),C=new Map(ut.map(j=>[j.deviceId,j])),R=new Map;for(const j of ut){const Q=dI(j);if(!Q)continue;const X=Mi(j.status),le=[j.lastStatusAt,X.capturedAt,X.collectedAt,X.timestamp,X.updatedAt].find(re=>typeof re=="string"&&re.trim()),te=Q1(Ns.current[j.deviceId],Q,le);te&&(Ns.current[j.deviceId]=te,R.set(j.deviceId,te),NS({platform:j.platform,topologyFingerprint:Q,consecutiveTopologySamples:te.consecutiveSamples})&&(vr.current[j.deviceId]=Q))}for(const j of Object.keys(Ns.current))S.has(j)||delete Ns.current[j];ne(j=>{const Q=j.filter(X=>S.has(X));return Pg(j,Q)?j:Q}),O(j=>j&&S.has(j)?j:""),ce(j=>j&&S.has(j)?j:""),Zs(j=>{let Q=!1;const X={};for(const[le,te]of Object.entries(j)){const re=C.get(le);if(!re){X[le]=te;continue}const Ye=R.get(le)||Ns.current[le],Le=Y1({requestedIndex:te,monitorCount:ru(re),platform:re.platform,topologyFingerprint:Ye?.fingerprint||"",consecutiveTopologySamples:Ye?.consecutiveSamples||0});X[le]=Le,Le!==te&&(Q=!0)}return Q?X:j}),gl(j=>{const Q=j.filter(X=>S.has(X));return Pg(j,Q)?j:Q})},[ut,os]),d.useEffect(()=>{lm([]),Au(!1)},[gs]),d.useEffect(()=>{!_a||No!=="selected"||Ia.length>0||tn.length===0||gl(tn.map(p=>p.deviceId))},[tn,Ia.length,No,_a]),d.useEffect(()=>{try{localStorage.setItem(T0,Xs)}catch{}},[Xs]),d.useEffect(()=>{vI(St)},[St]),d.useEffect(()=>{bI(qn)},[qn]),d.useEffect(()=>{hI(rn,vr.current)},[ut,rn]);const Pc=d.useCallback(async()=>{const p=new Set(y);p.add(Dn);try{const Q=await tt("/api/remote/status",void 0,Dn);Ib({endpoint:Q.agentEndpoint,endpoint_candidates:[...Q.agentEndpointCandidates||[],...Q.hostTargetEndpointCandidates||[]]}).forEach(X=>p.add(X))}catch{}const S=[...p].sort((Q,X)=>{const le=te=>{const re=hd(te);return re==="local"?0:re==="loopback"?1:2};return le(Q)-le(X)||Q.localeCompare(X)});let C=!1,R="",j=!1;try{for(const Q of S){const X=hd(Q);try{if(await tt("/api/health",void 0,Q),X==="local")return b(!0),dd(!0),Q;X==="loopback"&&(C=!0,R=Q)}catch{X==="local"&&(j=!0)}}return C?(j&&Fe("LiveDesk Hub is reachable on this PC, but not through the LAN address yet. Restart LiveDesk Hub to bind 5179 on the network."),b(!0),dd(!0),R||Dn):(b(!1),dd(!1),"")}catch{return b(!1),dd(!1),""}},[y]),vi=async()=>{if(ae("auth"),es(!1),window.liveDesk?.auth?.signInWithGoogle){const R=window.liveDesk.auth.signInWithGoogle();Pc();const j=await R;j?.ok===!1&&(Fe(j.error||"LiveDesk could not open the system browser for Google sign-in."),ae(""));return}const p=Pt.auth.signInWithOAuth({provider:"google",options:{redirectTo:`${window.location.origin}/callback`}});Pc();const{data:S,error:C}=await p;C&&(Fe(C.message),ae(""))},wm=async()=>{ae("auth"),es(!1),await Pt.auth.signOut({scope:"local"}),(await window.liveDesk?.auth?.persistSession?.(null))?.runtimeCleared===!1?Fe("Signed out locally. The LiveDesk runtime could not be reached to clear its session."):window.liveDesk?.auth?.persistSession||await tt("/api/auth/session",{method:"DELETE"},Dn).catch(()=>{}),ae("")};d.useEffect(()=>{if(!Jr)return;const p=C=>{C.target instanceof Element&&(C.target.closest(".account-popover, .rail-account")||es(!1))},S=C=>{C.key==="Escape"&&es(!1)};return window.addEventListener("pointerdown",p),window.addEventListener("keydown",S),()=>{window.removeEventListener("pointerdown",p),window.removeEventListener("keydown",S)}},[Jr]);const $u=d.useCallback(async(p={})=>{const S=p.silent===!0,C=p.takeover===!0,R=p.requestLocalAccess===!0;if(!n?.user){S||Fe("Sign in before publishing this host.","error");return}if(!Bi.current){Bi.current=!0,S||(ae("host"),V("Hub · 1/4 · Checking the local runtime…"));try{const Q=(R?await Pc():"")||T||Dn;if(!(k||await tt("/api/remote/status",void 0,Q)).started)throw new Error("Start LiveDesk on this computer before syncing the server.");S||V("Hub · 2/4 · Sending the signed-in session to the Hub…");const le=await tt("/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}})},Q);if(!le.ok||!le.authenticated)throw new Error(le.error||"hub-session-sync-failed");S||V("Hub · 3/4 · Claiming the Hub role and publishing its endpoint…");const te=await tt("/api/hub/sync",{method:"POST",body:JSON.stringify({takeover:C})},Q);if(!te.ok)throw new Error(te.error||"host-target-failed");if(!S){V("Hub · 4/4 · Verifying the endpoint and lease renewal…");const re=await tt("/api/hub/status",void 0,Q);if(!re.hostTargetActive)throw new Error(re.hostTargetLease?.lastError||"host-target-not-active-after-sync");const Ye=re.hostTargetEndpoint||re.agentEndpoint||"endpoint ready",Le=Number(re.connectedDeviceCount||0),st=Le>0?`${Le} client${Le===1?"":"s"} connected.`:"No clients connected yet; reconnect the laptop Client.";Fe(`Hub ready · ${Ye} · lease auto-renewal active. ${st}`,"success"),(R||x)&&(b(!0),dd(!0)),I()}u()}catch(j){if(!S){const Q=j instanceof Error?j.message:String(j);Q.includes("local network access")&&(b(!1),dd(!1)),Fe(`Hub setup failed · ${Q}`,"error")}}finally{Bi.current=!1,S||ae("")}}},[T,x,I,u,Pc,n,Fe,V,k]),jl=d.useCallback((p=!0)=>{z!=="host"&&(at(!1),p&&window.requestAnimationFrame(()=>At.current?.focus()))},[z]),ef=d.useCallback(()=>{z!=="host"&&(At.current=document.activeElement instanceof HTMLElement?document.activeElement:null,es(!1),at(!0))},[z]),tf=d.useCallback(()=>{at(!1),$u({takeover:!0,requestLocalAccess:!0})},[$u]);d.useEffect(()=>{if(!Xe)return;const p=window.requestAnimationFrame(()=>kt.current?.focus()),S=R=>{R.target instanceof Element&&R.target.closest(".client-hub-switch-popover, .hub-sync-trigger")||jl(!1)},C=R=>{R.key==="Escape"&&jl()};return window.addEventListener("pointerdown",S),window.addEventListener("keydown",C),()=>{window.cancelAnimationFrame(p),window.removeEventListener("pointerdown",S),window.removeEventListener("keydown",C)}},[jl,Xe]);const xm=d.useCallback(async()=>{if(!(!k?.update?.canApply||z==="update")){ae("update");try{const p=await tt("/api/update/apply",{method:"POST",body:JSON.stringify({})},T||Dn);if(!p.ok)throw new Error(p.error||"LiveDesk update could not be started.");const S=[...new Set((p.targets||[]).map(j=>String(j.deviceId||"").trim()).filter(Boolean))],C=!!(p.managerUpdateAvailable||p.clientPackageUpdateAvailable),R=p.state==="hub-restart-requested"?Date.now():void 0;(S.length>0||C)&&Wn({operationId:String(p.operationId||`wall-update-${Date.now()}`),targetIds:S,stage:p.state==="clients-updated"?"updated":"updating",requiresHubRestart:C,initialHostInstanceId:String(k.hostInstanceId||""),targetManagerVersion:String(p.latestVersion||k.update?.latestVersion||""),targetClientVersion:String(p.latestClientVersion||k.update?.latestClientVersion||""),restartRequestedAt:R,restartDeadlineAt:R?R+kp:void 0}),V(p.state==="hub-restart-requested"?Cp:mx),I()}catch(p){Fe(p instanceof Error?p.message:String(p),"error")}finally{ae("")}}},[z,T,I,Fe,V,k]);d.useEffect(()=>{const p=Ot,S=k?.update;if(!p||p.stage!=="updating"||!S)return;const C=S.restartResult?.operationId===p.operationId?S.restartResult:null;if(C?.outcome==="restored"){const te=C.error||`The requested Hub ${C.targetVersion||p.targetManagerVersion||"version"} failed verification.`;Wn(re=>re?.operationId===p.operationId?{...re,stage:"restored",error:te}:re),Fe(`LiveDesk update did not complete. Hub ${C.fallbackVersion||C.appVersion||"the previous version"} was restored. ${te}`,"error");return}if(C?.outcome==="failed"){const te=C.error||"No verified LiveDesk Hub replacement could be started.";Wn(re=>re?.operationId===p.operationId?{...re,stage:"failed",error:te}:re),Fe(`LiveDesk Hub update failed. ${te}`,"error");return}if(S.operationId===p.operationId&&S.state==="failed"){const te=S.error||"LiveDesk update failed before the Hub replacement completed.";Wn(re=>re?.operationId===p.operationId?{...re,stage:"failed",error:te}:re),Fe(te,"error");return}if(S.operationId===p.operationId){if(S.state==="hub-restart-requested"&&!p.restartDeadlineAt){const te=Date.now();Wn(re=>re?.operationId===p.operationId?{...re,restartRequestedAt:te,restartDeadlineAt:te+kp}:re),V(Cp)}!p.requiresHubRestart&&S.state==="clients-updated"&&(Wn(te=>te?.operationId===p.operationId?{...te,stage:"updated"}:te),Fe("LiveDesk clients updated and reconnected successfully.","success"));return}if(!p.requiresHubRestart)return;const R=k.started===!0&&(!p.initialHostInstanceId||k.hostInstanceId&&k.hostInstanceId!==p.initialHostInstanceId),j=!!S.checkedAt,Q=px(S.currentVersion,p.targetManagerVersion),X=!p.targetClientVersion||px(S.currentClientVersion,p.targetClientVersion),le=j&&S.state==="idle"&&S.updateAvailable===!1&&Q&&X;R&&le&&(Wn(te=>te?.operationId===p.operationId?{...te,stage:"updated"}:te),Fe(`LiveDesk Hub ${S.currentVersion||C?.appVersion||p.targetManagerVersion} restarted and passed version verification.`,"success"))},[Fe,V,k,Ot]),d.useEffect(()=>{const p=Ot;if(!p||p.stage!=="updating"||!p.requiresHubRestart||p.restartDeadlineAt)return;const S=()=>{const R=Date.now();Wn(j=>j?.operationId===p.operationId&&j.stage==="updating"&&!j.restartDeadlineAt?{...j,restartRequestedAt:R,restartDeadlineAt:R+kp}:j),V(Cp)};if(k?.update?.state==="hub-restart-requested"){S();return}if(!E)return;const C=window.setTimeout(S,UD);return()=>window.clearTimeout(C)},[E,V,k?.update?.state,Ot]),d.useEffect(()=>{const p=Ot;if(!p||p.stage!=="updating"||!p.requiresHubRestart||!p.restartDeadlineAt)return;const S=Math.max(0,p.restartDeadlineAt-Date.now()),C=p.operationId,R=window.setTimeout(()=>{const j=`LiveDesk Hub did not return and verify ${p.targetManagerVersion||"the requested version"} within ${Math.round(kp/6e4)} minutes. Check the Hub terminal or restart log, then run livedesk@latest manually if the Hub is still offline.`;Wn(Q=>Q?.operationId===C&&Q.stage==="updating"?{...Q,stage:"failed",error:j}:Q),Fe(j,"error")},S);return()=>window.clearTimeout(R)},[Fe,Ot]),d.useEffect(()=>{if(!Ot||Ot.stage!=="updated")return;const p=Ot.operationId,S=window.setTimeout(()=>{Wn(C=>C?.operationId===p?null:C)},8e3);return()=>window.clearTimeout(S)},[Ot]),d.useEffect(()=>{if(Ut!==mx&&Ut!==Cp)return;const p=k?.update;if(String(p?.state||"")==="failed"){Fe(p?.error||"LiveDesk update failed.","error");return}Ot?.stage==="updated"&&Fe("")},[Ut,Fe,k?.update?.error,k?.update?.state,Ot?.stage]);const Sm=d.useCallback(async()=>{if(!z){ae("pin");try{const S=await tt("/api/remote/pairing-pin",{method:"POST"},T||Dn);if(!S.ok)throw new Error(S.error||"pin-rotation-failed");await I(),Fe("New PIN published.")}catch(p){Fe(p instanceof Error?p.message:String(p))}finally{ae("")}}},[z,T,I]),ro=d.useCallback(p=>{p&&(O(p),ne(S=>S.includes(p)?S:[...S,p]))},[]),nf=d.useCallback(p=>{if(!p)return;const S=Hr.has(p);O(C=>S?C===p?"":C:p),ne(C=>S?C.filter(R=>R!==p):C.includes(p)?C:[...C,p])},[Hr]),El=d.useCallback(()=>{ne([]),O("")},[ms]),af=d.useCallback(()=>{ne(ut.map(p=>p.deviceId)),O("")},[ut]),Fc=d.useCallback((p,S)=>{const C=ut.find(j=>j.deviceId===p);if(!C)return;const R=ru(C);if(!(R<=1)&&(Zs(j=>{const Q=$f(j[p],R),X=(Q+S+R)%R;return X===Q?j:{...j,[p]:X}}),ca("wall",p),ca("control",p),ei(j=>{if(!j.has(p))return j;const Q=new Set(j);return Q.delete(p),Q}),js.current.delete(p),oa.current.delete(p),wt)){const j=Rl(p);Ce(!1),j||me("connecting"),Wa(!1),ce(p)}},[ut,ca,Rl,wt]);d.useEffect(()=>{const p=S=>{if($e&&sr&&Hs)return;const C=S.target,R=C?.tagName?.toLowerCase();C?.isContentEditable||R==="input"||R==="textarea"||R==="select"||((S.ctrlKey||S.metaKey)&&S.key.toLowerCase()==="a"&&(S.preventDefault(),af()),S.key==="Escape"&&El())};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[sr,El,Hs,$e,af]);const Cm=(p,S)=>{const C=ut.find(X=>X.deviceId===p),R=C?ru(C):1,j=$f(rn[p],R),Q=$f(S,R);if(j!==Q&&(Zs(X=>({...X,[p]:Q})),ei(X=>{if(!X.has(p))return X;const le=new Set(X);return le.delete(p),le}),js.current.delete(p),oa.current.delete(p),ca("wall",p),ca("control",p)),wt){const X=Rl(p);j!==Q&&(Ce(!1),X||me("connecting")),Wa(!1),ce(p)}else ro(p)},rf=p=>{const S=Se.current||Be?.deviceId||"",C=[...new Set([S,p].filter(Boolean))],R=pe||C.some(j=>Pe.current.has(j));ka(!1),Ae(!1);for(const j of C)Pe.current.delete(j);C.length!==0&&(async()=>{for(const j of C)await qr(()=>Ic(j,"remote-audio-control-entry"))})().catch(j=>{R&&Fe("Remote audio was muted locally, but Client capture stop was not confirmed: "+(j instanceof Error?j.message:String(j)),"error")})},Oc=async p=>{const S={requestId:++ch.current,deviceId:p,startedAt:performance.now(),startedAtEpochMs:Date.now()};if(ni.current=S,!Fs.has(p)){ni.current?.requestId===S.requestId&&(ni.current=null),qe(!1),Fe(fi);return}const C=ut.find(j=>j.deviceId===p);if(nl(C?.platform)&&(C?.capabilities?.controlPermission===!1||C?.capabilities?.accessibilityPermission===!1)){ni.current?.requestId===S.requestId&&(ni.current=null),qe(!1),Fe("Mac remote control needs Accessibility permission. Allow it for the terminal app that starts LiveDesk, then restart the Mac client.","error");return}rf(p),Rl(p),Wa(!1),ce(p),nn("control"),qe(!0),Fe(`Opening remote control${C?` for ${Rr(C)}`:""}.`,"success")},km=async()=>{if(!Be){Fe("Select a Client before playing audio.");return}if(!an){Fe(fi);return}if(!Va){Fe("Selected Client does not report remote audio support yet.");return}if(Te)return;const p=!pe,S=p?`audio-${Date.now()}-${Math.random().toString(36).slice(2,8)}`:Pe.current.get(Be.deviceId),C=ka(p,Be.deviceId);p&&S?Pe.current.set(Be.deviceId,S):p||Pe.current.delete(Be.deviceId),Ue("audio"),Ae(p);try{p?(await qr(()=>Ic(Be.deviceId,"remote-audio-user-enable-reconcile")),await gi(async()=>{if(!S||!Wr(C,Be.deviceId,S))return;const R=await tt(`/api/remote/devices/${encodeURIComponent(Be.deviceId)}/audio/start`,{method:"POST",body:JSON.stringify({streamId:S,mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},T);if(R?.ok===!1)throw new Error(R.error||"Remote audio start failed.");Wr(C,Be.deviceId,S)||await Gr(Be.deviceId,S,"remote-audio-stale-user-start-compensation")})):await qr(()=>Ic(Be.deviceId,"remote-audio-user-disabled")),Fe(`${p?"Audio started":"Audio stopped"} for ${Rr(Be)}.`,"success")}catch(R){ka(!1),p&&Pe.current.delete(Be.deviceId),Ae(!1),Fe(R instanceof Error?R.message:String(R),"error")}finally{Ue("")}},gh=async(p,S)=>{const C=p.deviceId,R=Rr(p),j=String(Ze.current[C]||""),Q=!!j&&Mt[C]===!0;if(S&&j&&!Q)return{ok:!0,skipped:!0,action:"pause",deviceId:C,title:R};if(!S&&!j)return{ok:!0,skipped:!0,action:"resume",deviceId:C,title:R};if(!S&&j.startsWith("pending:"))return{ok:!1,action:"resume",deviceId:C,title:R,error:"Pause is still pending confirmation."};if(S){const Ye=j||`pending:${Date.now()}:${C}`,Le=pt.current?.deviceId===C?pt.current:null,st=!!Le||$===C,qt=st?++On.current:0,sn=()=>uw({deviceId:C,requestTransitionGeneration:qt,currentTransitionGeneration:On.current,actualControlOwner:pt.current}),It=lt.current.get(C);lt.current.set(C,{deviceId:C,monitorIndex:Ws(p,rn[C]??It?.monitorIndex),previousControlOwner:Le||It?.previousControlOwner||null}),De(C,!0),ge(C,!1),G(C,Ye),Rc(C),st&&(ya.current="",me("paused"));try{const gn=await tt(`/api/remote/devices/${encodeURIComponent(C)}/live/pause`,{method:"POST",body:JSON.stringify({reason:"user-video-pause"})},T);if(!gn?.pauseToken)return Tt.current.delete(C),G(C,""),ge(C,!1),lt.current.delete(C),sn()&&(He.current=null,Ne(null),Ce(!1),L(`control-pause-rollback-${Date.now()}-${C}`),me("connecting")),{ok:!1,action:"pause",deviceId:C,title:R,error:gn?.error||"video-capture-pause-failed"};const Ya=String(Ze.current[C]||"");if(Ya!==Ye&&Ya!==gn.pauseToken)return{ok:!1,action:"pause",deviceId:C,title:R,error:"Pause ownership changed before confirmation."};const fa=sn(),Kc=fa&&pt.current?.deviceId===C?pt.current:Le,Ma=lt.current.get(C);return Ma&&(Ma.previousControlOwner=Kc),fa&&pt.current?.deviceId===C&&(pt.current=null),fa&&(He.current=null,Ne(null)),G(C,gn.pauseToken),fa&&me("paused"),gn.ok===!1||gn.captureStopConfirmed!==!0?(ge(C,!0),{ok:!1,unconfirmed:!0,action:"pause",deviceId:C,title:R,error:gn.stopError||gn.error||"Client capture shutdown was not confirmed."}):(ge(C,!1),{ok:!0,action:"pause",deviceId:C,title:R})}catch(gn){return ge(C,!0),{ok:!1,unconfirmed:!0,action:"pause",deviceId:C,title:R,error:gn instanceof Error?gn.message:String(gn)}}}const X=lt.current.get(C),le=X?.previousControlOwner||null,te=$===C&&(le!==null||nr.current?.deviceId===C||H==="paused"),re=te?On.current:0;try{De(C,!1);const Ye=await tt(`/api/remote/devices/${encodeURIComponent(C)}/live/resume`,{method:"POST",body:JSON.stringify({pauseToken:j})},T);if(Ye?.ok===!1)throw new Error(Ye.error||"video-capture-resume-failed");if(String(Ze.current[C]||"")!==j)return{ok:!1,action:"resume",deviceId:C,title:R,error:"Resume ownership changed before confirmation."};const Le=lt.current.get(C)||X,st=Le?.previousControlOwner||le,qt=te&&uw({deviceId:C,requestTransitionGeneration:re,currentTransitionGeneration:On.current,actualControlOwner:pt.current});if(G(C,""),ge(C,!1),lt.current.delete(C),qt){const sn=++On.current;ya.current="";const It=up(C,sn,{sessionId:p.sessionId||st?.sessionId,monitorIndex:Ws(p,rn[C]??Le?.monitorIndex)});pt.current=It,Nr(It),_r.current="",ko.current=null,He.current=null,Ne(null),be(""),ie(""),Ce(!1),ca("control",C);const gn=`control-video-resume-${sn}-${C}`;L(gn),ee(C),me("connecting")}else ca("wall",C);return{ok:!0,action:"resume",deviceId:C,title:R}}catch(Ye){return Tt.current.delete(C),{ok:!1,action:"resume",deviceId:C,title:R,error:Ye instanceof Error?Ye.message:String(Ye)}}},sf=async()=>{if(Gi.length===0){Fe("Select one or more Clients before pausing video.");return}if(Fa.length===0){Fe(fi);return}if(Te)return;const p=Fa.some(C=>{const R=String(Ze.current[C.deviceId]||"");return!R||R.startsWith("pending:")||Mt[C.deviceId]===!0}),S=Fa.filter(C=>{const R=String(Ze.current[C.deviceId]||"");return p?!R||R.startsWith("pending:")||Mt[C.deviceId]===!0:!!R});if(S.length===0){Fe(p?"Selected Clients are already paused.":"Selected Clients are already playing.");return}Ue("video");try{const C=await Promise.all(S.map(re=>gh(re,p)));I();const R=C.filter(re=>re.ok&&!re.skipped),j=C.filter(re=>!re.ok&&re.unconfirmed),Q=C.filter(re=>!re.ok&&!re.unconfirmed),X=Fa.length-S.length+C.filter(re=>re.skipped).length,le=Gi.length-Fa.length,te=p?"pause":"resume";if(Q.length>0||j.length>0){const re=Q.slice(0,2).map(Ye=>`${Ye.title}: ${Ye.error||"unknown error"}`).join(" · ");Fe([`Video ${te} completed for ${R.length}/${S.length} Clients.`,j.length>0?`${j.length} Client capture stop${j.length===1?"":"s"} remain unconfirmed.`:"",re,le>0?`${le} selected Client${le===1?"":"s"} were outside the current plan limit.`:""].filter(Boolean).join(" "),"error");return}Fe([`Video ${p?"paused":"resumed"} for ${R.length} Client${R.length===1?"":"s"}.`,X>0?`${X} already ${p?"paused":"playing"}.`:"",le>0?`${le} outside the current plan limit.`:""].filter(Boolean).join(" "),"success")}finally{Ue("")}},Qn=p=>{const S=p instanceof Error?p.message:String(p);return/remote-actions-disabled|remote-access-blocked-by-settings/i.test(S)?"Remote access is blocked. Change Settings > Remote Access > Access mode first.":/power-actions-disabled|allowPowerActions-blocked-by-settings/i.test(S)?"Power actions are off. Turn on Settings > Remote Access > Power actions first.":/agent-tool-capability-unavailable|unsupported-agent-operation/i.test(S)?"This Client needs a newer LiveDesk Client for power actions.":/device-not-connected|404 device-not-found/i.test(S)?"The Client disconnected before the action could be sent.":S},na=async p=>{if(!Be||Te)return;const S=Be,R={sleep:"Sleep",restart:"Restart",shutdown:"Shut down"}[p];if(window.confirm(`${R} ${Rr(S)}? Unsaved work on that computer may be lost.`)){Ue(p),Fe(`Sending ${R.toLowerCase()} request to ${Rr(S)}...`);try{const j=await tt(`/api/remote/devices/${encodeURIComponent(S.deviceId)}/quick-actions`,{method:"POST",body:JSON.stringify({action:p})},T);if(!j.ok)throw new Error(j.error||"The remote action could not be sent.");Fe(`${R} request sent to ${Rr(S)}.`,"success"),I()}catch(j){Fe(Qn(j),"error")}finally{Ue("")}}},of=async(p,S,C="files")=>{const R=p.filter(le=>le.file.size>=0);if(R.length===0)return{files:0,bytes:0};if(!an)throw new Error(fi);if(S.length===0)throw new Error("Select at least one connected Client.");const j=crypto.randomUUID(),Q=R.reduce((le,te)=>le+te.file.size,0);let X=0;oi({id:j,status:"reading",progress:1,message:`Preparing ${R.length} ${C}`});try{for(let le=0;le<R.length;le+=1){const te=R[le],re=te.file,Ye=Math.max(1,Math.ceil(re.size/Dg));for(let Le=0;Le<Ye;Le+=1){const st=Le*Dg,qt=Math.min(re.size,st+Dg),sn=re.size===0?new ArrayBuffer(0):await re.slice(st,qt).arrayBuffer(),It=Le===Ye-1;oi({id:j,status:"sending",progress:Math.max(2,Math.min(98,Math.round(X/Math.max(1,Q)*96))),message:`${le+1}/${R.length} ${te.relativePath}`});const gn=await tt("/api/remote/files/chunk",{method:"POST",body:JSON.stringify({transferId:j,deviceIds:S,remoteDirectory:Xs.trim(),name:re.name,relativePath:te.relativePath,size:re.size,type:re.type,lastModified:re.lastModified,offset:st,totalBytes:re.size,final:It,dataBase64:NI(sn)})},T);if(!gn.ok||gn.queued!==S.length)throw new Error(gn.error||`file-chunk-not-queued-${gn.queued}/${S.length}`);X+=sn.byteLength,await new Promise(Ya=>window.setTimeout(Ya,0))}}return oi({id:j,status:"queued",progress:100,message:`Sent ${R.length} file${R.length===1?"":"s"} to ${S.length} Client${S.length===1?"":"s"}`}),window.setTimeout(()=>{oi(le=>le?.id===j&&le.status==="queued"?null:le)},4500),{files:R.length,bytes:Q}}catch(le){throw oi({id:j,status:"failed",progress:100,message:le instanceof Error?le.message:String(le)}),le}},lf=async p=>{const S=tn.length>0?tn.map(C=>C.deviceId):Be?[Be.deviceId]:[];try{await of(Mx(p),S)}catch(C){Fe(C instanceof Error?C.message:String(C))}},cf=async p=>{try{await of(Mx(p),Vn)}catch(S){Fe(S instanceof Error?S.message:String(S))}};d.useEffect(()=>{Tu.current=!1},[]);const Mm=p=>{p.preventDefault(),p.stopPropagation(),Ed(!1),lf(p.dataTransfer.files)},qo=async(p="ltd")=>{if(!n){Fe("Sign in with Google before checkout.");return}if(U&&p===Cn){Fe("LiveDesk license is already active.");return}if(U&&Cn==="pro"){Fe("LiveDesk Pro is already active.");return}ae("checkout");try{const{data:S,error:C}=await Pt.functions.invoke("dodo-checkout",{body:{plan:p}});if(C)throw C;if(!S?.checkout_url)throw new Error("Checkout function did not return a checkout URL.");window.location.assign(S.checkout_url)}catch(S){Fe(S instanceof Error?S.message:String(S)),ae("")}},Hc=iI(),Bc=oI(),Uu=xc.filter(p=>Oo.has(p)).length,uf=ys==="open"&&Ho.sampleMs>0?`${Ho.framesPerSecond.toFixed(1)} fps`:ys,We=Be?wt?Fo.get(Be.deviceId):Oo.get(Be.deviceId):void 0,Dl=Be?Ws(Be,rn[Be.deviceId]):0,df=Be?uI(Be):[],Am=typeof We?.monitorIndex=="number"?$f(We.monitorIndex,Math.max(1,We.monitorCount||1)):Dl,zc=(We&&Am===Dl?O0(We):null)||(Be?F0(Be,Dl):null);zc&&`${zc.width}${zc.height}`;const Il=Be?pa(wt?"control":"wall",Be.deviceId):"",aa=Il?fc[Il]:void 0,ur=Il?vu[Il]:void 0,yt=ur?.lastInfo,qu=aa&&aa.sampleMs>0?`${aa.framesPerSecond.toFixed(1)} fps`:"waiting";aa&&`${aa.totalFrames}${qu}`,ur&&ur.sampleMs>0&&`${ur.framesPerSecond.toFixed(1)}`,ur&&ur.sampleMs>0&&`${ur.changedFramesPerSecond.toFixed(1)}`,yt&&(`${yt.frameSeq}${yt.decoderLabel}${yt.queueSize}${yt.renderQueueSize}${yt.droppedForLatency}${yt.decoderFlushCount}${yt.decoderTimestampFallbacks}${yt.decoderInputCount}${yt.decoderOutputCount}`,yt.visualChanged),yt&&`${Math.round(yt.queuedForMs)}${Math.round(yt.decodedForMs)}${Math.round(yt.scheduledForMs)}${yt.drawMs.toFixed(1)}`,yt?.targetPaintIntervalMs&&`${yt.targetPaintIntervalMs.toFixed(1)}${(1e3/yt.targetPaintIntervalMs).toFixed(1)}`,ur&&`${ur.decoderInputFps.toFixed(1)}${ur.decoderOutputFps.toFixed(1)}`,yt?.canvasPresentation,yt&&`${yt.interactiveBufferWaitCount}${Math.round(yt.interactiveBufferWaitMs)}${yt.interactiveQueueDrainCount}`,aa&&(We?.frameMode==="mode5-lzo-delta"?`${Uf(aa.averageFrameBytes)}${We.deltaVisualTileCount||0}${We.deltaRefreshTileCount||0}${We.deltaTotalTiles||0}`:`${Uf(aa.averageFrameBytes)}${Math.round(aa.tinyFrameRatio*100)}${Math.round(aa.repeatedFrameRatio*100)}`),aa&&aa.sourceSendSampleCount>0&&`${aa.sourceSendAverageMs.toFixed(1)}${aa.sourceSendP95Ms.toFixed(1)}`,vx(aa),vx(ur),aa&&ur&&`${yx(aa)}${yx(ur)}`,We?We.frameMode||We.mode||We.codec||We.mimeType:wt?qn.frameMode:St.frameMode,wt?qn.frameMode:St.frameMode,We?`${We.width}${We.height}${Uf(We.byteLength)}`:wt?`${Ui.maxWidth}${Ui.maxHeight}`:`${St.maxWidth}${St.maxHeight}`,We&&`${We.isKeyFrame?"key":String(We.chunkType||"delta")}`,We&&We.monitorCount&&((We.monitorIndex??0)+1,`${We.monitorCount}`),We&&[`src ${Math.round(We.sourceGapMs||0)}ms`,`gap ${Math.round(We.agentSendGapMs||0)}ms`,`tx ${Math.round(We.agentSendDurationMs||0)}ms`,`pace ${Math.round(We.agentPaceMs||0)}ms`,`queue ${Math.round(We.agentQueueBeforePaceMs||0)}ms`,`age ${Math.round(We.agentFrameAgeMs||0)}ms`,We.hubPacketTransitAgeMs!==void 0?`sock ${Math.max(0,Math.round(We.hubPacketTransitAgeMs))}ms`:"",We.droppedByAgent?`drop ${We.droppedByAgent}`:"",We.hubIngressDropped?`ingress-drop ${We.hubIngressDropped}`:"",We.hubClientDropped?`ws-drop ${We.hubClientDropped}`:"",We.captureStageMs?`capture ${Math.round(We.captureStageMs)}ms`:"",We.requestedFps?`req ${Math.round(We.requestedFps)}fps`:"",We.effectiveFps?`eff ${Math.round(We.effectiveFps)}fps`:"",We.captureAverageMs?`avg ${Math.round(We.captureAverageMs)}ms`:"",We.captureP95Ms?`p95 ${Math.round(We.captureP95Ms)}ms`:"",We.slowFrameCount?`slow ${Math.round(We.slowFrameCount)}`:"",We.captureHelperRestarts?`helper ${Math.round(We.captureHelperRestarts)}`:"",We.convertMs?`rgb565 ${Math.round(We.convertMs)}ms`:"",We.compressMs?`lzo ${Math.round(We.compressMs)}ms`:"",We.captureSourceSerial?`cap #${We.captureSourceSerial}`:"",We.captureSourceSkipped?`cap skip ${We.captureSourceSkipped}`:"",We.frameMode==="mode5-lzo-delta"?`tiles ${We.deltaVisualTileCount||0}+${We.deltaRefreshTileCount||0}/${We.deltaTotalTiles||0}@${We.deltaTileSize||0}`:"",We.platformProfile||We.hardwareEncoder||"-",We.atlasComposeMs?`atlas ${We.atlasComposeMs.toFixed(1)}ms`:"",We.atlasPoolStarved?`pool ${We.atlasPoolStarved}`:"",We.atlasTileCount?`tiles ${We.atlasReadyTiles||0}/${We.atlasTileCount}`:"",We.atlasInputRevision?`input #${We.atlasInputRevision}`:"",We.atlasSourceMaxAgeMs!==void 0?`input-age ${Math.round(We.atlasSourceMaxAgeMs)}ms`:"",yt?.inputFeedbackMs!==void 0&&yt.inputFeedbackAt!==void 0&&performance.now()-yt.inputFeedbackAt<=lx?`feedback ${Math.round(yt.inputFeedbackMs)}ms`:"",We.contentHash?`enc ${We.contentHash.slice(0,6)}`:"",yt?.visualHash?`pix ${yt.visualHash.slice(0,6)}`:""].filter(Boolean).join(" / "),Fu==="open"&&[`${bs.sentPerSecond.toFixed(1)} hz`,bs.lastInputSeq>0?`rtt ${Math.round(bs.lastRoundTripMs)}ms`:"",bs.lastInputSeq>0?`apply ${bs.lastAgentApplyMs.toFixed(1)}ms`:"",bs.droppedPerSecond>0?`drop ${bs.droppedPerSecond.toFixed(1)}/s`:"",bs.bufferedAmount>0?`buf ${Uf(bs.bufferedAmount)}`:"",bs.lastInputType||"ready"].filter(Boolean).join(" / "),yt?.inputFeedbackMs!==void 0&&yt.inputFeedbackAt!==void 0&&performance.now()-yt.inputFeedbackAt<=lx&&[yt.inputFeedbackExact?"exact":"estimated",yt.inputFeedbackInputType||"",`total ${Math.round(yt.inputFeedbackMs)}ms`,yt.inputFeedbackAgentApplyMs!==void 0?`apply ${yt.inputFeedbackAgentApplyMs.toFixed(1)}ms`:"",yt.inputFeedbackApplyToCaptureMs!==void 0?`apply→frame ${Math.round(yt.inputFeedbackApplyToCaptureMs)}ms`:"",yt.inputFeedbackInputToFrameMs!==void 0?`input→browser ${Math.round(yt.inputFeedbackInputToFrameMs)}ms`:"",yt.inputFeedbackFrameToPaintMs!==void 0?`browser→paint ${Math.round(yt.inputFeedbackFrameToPaintMs)}ms`:"",yt.inputFeedbackSampleCount?`p50 ${Math.round(yt.inputFeedbackP50Ms||0)}ms`:"",yt.inputFeedbackSampleCount?`p95 ${Math.round(yt.inputFeedbackP95Ms||0)}ms`:"",yt.inputFeedbackSampleCount?`n=${yt.inputFeedbackSampleCount}`:"",`input #${yt.inputFeedbackSeq||0}`].filter(Boolean).join(" / "),We&&`${We.frameSeq}${Gx(We.receivedAt||We.capturedAt)}`;const so=Math.max(0,Ho.bytesPerSecond*8/1e6),ff={activeTool:gt,audioError:Jd,audioMode:pe,audioState:Hu,audioStats:Tn,lastAudioFrame:Bu,selectedAudioCaptureStreamId:Xd,controlFrames:Fo,controlInputReady:Ou,controlMode:$e,controlPresentationReady:Nd,controlSessionDeviceId:$,controlSessionFrameReady:ue,controlSessionState:H,controlStreamBinding:Me,devices:N,documentPresentationVisible:Ea,focusedDeviceId:q,frames:Oo,localFeatureAccess:an,quickActionBusy:Te,selectedDeviceId:Be?.deviceId||"",selectedIds:K,showControlFocus:wt,videoCaptureStopUnconfirmedByDeviceId:Mt,videoCapturePausedDeviceIds:dt,wallPresentationReadyDeviceIds:ji},Wu=d.useRef(ff);Wu.current=ff,d.useEffect(()=>{if(!kd.current)return;const p=window,S=le=>{if(!le)return null;const te=le.sourceGapMs,re=te==null||te===""?null:Number.isFinite(Number(te))?Number(te):null,Ye=le;return{deviceId:le.deviceId,sessionId:le.sessionId||"",streamId:le.streamId||"",commandId:le.commandId||"",captureGeneration:Number(le.captureGeneration||0),monitorIndex:Number(le.monitorIndex||0),streamPurpose:le.streamPurpose||"",frameSeq:Number(le.frameSeq||0),frameMode:le.frameMode||"",mimeType:le.mimeType||"",currentGenerationVerified:Ye.currentGenerationVerified===!0,receivedAt:Ye.receivedAt||"",capturedAt:Ye.capturedAt||"",sourceGapMs:re,inputFeedbackEventId:String(le.inputFeedbackEventId||""),inputFeedbackInputSeq:Number(le.inputFeedbackInputSeq||0),inputFeedbackIssuedAtEpochMs:Number(le.inputFeedbackIssuedAtEpochMs||0),inputFeedbackAgentApplyMs:Number(le.inputFeedbackAgentApplyMs||0),inputFeedbackApplyToCaptureMs:Number(le.inputFeedbackApplyToCaptureMs||0)}},C=le=>{if(!le)return null;const te=window.getComputedStyle(le),re=le.getBoundingClientRect(),Ye=Math.max(0,Math.min(re.right,window.innerWidth)-Math.max(re.left,0)),Le=Math.max(0,Math.min(re.bottom,window.innerHeight)-Math.max(re.top,0)),st=Number(te.opacity),qt=le.isConnected&&te.display!=="none"&&te.visibility!=="hidden"&&te.visibility!=="collapse"&&Number.isFinite(st)&&st>0&&re.width>0&&re.height>0&&Ye>0&&Le>0;return{connected:le.isConnected,userVisible:qt,width:Math.max(0,Number(le.width||0)),height:Math.max(0,Number(le.height||0)),css:{display:te.display,visibility:te.visibility,opacity:Number.isFinite(st)?st:0},rect:{left:re.left,top:re.top,right:re.right,bottom:re.bottom,width:re.width,height:re.height,viewportIntersectionWidth:Ye,viewportIntersectionHeight:Le},codec:op(le)}},R=(le,te)=>{const re=ti.current.get(pa(le,te));return re?{bindingKey:re.bindingKey||"",totalFrames:re.totalFrames,totalChangedFrames:re.totalChangedFrames,lastFrameSeq:Number(re.lastFrameSeq||0),lastPaintAgeMs:re.lastAt===void 0?-1:Math.max(0,performance.now()-re.lastAt),lastInfo:re.lastInfo?{frameSeq:Number(re.lastInfo.frameSeq||0),decoderInputCount:Number(re.lastInfo.decoderInputCount||0),decoderOutputCount:Number(re.lastInfo.decoderOutputCount||0),targetPaintIntervalMs:Number(re.lastInfo.targetPaintIntervalMs||0),droppedForLatency:Number(re.lastInfo.droppedForLatency||0),visualChanged:re.lastInfo.visualChanged===!0,inputFeedbackExact:re.lastInfo.inputFeedbackExact===!0,inputFeedbackMs:Number(re.lastInfo.inputFeedbackMs||0),inputFeedbackSampleCount:Number(re.lastInfo.inputFeedbackSampleCount||0),inputFeedbackP50Ms:Number(re.lastInfo.inputFeedbackP50Ms||0),inputFeedbackP95Ms:Number(re.lastInfo.inputFeedbackP95Ms||0),inputFeedbackTargetMs:ux,inputFeedbackTargetMinSamples:dx,inputFeedbackOnTarget:re.lastInfo.inputFeedbackExact===!0&&Number(re.lastInfo.inputFeedbackSampleCount||0)>=dx&&Number(re.lastInfo.inputFeedbackP95Ms)<ux}:null}:null},j=(le,te)=>{if(!le)return null;if(te==="wall-visible"){const Ye=ti.current.get(pa("wall",le));return Ye?{bindingKey:Ye.bindingKey||"",total:Ye.totalFrames,lastFrameSeq:Number(Ye.lastFrameSeq||0),lastPaintAgeMs:Ye.lastAt===void 0?-1:Math.max(0,performance.now()-Ye.lastAt)}:null}if(te!=="control-visible"&&te!=="wall-reuse-visible")return null;const re=hu.current.get(`${te}:${le}`);return re?{bindingKey:re.bindingKey,total:re.totalPaints,lastFrameSeq:re.lastFrameSeq,lastPaintAgeMs:Math.max(0,performance.now()-re.lastPaintAt)}:null},Q=(le,te)=>{const re=j(le,te);return re?{bindingKey:re.bindingKey,totalPaints:re.total,lastPaintAgeMs:re.lastPaintAgeMs,lastFrameSeq:re.lastFrameSeq}:null},X={readPresentationCounter(le,te){return j(String(le||""),te)},snapshot(le){const te=String(le||""),re=Wu.current,Ye=re.devices.find(Ma=>Ma.deviceId===te)?.liveCapturePause,Le=String(Ze.current[te]||""),st=Ht.current.get(te)||null,qt=pn.current.get(te)||null,sn=Fn.current.get(te)||null,It=h1(),gn=g1(),Ya={frameStats:bu.current===null?0:1,wallRecovery:cl.current===null?0:1,controlWarm:ns.current===null?0:1,controlWallDownshift:ar.current===null?0:1},fa=ni.current?.deviceId===te?ni.current:null,Kc=om.current.get(te)||null;return{capturedAt:Date.now(),deviceId:te,activeTool:re.activeTool,documentPresentationVisible:re.documentPresentationVisible,showControlFocus:re.showControlFocus,selectedDeviceId:re.selectedDeviceId,focusedDeviceId:re.focusedDeviceId,selectedDeviceIds:[...re.selectedIds],localFeatureAccess:re.localFeatureAccess,quickActionBusy:re.quickActionBusy,audioMode:re.audioMode,audioState:re.audioState,audioError:re.audioError,audioCaptureStreamId:re.selectedAudioCaptureStreamId,audioFrame:re.lastAudioFrame?{deviceId:re.lastAudioFrame.deviceId,streamId:re.lastAudioFrame.streamId,frameSeq:Number(re.lastAudioFrame.frameSeq||0),mimeType:re.lastAudioFrame.mimeType,sampleRate:Number(re.lastAudioFrame.sampleRate||0),channels:Number(re.lastAudioFrame.channels||0),byteLength:Number(re.lastAudioFrame.byteLength||0)}:null,audioStats:{...re.audioStats},videoCapturePausePhase:Le?Le.startsWith("pending:")?"pending":"confirmed":"none",videoCaptureStopUnconfirmed:re.videoCaptureStopUnconfirmedByDeviceId[te]===!0,authoritativeLiveCapturePause:Ye?{phase:Ye.phase||"",captureStopConfirmed:Ye.captureStopConfirmed===!0,stopAttemptCount:Math.max(0,Number(Ye.stopAttemptCount||0)),stopError:Ye.stopError||""}:null,controlMode:re.controlMode,controlSessionDeviceId:re.controlSessionDeviceId,controlSessionState:re.controlSessionState,controlSessionFrameReady:re.controlSessionFrameReady,controlPresentationReady:re.controlPresentationReady,controlInputReady:re.controlInputReady,controlConnection:Kc?{...Kc}:null,pendingControlConnection:fa?{...fa,elapsedMs:Math.max(0,performance.now()-fa.startedAt)}:null,videoCapturePaused:re.videoCapturePausedDeviceIds.has(te),wallPresentationReady:re.wallPresentationReadyDeviceIds.has(te),controlBinding:re.controlStreamBinding?.deviceId===te?{...re.controlStreamBinding}:null,actualControlOwner:pt.current?.deviceId===te?{...pt.current}:null,wallCapturePauseOwner:nr.current?.deviceId===te?{...nr.current}:null,frameSubscriptions:It,audioSubscriptions:gn,presentationTimers:{...Ya,total:Object.values(Ya).reduce((Ma,Yo)=>Ma+Yo,0)},wallFrame:S(re.frames.get(te)),controlFrame:S(js.current.get(te)||re.controlFrames.get(te)),wallPaint:R("wall",te),controlPaint:R("control",te),controlVisiblePaint:Q(te,"control-visible"),wallReuseVisiblePaint:Q(te,"wall-reuse-visible"),presentationPaintSequence:gu.current,presentationPaintEvents:Md.current.filter(Ma=>Ma.deviceId===te).sort((Ma,Yo)=>Ma.sequence-Yo.sequence).map(Ma=>({...Ma})),wallCanvas:C(st),controlDecodeCanvas:C(qt),controlPresentationCanvas:C(sn),globalCodec:op()}}};return p.__liveDeskTransmissionProbe=X,()=>{p.__liveDeskTransmissionProbe===X&&delete p.__liveDeskTransmissionProbe}},[]);const Wo=d.useCallback(()=>{As(!0),Xr(Date.now()),I(),Ir.current!==null&&window.clearTimeout(Ir.current),Ir.current=window.setTimeout(()=>{Ir.current=null,Xr(Date.now()),As(!1)},650)},[I]),Bs=d.useCallback(()=>{if(jn){Dr(!1);return}ea(!1),Dr(!0),Wo()},[Wo,jn]),Gu=d.useCallback(()=>{if(In){ea(!1);return}Dr(!1),ea(!0),Wo()},[In,Wo]),Nm=d.useCallback(()=>{if(en){Qs(!1);return}Qs(!0),Wo()},[en,Wo]),mf=jn||In,zs=JSON.stringify(ut.filter(p=>p.connected).map(p=>p.deviceId).sort());d.useEffect(()=>{if(!mf)return;const p=JSON.parse(zs);if(p.length===0){As(!1);return}const S=new AbortController,C=[];let R=!1;return Ir.current!==null&&(window.clearTimeout(Ir.current),Ir.current=null),As(!0),Xr(Date.now()),Promise.allSettled(p.map(j=>tt(`/api/remote/devices/${encodeURIComponent(j)}/status-diagnostic`,{method:"POST",body:JSON.stringify({purpose:"remote-status-current-snapshot"}),signal:S.signal,timeoutMs:1500},T))).then(()=>{R||[500,1800,4500].forEach((j,Q,X)=>{const le=window.setTimeout(()=>{R||(I(),Xr(Date.now()),Q===X.length-1&&As(!1))},j);C.push(le)})}),()=>{R=!0,S.abort();for(const j of C)window.clearTimeout(j)}},[T,I,zs,mf]);const Go=new Map,$c=new Map;if(jn||In||en)for(const p of ut){const S=p.deviceId,C=wt&&$===S,j=pa(C?"control":"wall",S),Q=C?Fo.get(S):Oo.get(S),X=C?pn.current.get(S)||Fn.current.get(S)||null:Ht.current.get(S)||(Dt?yr.current:null),le={device:p,frame:Q,receiveStat:fc[j],paintStat:vu[j],codec:X?op(X):{},selectedMonitorIndex:Ws(p,rn[S]),control:C,controlInputReady:C&&Ou,controlBinding:C&&Me?.deviceId===S?Me:void 0,hubRelay:k?.relay,capturePaused:dt.has(S),capturePauseConfirmed:p.liveCapturePause?.captureStopConfirmed===!0,capturePauseError:p.liveCapturePause?.stopError||"",clientHeartbeatMs:Number(k?.heartbeatMs||5e3),now:Date.now()},te=["open","playing","silent"].includes(Hu),re=Tn.nativeCallbackDiagnosticsAvailable&&(Tn.nativeRejectedCallbackCount>0||Tn.nativeCurrentnessDropCount>0),Ye=te&&!re,Le=S===Be?.deviceId&&pe?{id:"browser-remote-audio",state:Ye?"ok":"warning",label:Ye?"Remote audio is healthy":"Remote audio needs attention",detail:Tn.lastUpdatedAt>0?[Hu,`context ${Tn.audioContextState}`,`queue ${Math.round(Tn.queuedMs)}ms`,`packet ${Math.round(Tn.lastPacketAgeMs)}ms`,`capture ${Tn.captureHealthy?"healthy":Tn.captureAwaitingCurrentPcm?"awaiting PCM":"down"}`,Tn.backendKind?`backend ${Tn.backendKind}`:"backend unknown",Tn.helperRequired?`helper ${Tn.helperAlive&&Tn.helperPid>0?`pid ${Tn.helperPid}`:"missing"}`:"helper N/A",`drop ${Tn.drops}`,`restart ${Tn.automaticRestarts}`,Tn.nativeCallbackDiagnosticsAvailable?`native reject ${Tn.nativeRejectedCallbackCount}`:"native callback diagnostics unknown",Tn.nativeCallbackDiagnosticsAvailable?`native stale ${Tn.nativeCurrentnessDropCount}`:"",Tn.nativeLastDropReason?`native reason ${Tn.nativeLastDropReason}`:"",Bu?`frame #${Bu.frameSeq}`:"waiting for frame"].filter(Boolean).join(" · "):"Browser audio diagnostics are collecting while Remote or Debug status is open."}:null;if(jn||en){const st=cD(le);jn&&Le&&st.push(Le),Go.set(S,st)}if(In){const st=uD(le);Le&&st.push(Le),$c.set(S,st)}}const Vu=en?dD({status:k||{},deviceDiagnostics:[...Go.values()],codec:op(),browser:{hardwareConcurrency:navigator.hardwareConcurrency,deviceMemory:Number(navigator.deviceMemory||0)},frameStats:Ho}):[],Ll=Po?.atlasReadyTiles??Uu,hn=Po?.atlasTileCount??Uu,yh=Ll===hn?`${hn} tiles`:`${Ll}/${hn} tiles`,bh=Sa.length>0;wt?`${uf}${so.toFixed(so>=10?0:1)}`:bh?`${yh}${uf}${so.toFixed(so>=10?0:1)}`:`${Uu}${uf}${so.toFixed(so>=10?0:1)}`;const Ku=tn.length,Uc=wt?Be?Rr(Be):"No Client":Ku===0?"No Client":Ku>1?`${Ku} selected`:Be?Rr(Be):"No Client",io=wt?[Be?.deviceId].filter(p=>!!p):tn.map(p=>p.deviceId),Ha=yd[Ln]||yd.en,qc=Ha.sync||yd.en.sync,Wc=r||F?"checking":U?Cn==="pro"?"Pro LTD active":`Plus LTD ${ut.length}/${zf}`:Io?`Free ${ut.length}/${Bf}`:`Upgrade ${ut.length}/${Bf}`,Tm=U?Cn==="pro"?"Pro active":"Upgrade to Pro LTD":n?z==="checkout"?"Opening checkout":Cn==="ltd"?"Buy Pro LTD":"Buy Plus LTD":z==="auth"?"Opening Google":"Sign in to buy",pf=Cn==="pro"||z==="checkout"||z==="auth"||r||F,hf=n?.user?.user_metadata,_l=Nx(hf,"avatar_url","picture"),Vo=Nx(hf,"full_name","name")||n?.user?.email||"Google",Gc=Vo.slice(0,1).toUpperCase(),Rm=k?.started?"Local app ready":"Start LiveDesk",bi=i?.active?"Published":n?"Not published":"Sign in required",Yn=/^\d{6}$/.test(k?.pairingPin||"")?k?.pairingPin:"------",Vc=p=>{if(typeof window<"u"&&(p==="support"?window.history.pushState({},"","/support"):gt==="support"&&window.history.pushState({},"","/")),p==="control"){const S=Pa||di;if(S&&(Rl(S.deviceId),Wa(!1),ce(S.deviceId)),nn(p),!an){qe(!1),Fe(fi);return}qe(!0);return}p==="wall"&&ol(S=>S+1),nn(p),qe(!1)},Ko=z==="update"||Ot?.stage==="updating"||["dispatching","waiting-for-clients","hub-restart-requested"].includes(k?.update?.state||""),da=!!(k?.update?.updateAvailable&&k.update.canApply||Ko||Ot?.error||!k&&Ot),Qo=bM(Ln),gf=d.useCallback(p=>{if(!Ot?.targetIds.includes(p))return;const S=k?.update?.operationId===Ot.operationId?k.update.targets?.find(C=>C.deviceId===p):void 0;switch(S?.state){case"completed":return{state:"updated",label:"Updated"};case"failed":return{state:"failed",label:"Update failed",error:S.error};case"pending-offline":return{state:"offline",label:"Waiting for reconnect"};case"queued":return Ot.stage==="updating"?{state:"queued",label:"Queued"}:void 0;case"waiting":return Ot.stage==="updating"?S.candidateSince?{state:"updating",label:"Verifying restart..."}:{state:"updating",label:"Restarting..."}:void 0;default:return Ot.stage==="updated"?{state:"updated",label:"Updated"}:Ot.stage==="updating"?{state:"updating",label:"Verifying..."}:void 0}},[k?.update,Ot]),vf=(p,S,C)=>{const R=p.device,j=R?o.jsx(Rx,{device:R,frame:Oo.get(R.deviceId),selected:Hr.has(R.deviceId),controlEnabled:!C&&sr&&$e&&Hs&&Be?.deviceId===R.deviceId,showStatus:St.showScreenStatus,monitorIndex:Ws(R,rn[R.deviceId]),monitorCount:ru(R),onSelect:()=>nf(R.deviceId),onFocusDevice:()=>ro(R.deviceId),onOpenControl:()=>Oc(R.deviceId),onCycleMonitor:X=>Fc(R.deviceId,X),onCanvasReady:C&&_f({mode4Enabled:Dt,directMode4WallEnabled:ir,isMac:nl(R.platform)})!=="direct"?_t:Mr,sendInput:Dc,remoteModifierState:Yd,updateIndicator:gf(R.deviceId),presentationReady:St.autoStartLive&&us.includes(R.deviceId)?ji.has(R.deviceId):void 0,showPresentationSpinner:St.autoStartLive&&us.includes(R.deviceId),remoteDiagnostics:In?$c.get(R.deviceId):jn?Go.get(R.deviceId):void 0,diagnosticsMode:In?"debug":"remote"},R.deviceId):p.offline&&p.saved?o.jsx(HI,{entry:p.saved,slotNumber:p.slotNumber}):o.jsx(OI,{index:S}),Q=R?.deviceId||p.saved?.deviceId||"";return o.jsx("div",{className:`wall-slot-drop-zone ${Et?"layout-locked":jt?"layout-draft":""} ${!Xt&&!Wt?"layout-editable":""} ${Ks===Q&&Q?"drag-source":""} ${Un===p.slotNumber?"drop-target":""}`,"data-wall-slot-number":p.slotNumber,draggable:!!Q&&!Xt&&!Wt,onDragStart:X=>Q&&Fd(Q,X),onDragEnd:yl,onDragOver:X=>{!Ja.current||Xt||Wt||(X.preventDefault(),X.dataTransfer.dropEffect="move",Ni(p.slotNumber))},onDragLeave:X=>{X.currentTarget.contains(X.relatedTarget)||Ni(le=>le===p.slotNumber?0:le)},onDrop:X=>{Xt||Wt||(X.preventDefault(),bl(p.slotNumber))},children:j},Q||p.saved?.deviceId||`slot-${p.slotNumber}`)};return o.jsxs("main",{className:"app-shell",children:[o.jsxs("aside",{className:"tool-rail","aria-label":"LiveDesk tools",children:[o.jsx("div",{className:"rail-brand",title:"LiveDesk",children:o.jsx(Vx,{size:25})}),o.jsx("nav",{className:"rail-tools",children:II.map(p=>{const S=p.icon,C=Hp(p.tooltip,Ln);return o.jsxs("button",{className:`rail-tool ${p.id==="sync-server"?"sync-server hub-sync-trigger":""} ${gt===p.id?"active":""} accent-${p.accent}`,onClick:()=>p.id==="sync-server"?ef():Vc(p.id),"data-tooltip":p.id==="sync-server"&&Xe?void 0:Qg(p.label,p.tooltip,Ln),"aria-label":`${p.label}. ${C}`,type:"button",disabled:p.id==="sync-server"&&z==="host","aria-busy":p.id==="sync-server"&&z==="host","aria-expanded":p.id==="sync-server"?Xe:void 0,"aria-haspopup":p.id==="sync-server"?"dialog":void 0,"aria-controls":p.id==="sync-server"&&Xe?"hub-sync-popover":void 0,children:[p.id==="sync-server"&&z==="host"?o.jsx("span",{className:"sync-server-spinner","aria-hidden":"true"}):o.jsx(S,{size:19}),o.jsx("span",{children:p.id==="sync-server"&&z==="host"?"Syncing…":p.label})]},p.id)})}),o.jsxs("div",{className:"rail-footer",children:[LI.map(p=>{const S=p.icon;return o.jsxs("button",{className:`rail-tool compact ${gt===p.id?"active":""} accent-${p.accent}`,onClick:()=>Vc(p.id),title:p.label,type:"button",children:[o.jsx(S,{size:18}),o.jsx("span",{children:p.label})]},p.id)}),o.jsxs("button",{className:`rail-tool compact local-settings ${vl?"active":""}`,onClick:()=>{nn("settings"),typeof window<"u"&&window.history.pushState({},"","/"),es(!1),qe(!1),Ti(!1)},title:"Settings",type:"button",children:[o.jsx(Cv,{size:18}),o.jsx("span",{children:"Settings"})]}),o.jsxs("button",{className:`rail-account ${n?"signed-in":""}`,onClick:()=>{es(p=>!p)},disabled:r||z==="auth","aria-expanded":Jr,title:n?`Account: ${n.user?.email||Vo}`:"Sign in with Google",type:"button",children:[n?_l?o.jsx("img",{src:_l,alt:Vo,referrerPolicy:"no-referrer"}):o.jsx("span",{className:"avatar-fallback",children:Gc}):o.jsx(lu,{size:18}),o.jsx("span",{children:n?"Account":"Google"})]}),Jr&&o.jsxs("section",{className:"account-popover",role:"dialog","aria-label":"LiveDesk account",children:[o.jsxs("div",{className:"account-popover-head",children:[o.jsx("div",{className:"account-popover-avatar",children:n&&_l?o.jsx("img",{src:_l,alt:Vo,referrerPolicy:"no-referrer"}):n?o.jsx("span",{children:Gc}):o.jsx(lu,{size:18})}),o.jsxs("div",{children:[o.jsx("strong",{children:n?Vo:"Account"}),o.jsx("p",{children:n?.user?.email||"Not signed in"})]})]}),o.jsxs("dl",{className:"account-popover-facts",children:[o.jsx("dt",{children:"User"}),o.jsx("dd",{children:n?.user?.email||"Not signed in"}),o.jsx("dt",{children:"Network"}),o.jsx("dd",{children:Rm}),o.jsx("dt",{children:"Access"}),o.jsx("dd",{children:bi}),o.jsx("dt",{children:"Plan"}),o.jsx("dd",{children:Wc}),o.jsx("dt",{children:"Ads"}),o.jsx("dd",{children:Cn==="free"?"Standard banner":"Removed"})]}),n?o.jsxs("button",{className:"account-popover-action",onClick:wm,disabled:z==="auth",type:"button",children:[o.jsx(Dx,{size:16}),"Logout"]}):o.jsxs("button",{className:"account-popover-action primary",onClick:vi,disabled:z==="auth",type:"button",children:[o.jsx(lu,{size:16}),"Sign in with Google"]})]})]})]}),Xe&&o.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:[o.jsxs("header",{className:"client-hub-switch-head",children:[o.jsx("span",{className:"client-hub-switch-mark","aria-hidden":"true",children:o.jsx(mo,{size:19})}),o.jsx("span",{className:"client-hub-switch-eyebrow",children:Qo.eyebrow}),o.jsx("button",{className:"client-hub-switch-close",type:"button",onClick:()=>jl(),"aria-label":Qo.closeLabel,children:o.jsx(hr,{size:17})})]}),o.jsx("h2",{id:"hub-sync-title",children:Qo.title}),o.jsx("p",{id:"hub-sync-description",children:Qo.description}),o.jsxs("p",{id:"hub-sync-notice",className:"client-hub-switch-notice",children:[o.jsx(Na,{size:16,"aria-hidden":"true"}),o.jsx("span",{children:Qo.restartNotice})]}),o.jsxs("div",{className:"client-hub-switch-actions",children:[o.jsx("button",{type:"button",onClick:()=>jl(),children:Qo.cancel}),o.jsxs("button",{ref:kt,className:"primary",type:"button",onClick:tf,disabled:z==="host",children:[o.jsx(mo,{size:16}),Qo.confirm]})]})]}),o.jsxs("section",{className:`desk-stage ${Ls&&!Zr?"dock-open":""} ${wt?"control-stage":""} ${zi?"agents-stage":""}`,children:[o.jsxs("header",{className:"topbar",children:[o.jsxs("div",{className:"brand",children:[o.jsx("span",{className:"brand-mark",children:o.jsx(Zl,{size:18})}),o.jsxs("div",{className:"brand-copy",children:[o.jsx("h1",{children:"LiveDesk"}),o.jsx("p",{children:"Control wall for local machines"})]}),da?o.jsxs("button",{className:"topbar-update-button",onClick:()=>{xm()},title:Ot?.error?`LiveDesk Hub update failed: ${Ot.error}`:`Update LiveDesk to ${k?.update?.latestVersion||Ot?.targetManagerVersion||"latest"}`,"aria-label":Ot?.error?`LiveDesk Hub update failed: ${Ot.error}`:Ko?"LiveDesk update in progress":`Update LiveDesk to ${k?.update?.latestVersion||Ot?.targetManagerVersion||"latest"}`,type:"button",disabled:Ko||!k?.update?.canApply,"aria-busy":Ko,children:[Ko?o.jsx("span",{className:"topbar-update-spinner","aria-hidden":"true"}):o.jsx(Sv,{size:19,"aria-hidden":"true"}),Ko&&k?.update?.targetCount?o.jsxs("span",{className:"topbar-update-count","aria-hidden":"true",children:[k.update.completedCount||0,"/",k.update.targetCount]}):null]}):null]}),o.jsxs("div",{className:"topbar-tray",children:[_a&&!wt&&o.jsxs("div",{className:"file-share-top-route","aria-label":"File distribution route",children:[o.jsxs("div",{children:[o.jsx(su,{size:17}),o.jsxs("span",{children:[o.jsx("small",{children:"Source"}),o.jsx("strong",{children:"LiveDesk Hub"})]})]}),o.jsx(Mv,{size:15}),o.jsx(hk,{size:16}),o.jsxs("div",{children:[o.jsx("span",{className:"file-share-top-route-laptops",children:"▣ ▣ ▣"}),o.jsxs("span",{children:[o.jsx("small",{children:"Destination"}),o.jsxs("strong",{children:[Pd," Client",Pd===1?"":"s"]}),o.jsx("em",{children:Xs.trim()||"Desktop/LiveDeskFiles"})]})]})]}),Ls&&!wt&&o.jsxs("div",{className:"top-actions",children:[o.jsx(ax,{active:en,refreshing:en&&Ys,onClick:Nm}),o.jsx(tx,{active:jn,refreshing:jn&&Ys,onClick:Bs}),o.jsx(nx,{active:In,refreshing:In&&Ys,onClick:Gu}),o.jsx("span",{className:"top-actions-divider","aria-hidden":"true"}),o.jsx(ex,{controller:mi,onError:Fe}),o.jsx("span",{className:"top-actions-divider","aria-hidden":"true"}),o.jsxs("button",{className:"text-button wall-layout-button",onClick:()=>{ui()},disabled:!Et&&!jt||Xt||Wt,title:"Release the saved Wall layout and return to Client slot order",type:"button",children:[o.jsx($g,{size:15}),"Reset"]}),o.jsxs("button",{className:`text-button wall-layout-button ${Et?"active":""}`,onClick:()=>{Wi()},disabled:Xt||Wt||!n||Et&&!yc,title:n?Et?yc?"Save newly placed Clients to the locked account layout":"The current Wall layout is locked and saved":"Remember and lock the current Wall layout for this account":"Sign in to save the Wall layout","aria-pressed":Et,type:"button",children:[Wt||Xt?o.jsx(Si,{className:"spin",size:15}):o.jsx(Ci,{size:15}),Et?yc?"Save":"Locked":"Lock"]}),o.jsx("span",{className:"top-actions-divider","aria-hidden":"true"}),o.jsx("div",{className:"segmented-control wall-cadence-control","aria-label":"Wall frame speed",children:EI.map(p=>o.jsx("button",{className:qa===p.id?"active":"",onClick:()=>{fe(p.id),Ts(p.fps),xI(p.id)},title:p.label+" Wall streaming ("+p.fps+" fps)","aria-pressed":qa===p.id,type:"button",children:p.label},p.id))}),o.jsx("span",{className:"top-actions-divider","aria-hidden":"true"}),o.jsx("div",{className:"segmented-control","aria-label":"Wall view",children:DI.map(p=>o.jsx("button",{className:Sn===p.id?"active":"",onClick:()=>Ms(p.id),type:"button",children:p.label},p.id))})]}),wt&&o.jsxs("div",{className:"top-actions",children:[o.jsx(ax,{active:en,refreshing:en&&Ys,onClick:Nm}),o.jsx(tx,{active:jn,refreshing:jn&&Ys,onClick:Bs}),o.jsx(nx,{active:In,refreshing:In&&Ys,onClick:Gu}),o.jsx("span",{className:"top-actions-divider","aria-hidden":"true"}),o.jsx(ex,{controller:mi,onError:Fe})]})]})]}),en&&Ls&&o.jsx(JE,{items:Vu,collectedAt:lc,onClose:()=>Qs(!1)}),Ru?o.jsxs("section",{className:"doc-page",lang:Ln,dir:Ln==="ar"?"rtl":"ltr",children:[o.jsxs("section",{className:"doc-hero",children:[o.jsxs("div",{className:"doc-hero-copy",children:[o.jsxs("span",{className:"pricing-eyebrow",children:[o.jsx(Pp,{size:16}),Ha.eyebrow]}),o.jsx("h2",{children:Ha.title}),o.jsx("p",{children:Ha.intro})]}),o.jsxs("label",{className:"doc-language-picker",children:[o.jsxs("span",{children:[o.jsx(gk,{size:17}),Ha.languageLabel]}),o.jsx("select",{value:Ln,onChange:p=>vo(p.target.value),children:PI.map(p=>o.jsx("option",{value:p.id,children:p.label},p.id))})]})]}),o.jsx("section",{className:"doc-grid",children:Ha.sections.map((p,S)=>{const R=[mo,Wg,bb,Na,wd][S]||Pp;return o.jsxs("article",{className:"doc-card",children:[o.jsx("div",{className:"doc-card-icon",children:o.jsx(R,{size:19})}),o.jsxs("div",{children:[o.jsx("h3",{children:p.title}),o.jsx("p",{children:p.body}),o.jsx("ul",{children:p.points.map(j=>o.jsx("li",{children:j},j))})]})]},p.title)})}),qc&&o.jsxs("section",{className:"doc-sync",children:[o.jsxs("div",{className:"doc-sync-head",children:[o.jsx(bb,{size:20}),o.jsxs("div",{children:[o.jsx("h3",{children:qc.title}),o.jsx("p",{children:qc.body})]})]}),o.jsx("ul",{children:qc.points.map(p=>o.jsx("li",{children:p},p))})]}),o.jsxs("section",{className:"doc-firewall",children:[o.jsxs("div",{className:"doc-firewall-head",children:[o.jsx(Na,{size:20}),o.jsxs("div",{children:[o.jsx("h3",{children:Ha.firewall.title}),o.jsx("p",{children:Ha.firewall.body})]})]}),o.jsx("ul",{children:Ha.firewall.points.map(p=>o.jsx("li",{children:p},p))})]}),o.jsxs("section",{className:"doc-command-panel",children:[o.jsxs("div",{className:"doc-command-head",children:[o.jsx(Wg,{size:20}),o.jsxs("div",{children:[o.jsx("h3",{children:Ha.commands.title}),o.jsx("p",{children:Ha.commands.body})]})]}),o.jsxs("div",{className:"doc-command-list",children:[Ha.commands.manager&&o.jsxs("div",{className:"doc-command-row",children:[o.jsx("span",{children:Ha.commands.manager}),o.jsx("code",{children:Bc}),o.jsx("button",{className:"icon-button",onClick:()=>Rp(Bc),title:"Copy command",type:"button",children:o.jsx(ng,{size:16})})]}),o.jsxs("div",{className:"doc-command-row",children:[o.jsx("span",{children:Ha.commands.primary}),o.jsx("code",{children:Hc}),o.jsx("button",{className:"icon-button",onClick:()=>Rp(Hc),title:"Copy command",type:"button",children:o.jsx(ng,{size:16})})]}),o.jsxs("div",{className:"doc-command-row",children:[o.jsx("span",{children:Ha.commands.slot}),o.jsx("code",{children:`${Hc} 3`}),o.jsx("button",{className:"icon-button",onClick:()=>Rp(`${Hc} 3`),title:"Copy command",type:"button",children:o.jsx(ng,{size:16})})]})]})]})]}):zi?o.jsx(Xw,{hubUrl:T,devices:N}):_a?o.jsx(Yj,{hubUrl:T,devices:ut,localFeatureAccess:an,upgradeNotice:fi,remoteDirectory:Xs,onRemoteDirectoryChange:sl,targetMode:No,selectedTargetIds:Ia,onTargetModeChange:Dd,onTargetToggle:p=>gl(S=>S.includes(p)?S.filter(C=>C!==p):[...S,p]),filePickerRef:To,folderPickerRef:um,onBrowserFileImport:p=>{cf(p)},onBrowserFolderImport:p=>{cf(p)},onNotice:Fe,onTransferChange:p=>{if(!p){oi(null);return}const S=p.state==="failed"||p.state==="partially-failed"||p.state==="cancelled"?"failed":p.state==="completed"?"queued":p.state==="sending"?"sending":"reading";oi({id:p.id,status:S,progress:p.progress,message:p.message}),["completed","partially-failed","failed","cancelled"].includes(p.state)&&window.setTimeout(()=>oi(C=>C?.id===p.id?null:C),4500)}}):_d?o.jsx(Ux,{session:n,currentProductKey:"livedesk",appVersion:"",onSignIn:vi}):vl?o.jsx(pN,{hubUrl:T,runtimeRole:k?.runtimeRole||"hub",runtimeDeviceId:k?.deviceId||"",sessionAccessToken:n?.access_token||"",pin:o.jsxs(hN,{children:[o.jsx("div",{className:"settings-section-grid",children:o.jsxs("section",{className:"settings-section-card settings-pairing-card",children:[o.jsxs("div",{className:"settings-section-heading",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Pair a Client"}),o.jsx("h3",{children:"Connect another local PC"})]}),o.jsx(Ta,{size:20})]}),o.jsxs("div",{className:"settings-pin-display",children:[o.jsx("span",{children:"Hub PIN"}),o.jsx("strong",{children:Yn}),o.jsxs("button",{className:"text-button ghost compact",onClick:Sm,disabled:!k?.started||z==="pin",type:"button",children:[o.jsx(Ci,{size:15}),z==="pin"?"Creating":"New PIN"]})]})]})}),o.jsxs("section",{className:"settings-section-card",children:[o.jsxs("div",{className:"settings-section-heading",children:[o.jsxs("div",{children:[o.jsx("span",{children:"File transfer"}),o.jsx("h3",{children:"Client destination folder"})]}),o.jsx(pd,{size:20})]}),o.jsxs("label",{className:"settings-field",children:[o.jsx("span",{children:"Remote folder"}),o.jsx("input",{value:Xs,onChange:p=>sl(p.target.value),placeholder:"Desktop/LiveDeskFiles"})]}),o.jsx("p",{className:"settings-help",children:"Blank uses Desktop/LiveDeskFiles on each Client."})]})]}),agent:o.jsx(vN,{hubUrl:T}),captureGallery:o.jsx(ZE,{hubUrl:T,onToast:Fe}),advertisementsHidden:et,onAdvertisementsHiddenChange:An}):Ld?o.jsxs("section",{className:"pricing-page",children:[o.jsxs("header",{className:"pricing-header",children:[o.jsxs("div",{children:[o.jsxs("span",{className:"pricing-eyebrow",children:[o.jsx(Ug,{size:15})," LiveDesk plans"]}),o.jsx("h2",{children:"Choose the plan that fits your wall"}),o.jsx("p",{children:"Start free with a local screen wall. Upgrade when you need ad-free monitoring, more Clients, or commercial controls."})]}),o.jsx("button",{className:"pricing-close",onClick:()=>Vc("wall"),title:"Close pricing",type:"button",children:o.jsx(hr,{size:18})})]}),o.jsxs("div",{className:"pricing-status","aria-live":"polite",children:[o.jsx("span",{children:"Current plan"}),o.jsx("strong",{children:hm.name}),o.jsxs("small",{children:[ut.length,"/",YD(ju)," connected devices"]})]}),o.jsxs("div",{className:"pricing-cards","aria-label":"LiveDesk plans",children:[o.jsxs("article",{className:`pricing-plan-card ${Cn==="free"?"current":""}`,children:[o.jsxs("div",{className:"pricing-plan-topline",children:[o.jsx("span",{className:"pricing-plan-badge free",children:"Free"}),o.jsx("strong",{children:"$0"})]}),o.jsx("p",{className:"pricing-plan-audience",children:Jc.free.audience}),o.jsx("h3",{children:"Monitor your local wall"}),o.jsx("p",{children:Jc.free.note}),o.jsxs("ul",{children:[o.jsxs("li",{children:[o.jsx(Ba,{size:16})," Up to ",Bf," devices"]}),o.jsxs("li",{children:[o.jsx(Ba,{size:16})," Live view and local control"]}),o.jsxs("li",{children:[o.jsx(Ba,{size:16})," Optional banner, controlled in Settings"]})]}),o.jsx("span",{className:"pricing-current-label",children:Cn==="free"?"Current plan":"Included for everyone"})]}),o.jsxs("article",{className:`pricing-plan-card featured ${Cn==="ltd"?"current":""}`,children:[o.jsxs("div",{className:"pricing-plan-topline",children:[o.jsxs("span",{className:"pricing-plan-badge plus",children:[o.jsx(vk,{size:14})," Plus"]}),o.jsx("strong",{children:"$5"})]}),o.jsx("p",{className:"pricing-plan-audience",children:Jc.ltd.audience}),o.jsx("h3",{children:"Ad-free monitoring"}),o.jsx("p",{children:"More room for personal computers without the standard banner."}),o.jsxs("ul",{children:[o.jsxs("li",{children:[o.jsx(Ba,{size:16})," Up to ",zf," devices"]}),o.jsxs("li",{children:[o.jsx(Ba,{size:16})," No standard ad banner"]}),o.jsxs("li",{children:[o.jsx(Ba,{size:16})," ",Jc.ltd.ltd]})]}),o.jsxs("button",{className:"pricing-plan-button",onClick:n?()=>qo("ltd"):vi,disabled:Cn!=="free"||z==="checkout"||z==="auth"||r||F,type:"button",children:[o.jsx(Wf,{size:16}),Cn==="free"?n?"Choose Plus":"Sign in for Plus":"Plus active"]})]}),o.jsxs("article",{className:`pricing-plan-card pro ${Cn==="pro"?"current":""}`,children:[o.jsxs("div",{className:"pricing-plan-topline",children:[o.jsxs("span",{className:"pricing-plan-badge pro",children:[o.jsx(Na,{size:14})," Pro"]}),o.jsx("strong",{children:"$15"})]}),o.jsx("p",{className:"pricing-plan-audience",children:Jc.pro.audience}),o.jsx("h3",{children:"For serious operations"}),o.jsx("p",{children:"Commercial-ready monitoring for larger studios, offices, and teams."}),o.jsxs("ul",{children:[o.jsxs("li",{children:[o.jsx(Ba,{size:16})," 30+ Client walls"]}),o.jsxs("li",{children:[o.jsx(Ba,{size:16})," Commercial use included"]}),o.jsxs("li",{children:[o.jsx(Ba,{size:16})," ",Jc.pro.ltd]})]}),o.jsxs("button",{className:"pricing-plan-button",onClick:n?()=>qo("pro"):vi,disabled:Cn==="pro"||z==="checkout"||z==="auth"||r||F,type:"button",children:[o.jsx(Wf,{size:16}),Cn==="pro"?"Pro active":n?"Choose Pro":"Sign in for Pro"]})]})]}),o.jsxs("section",{className:"pricing-includes",children:[o.jsxs("div",{children:[o.jsx(Ta,{size:17}),o.jsx("span",{children:"Screen wall"}),o.jsx("strong",{children:"120+ slots"})]}),o.jsxs("div",{children:[o.jsx(qg,{size:17}),o.jsx("span",{children:"Focused control"}),o.jsx("strong",{children:"Local-first"})]}),o.jsxs("div",{children:[o.jsx(wb,{size:17}),o.jsx("span",{children:"Remote audio"}),o.jsx("strong",{children:"Available"})]}),o.jsxs("div",{children:[o.jsx(pd,{size:17}),o.jsx("span",{children:"File transfer"}),o.jsx("strong",{children:"Included"})]})]}),o.jsxs("p",{className:"pricing-note",children:[o.jsx(Ba,{size:15})," Commercial use requires Pro. Plus LTD is for personal, creator, and homelab use."]}),o.jsxs("button",{className:"pricing-primary-cta",onClick:n?()=>qo(Cn==="ltd"?"pro":"ltd"):vi,disabled:pf,type:"button",children:[o.jsx(Wf,{size:18}),Tm]})]}):o.jsx(o.Fragment,{children:o.jsxs("section",{className:`monitor-layout ${Zr?"dock-collapsed":""}`,children:[o.jsxs("section",{ref:vc,className:`screen-wall-panel ${mh?"drop-active":""}`,onClick:p=>{p.currentTarget===p.target&&El()},onDragEnter:p=>{p.preventDefault(),Ed(!0)},onDragOver:p=>{p.preventDefault(),p.dataTransfer.dropEffect="copy"},onDragLeave:p=>{p.currentTarget===p.target&&Ed(!1)},onDrop:Mm,children:[Sa.length>0&&o.jsx("canvas",{ref:Du,className:"atlas-source-canvas",width:eo?.width||1920,height:eo?.height||1080,"aria-hidden":"true"}),wt?o.jsx("section",{className:"control-focus",children:o.jsxs("div",{className:"control-wall",children:[Be&&df.length>1&&o.jsx("div",{className:"control-monitor-tabs","aria-label":"Select monitor",children:df.map(p=>o.jsxs("button",{className:p.index===Dl?"active":"",onClick:()=>Cm(Be.deviceId,p.index),title:fI(p),type:"button",children:[o.jsx("span",{children:p.name||`Display ${p.index+1}`}),p.width>0&&p.height>0&&o.jsxs("small",{children:[p.width,"x",p.height]})]},p.index))}),Be&&Hs&&o.jsx("div",{className:"control-modifier-bar","aria-label":"Hold remote modifier keys",children:DD.map(p=>{const S=p.code==="MetaLeft"&&nl(Be.platform)?"Cmd":p.label,C=vt.includes(p.code);return o.jsx("button",{className:C?"active":"",type:"button","aria-pressed":C,title:`Hold ${S} on the remote computer`,onClick:()=>he.current?.(p.code),children:S},p.code)})}),Be?o.jsx(Rx,{device:Be,frame:We,selected:!1,controlEnabled:sr&&$e&&Hs,showStatus:qn.showScreenStatus,monitorIndex:Ws(Be,rn[Be.deviceId]),monitorCount:ru(Be),onSelect:()=>{},onFocusDevice:()=>ce(Be.deviceId),onOpenControl:()=>Oc(Be.deviceId),onCycleMonitor:p=>Fc(Be.deviceId,p),onCanvasReady:$r,sendInput:Dc,remoteModifierState:Yd,presentationReady:Nd,remoteDiagnostics:In?$c.get(Be.deviceId):jn?Go.get(Be.deviceId):void 0,diagnosticsMode:In?"debug":"remote"},Be.deviceId):o.jsxs("div",{className:"control-empty",children:[o.jsx(Ta,{size:30}),o.jsx("strong",{children:"No Client"}),o.jsx("span",{children:"Open a Client from the Wall."})]}),Be&&Do&&o.jsxs("div",{className:"control-connection-overlay",role:"alert",children:[o.jsx(Na,{size:22,"aria-hidden":"true"}),o.jsx("strong",{children:"Accessibility permission required"}),o.jsx("small",{children:"On the Mac, allow Accessibility for the terminal app that starts LiveDesk, then restart the Mac client."})]}),Be&&!Do&&!Nd&&o.jsxs("div",{className:"control-connection-overlay",role:"status","aria-live":"polite",children:[H!=="error"&&o.jsx("span",{className:"control-connection-spinner","aria-hidden":"true"}),o.jsx("strong",{children:H==="error"?"Connection failed":"Connecting"}),o.jsx("small",{children:H==="error"?"See the notification for details. Reopen Control to retry.":kn||Ve?"Control stream is recovering. See the notification for details.":ys==="open"?"Preparing the first control frame":"Opening the Control stream"})]})]})}):Sn==="list"?o.jsxs("div",{className:"wall-device-list",role:"grid","aria-label":"Computer status list",children:[o.jsxs("div",{className:"wall-device-list-head",role:"row",children:[o.jsx("span",{role:"columnheader",children:"Computer"}),o.jsx("span",{role:"columnheader",children:"Status"}),o.jsx("span",{role:"columnheader",children:"CPU"}),o.jsx("span",{role:"columnheader",children:"GPU"}),o.jsx("span",{role:"columnheader",children:"RAM"}),o.jsx("span",{role:"columnheader",children:"VRAM"}),o.jsx("span",{role:"columnheader",children:"Network"}),o.jsx("span",{role:"columnheader",children:"HDD"}),o.jsx("span",{role:"columnheader",children:"Temp"})]}),Ps.length>0?Ps.map(p=>p.device?o.jsx(zI,{device:p.device,slotNumber:p.slotNumber,selected:Hr.has(p.device.deviceId),updateIndicator:gf(p.device.deviceId),remoteDiagnostics:In?$c.get(p.device.deviceId):jn?Go.get(p.device.deviceId):void 0,diagnosticsMode:In?"debug":"remote",onSelect:()=>nf(p.device.deviceId),onOpenControl:()=>Oc(p.device.deviceId)},p.device.deviceId):p.saved?o.jsx(BI,{entry:p.saved,slotNumber:p.slotNumber},`offline-${p.saved.deviceId}`):null):o.jsxs("div",{className:"wall-device-list-empty",children:[o.jsx(Ta,{size:24,"aria-hidden":"true"}),o.jsx("strong",{children:"No connected computers"})]})]}):Dt?o.jsx("div",{className:`screen-wall atlas-slot-wall size-${Sn}`,onClick:p=>{p.currentTarget===p.target&&El()},children:Or.map((p,S)=>vf(p,S,!0))}):o.jsx("div",{className:`screen-wall size-${Sn}`,onClick:p=>{p.currentTarget===p.target&&El()},children:Or.map((p,S)=>vf(p,S,!1))}),o.jsx(qI,{visible:vm&&!wt})]}),!vl&&o.jsxs("aside",{className:`right-dock actions-mode ${Zr?"collapsed":""}`,"aria-label":"LiveDesk tools",children:[o.jsx("button",{className:"dock-toggle",onClick:()=>Ti(p=>!p),"aria-label":Zr?"Show control panel":"Hide control panel",title:Zr?"Show control panel":"Hide control panel",type:"button",children:Zr?o.jsx(zx,{size:18}):o.jsx(Av,{size:18})}),!Zr&&o.jsxs(o.Fragment,{children:[o.jsxs("section",{className:"action-dock",children:[o.jsx("input",{ref:Nu,className:"hidden-file-input",type:"file",multiple:!0,onChange:p=>{p.currentTarget.files&&lf(p.currentTarget.files),p.currentTarget.value=""}}),o.jsxs("div",{className:"manual-action-bar",role:"toolbar","aria-label":"Manual Client controls",children:[o.jsx(Zc,{label:"Control",tooltip:Be?Do?"Allow Accessibility for the terminal app that starts LiveDesk, then restart the Mac client.":sr?Ou?"Keyboard and mouse control is ready":Hs?"Remote input is reconnecting; ordered clicks and keys are buffered briefly":"Waiting for the current Control capture session":"Remote control is not available on this Client":"Select a Client to use Control",onClick:()=>{if(Be){if(wt&&$e){qe(!1),Fe("Remote control paused. Screen viewing stays on.");return}Oc(Be.deviceId)}},disabled:!sr||!!Te,active:$e,pressed:wt&&$e,children:o.jsx(qg,{size:17})}),o.jsx(Zc,{label:"Audio",tooltip:Be?Va?pe?"Stop hearing this Client":"Hear this Client":"Audio is not available on this Client":"Select a Client to use Audio",onClick:()=>{km()},disabled:!Eu||!!Te,active:pe,pressed:pe,children:Te==="audio"?o.jsx(Si,{className:"spin",size:17}):o.jsx(wb,{size:17})}),o.jsx(Zc,{label:bc?"Retry pause":cs?"Pause video":"Resume video",tooltip:Gi.length===0?"Select one or more Clients to pause video":bc?"Retry every selected Client whose capture shutdown is unconfirmed":cs?`Pause video for ${Fa.length} selected Client${Fa.length===1?"":"s"}`:`Resume video for ${Fa.length} selected Client${Fa.length===1?"":"s"}`,onClick:()=>{sf()},disabled:Fa.length===0||!!Te,active:!cs,pressed:!cs,children:Te==="video"?o.jsx(Si,{className:"spin",size:17}):!cs&&!bc?o.jsx(yk,{size:17}):o.jsx(bk,{size:17})}),o.jsx(Zc,{label:"Send files",tooltip:tn.length===0&&!wt?"Select one or more Clients to send files":Be?"Choose files and send them to the selected Client":"Select a Client to send files",onClick:()=>{Fe(`Choose files to send to ${Uc}.`),Nu.current?.click()},disabled:!!Te||!an||(wt?!Be:tn.length===0),children:o.jsx(pd,{size:17})}),o.jsx(Zc,{label:"Restart",tooltip:Be?ls?"Restart Client":"Restart is not available on this Client":"Select a Client to restart",onClick:()=>{na("restart")},disabled:!Be||!an||!!Te||!ls,children:Te==="restart"?o.jsx(Si,{className:"spin",size:17}):o.jsx($g,{size:17})}),o.jsx(Zc,{label:"Sleep",tooltip:Be?ls?"Put Client to sleep":"Sleep is not available on this Client":"Select a Client to put to sleep",onClick:()=>{na("sleep")},disabled:!Be||!an||!!Te||!ls,children:Te==="sleep"?o.jsx(Si,{className:"spin",size:17}):o.jsx(wk,{size:17})}),o.jsx(Zc,{label:"Shut down",tooltip:Be?ls?"Shut down Client":"Shut down is not available on this Client":"Select a Client to shut down",onClick:()=>{na("shutdown")},disabled:!Be||!an||!!Te||!ls,danger:!0,children:Te==="shutdown"?o.jsx(Si,{className:"spin",size:17}):o.jsx(_x,{size:17})})]})]}),o.jsx(Xw,{hubUrl:T,devices:N,variant:"dock",selectedDeviceIds:io})]})]})]})})]}),Hi&&o.jsxs("aside",{className:`transfer-bar state-${Hi.status}`,"aria-live":"polite",children:[o.jsx("span",{className:"transfer-bar-icon","aria-hidden":"true",children:Hi.status==="queued"?o.jsx(Ba,{size:18}):Hi.status==="failed"?o.jsx(hr,{size:18}):o.jsx(Px,{size:18})}),o.jsxs("div",{className:"transfer-bar-copy",children:[o.jsx("p",{children:Hi.message}),o.jsx("div",{className:"transfer-bar-track",children:o.jsx("span",{style:{width:`${Math.max(0,Math.min(100,Hi.progress))}%`}})})]}),o.jsxs("strong",{children:[Math.max(0,Math.min(100,Hi.progress)),"%"]})]}),sa&&o.jsxs("aside",{className:`livedesk-toast tone-${sa.tone}`,role:sa.tone==="error"?"alert":"status","aria-live":sa.tone==="error"?"assertive":"polite","aria-busy":sa.tone==="progress",children:[sa.tone==="progress"&&o.jsx("span",{className:"livedesk-toast-spinner","aria-hidden":"true"}),o.jsx("span",{children:sa.message}),o.jsx("button",{className:"livedesk-toast-close",onClick:()=>Fe(""),type:"button","aria-label":"Dismiss notification",title:"Dismiss notification",children:o.jsx(hr,{size:15})})]})]})}const GI=1e3,VI=5e3;function KI(){return typeof window>"u"?[]:[...new Set([window.location.origin,Dn].filter(Boolean))]}function QI(){const[r,i]=d.useState(null),l=d.useRef(null);return d.useEffect(()=>{let u=!1,f=!1,h=null;const g=new AbortController,y=async()=>{for(const x of KI()){if(g.signal.aborted)return;try{const k=(await tt("/api/runtime",{signal:g.signal,timeoutMs:900},x)).role==="hub"?"hub":"client";f=!0,u||i(N=>N?.role===k&&N.baseUrl===x?N:{role:k,baseUrl:x});return}catch{if(g.signal.aborted)return}}},w=()=>{Op(l,y).finally(()=>{!u&&!g.signal.aborted&&(h=window.setTimeout(w,f?VI:GI))}).catch(()=>{})};w();const b=window.setTimeout(()=>{!u&&!f&&i(x=>x?.role==="client"&&x.baseUrl===Dn?x:{role:"client",baseUrl:Dn})},2500);return()=>{u=!0,g.abort(new Error("LiveDesk runtime role probe stopped.")),h!==null&&window.clearTimeout(h),window.clearTimeout(b)}},[null]),r?r.role==="client"?o.jsx(LM,{runtimeBaseUrl:r.baseUrl}):o.jsx(WI,{runtimeBaseUrl:r.baseUrl}):o.jsxs("main",{className:"runtime-role-boot","aria-busy":"true","aria-label":"Starting LiveDesk",children:[o.jsx("span",{className:"runtime-role-boot-mark","aria-hidden":"true"}),o.jsx("strong",{children:"Starting LiveDesk"}),o.jsx("p",{children:"Loading this computer's assigned role..."})]})}Tk.createRoot(document.getElementById("root")).render(o.jsx(d.StrictMode,{children:o.jsx(QI,{})}));