livedesk 0.1.591 → 0.1.592

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,13 +1,13 @@
1
- import{j as r,M as ib,w as ob,D as an,r as Qa,g as Ul,i as eu,h as Oe,c as fu,a as gu,n as cb,b as Dy,d as Ly,e as Vl,f as lb,k as ub,l as _y,m as Eh,p as ks,P as $o,F as yl}from"./index-BPgqiKB-.js";import{a as o,m as Yo,k as Zt,n as Ya,B as $y,P as tp,X as xn,o as nc,l as Ns,F as Fh,p as As,q as db,s as Oy,t as Dh,u as Lh,v as By,D as rc,b as En,w as Hy,x as pb,y as Wy,z as zy,g as os,c as pn,H as tu,I as Xo,J as nu,K as Gs,O as mb,Q as qy,U as hb,V as _h,Y as Uy,Z as Vy,_ as qa,W as bu,$ as Gy,a0 as Ky,a1 as Xi,a2 as Ji,a3 as Qy,a4 as np,S as Xs,a5 as fb,a6 as gb,a7 as Yy,a8 as Xy,a9 as Jy,aa as Fp,ab as Zy,N as Dp,ac as bb,ad as ex,ae as Zn,af as $h,C as Lp,ag as vu,ah as sc,ai as Jo,aj as vb,ak as tx,al as wb,am as nx,an as yb,ao as rx,ap as rp,aq as sx,ar as sp,as as xb,at as ax,au as ix,av as ox,aw as cx,ax as Sb,ay as lx,az as Oh,aA as ux,aB as dx,aC as px,aD as Cb,f as Uo,T as Gl,A as mx,E as hx,aE as Bh,aF as wd,aG as fx,aH as yd,aI as Hh,aJ as Wh,aK as gx,aL as kb,aM as bx,G as vx}from"./icons-CebEqIp7.js";import{c as wx}from"./supabase-C0Z0FS3K.js";import{r as yx}from"./react-BHQWCi9c.js";const xx="https://otbyfkjxrkngvjziawki.supabase.co",Sx="sb_publishable_NpUs0RDJH2YnllsqTKO6TQ_1jTdSsNQ",Cx={getItem:()=>null,setItem:()=>{},removeItem:()=>{}},xd=typeof window<"u"&&!!window.liveDesk,pt=wx(xx,Sx,{auth:{autoRefreshToken:!xd,persistSession:!xd,storage:xd?Cx:void 0,detectSessionInUrl:!0,flowType:"pkce",storageKey:"livedesk.mindexec.supabase.auth"}}),kx=new Set(["browserLanguage","platform","online","viewport","timezone","screen"]),Mx={id:"browser-safe-v1",collect(){if(typeof navigator>"u")return{};const e={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(e).filter(([t,n])=>kx.has(t)&&n!==void 0))}};function Ax(e,t="Support request failed."){if(e&&typeof e=="object"&&"message"in e){const n=String(e.message||"").trim();if(n)return n.replace(/^.*Support request failed:\s*/i,"")}return e instanceof Error?e.message:t}function Nx(e=Mx){return e.collect()}async function Rx(e,t="livedesk"){const{data:n,error:s}=await pt.from("app_admins").select("role").eq("user_id",e).limit(1);if(s)throw s;const a=n?.[0]?.role||"user";if(a!=="owner"){const{error:w}=await pt.rpc("register_product_access",{p_product_key:t,p_access_type:"free"});if(w)throw w}const[i,c,u]=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",e),pt.from("user_products").select("product_id").eq("user_id",e).eq("is_active",!0)]);if(i.error)throw i.error;if(c.error)throw c.error;if(u.error)throw u.error;const d=i.data||[],p=(c.data||[]).map(w=>String(w.product_id)),h=(u.data||[]).map(w=>String(w.product_id)),m=a==="owner",g=m?d.map(w=>w.id):[...new Set([...p,...h])];return{products:d,access:{userId:e,globalRole:a,accessibleProductIds:g,managedProductIds:m?d.map(w=>w.id):p,canViewAllProducts:m,canViewAllPrivatePosts:m,canManageAllProducts:m,canCreateAnnouncements:m||p.length>0}}}async function Tx(e=""){const{data:t,error:n}=await pt.rpc("search_support_posts",{p_query:e.trim()||null,p_limit:250});if(n)throw n;return t||[]}async function Px(e){const{data:t,error:n}=await pt.from("support_attachments").select("*").eq("post_id",e).order("created_at");if(n)throw n;const s=t||[];return Promise.all(s.map(async a=>{const i=await pt.storage.from("support-attachments").createSignedUrl(a.storage_path,3600);return{...a,signed_url:i.data?.signedUrl||void 0}}))}async function Ix(){const{data:e,error:t}=await pt.from("support_notifications").select("*").order("created_at",{ascending:!1}).limit(30);if(t)throw t;return e||[]}async function jx(e){const{error:t}=await pt.rpc("mark_support_notification_read",{p_notification_id:e});if(t)throw t}async function zh(e){const{data:t,error:n}=await pt.from("support_comments").select("*").eq("post_id",e).order("created_at");if(n)throw n;return t||[]}async function Ex(e){const{data:t,error:n}=await pt.from("support_votes").select("post_id").eq("user_id",e);if(n)throw n;return new Set((t||[]).map(s=>String(s.post_id)))}async function Fx(e){const{data:t,error:n}=await pt.rpc("create_support_post",{p_product_id:e.productId,p_post_type:e.postType,p_title:e.title,p_body:e.body,p_visibility:e.visibility,p_app_version:e.appVersion||null,p_platform:typeof navigator>"u"?null:navigator.platform||null,p_os_version:typeof navigator>"u"?null:navigator.platform||null,p_environment:e.includeEnvironment?Nx():{}});if(n)throw n;const s=Array.isArray(t)?t[0]?.post_id:t?.post_id;if(!s)throw new Error("Support post was not created.");return String(s)}const Dx=new Set(["image/png","image/jpeg","image/webp","text/plain","text/markdown","application/json","application/pdf"]);async function Lx(e,t){if(!Dx.has(t.type))throw new Error("This file type is not allowed.");if(t.size<=0||t.size>10*1024*1024)throw new Error("Attachments must be smaller than 10 MB.");const n=t.name.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"attachment",s=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`,a=`${e}/${s}-${n}`,i=await pt.storage.from("support-attachments").upload(a,t,{contentType:t.type,upsert:!1});if(i.error)throw i.error;const{data:c,error:u}=await pt.rpc("add_support_attachment",{p_post_id:e,p_storage_path:a,p_file_name:n,p_mime_type:t.type,p_size_bytes:t.size});if(u)throw await pt.storage.from("support-attachments").remove([a]),u;const d=Array.isArray(c)?c[0]?.attachment_id:c?.attachment_id;if(!d)throw new Error("Attachment metadata was not created.");return String(d)}async function _x(e,t,n,s){const{error:a}=await pt.rpc("update_support_post",{p_post_id:e,p_title:t,p_body:n,p_visibility:s});if(a)throw a}async function $x(e,t){const{error:n}=await pt.rpc("add_support_comment",{p_post_id:e,p_body:t});if(n)throw n}async function Ox(e){const{data:t,error:n}=await pt.rpc("toggle_support_vote",{p_post_id:e});if(n)throw n;const s=Array.isArray(t)?t[0]:t;return{voted:!!s?.voted,totalVotes:Number(s?.total_votes||0)}}async function Bx(e,t){const{error:n}=await pt.rpc("change_support_post_status",{p_post_id:e,p_target_status:t});if(n)throw n}async function Hx(e){const{error:t}=await pt.rpc("set_support_post_hidden",{p_post_id:e,p_hidden:!0});if(t)throw t}async function Wx(e,t){const{error:n}=await pt.rpc("set_support_post_locked",{p_post_id:e,p_locked:t});if(n)throw n}async function zx(e,t){const{error:n}=await pt.rpc("set_support_post_pinned",{p_post_id:e,p_pinned:t});if(n)throw n}async function qx(e,t){const{error:n}=await pt.rpc("mark_support_duplicate",{p_post_id:e,p_duplicate_of_post_id:t});if(n)throw n}async function Ux(e,t){const{error:n}=await pt.rpc("accept_support_answer",{p_post_id:e,p_comment_id:t});if(n)throw n}async function Vx(e,t=!0){const{error:n}=await pt.rpc("hide_support_comment",{p_comment_id:e,p_hidden:t});if(n)throw n}const ap=[{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"}],Gx=[{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"}],Kx={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"]},Qx={type:"all",product:"",status:"all",visibility:"all",sort:"recent",query:""};function Sd(){if(typeof window>"u")return Qx;const e=new URLSearchParams(window.location.search),t=window.location.pathname.match(/^\/support\/(questions|issues|features|announcements)$/)?.[1],n=e.get("type")||t||"",s=n==="questions"||n==="question"?"question":n==="issues"||n==="issue"?"issue":n==="features"||n==="feature"?"feature":n==="announcements"||n==="announcement"?"announcement":"all",a=e.get("visibility"),i=e.get("sort");return{type:s,product:e.get("product")||"",status:e.get("status")||"all",visibility:a==="public"||a==="private"?a:"all",sort:i==="votes"||i==="newest"?i:"recent",query:e.get("q")||""}}function Yx(e){return e==="all"?"":e==="question"?"questions":e==="issue"?"issues":e==="feature"?"features":"announcements"}function Xx(e,t){const n={...e,...t},s=new URLSearchParams;n.product&&s.set("product",n.product),n.status!=="all"&&s.set("status",n.status),n.visibility!=="all"&&s.set("visibility",n.visibility),n.sort!=="recent"&&s.set("sort",n.sort),n.query&&s.set("q",n.query);const a=Yx(n.type),i=s.toString();return`/support${a?`/${a}`:""}${i?`?${i}`:""}`}function xl(e){const t=new Date(e);return Number.isFinite(t.getTime())?t.toLocaleString(void 0,{dateStyle:"medium",timeStyle:"short"}):e}function Cd(e){return e.replaceAll("-"," ").replace(/\b\w/g,t=>t.toUpperCase())}function qh(e){return e==="question"?Hy:e==="issue"?pb:e==="feature"?Wy:zy}function Uh(e){return ap.find(t=>t.id===e)?.shortLabel||e}function Xn(e){const t=Ax(e);return/relation .* does not exist|function .* does not exist|schema cache/i.test(t)?"Support Board database is not installed yet. Apply the latest Supabase migration first.":/not-authenticated|jwt/i.test(t)?"Sign in again to use Support.":/product-access-denied|product-not-found/i.test(t)?"You do not have access to this product.":t}function Mb({session:e,currentProductKey:t="livedesk",appVersion:n="",onSignIn:s}){const[a,i]=o.useState(()=>Sd()),[c,u]=o.useState(null),[d,p]=o.useState([]),[h,m]=o.useState([]),[g,w]=o.useState(""),[v,y]=o.useState([]),[k,N]=o.useState([]),[C,A]=o.useState([]),[E,I]=o.useState(()=>new Set),[F,M]=o.useState(!0),[H,V]=o.useState(""),[P,D]=o.useState(""),[O,X]=o.useState(!1),[G,U]=o.useState(!1),[ie,j]=o.useState(""),[re,de]=o.useState(()=>Sd().query),[Q,ge]=o.useState(!1),[oe,me]=o.useState(!1),[Ae,Te]=o.useState(""),[Pe,Se]=o.useState(""),[te,Ce]=o.useState("free"),[Fe,Le]=o.useState(""),[Ue,ne]=o.useState(""),[ae,le]=o.useState("admin"),[ce,J]=o.useState(""),[ye,ue]=o.useState(""),[Ee,nt]=o.useState([]),[T,ve]=o.useState({productId:"",postType:"question",title:"",body:"",visibility:"public",includeEnvironment:!0,files:[]}),De=o.useCallback(_=>{const je={...a,..._};i(je),typeof window<"u"&&window.history.pushState({},"",Xx(a,_))},[a]);o.useEffect(()=>{const _=()=>i(Sd());return window.addEventListener("popstate",_),()=>window.removeEventListener("popstate",_)},[]);const qe=o.useCallback(async()=>{const _=await Tx(a.query);return m(_),e?.user.id&&I(await Ex(e.user.id)),_},[a.query,e?.user.id]),_e=o.useCallback(async()=>{if(!e?.user.id){u(null),p([]),m([]),w(""),A([]),M(!1);return}M(!0),D("");try{const _=await Rx(e.user.id,t);u(_.access),p(_.products),await qe(),A(await Ix())}catch(_){D(Xn(_))}finally{M(!1)}},[t,qe,e?.user.id]);o.useEffect(()=>{_e()},[_e]);const $e=o.useMemo(()=>{if(!c)return[];const _=d.find(je=>je.product_key===t);return _?c.canViewAllProducts||c.accessibleProductIds.includes(_.id)?[_]:[]:[]},[c,t,d]),mt=$e[0]?.id||"",ct=o.useMemo(()=>{const _=new Map(d.map(Qe=>[Qe.id,Qe.product_key]));return[...h.filter(Qe=>a.type!=="all"&&Qe.post_type!==a.type||!mt||Qe.product_id!==mt||a.status==="needs-response"&&!["open","needs-info"].includes(Qe.status)||a.status!=="all"&&a.status!=="needs-response"&&Qe.status!==a.status||a.visibility!=="all"&&Qe.visibility!==a.visibility?!1:_.has(Qe.product_id))].sort((Qe,Ye)=>a.sort==="votes"?Ye.vote_count-Qe.vote_count||Ye.updated_at.localeCompare(Qe.updated_at):a.sort==="newest"?Ye.created_at.localeCompare(Qe.created_at):Number(Ye.is_pinned)-Number(Qe.is_pinned)||Ye.updated_at.localeCompare(Qe.updated_at))},[h,d,a.sort,a.status,a.type,a.visibility,mt]),z=ct.find(_=>_.id===g)||ct[0]||null,pe=!!(z&&c&&(c.canViewAllProducts||c.managedProductIds.includes(z.product_id))),Y=!!(z&&e?.user.id===z.author_id)||pe;o.useEffect(()=>{if(!z){w(""),y([]),U(!1);return}z.id!==g&&w(z.id)},[z,g]),o.useEffect(()=>{let _=!0;return g?(zh(g).then(je=>{_&&y(je)}).catch(je=>{_&&D(Xn(je))}),Px(g).then(je=>{_&&N(je)}).catch(je=>{_&&D(Xn(je))}),()=>{_=!1}):(y([]),N([]),()=>{_=!1})},[g]),o.useEffect(()=>{!T.productId&&$e[0]&&ve(_=>({..._,productId:mt||$e[0].id}))},[$e,T.productId,mt]),o.useEffect(()=>{de(a.query)},[a.query]),o.useEffect(()=>{!Pe&&$e[0]&&Se($e[0].id),!Ue&&$e[0]&&ne($e[0].id)},[$e,Pe,Ue]);const K=_=>{z&&m(je=>je.map(Qe=>Qe.id===z.id?{...Qe,..._}:Qe))},ee=async _=>{if(_.preventDefault(),!(!e||!T.productId)){V("create"),D("");try{const je=await Fx({productId:T.productId,postType:T.postType,title:T.title,body:T.body,visibility:T.postType==="announcement"?"public":T.visibility,appVersion:n,includeEnvironment:T.postType==="issue"&&T.includeEnvironment});for(const Ye of Ee)await Lx(je,Ye);const Qe=await qe();X(!1),nt([]),ve(Ye=>({...Ye,title:"",body:"",files:[]})),w(je),Qe.some(Ye=>Ye.id===je)||await _e()}catch(je){D(Xn(je))}finally{V("")}}},R=async _=>{if(_.preventDefault(),!!z){V("edit"),D("");try{await _x(z.id,z.title,z.body,z.visibility),U(!1),await qe()}catch(je){D(Xn(je))}finally{V("")}}},se=async _=>{if(_.preventDefault(),!(!z||!ie.trim())){V("comment"),D("");try{await $x(z.id,ie),j(""),y(await zh(z.id)),await qe()}catch(je){D(Xn(je))}finally{V("")}}},Ie=async()=>{if(!(!z||z.post_type!=="feature")){V("vote"),D("");try{const _=await Ox(z.id);I(je=>{const Qe=new Set(je);return _.voted?Qe.add(z.id):Qe.delete(z.id),Qe}),K({vote_count:_.totalVotes})}catch(_){D(Xn(_))}finally{V("")}}},He=async _=>{if(z){V("status"),D("");try{await Bx(z.id,_),K({status:_}),await qe()}catch(je){D(Xn(je))}finally{V("")}}},Be=async()=>{if(!(!z||!window.confirm("Hide this Support post from the board?"))){V("hide"),D("");try{await Hx(z.id),w(""),await qe()}catch(_){D(Xn(_))}finally{V("")}}},xe=async()=>{if(z){V("lock"),D("");try{await Wx(z.id,!z.is_locked),K({is_locked:!z.is_locked}),await qe()}catch(_){D(Xn(_))}finally{V("")}}},Ge=async()=>{if(z){V("pin"),D("");try{await zx(z.id,!z.is_pinned),K({is_pinned:!z.is_pinned}),await qe()}catch(_){D(Xn(_))}finally{V("")}}},rt=async _=>{if(z){V(`accept-${_}`),D("");try{await Ux(z.id,_),K({accepted_comment_id:_,status:z.post_type==="question"?"answered":z.status}),await qe()}catch(je){D(Xn(je))}finally{V("")}}},Ke=async()=>{if(!(!z||!ce||ce===z.id)){V("duplicate"),D("");try{await qx(z.id,ce),w(""),J(""),await qe()}catch(_){D(Xn(_))}finally{V("")}}},gt=async _=>{if(!_.read_at)try{await jx(_.id),A(je=>je.map(Qe=>Qe.id===_.id?{...Qe,read_at:new Date().toISOString()}:Qe))}catch(je){D(Xn(je))}_.post_id&&w(_.post_id),ge(!1)};return e?F&&!c?r.jsxs("section",{className:"support-page support-loading",children:[r.jsx(Ya,{className:"support-spin",size:23})," Loading Support Board..."]}):r.jsxs("section",{className:"support-page",children:[r.jsx("header",{className:"support-page-header support-page-actions-only",children:r.jsxs("div",{className:"support-header-actions",children:[r.jsxs("div",{className:"support-notification-wrap",children:[r.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>ge(_=>!_),title:"Notifications",children:[r.jsx($y,{size:16})," ",C.filter(_=>!_.read_at).length>0&&r.jsx("b",{children:C.filter(_=>!_.read_at).length})]}),Q&&r.jsxs("div",{className:"support-notification-popover",children:[r.jsx("strong",{children:"Notifications"}),C.length===0?r.jsx("span",{className:"support-muted",children:"No notifications yet."}):C.map(_=>r.jsxs("button",{type:"button",className:_.read_at?"":"unread",onClick:()=>{gt(_)},children:[r.jsx("b",{children:_.title}),r.jsx("span",{children:_.body}),r.jsx("small",{children:xl(_.created_at)})]},_.id))]})]}),c?.canViewAllProducts&&r.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>me(_=>!_),children:[r.jsx(Zt,{size:16})," Admin"]}),r.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>{_e()},disabled:F,children:[r.jsx(Ya,{size:16,className:F?"support-spin":""})," Refresh"]}),r.jsxs("button",{className:"support-primary-button",type:"button",onClick:()=>X(!0),disabled:$e.length===0,children:[r.jsx(tp,{size:17})," New request"]})]})}),P&&r.jsxs("div",{className:"support-error",role:"alert",children:[r.jsx(xn,{size:17})," ",r.jsx("span",{children:P}),r.jsx("button",{type:"button",onClick:()=>D(""),"aria-label":"Dismiss error",children:r.jsx(xn,{size:15})})]}),O&&r.jsxs("form",{className:"support-composer",onSubmit:_=>{ee(_)},children:[r.jsxs("div",{className:"support-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"New Support request"}),r.jsx("strong",{children:"Describe one actionable problem or idea."})]}),r.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>X(!1),"aria-label":"Close composer",children:r.jsx(xn,{size:18})})]}),r.jsxs("div",{className:"support-form-grid",children:[r.jsxs("label",{children:[r.jsx("span",{children:"Type"}),r.jsx("select",{value:T.postType,onChange:_=>ve(je=>({...je,postType:_.target.value})),children:ap.filter(_=>_.id!=="announcement"||c?.canCreateAnnouncements).map(_=>r.jsx("option",{value:_.id,children:_.label},_.id))})]}),r.jsxs("label",{className:"support-form-wide",children:[r.jsx("span",{children:"Title"}),r.jsx("input",{required:!0,minLength:3,maxLength:180,value:T.title,onChange:_=>ve(je=>({...je,title:_.target.value})),placeholder:"A short, searchable summary"})]}),r.jsxs("label",{className:"support-form-wide",children:[r.jsx("span",{children:T.postType==="issue"?"What happened?":T.postType==="feature"?"Describe the desired behavior":T.postType==="announcement"?"Announcement":"Question"}),r.jsx("textarea",{required:!0,value:T.body,onChange:_=>ve(je=>({...je,body:_.target.value})),placeholder:"Include the context another person needs to respond.",rows:6})]}),r.jsxs("label",{children:[r.jsx("span",{children:"Visibility"}),r.jsxs("select",{value:T.visibility,disabled:T.postType==="announcement",onChange:_=>ve(je=>({...je,visibility:_.target.value})),children:[r.jsx("option",{value:"public",children:"Public"}),r.jsx("option",{value:"private",children:"Private"})]})]}),T.postType==="issue"&&r.jsxs("label",{className:"support-checkbox",children:[r.jsx("input",{type:"checkbox",checked:T.includeEnvironment,onChange:_=>ve(je=>({...je,includeEnvironment:_.target.checked}))}),r.jsx("span",{children:"Attach safe browser/runtime details"})]}),r.jsxs("label",{className:"support-form-wide",children:[r.jsx("span",{children:"Attachments"}),r.jsx("input",{type:"file",multiple:!0,accept:"image/png,image/jpeg,image/webp,text/plain,text/markdown,application/json,application/pdf",onChange:_=>nt(Array.from(_.target.files||[]).slice(0,5))}),r.jsx("small",{className:"support-muted",children:"Up to 5 files, 10 MB each. Images, text, JSON, Markdown, and PDF."})]})]}),r.jsxs("div",{className:"support-composer-footer",children:[r.jsx("span",{children:Ee.length>0?`${Ee.length} attachment${Ee.length===1?"":"s"} selected.`:"Private posts are visible only to you and LiveDesk Support."}),r.jsxs("button",{className:"support-primary-button",type:"submit",disabled:H==="create",children:[r.jsx(nc,{size:16})," ",H==="create"?"Submitting...":"Submit request"]})]})]}),r.jsxs("div",{className:"support-tabs",role:"tablist","aria-label":"Support post type",children:[r.jsx("button",{className:a.type==="all"?"active":"",type:"button",onClick:()=>De({type:"all"}),children:"All"}),ap.map(_=>{const je=qh(_.id);return r.jsxs("button",{className:a.type===_.id?"active":"",type:"button",onClick:()=>De({type:_.id}),children:[r.jsx(je,{size:15})," ",_.label]},_.id)})]}),oe&&c?.canViewAllProducts&&r.jsxs("section",{className:"support-admin-panel",children:[r.jsxs("div",{className:"support-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"LiveDesk owner controls"}),r.jsx("strong",{children:"Manage LiveDesk support access and staff roles by email."})]}),r.jsx(Zt,{size:19})]}),r.jsxs("div",{className:"support-admin-grid",children:[r.jsxs("form",{onSubmit:_=>{},children:[r.jsx("strong",{children:"Grant LiveDesk access"}),r.jsx("input",{type:"email",required:!0,placeholder:"User email",value:Ae,onChange:_=>Te(_.target.value)}),r.jsxs("select",{value:te,onChange:_=>Ce(_.target.value),children:[r.jsx("option",{value:"free",children:"Free"}),r.jsx("option",{value:"user",children:"User"}),r.jsx("option",{value:"paid",children:"Paid"}),r.jsx("option",{value:"beta",children:"Beta"}),r.jsx("option",{value:"staff",children:"Staff"})]}),r.jsxs("button",{className:"support-secondary-button",type:"submit",disabled:ye==="access",children:[r.jsx(Ns,{size:15})," Grant access"]})]}),r.jsxs("form",{onSubmit:_=>{},children:[r.jsx("strong",{children:"Assign LiveDesk staff"}),r.jsx("input",{type:"email",required:!0,placeholder:"Staff email",value:Fe,onChange:_=>Le(_.target.value)}),r.jsxs("select",{value:ae,onChange:_=>le(_.target.value),children:[r.jsx("option",{value:"admin",children:"Admin"}),r.jsx("option",{value:"support",children:"Support"}),r.jsx("option",{value:"moderator",children:"Moderator"})]}),r.jsxs("button",{className:"support-secondary-button",type:"submit",disabled:ye==="product-admin",children:[r.jsx(Zt,{size:15})," Assign staff"]})]})]})]}),r.jsxs("form",{className:"support-search-bar",onSubmit:_=>{_.preventDefault(),De({query:re.trim()})},children:[r.jsxs("label",{children:[r.jsx("span",{children:"Search Support"}),r.jsx("input",{value:re,onChange:_=>de(_.target.value),placeholder:"Search titles and request details"})]}),r.jsxs("button",{className:"support-secondary-button",type:"submit",children:[r.jsx(Fh,{size:15})," Search"]}),a.query&&r.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>{de(""),De({query:""})},"aria-label":"Clear search",children:r.jsx(xn,{size:16})})]}),r.jsxs("div",{className:"support-filter-bar",children:[r.jsxs("div",{className:"support-filter-title",children:[r.jsx(Fh,{size:16}),r.jsx("span",{children:"Filter"})]}),r.jsxs("label",{children:[r.jsx("span",{children:"Status"}),r.jsx("select",{value:a.status,onChange:_=>De({status:_.target.value}),children:Gx.map(_=>r.jsx("option",{value:_.id,children:_.label},_.id))})]}),r.jsxs("label",{children:[r.jsx("span",{children:"Visibility"}),r.jsxs("select",{value:a.visibility,onChange:_=>De({visibility:_.target.value}),children:[r.jsx("option",{value:"all",children:"All visibility"}),r.jsx("option",{value:"public",children:"Public"}),r.jsx("option",{value:"private",children:"Private"})]})]}),r.jsxs("label",{children:[r.jsx("span",{children:"Sort"}),r.jsxs("select",{value:a.sort,onChange:_=>De({sort:_.target.value}),children:[r.jsx("option",{value:"recent",children:"Recently updated"}),r.jsx("option",{value:"newest",children:"Newest"}),r.jsx("option",{value:"votes",children:"Most votes"})]})]})]}),c?.canViewAllProducts&&r.jsxs("div",{className:"support-admin-shortcuts",children:[r.jsxs("span",{children:[r.jsx(Zt,{size:15})," LiveDesk owner"]}),r.jsx("button",{type:"button",onClick:()=>De({status:"needs-response"}),children:"Needs response"}),r.jsx("button",{type:"button",onClick:()=>De({visibility:"private"}),children:"Private requests"}),r.jsx("button",{type:"button",onClick:()=>De({type:"feature",status:"all",sort:"votes"}),children:"High-vote features"})]}),r.jsxs("div",{className:"support-board-layout",children:[r.jsxs("section",{className:"support-post-list","aria-label":"Support posts",children:[r.jsxs("div",{className:"support-list-heading",children:[r.jsxs("span",{children:[ct.length," request",ct.length===1?"":"s"]}),r.jsx("small",{children:"LiveDesk"})]}),ct.length===0?r.jsxs("div",{className:"support-list-empty",children:[r.jsx(Yo,{size:25}),r.jsx("strong",{children:"No posts match these filters."}),r.jsx("span",{children:"Start with a focused question, issue report, or feature request."}),$e.length>0&&r.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>X(!0),children:[r.jsx(tp,{size:16})," Create the first request"]})]}):ct.map(_=>{const je=qh(_.post_type);return r.jsxs("button",{type:"button",className:`support-post-row ${_.id===z?.id?"active":""}`,onClick:()=>{w(_.id),U(!1)},children:[r.jsx("span",{className:"support-post-row-icon",children:r.jsx(je,{size:17})}),r.jsxs("span",{className:"support-post-row-copy",children:[r.jsxs("span",{className:"support-post-row-meta",children:[r.jsx("em",{children:Uh(_.post_type)}),_.visibility==="private"&&r.jsx(As,{size:13})]}),r.jsx("strong",{children:_.title}),r.jsxs("small",{children:[Cd(_.status)," · ",xl(_.updated_at)," · ",_.comment_count," comments"]})]}),_.post_type==="feature"&&r.jsxs("span",{className:"support-vote-count",children:[r.jsx(db,{size:14})," ",_.vote_count]})]},_.id)})]}),r.jsx("section",{className:"support-post-detail","aria-label":"Support post detail",children:z?r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"support-detail-head",children:[r.jsxs("div",{className:"support-detail-badges",children:[r.jsx("span",{className:"support-type-badge",children:Uh(z.post_type)}),r.jsx("span",{className:`support-status-badge status-${z.status}`,children:Cd(z.status)}),z.visibility==="private"&&r.jsxs("span",{className:"support-private-badge",children:[r.jsx(As,{size:13})," Private"]})]}),r.jsxs("div",{className:"support-detail-actions",children:[Y&&r.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>U(_=>!_),title:"Edit post",children:r.jsx(Oy,{size:16})}),pe&&r.jsxs(r.Fragment,{children:[r.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>{Ge()},disabled:H==="pin",title:z.is_pinned?"Unpin post":"Pin post",children:r.jsx(Dh,{size:16})}),r.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>{xe()},disabled:H==="lock",title:z.is_locked?"Unlock post":"Lock post",children:r.jsx(As,{size:16})}),r.jsx("button",{className:"support-icon-button danger",type:"button",onClick:()=>{Be()},disabled:H==="hide",title:"Hide post",children:r.jsx(Lh,{size:16})})]})]})]}),G?r.jsxs("form",{className:"support-edit-form",onSubmit:_=>{R(_)},children:[r.jsx("input",{value:z.title,onChange:_=>K({title:_.target.value}),minLength:3,maxLength:180,required:!0}),r.jsx("textarea",{value:z.body,onChange:_=>K({body:_.target.value}),rows:9,required:!0}),r.jsxs("div",{className:"support-edit-actions",children:[r.jsxs("select",{value:z.visibility,onChange:_=>K({visibility:_.target.value}),children:[r.jsx("option",{value:"public",children:"Public"}),r.jsx("option",{value:"private",children:"Private"})]}),r.jsxs("button",{className:"support-primary-button",type:"submit",disabled:H==="edit",children:[r.jsx(Ns,{size:16})," Save changes"]})]})]}):r.jsxs(r.Fragment,{children:[r.jsx("h3",{children:z.title}),r.jsx("div",{className:"support-detail-body",children:z.body.split(`
2
- `).map((_,je)=>r.jsx("p",{children:_||" "},`${z.id}-body-${je}`))})]}),r.jsxs("div",{className:"support-detail-meta",children:[r.jsxs("span",{children:["Opened ",xl(z.created_at)]}),z.app_version&&r.jsxs("span",{children:["Version ",z.app_version]}),z.platform&&r.jsx("span",{children:z.platform}),z.is_locked&&r.jsxs("span",{children:[r.jsx(As,{size:13})," Locked"]}),z.is_pinned&&r.jsxs("span",{children:[r.jsx(Dh,{size:13})," Pinned"]})]}),r.jsxs("div",{className:"support-detail-controls",children:[z.post_type==="feature"&&r.jsxs("button",{className:`support-vote-button ${E.has(z.id)?"voted":""}`,type:"button",onClick:()=>{Ie()},disabled:H==="vote",children:[r.jsx(By,{size:16})," ",E.has(z.id)?"Voted":"Vote"," ",r.jsx("b",{children:z.vote_count})]}),pe&&r.jsxs("label",{className:"support-status-control",children:[r.jsx("span",{children:"Change status"}),r.jsx("select",{value:z.status,onChange:_=>{He(_.target.value)},disabled:H==="status",children:(Kx[z.post_type]||[]).map(_=>r.jsx("option",{value:_,children:Cd(_)},_))})]}),pe&&r.jsxs(r.Fragment,{children:[r.jsxs("select",{className:"support-status-control",value:ce,onChange:_=>J(_.target.value),children:[r.jsx("option",{value:"",children:"Duplicate of..."}),ct.filter(_=>_.id!==z.id&&_.product_id===z.product_id).map(_=>r.jsx("option",{value:_.id,children:_.title.slice(0,55)},_.id))]}),r.jsx("button",{className:"support-secondary-button",type:"button",onClick:()=>{Ke()},disabled:!ce||H==="duplicate",children:"Merge duplicate"})]})]}),k.length>0&&r.jsxs("div",{className:"support-attachments",children:[r.jsx("div",{className:"support-section-heading",children:r.jsxs("div",{children:[r.jsx("span",{children:"Attachments"}),r.jsxs("strong",{children:[k.length," file",k.length===1?"":"s"]})]})}),k.map(_=>r.jsxs("a",{href:_.signed_url,target:"_blank",rel:"noreferrer",children:[r.jsx(rc,{size:14})," ",_.file_name,r.jsxs("small",{children:[Math.ceil(_.size_bytes/1024)," KB"]})]},_.id))]}),r.jsxs("div",{className:"support-comments",children:[r.jsxs("div",{className:"support-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Discussion"}),r.jsxs("strong",{children:[v.length," comment",v.length===1?"":"s"]})]}),z.is_locked&&r.jsxs("span",{className:"support-locked-label",children:[r.jsx(As,{size:14})," Locked"]})]}),v.length===0?r.jsx("p",{className:"support-muted",children:"No response yet. Keep the conversation focused on this request."}):r.jsx("div",{className:"support-comment-list",children:v.map(_=>r.jsxs("article",{className:`support-comment ${_.is_staff_answer?"staff":""} ${z.accepted_comment_id===_.id?"accepted":""}`,children:[r.jsxs("div",{className:"support-comment-head",children:[r.jsx("strong",{children:_.is_staff_answer?"LiveDesk Support":_.author_id===e.user.id?"You":"Support user"}),_.is_staff_answer&&r.jsxs("span",{children:[r.jsx(Zt,{size:13})," Staff answer"]}),z.accepted_comment_id===_.id&&r.jsxs("span",{children:[r.jsx(En,{size:13})," Accepted"]}),r.jsx("time",{children:xl(_.created_at)})]}),r.jsx("p",{children:_.body}),r.jsxs("div",{className:"support-comment-actions",children:[(e.user.id===z.author_id||pe)&&z.post_type==="question"&&z.accepted_comment_id!==_.id&&r.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>{rt(_.id)},disabled:H===`accept-${_.id}`,children:[r.jsx(Ns,{size:14})," Accept answer"]}),pe&&r.jsx("button",{className:"support-icon-button danger",type:"button",onClick:()=>{Vx(_.id)},title:"Hide comment",children:r.jsx(Lh,{size:14})})]})]},_.id))}),!z.is_locked&&r.jsxs("form",{className:"support-comment-form",onSubmit:_=>{se(_)},children:[r.jsx("textarea",{value:ie,onChange:_=>j(_.target.value),placeholder:"Add a focused reply...",rows:3}),r.jsxs("button",{className:"support-primary-button",type:"submit",disabled:H==="comment"||!ie.trim(),children:[r.jsx(nc,{size:15})," Reply"]})]})]})]}):r.jsxs("div",{className:"support-detail-empty",children:[r.jsx(Yo,{size:28}),r.jsx("strong",{children:"Select a Support request"}),r.jsx("span",{children:"Its discussion and staff actions will appear here."})]})})]})]}):r.jsx("section",{className:"support-page support-auth-page",children:r.jsxs("div",{className:"support-empty-hero",children:[r.jsx("span",{className:"support-hero-icon",children:r.jsx(Yo,{size:28})}),r.jsx("p",{className:"support-eyebrow",children:"LiveDesk Support"}),r.jsx("h2",{children:"Get help, report issues, and shape the product."}),r.jsx("p",{children:"Sign in to view LiveDesk support and submit a private or public request."}),r.jsxs("button",{className:"support-primary-button",type:"button",onClick:s,children:[r.jsx(Zt,{size:17})," Sign in with Google"]})]})})}function Jx(e){if(!e)return"Reading the installed version...";switch(e.state){case"checking":return"Checking for a newer LiveDesk version...";case"available":return`Version ${e.availableVersion||""} is available.`;case"downloading":return`Downloading version ${e.availableVersion||""} (${Math.round(e.progress||0)}%).`;case"downloaded":return`Version ${e.availableVersion||""} is ready. Restart to install it.`;case"installing":return"Closing LiveDesk safely and starting the update...";case"current":return"This computer has the latest LiveDesk version.";case"error":return"The update server could not be reached. This version will keep running.";case"development":return"Desktop updates are available in an installed LiveDesk build.";case"unavailable":return"Updates are not available for this desktop build.";default:return"LiveDesk checks once when the desktop app starts."}}function Ab(){const e=window.liveDesk?.updates,[t,n]=o.useState(null),[s,a]=o.useState(!1);if(o.useEffect(()=>{if(!e)return;let d=!0;e.getStatus?.().then(h=>{d&&n(h)});const p=e.onStatus?.(h=>{d&&n(h)});return()=>{d=!1,p?.()}},[e]),!e)return null;const i=t?.state==="downloaded"||t?.downloaded===!0,c=s||t?.state==="checking"||t?.state==="downloading"||t?.state==="installing",u=async()=>{a(!0);try{const d=i?await e.install?.():await e.check?.();d&&n(d)}finally{a(!1)}};return r.jsxs("section",{className:"settings-section-card desktop-update-card",children:[r.jsxs("div",{className:"settings-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Desktop app"}),r.jsx("h3",{children:"LiveDesk updates"})]}),r.jsx(rc,{size:20})]}),r.jsx("p",{className:"settings-help","aria-live":"polite",children:Jx(t)}),r.jsxs("div",{className:"desktop-update-meta",children:[r.jsx("span",{children:"Installed"}),r.jsx("strong",{children:t?.currentVersion||"Unknown"}),t?.availableVersion&&r.jsxs(r.Fragment,{children:[r.jsx("span",{children:"Available"}),r.jsx("strong",{children:t.availableVersion})]})]}),r.jsxs("button",{className:"settings-reset desktop-update-action",onClick:()=>{u()},disabled:c,type:"button",children:[r.jsx(Ya,{size:15,className:c?"desktop-update-spin":""}),i?"Restart and update":c?"Updating...":"Check for updates"]})]})}function Sl(e){return!!e&&typeof e=="object"}function Nb(e){let t=e;return Sl(t)&&"data"in t&&(t=t.data),Sl(t)&&"session"in t&&(t=t.session),!Sl(t)||typeof t.access_token!="string"||!t.access_token||!Sl(t.user)||typeof t.user.id!="string"||!t.user.id?null:t}function Vh(e){return e?.access_token?e.refresh_token?"":"refresh-token-required":"access-token-required"}const Rb={hub:"Use this computer as Hub. Hub connects to and manages Client computers.","switch-to-hub":"Switch this computer from Client to Hub. It will manage Client computers instead of sharing its own screen.",client:"Keep this computer in Client mode so its screens, files, audio, and remote controls remain available to the active Hub.",wall:"Show live thumbnails from every connected Client. Choose a display, change tile size, or move into Control without opening another connection.",control:"Open the selected Client at full resolution and send mouse and keyboard input through the existing Hub session.","share-files":"Browse files on the Hub, send files to selected Clients, and manage shared folders and transfer progress.",agents:"Run approved commands on connected Clients through the Hub-hosted Codex Agent and LiveDesk permission controls."},ip={en:Rb,ko:{hub:"이 컴퓨터를 Hub로 사용합니다. Hub는 Client 컴퓨터를 연결하고 관리합니다.","switch-to-hub":"이 컴퓨터를 Client에서 Hub로 바꿉니다. 자신의 화면 공유를 멈추고 Client 컴퓨터를 관리합니다.",client:"이 컴퓨터를 Client 모드로 유지합니다. 화면, 파일, 오디오와 원격 제어 기능이 활성 Hub에서 계속 사용 가능하도록 연결합니다.",wall:"연결된 모든 Client의 실시간 화면을 한곳에 표시합니다. 모니터와 타일 크기를 선택하고 새 연결 없이 Control로 이동할 수 있습니다.",control:"선택한 Client 화면을 전체 해상도로 열고 기존 Hub 세션을 통해 마우스와 키보드 입력을 전송합니다.","share-files":"Hub의 파일을 탐색하고 선택한 Client로 전송하며 공유 폴더와 전송 진행 상태를 관리합니다.",agents:"Hub의 Codex가 연결된 Client에서 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 wu(e){const t=e?[e]:typeof navigator>"u"?["en"]:navigator.languages?.length?navigator.languages:[navigator.language];for(const n of t){const s=String(n||"").trim(),a=s.toLowerCase();if(!a)continue;if(a.startsWith("zh-tw")||a.startsWith("zh-hk"))return"zh-TW";if(a.startsWith("zh"))return"zh";if(a.startsWith("pt"))return"pt-BR";const i=a.split("-")[0];if(ip[s])return s;if(ip[i])return i}return"en"}function ru(e,t){const n=wu(t);return ip[n]?.[e]||Rb[e]}function op(e,t,n){return`${e}
3
- ${ru(t,n)}`}const Tb={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"},Zx={en:Tb,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"}},Pb={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"},eS={en:Pb,ko:{eyebrow:"컴퓨터 역할",title:"이 컴퓨터를 Hub로 사용할까요?",description:"Hub는 Client 컴퓨터를 연결하고 관리합니다.",restartNotice:"다른 컴퓨터가 Hub라면 이 컴퓨터가 새 Hub가 됩니다.",cancel:"취소",confirm:"Hub로 설정",closeLabel:"Hub 설정 확인 닫기"}};function tS(e){const t=wu(e);return Zx[t]||Tb}function nS(e){const t=wu(e);return eS[t]||Pb}function rS(e=[]){return[...new Set(e.filter(t=>typeof t=="string").map(t=>t.trim()).filter(Boolean))]}function sS(e=[],t=new Set){return e.find(n=>!t.has(n))||""}const aS=[{id:"docs",label:"Doc",icon:tu},{id:"support",label:"Support",icon:Yo},{id:"pricing",label:"Pricing",icon:Xo},{id:"settings",label:"Settings",icon:nu}],Gh=[0,1e3,2e3,5e3,1e4,2e4,3e4],iS=15e3;function oS(e=""){const t=e.trim().replace(/\/+$/,"");return t||(typeof window>"u"?"":window.location.port==="5179"?window.location.origin:"http://127.0.0.1:5179")}async function _a(e,t=!1){const n=t?"":sessionStorage.getItem("livedesk.client.csrf");if(n)return n;const s=await fetch(`${e}/api/runtime/status`,{cache:"no-store"}),a=await s.json().catch(()=>({}));if(!s.ok)throw new Error(a.error||`Client runtime returned HTTP ${s.status}.`);const i=String(a.csrfToken||"");return i&&sessionStorage.setItem("livedesk.client.csrf",i),i}function cp(e){return`${Math.max(0,Math.min(100,Number(e||0))).toFixed(0)}%`}function kd(e){return Number.isFinite(e)?`${Math.max(0,Math.min(100,Number(e))).toFixed(0)}%`:"—"}function Ib(e){return Number.isFinite(e)?cp(Number(e)):"0%"}function Ua(e){const t=Number(e);return!Number.isFinite(t)||t<0?"—":t>=1024**4?`${(t/1024**4).toFixed(t>=10*1024**4?0:1)} TB`:t>=1024**3?`${(t/1024**3).toFixed(t>=10*1024**3?0:1)} GB`:`${(t/1024**2).toFixed(0)} MB`}function Kh(e){const t=Math.max(0,Number(e||0));return t>=1024**3?`${(t/1024**3).toFixed(1)} GB/s`:t>=1024**2?`${(t/1024**2).toFixed(1)} MB/s`:t>=1024?`${(t/1024).toFixed(1)} KB/s`:`${t.toFixed(0)} B/s`}function cS(e,t){const n=Number(e||0)/1073741824,s=Number(t||0)/1024**3;return s>0?`${n.toFixed(1)} / ${s.toFixed(1)} GB`:"Checking..."}function lS(e,t){return!Number.isFinite(t)||Number(t)<=0?"Dedicated memory unavailable":Number.isFinite(e)?`${Ua(e)} / ${Ua(t)}`:`${Ua(t)} available`}function uS(e){const t=Math.max(0,Math.floor(Number(e||0)/60)),n=Math.floor(t/1440),s=Math.floor(t%1440/60),a=t%60;return n>0?`${n}d ${s}h`:s>0?`${s}h ${a}m`:`${a}m`}function Cl({icon:e,label:t,value:n,detail:s,percent:a}){return r.jsxs("article",{className:"client-resource-metric",children:[r.jsxs("div",{className:"client-resource-metric-head",children:[r.jsx(e,{size:17}),r.jsx("span",{children:t}),r.jsx("strong",{children:n})]}),r.jsx("small",{title:s,children:s}),r.jsx("i",{"aria-hidden":"true",children:r.jsx("b",{style:{width:Ib(a)}})})]})}function dS(e,t){const n=e?.user.user_metadata||{},s=n.full_name||n.name||n.preferred_username||e?.user.email||e?.user.id||t?.userName||t?.auth?.name||t?.userEmail||t?.userId||"Account";return String(s).trim()||"Account"}function pS(e,t){const n=e?.user.user_metadata||{};return rS([n.avatar_url,n.picture,t?.userAvatarUrl,t?.auth?.avatarUrl])}function mS({page:e,status:t}){const s={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."}}[e];return r.jsxs("section",{className:"client-service-page",children:[r.jsx("span",{className:"client-unified-section-label",children:s.label}),r.jsx("h2",{children:s.title}),r.jsx("p",{children:s.body}),r.jsxs("div",{className:"client-service-page-card",children:[e==="docs"&&r.jsxs(r.Fragment,{children:[r.jsx("strong",{children:"Automatic connection"}),r.jsx("span",{children:"Start LiveDesk. This computer signs in, finds the Hub, and becomes available without another action."})]}),e==="pricing"&&r.jsxs(r.Fragment,{children:[r.jsx("strong",{children:"One plan, managed at the Hub"}),r.jsx("span",{children:"Computer access follows the account and plan used by the Hub."})]}),e==="settings"&&r.jsxs(r.Fragment,{children:[r.jsx("strong",{children:"Saved sign-in"}),r.jsx("span",{children:t?.auth?.persisted?"Enabled on this computer":"Sign in once to enable automatic reconnection"})]})]}),e==="settings"&&r.jsx(Ab,{})]})}function hS({session:e,status:t,pin:n,roleChangeMessage:s,videoAccelerationBusy:a,slotInput:i,slotBusy:c,onSignIn:u,onPinChange:d,onSubmitPin:p,onSlotInputChange:h,onSaveSlot:m,onEnableVideoAcceleration:g}){const w=t?.connectionState==="connected",v=t?.videoAcceleration,y=a||v?.busy||v?.state==="installing",k=v?.ready?`${v.encoder||"H.264"} · ${v.driver||"VAAPI"}`:y?"Setting up…":v?.message||"Setup available",N=t?.system?.memoryTotalBytes?Number(t.system.memoryUsedBytes||0)/t.system.memoryTotalBytes*100:0,C=t?.system?.gpus||[],A=C.find(O=>Number.isFinite(O.usagePercent)||Number.isFinite(O.memoryTotalBytes))||C[0],E=Number.isFinite(A?.usagePercent)?Number(A?.usagePercent):null,I=Number.isFinite(A?.memoryTotalBytes)&&Number(A?.memoryTotalBytes)>0&&Number.isFinite(A?.memoryUsedBytes)?Number(A?.memoryUsedBytes)/Number(A?.memoryTotalBytes)*100:null,F=t?.system?.disks||[],M=t?.system?.network,H=!!M?.sampledAt,V=M?.interfaces||[],P=[...new Set(V.map(O=>O.name).filter(Boolean))],D=V.map(O=>O.address).filter(Boolean);return r.jsxs("section",{className:"client-home-page",children:[r.jsxs("header",{className:"client-home-heading",children:[r.jsxs("div",{children:[r.jsx("p",{className:"client-unified-eyebrow",children:"THIS COMPUTER"}),r.jsx("h2",{children:t?.deviceName||"This Computer"})]}),r.jsxs("span",{className:`client-unified-role-chip ${w?"connected":""}`,children:[r.jsx(pn,{size:15})," ",w?"Online":"Connecting"]})]}),r.jsxs("div",{className:"client-home-layout",children:[r.jsxs("section",{className:"client-main-surface","aria-label":"Client computer",children:[r.jsxs("div",{className:"client-main-surface-head",children:[r.jsxs("div",{children:[r.jsx("span",{className:"client-unified-section-label",children:"SYSTEM STATUS"}),r.jsx("strong",{children:"Hardware at a glance"})]}),r.jsxs("small",{children:[r.jsx(hb,{size:14})," Uptime ",uS(t?.system?.uptimeSeconds)]})]}),r.jsxs("div",{className:"client-system-dashboard",children:[r.jsxs("section",{className:"client-performance-panel","aria-label":"Performance",children:[r.jsxs("div",{className:"client-system-subhead",children:[r.jsxs("div",{children:[r.jsx("span",{className:"client-unified-section-label",children:"PERFORMANCE"}),r.jsx("strong",{children:"Live resources"})]}),r.jsx("small",{children:"Live updates"})]}),r.jsxs("div",{className:"client-live-metrics",children:[r.jsx(Cl,{icon:_h,label:"CPU",value:cp(t?.system?.cpuUsagePercent),detail:t?.system?.cpuLogicalCores?`${t.system.cpuLogicalCores} logical cores · Current processor usage`:"Current processor usage",percent:t?.system?.cpuUsagePercent}),r.jsx(Cl,{icon:Uy,label:"Memory",value:cp(N),detail:cS(t?.system?.memoryUsedBytes,t?.system?.memoryTotalBytes),percent:N}),r.jsx(Cl,{icon:Vy,label:"GPU",value:kd(E),detail:A?.name||(t?.system?.hardwareCollecting?"Detecting graphics hardware…":"Graphics usage unavailable"),percent:E}),r.jsx(Cl,{icon:os,label:"VRAM",value:kd(I),detail:lS(A?.memoryUsedBytes,A?.memoryTotalBytes),percent:I})]})]}),r.jsxs("section",{className:"client-storage-panel","aria-label":"Local storage",children:[r.jsxs("div",{className:"client-system-subhead",children:[r.jsxs("div",{children:[r.jsx("span",{className:"client-unified-section-label",children:"STORAGE"}),r.jsx("strong",{children:"Local drives"})]}),r.jsx("small",{children:F.length>0?`${F.length} ${F.length===1?"drive":"drives"}`:t?.system?.hardwareCollecting?"Detecting…":"Unavailable"})]}),r.jsxs("div",{className:"client-disk-list",children:[F.map(O=>r.jsxs("article",{className:"client-disk-row",children:[r.jsxs("div",{className:"client-disk-row-head",children:[r.jsxs("span",{children:[r.jsx(qa,{size:16}),r.jsx("strong",{children:O.mount||"Disk"}),r.jsx("small",{children:O.name||"Local disk"})]}),r.jsx("strong",{children:kd(O.usedPercent)})]}),r.jsxs("small",{children:[Ua(O.freeBytes)," free · ",Ua(O.totalBytes)," total"]}),r.jsx("i",{"aria-hidden":"true",children:r.jsx("b",{style:{width:Ib(O.usedPercent)}})})]},`${O.mount}-${O.name||""}`)),F.length===0&&r.jsxs("div",{className:"client-disk-empty",children:[r.jsx(qa,{size:18}),r.jsx("span",{children:t?.system?.hardwareCollecting?"Detecting local drives…":"Storage information is not available."})]})]})]}),r.jsxs("section",{className:"client-network-panel","aria-label":"Network activity",children:[r.jsxs("div",{className:"client-system-subhead",children:[r.jsxs("div",{children:[r.jsx("span",{className:"client-unified-section-label",children:"NETWORK"}),r.jsx("strong",{children:"Live traffic"})]}),r.jsx("small",{children:P.length>0?P.join(", "):"Detecting adapter"})]}),r.jsxs("div",{className:"client-network-live",children:[r.jsxs("div",{className:"client-network-adapter",children:[r.jsx(bu,{size:18}),r.jsxs("span",{children:[r.jsx("strong",{children:P.join(", ")||"Network"}),r.jsx("small",{children:D.join(" / ")||"Checking active connection"})]})]}),r.jsxs("div",{className:"client-network-rate download",children:[r.jsx(Gy,{size:17}),r.jsxs("span",{children:[r.jsx("small",{children:"Receive"}),r.jsx("strong",{children:Kh(H?M?.receiveBytesPerSecond:void 0)})]})]}),r.jsxs("div",{className:"client-network-rate upload",children:[r.jsx(Ky,{size:17}),r.jsxs("span",{children:[r.jsx("small",{children:"Send"}),r.jsx("strong",{children:Kh(H?M?.sendBytesPerSecond:void 0)})]})]}),r.jsx("small",{className:"client-network-total",children:H?`Total ${Ua(M?.receivedBytes)} received / ${Ua(M?.sentBytes)} sent`:"Traffic has not been measured yet."})]})]})]})]}),r.jsxs("aside",{className:"client-connection-panel",children:[r.jsx("span",{className:"client-unified-section-label",children:"LIVEDESK SERVICES"}),r.jsx("h3",{children:w?"Connected to the Hub":t?.authenticated?"Finding the Hub":"Connect this computer"}),w?r.jsxs(r.Fragment,{children:[r.jsx("p",{className:"client-unified-copy",children:"This computer is available from the LiveDesk Hub."}),r.jsxs("div",{className:"client-service-status-list",children:[r.jsxs("div",{children:[r.jsx(pn,{size:17}),r.jsxs("span",{children:[r.jsx("strong",{children:"Screen sharing"}),r.jsx("small",{children:t?.permissions?.screenCapture?"Active":"Waiting"})]})]}),r.jsxs("div",{children:[r.jsx(Zt,{size:17}),r.jsxs("span",{children:[r.jsx("strong",{children:"Remote control"}),r.jsx("small",{children:t?.permissions?.remoteInput?"Available":"Unavailable"})]})]}),r.jsxs("div",{children:[r.jsx(Xi,{size:17}),r.jsxs("span",{children:[r.jsx("strong",{children:"File delivery"}),r.jsx("small",{children:t?.permissions?.files?"Ready to receive":"Unavailable"})]})]}),r.jsxs("div",{children:[r.jsx(Ji,{size:17}),r.jsxs("span",{children:[r.jsx("strong",{children:"Computer audio"}),r.jsx("small",{children:t?.permissions?.audio?"Available":"Unavailable"})]})]})]})]}):r.jsxs(r.Fragment,{children:[r.jsx("p",{className:"client-unified-copy",children:t?.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."}),!e&&!t?.authenticated?r.jsxs("button",{className:"client-unified-primary",type:"button",onClick:u,children:[r.jsx(Gs,{size:16})," Sign in with Google"]}):r.jsxs("p",{className:"client-unified-success",children:[r.jsx(En,{size:16})," Signed in as ",e?.user.email||e?.user.id||t?.userEmail||t?.userId||"saved account"]}),r.jsxs("div",{className:"client-unified-pin-row",children:[r.jsx(Qy,{size:16}),r.jsx("input",{value:n,onChange:O=>d(O.target.value),placeholder:"6-digit Hub PIN",inputMode:"numeric","aria-label":"6-digit Hub PIN"}),r.jsx("button",{className:"client-unified-secondary",type:"button",onClick:p,disabled:n.length!==6,children:"Connect"})]})]}),v?.supported&&r.jsxs("div",{className:`client-video-acceleration state-${v.ready?"ready":v.state||"setup-required"}`,children:[r.jsx(_h,{size:17}),r.jsxs("span",{children:[r.jsx("strong",{children:"Hardware video"}),r.jsx("small",{children:k})]}),!v.ready&&v.canInstall&&r.jsx("button",{type:"button",onClick:g,disabled:y,title:"Install and verify Linux FFmpeg hardware video support",children:y?"Setting up":"Enable"})]}),s&&r.jsx("p",{className:"client-unified-success",children:s}),r.jsxs("div",{className:"client-slot-setting",children:[r.jsxs("label",{htmlFor:"client-slot-number",children:[r.jsx("span",{children:"Slot"}),r.jsx("input",{id:"client-slot-number",value:i,onChange:O=>h(O.target.value),inputMode:"numeric",pattern:"[0-9]*",placeholder:"1-999","aria-label":"Wall slot number",disabled:!w||c})]}),r.jsxs("button",{type:"button",onClick:m,disabled:!w||c||!i,"aria-label":"Save slot number",title:"Save slot number",children:[r.jsx(nu,{size:17}),r.jsx("span",{children:c?"Saving":"Set"})]})]})]})]})]})}function fS({runtimeBaseUrl:e=""}){const[t,n]=o.useState(null),[s,a]=o.useState(null),[i,c]=o.useState(!1),[u,d]=o.useState(""),[p,h]=o.useState(""),[m,g]=o.useState(""),[w,v]=o.useState(!1),[y,k]=o.useState(!1),[N,C]=o.useState(""),[A,E]=o.useState(!1),[I,F]=o.useState(null),[M,H]=o.useState(!1),[V,P]=o.useState("computer"),[D,O]=o.useState(!1),X=o.useRef(null),G=o.useRef(null),U=o.useRef(!1),ie=o.useRef(null),j=o.useRef(null),re=o.useRef(!1),de=o.useRef(!1),Q=o.useRef(0),ge=o.useRef(!1),oe=o.useRef(""),me=o.useMemo(()=>oS(e),[e]),Ae=o.useMemo(()=>dS(s,t),[s,t]),Te=o.useMemo(()=>pS(s,t),[s,t]),Pe=JSON.stringify(Te),[Se,te]=o.useState(()=>new Set),Ce=sS(Te,Se),Fe=Ae.slice(0,1).toUpperCase()||"L";o.useEffect(()=>{te(new Set)},[Pe]);const Le=o.useCallback(z=>{te(pe=>{if(!z||pe.has(z))return pe;const Y=new Set(pe);return Y.add(z),Y})},[]),Ue=o.useCallback(async()=>{if(h(""),window.liveDesk?.auth?.signInWithGoogle){const z=await window.liveDesk.auth.signInWithGoogle();return z?.ok===!1?(h(z.error||"LiveDesk could not open the system browser for Google sign-in."),!1):!0}return window.location.assign(`${me}/auth/google`),!0},[me]),ne=o.useCallback(async()=>{de.current||(de.current=!0,h("Your saved Google sign-in is incomplete. LiveDesk is reopening sign-in once to repair it."),await pt.auth.signOut({scope:"local"}).catch(()=>{}),a(null),await Ue()||(de.current=!1))},[Ue]),ae=o.useCallback(async z=>{const pe=Vh(z);if(pe)throw new Error(pe);if(U.current)return!1;U.current=!0;try{if(window.liveDesk?.auth?.persistSession){const Y=await window.liveDesk.auth.persistSession(z);if(Y?.ok===!1)throw new Error(Y.error||"LiveDesk could not validate the desktop session.");return h(""),!0}for(let Y=0;Y<2;Y+=1){const K=await _a(me,Y>0),ee=await fetch(`${me}/api/auth/session`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":K},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}})}),R=await ee.json().catch(()=>({}));if(ee.status===403&&Y===0){sessionStorage.removeItem("livedesk.client.csrf");continue}if(!ee.ok)throw new Error(R.error||`Client runtime returned HTTP ${ee.status}.`);return h(""),!0}throw new Error("Client runtime rejected the session transfer.")}finally{U.current=!1}},[me]),le=o.useCallback(()=>{const z=ie.current;if(z)return z;const pe=(async()=>{try{const Y=await fetch(`${me}/api/client/status`,{cache:"no-store",signal:AbortSignal.timeout(1500)}),K=await Y.json().catch(()=>({}));if(!Y.ok)throw new Error(K.error||`Client runtime returned HTTP ${Y.status}.`);if(K.csrfToken&&sessionStorage.setItem("livedesk.client.csrf",K.csrfToken),String(K.role||"").toLowerCase()==="hub")throw new Error("This computer is assigned to the Hub role.");n(K)}catch(Y){h(Y instanceof Error?Y.message:String(Y))}})();return ie.current=pe,pe.finally(()=>{ie.current===pe&&(ie.current=null)}),pe},[me]),ce=o.useCallback(()=>{const z=j.current;if(z)return z;const pe=(async()=>{const Y=await fetch(`${me}/api/client/diagnostics`,{cache:"no-store",signal:AbortSignal.timeout(8e3)}),K=await Y.json().catch(()=>({}));if(!Y.ok)throw new Error(K.error||`Client diagnostics returned HTTP ${Y.status}.`);if(String(K.role||"").toLowerCase()==="hub")throw new Error("This computer is assigned to the Hub role.");n(K)})();return j.current=pe,pe.finally(()=>{j.current===pe&&(j.current=null)}),pe},[me]);o.useEffect(()=>{let z=!1,pe=null;const Y=async()=>{await le(),z||(pe=window.setTimeout(()=>{Y()},2e3))};return Y(),()=>{z=!0,pe!==null&&window.clearTimeout(pe)}},[le]),o.useEffect(()=>{if(V!=="computer")return;let z=!1,pe=null;const Y=()=>{z||(pe=window.setTimeout(()=>{K()},iS))},K=async()=>{document.visibilityState==="visible"&&await ce().catch(()=>{}),Y()},ee=()=>{document.visibilityState==="visible"&&(pe!==null&&(window.clearTimeout(pe),pe=null),K())};return document.addEventListener("visibilitychange",ee),K(),()=>{z=!0,document.removeEventListener("visibilitychange",ee),pe!==null&&window.clearTimeout(pe)}},[V,ce]),o.useEffect(()=>{if(ge.current)return;const z=Number(t?.slotNumber||0);C(z>0?String(z):"")},[t?.slotNumber]),o.useEffect(()=>{if(!I)return;const z=window.setTimeout(()=>F(null),5e3);return()=>window.clearTimeout(z)},[I]),o.useEffect(()=>{const z=String(p||t?.lastError||"").trim();if(!z){oe.current="";return}if(oe.current===z)return;oe.current=z;const pe=/supabase-user-verification-failed:(401|403)/i.test(z)?"Saved sign-in needs refresh. LiveDesk will retry it automatically.":z;F({kind:"error",message:pe})},[p,t?.lastError]);const J=o.useCallback(async()=>{const z=Date.now();if(!(!t?.authenticated||t.connectionState==="connected"||!["waiting","reconnecting"].includes(String(t.agent?.state||""))||z-Q.current<4e3)){Q.current=z;try{const pe=await fetch(`${me}/api/client/reconnect`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await _a(me)},body:JSON.stringify({onlyIfWaiting:!0,reason:"app-active"})});if(!pe.ok)throw new Error(`Client reconnect returned HTTP ${pe.status}.`);await le()}catch(pe){h(pe instanceof Error?pe.message:String(pe))}}},[me,le,t]);o.useEffect(()=>{const z=()=>{J()},pe=()=>{J()},Y=()=>{document.visibilityState==="visible"&&J()};return window.addEventListener("online",z),window.addEventListener("focus",pe),document.addEventListener("visibilitychange",Y),()=>{window.removeEventListener("online",z),window.removeEventListener("focus",pe),document.removeEventListener("visibilitychange",Y)}},[J]),o.useEffect(()=>{if(!i||!t||!s?.access_token||t.authenticated)return;if(Vh(s)==="refresh-token-required"){ne().catch(ee=>{de.current=!1,h(ee instanceof Error?ee.message:String(ee))});return}let z=!1,pe,Y=0;const K=async()=>{if(z)return;try{const R=await ae(s);if(await le(),R)return}catch(R){h(R instanceof Error?R.message:String(R))}if(z)return;const ee=Gh[Math.min(Y,Gh.length-1)];Y+=1,pe=window.setTimeout(()=>{K()},ee)};return K(),()=>{z=!0,pe!==void 0&&window.clearTimeout(pe)}},[i,le,ne,s,t,ae]),o.useEffect(()=>{const z=new URLSearchParams(window.location.search),pe=z.get("auth_error");if(!pe)return;h(pe),z.delete("auth_error");const Y=z.toString();window.history.replaceState(window.history.state,"",`${window.location.pathname}${Y?`?${Y}`:""}${window.location.hash}`)},[]),o.useEffect(()=>{let z=!0;if(!window.liveDesk?.auth)return a(null),c(!0),le(),()=>{z=!1};const pe=window.liveDesk?.auth?.onComplete?.(K=>{K.ok&&K.session?pt.auth.setSession(K.session).catch(ee=>h(ee instanceof Error?ee.message:String(ee))):K.ok&&K.signedOut?(a(null),c(!0),pt.auth.signOut({scope:"local"})):K.error&&h(K.error)});(async()=>{try{const K=window.liveDesk?.auth?.getSession?await window.liveDesk.auth.getSession():await pt.auth.getSession();if(!z)return;const ee=Nb(K);a(ee),le()}catch(K){z&&h(K instanceof Error?K.message:String(K))}finally{z&&c(!0)}})();const{data:Y}=pt.auth.onAuthStateChange((K,ee)=>{if(z){if(!ee&&window.liveDesk?.auth){c(!0);return}a(ee),c(!0),le()}});return()=>{z=!1,pe?.(),Y.subscription.unsubscribe()}},[le]),o.useEffect(()=>{if(!i||!t||re.current||de.current||s||t.authenticated)return;const z=new URLSearchParams(window.location.search);if(!z.has("livedesk_launch"))return;re.current=!0,z.delete("livedesk_launch");const pe=z.toString();window.history.replaceState(window.history.state,"",`${window.location.pathname}${pe?`?${pe}`:""}${window.location.hash}`),Ue().catch(Y=>h(Y instanceof Error?Y.message:String(Y)))},[i,s,Ue,t]);const ye=async()=>{O(!1),window.liveDesk?.auth?.signOut?(await pt.auth.signOut(),(await window.liveDesk.auth.signOut())?.runtimeCleared===!1&&h("Signed out locally. The LiveDesk runtime could not be reached to clear its session.")):await fetch(`${me}/api/auth/session`,{method:"DELETE",headers:{"X-LiveDesk-CSRF":await _a(me)}}).catch(()=>{}),a(null),await le()};o.useEffect(()=>{if(!D)return;const z=Y=>{Y.target instanceof Element&&Y.target.closest(".account-popover, .rail-account")||O(!1)},pe=Y=>{Y.key==="Escape"&&O(!1)};return window.addEventListener("pointerdown",z),window.addEventListener("keydown",pe),()=>{window.removeEventListener("pointerdown",z),window.removeEventListener("keydown",pe)}},[D]);const ue=o.useCallback((z=!0)=>{w||(H(!1),z&&window.requestAnimationFrame(()=>G.current?.focus()))},[w]),Ee=o.useCallback(()=>{w||!t?.authenticated||(G.current=document.activeElement instanceof HTMLElement?document.activeElement:null,g(""),H(!0))},[w,t?.authenticated]);o.useEffect(()=>{if(!M)return;const z=window.requestAnimationFrame(()=>X.current?.focus()),pe=K=>{K.target instanceof Element&&K.target.closest(".client-hub-switch-popover, .client-hub-switch-trigger")||ue(!1)},Y=K=>{K.key==="Escape"&&ue()};return window.addEventListener("pointerdown",pe),window.addEventListener("keydown",Y),()=>{window.cancelAnimationFrame(z),window.removeEventListener("pointerdown",pe),window.removeEventListener("keydown",Y)}},[ue,M]);const nt=async()=>{h("");try{const z=await fetch(`${me}/api/client/pin`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await _a(me)},body:JSON.stringify({pin:u})}),pe=await z.json().catch(()=>({}));if(!z.ok||pe?.ok===!1)throw new Error(pe?.error||"PIN could not be accepted.");d(""),await le()}catch(z){h(z instanceof Error?z.message:String(z))}},T=async()=>{H(!1),v(!0),g(""),h("");try{const z=await fetch(`${me}/api/runtime/switch-role`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await _a(me)},body:JSON.stringify({role:"hub"})}),pe=await z.json().catch(()=>({}));if(!z.ok||pe?.ok===!1)throw new Error(pe?.error||`Role change failed with HTTP ${z.status}.`);g("Hub role accepted. LiveDesk is restarting this computer with the Hub Wall.");const Y=Number(t?.runtimePid||0);await ob({baseUrl:me,targetRole:"hub",previousRuntimePid:Y,allowedStates:["running"]}),window.location.reload()}catch(z){h(z instanceof Error?z.message:String(z)),v(!1)}},ve=async()=>{if(A)return;const z=Number(N);if(!Number.isInteger(z)||z<1||z>999){F({kind:"error",message:"Enter a slot number from 1 to 999."});return}E(!0),F(null);try{const pe=await fetch(`${me}/api/client/slot`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await _a(me)},body:JSON.stringify({slotNumber:z})}),Y=await pe.json().catch(()=>({}));if(!pe.ok||Y.ok===!1){if(Y.error==="slot-taken"){const K=Y.conflict?.deviceName||Y.conflict?.hostname||Y.conflict?.deviceId||"another computer";throw new Error(`Slot ${String(z).padStart(3,"0")} is already used by ${K}.`)}throw new Error(Y.error||`Slot update failed with HTTP ${pe.status}.`)}ge.current=!1,C(String(z)),n(Y),F({kind:"success",message:`Slot ${String(z).padStart(3,"0")} saved. LiveDesk is reconnecting this Client.`})}catch(pe){F({kind:"error",message:pe instanceof Error?pe.message:String(pe)})}finally{E(!1),await le()}},De=async()=>{if(!y){k(!0),h("");try{const z=await fetch(`${me}/api/client/video-acceleration/install`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await _a(me)},body:JSON.stringify({confirm:!0})}),pe=await z.json().catch(()=>({}));if(n(pe),!z.ok||pe.videoAcceleration?.ready!==!0)throw new Error(pe.videoAcceleration?.error||pe.error||"Linux hardware video setup did not complete.")}catch(z){h(z instanceof Error?z.message:String(z))}finally{k(!1),await le()}}},qe=!!(t?.authenticated||s),_e=o.useMemo(()=>wu(),[]),$e=ru("switch-to-hub",_e),mt=ru("client",_e),ct=tS(_e);return r.jsxs("main",{className:"app-shell client-unified-shell",children:[r.jsxs("aside",{className:"tool-rail","aria-label":"LiveDesk Client tools",children:[r.jsx("div",{className:"rail-brand",title:"LiveDesk",children:r.jsx(ib,{size:25})}),r.jsx("nav",{className:"rail-tools","aria-label":"Client navigation",children:r.jsxs("div",{className:"client-main-tool-slot",children:[r.jsxs("button",{className:"rail-tool client-main-tool client-hub-tool client-hub-switch-trigger accent-blue",type:"button",onClick:Ee,disabled:w||!t?.authenticated,"aria-busy":w,"aria-expanded":M,"aria-haspopup":"dialog","aria-controls":M?"client-hub-switch-popover":void 0,"aria-label":`Hub. ${$e}`,"data-tooltip":M?void 0:op("Hub","switch-to-hub",_e),children:[r.jsx(os,{size:19}),r.jsx("span",{children:w?"Switching…":"Hub"})]}),r.jsxs("button",{className:`rail-tool client-main-tool accent-blue ${V==="computer"?"active":""}`,type:"button",onClick:()=>P("computer"),"aria-current":V==="computer"?"page":void 0,"aria-label":`Client. ${mt}`,"data-tooltip":op("Client","client",_e),children:[r.jsx(pn,{size:19}),r.jsx("span",{children:"Client"})]})]})}),r.jsxs("div",{className:"rail-footer",children:[aS.map(z=>{const pe=z.icon;return r.jsxs("button",{className:`rail-tool compact ${V===z.id?"active":""}`,type:"button",onClick:()=>P(z.id),title:z.label,children:[r.jsx(pe,{size:18}),r.jsx("span",{children:z.label})]},z.id)}),r.jsxs("button",{className:`rail-account ${qe?"signed-in":""}`,type:"button",onClick:()=>O(z=>!z),"aria-expanded":D,"aria-haspopup":"dialog",title:qe?"Account":"Sign in",children:[qe&&Ce?r.jsx("img",{src:Ce,alt:Ae,referrerPolicy:"no-referrer",onError:()=>Le(Ce)},Ce):qe?r.jsx("span",{className:"avatar-fallback",children:Fe}):r.jsx(Gs,{size:18}),r.jsx("span",{children:qe?"Account":"Sign in"})]})]})]}),M&&r.jsxs("section",{id:"client-hub-switch-popover",className:"client-hub-switch-popover",role:"dialog","aria-modal":"false","aria-labelledby":"client-hub-switch-title","aria-describedby":"client-hub-switch-description client-hub-switch-restart",children:[r.jsxs("header",{className:"client-hub-switch-head",children:[r.jsx("span",{className:"client-hub-switch-mark","aria-hidden":"true",children:r.jsx(os,{size:19})}),r.jsx("span",{className:"client-hub-switch-eyebrow",children:ct.eyebrow}),r.jsx("button",{className:"client-hub-switch-close",type:"button",onClick:()=>ue(),"aria-label":ct.closeLabel,children:r.jsx(xn,{size:17})})]}),r.jsx("h2",{id:"client-hub-switch-title",children:ct.title}),r.jsx("p",{id:"client-hub-switch-description",children:ct.description}),r.jsxs("p",{id:"client-hub-switch-restart",className:"client-hub-switch-notice",children:[r.jsx(Zt,{size:16,"aria-hidden":"true"}),r.jsx("span",{children:ct.restartNotice})]}),r.jsxs("div",{className:"client-hub-switch-actions",children:[r.jsx("button",{type:"button",onClick:()=>ue(),children:ct.cancel}),r.jsxs("button",{ref:X,className:"primary",type:"button",onClick:()=>{T()},disabled:w||!t?.authenticated,children:[r.jsx(os,{size:16}),ct.confirm]})]})]}),D&&r.jsxs("section",{className:"account-popover",role:"dialog","aria-label":"LiveDesk account",children:[r.jsxs("div",{className:"account-popover-head",children:[r.jsx("div",{className:"account-popover-avatar",children:qe&&Ce?r.jsx("img",{src:Ce,alt:Ae,referrerPolicy:"no-referrer",onError:()=>Le(Ce)},Ce):qe?r.jsx("span",{children:Fe}):r.jsx(Gs,{size:18})}),r.jsxs("div",{children:[r.jsx("strong",{children:qe?Ae:"Account"}),r.jsx("p",{children:s?.user.email||t?.userEmail||t?.userId||"Not signed in"})]})]}),r.jsxs("dl",{className:"account-popover-facts",children:[r.jsx("dt",{children:"User"}),r.jsx("dd",{children:s?.user.email||t?.userEmail||t?.userId||"Not signed in"}),r.jsx("dt",{children:"Runtime"}),r.jsx("dd",{children:t?"Local app ready":"Checking local app"}),r.jsx("dt",{children:"Session"}),r.jsx("dd",{children:t?.auth?.persisted?"Saved on this computer":qe?"Active for this run":"Not saved"}),r.jsx("dt",{children:"Role"}),r.jsx("dd",{children:"Client"})]}),qe?r.jsxs("button",{className:"account-popover-action",onClick:()=>{ye()},type:"button",children:[r.jsx(mb,{size:16}),"Logout"]}):r.jsxs("button",{className:"account-popover-action primary",onClick:()=>{O(!1),Ue()},type:"button",children:[r.jsx(Gs,{size:16}),"Sign in with Google"]})]}),r.jsx("section",{className:"desk-stage client-unified-stage",children:V==="support"?r.jsx("section",{className:"client-unified-page",children:r.jsx(Mb,{session:s,currentProductKey:"livedesk",appVersion:t?.appVersion||"",onSignIn:()=>{Ue()}})}):V!=="computer"?r.jsx("section",{className:"client-unified-page",children:r.jsx(mS,{page:V,status:t})}):r.jsx(hS,{session:s,status:t,pin:u,roleChangeMessage:m,videoAccelerationBusy:y,slotInput:N,slotBusy:A,onSignIn:()=>{Ue()},onPinChange:z=>d(z.replace(/\D/g,"").slice(0,6)),onSubmitPin:()=>{nt()},onSlotInputChange:z=>{ge.current=!0,C(z.replace(/\D/g,"").slice(0,3))},onSaveSlot:()=>{ve()},onEnableVideoAcceleration:()=>{De()}})}),I&&r.jsxs("div",{className:`client-side-toast ${I.kind}`,role:I.kind==="error"?"alert":"status",children:[I.kind==="error"?r.jsx(qy,{size:18}):r.jsx(En,{size:18}),r.jsx("span",{children:I.message}),r.jsx("button",{type:"button",onClick:()=>F(null),"aria-label":"Dismiss notification",children:r.jsx(xn,{size:16})})]})]})}function Vs(e,t,n){if(n<0||t<0||t+n>e.length)throw new Error("Invalid LZO1X block: input overrun.")}function Md(e,t,n){let s=0;for(;Vs(e,t.inputIndex,1),e[t.inputIndex]===0;)s+=1,t.inputIndex+=1;const a=s*255+n+e[t.inputIndex];return t.inputIndex+=1,a}function kl(e,t,n,s){if(Vs(e,t.inputIndex,s),t.outputIndex+s>n.length)throw new Error("Invalid LZO1X block: output overrun.");n.set(e.subarray(t.inputIndex,t.inputIndex+s),t.outputIndex),t.inputIndex+=s,t.outputIndex+=s}function gS(e,t,n,s){const a=t-n;if(a<=0||s<=0)throw new Error("Invalid LZO1X block: invalid match distance.");let i=Math.min(a,s);for(e.set(e.subarray(n,n+i),t);i<s;){const c=Math.min(i,s-i);e.copyWithin(t+i,t,t+c),i+=c}return t+s}function jb(e,t){if(!(e instanceof Uint8Array)||e.length<3||t<0)throw new Error("Invalid LZO1X block.");const n=new Uint8Array(t),s={inputIndex:0,outputIndex:0};let a=0,i=0;if(e[s.inputIndex]>=22){const c=e[s.inputIndex]-17;s.inputIndex+=1,kl(e,s,n,c),a=4}else e[s.inputIndex]>=18&&(a=e[s.inputIndex]-17,s.inputIndex+=1,kl(e,s,n,a));for(;;){Vs(e,s.inputIndex,1);const c=e[s.inputIndex];s.inputIndex+=1;let u,d;if((c&192)!==0)Vs(e,s.inputIndex,1),d=s.outputIndex-((e[s.inputIndex]<<3)+(c>>2&7)+1),s.inputIndex+=1,i=(c>>5)+1,u=c&3;else if((c&32)!==0){i=(c&31)+2,i===2&&(i+=Md(e,s,31)),Vs(e,s.inputIndex,2);const p=e[s.inputIndex]|e[s.inputIndex+1]<<8;s.inputIndex+=2,d=s.outputIndex-((p>>2)+1),u=p&3}else if((c&16)!==0){i=(c&7)+2,i===2&&(i+=Md(e,s,7)),Vs(e,s.inputIndex,2);const p=e[s.inputIndex]|e[s.inputIndex+1]<<8;if(s.inputIndex+=2,d=s.outputIndex-(((c&8)<<11)+(p>>2)),u=p&3,d===s.outputIndex)break;d-=16384}else if(a===0){let p=c+3;p===3&&(p+=Md(e,s,15)),kl(e,s,n,p),a=4;continue}else a!==4?(Vs(e,s.inputIndex,1),u=c&3,d=s.outputIndex-((c>>2)+(e[s.inputIndex]<<2)+1),s.inputIndex+=1,i=2):(Vs(e,s.inputIndex,1),u=c&3,d=s.outputIndex-((c>>2)+(e[s.inputIndex]<<2)+2049),s.inputIndex+=1,i=3);if(d<0||s.outputIndex+i+u>n.length)throw new Error("Invalid LZO1X block: lookbehind overrun.");s.outputIndex=gS(n,s.outputIndex,d,i),a=u,kl(e,s,n,u)}if(i!==3||s.inputIndex!==e.length||s.outputIndex!==n.length)throw new Error("Invalid LZO1X block: incomplete output.");return n}const Qh=16,Yh=8,bS=24*1024*1024,Eb=new Uint8Array(new Uint32Array([16909060]).buffer)[0]===4,lp=new Uint32Array(65536);for(let e=0;e<lp.length;e+=1){const t=Math.round((e>>11&31)*255/31),n=Math.round((e>>5&63)*255/63),s=Math.round((e&31)*255/31);lp[e]=Eb?(t|n<<8|s<<16|4278190080)>>>0:(t<<24|n<<16|s<<8|255)>>>0}function Ws(e,t){return e[t]|e[t+1]<<8}function vS(e,t){const n=Number(t);if(!Number.isSafeInteger(n)||n<Qh||n>bS)throw new Error(`Invalid Mode 5 packet length: ${t}.`);const s=e instanceof Uint8Array?e:new Uint8Array(e),a=jb(s,n);if(a[0]!==76||a[1]!==68||a[2]!==53||a[3]!==68)throw new Error("Invalid Mode 5 packet magic.");if(a[4]!==1)throw new Error(`Unsupported Mode 5 packet version: ${a[4]}.`);const i=(a[5]&1)!==0,c=Ws(a,6),u=Ws(a,8),d=Ws(a,10),p=Ws(a,12);if(c<=0||u<=0||c>3840||u>2160)throw new Error(`Invalid Mode 5 frame size: ${c}x${u}.`);if(d<=0||d>256||p>8192)throw new Error(`Invalid Mode 5 tile header: ${d}/${p}.`);const h=[];let m=Qh;for(let g=0;g<p;g+=1){if(m+Yh>a.length)throw new Error("Mode 5 tile header is truncated.");const w=Ws(a,m),v=Ws(a,m+2),y=Ws(a,m+4),k=Ws(a,m+6);m+=Yh;const N=y*k*2;if(y<=0||k<=0||y>d||k>d||w+y>c||v+k>u||m+N>a.length)throw new Error(`Invalid Mode 5 tile ${g}.`);h.push({x:w,y:v,width:y,height:k,pixels:a.subarray(m,m+N)}),m+=N}if(m!==a.length)throw new Error(`Mode 5 packet has ${a.length-m} trailing bytes.`);return{keyFrame:i,width:c,height:u,tileSize:d,tiles:h}}function wS(e,t,n,s){if(!(e instanceof Uint8ClampedArray)||e.length!==t*n*4||s.width!==t||s.height!==n)throw new Error("Mode 5 canvas state does not match the packet dimensions.");let a=t,i=n,c=0,u=0;const d=new Uint32Array(e.buffer,e.byteOffset,e.byteLength>>>2);for(const p of s.tiles){const h=Eb&&(p.pixels.byteOffset&1)===0?new Uint16Array(p.pixels.buffer,p.pixels.byteOffset,p.pixels.byteLength>>>1):null;let m=0;for(let g=0;g<p.height;g+=1){let w=(p.y+g)*t+p.x;for(let v=0;v<p.width;v+=1){const y=m<<1,k=h?h[m]:p.pixels[y]|p.pixels[y+1]<<8;d[w]=lp[k],m+=1,w+=1}}a=Math.min(a,p.x),i=Math.min(i,p.y),c=Math.max(c,p.x+p.width),u=Math.max(u,p.y+p.height)}return s.tiles.length>0?{x:a,y:i,width:c-a,height:u-i}:null}function yS(e){if(!e)return!0;const t=Vt.get(e);return!t||t.hardwareAcceleration==="prefer-hardware"}const Vt=new WeakMap,Xh=854,Jh=480,xS=3840,SS=2160,CS=500,ac=new WeakMap,up=new WeakMap,Xa=new Set,Va=new Set,Zs=new WeakMap,Ga=new Set,no=new WeakMap,dp=new WeakMap,pp=new WeakMap,su=new WeakMap,Fb=4,kS=2,Qi=4,MS=2,AS=2,NS=18,RS=0,TS=250,Db=80,PS=5,IS=150,jS=1200,ES=18,FS=.65,Lb=80,_b=125,DS=4,LS=2*1024*1024,_S=8,$S=16,OS=180,BS=3,_p=2e3,$b=64,Ob=32*1024*1024,HS=500,WS=25,zS=45,qS=20,Bb=new Uint8Array(0),$p=250,US=globalThis.LIVEDESK_ENABLE_CANVAS_VISUAL_SAMPLING===!0;let Hb=1,Wb=0,zb=0,mp=0,qb=0;const Vo=[];let lc=0,Ub=0,Vb,Gb=0,Kb,Qb;function uc(e,t){Vo.push({sequence:++qb,type:e,canvasId:no.get(t)||0,observedAt:Date.now(),activeDecoderCount:Xa.size,hardwareLeaseCount:Va.size,hardwareReleaseGeneration:lc}),Vo.length>256&&Vo.splice(0,Vo.length-256)}let Ts={h264DecodeAcceleration:"prefer-hardware"};function VS(e){e.h264DecodeAcceleration&&(Ts={...Ts,h264DecodeAcceleration:e.h264DecodeAcceleration})}function GS(e){return e.payload.byteLength===0?e:{...e,payload:Bb}}function Yb(e,t){const n=String(e.streamPurpose||"").trim().toLowerCase();return n==="wall"?!0:n==="control"?!1:t>=45e3}function Xb(e){try{return e.paintIsCancelled()}catch{return!0}}function yu(e,t){const n=e.pendingFrames.get(t);if(n)return e.pendingFrames.delete(t),e.pendingFrameBytes=Math.max(0,e.pendingFrameBytes-n.encodedByteLength),e.pendingFrames.size===0&&e.pendingTrimTimer!==null&&(window.clearTimeout(e.pendingTrimTimer),e.pendingTrimTimer=null),n}function KS(e){const t=e.pendingFrames.entries().next().value;return t?yu(e,t[0]):void 0}function Jb(e){e.pendingTrimTimer!==null&&(window.clearTimeout(e.pendingTrimTimer),e.pendingTrimTimer=null),e.pendingFrames.clear(),e.pendingFrameBytes=0,e.pendingFrameEvictedThroughTimestamp=-1}function xu(e,t=performance.now()){for(;e.pendingFrames.size>0;){const n=e.pendingFrames.entries().next().value;if(!n)break;const s=t-n[1].queuedAt>_p,a=e.pendingFrames.size>$b,i=e.pendingFrameBytes>Ob;if(!s&&!a&&!i)break;e.pendingFrameEvictedThroughTimestamp=Math.max(e.pendingFrameEvictedThroughTimestamp,n[0]),yu(e,n[0]),e.pendingFrameEvictionCount+=1}}function QS(e,t,n,s,a,i=performance.now()){yu(e,t);const c={frame:n,queuedAt:i,queueSize:s,encodedByteLength:Math.max(0,Math.floor(Number(n.payload.byteLength||0))),paintIsCancelled:a};e.pendingFrames.set(t,c),e.pendingFrameBytes+=c.encodedByteLength,xu(e,i),e.pendingFrameHighWaterMark=Math.max(e.pendingFrameHighWaterMark,e.pendingFrames.size),e.pendingFrameByteHighWaterMark=Math.max(e.pendingFrameByteHighWaterMark,e.pendingFrameBytes)}function Zb(e,t){if(t.pendingTrimTimer!==null||t.pendingFrames.size===0)return;const n=t.pendingFrames.values().next().value;if(!n)return;const s=Math.max(1,_p-(performance.now()-n.queuedAt)+1);t.pendingTrimTimer=window.setTimeout(()=>{t.pendingTrimTimer=null,Vt.get(e)===t&&(xu(t),Zb(e,t))},s)}function ev(e){return Va.delete(e)?(lc+=1,uc("hardware-release",e),!0):!1}function YS(e,t,n){if(t!=="prefer-hardware"||!n)return!1;const s=Zs.get(e);return!s||s.requested!==t||s.actual!=="prefer-software"||lc<=s.failedHardwareReleaseGeneration?!1:(Zs.delete(e),Ga.delete(e),Ub+=1,Vb=Date.now(),!0)}function hp(e,t=Ts.h264DecodeAcceleration){const n=Zs.get(e);return n?.requested===t?(n.actual!=="prefer-hardware"&&(Va.delete(e),Ga.add(e)),n.actual):(n&&(Zs.delete(e),Ga.delete(e)),t!=="prefer-hardware"?(ev(e),Ga.delete(e),t):(Va.has(e)||Va.add(e),"prefer-hardware"))}function Su(e,t,n){if(t!=="prefer-hardware")return!1;const s=Zs.get(e),a=Vt.get(e),i=Date.now();return no.has(e)||no.set(e,Hb++),Zs.set(e,{requested:t,actual:"prefer-software",reason:n,failedAt:i,failureCount:(s?.requested===t?s.failureCount:0)+1,codec:a?.codec||s?.codec||"",latencyMode:a?.latencyMode||s?.latencyMode||"smooth",inputCount:a?.inputSerial??s?.inputCount??0,outputCount:a?.outputSerial??s?.outputCount??0,lastInputAt:a?.lastInputAt??s?.lastInputAt??0,lastOutputAt:a?.lastOutputAt??s?.lastOutputAt??0,lastPaintAt:a?.lastPaintAt??s?.lastPaintAt??0,decodeQueueHighWaterMark:Math.max(a?.decodeQueueHighWaterMark??0,s?.decodeQueueHighWaterMark??0),decodeQueueOverflowSamples:Math.max(a?.decodeQueueOverflowSamples??0,s?.decodeQueueOverflowSamples??0),decodeQueueOverflowAgeMs:a?.decodeQueueOverflowStartedAt?Math.max(0,performance.now()-a.decodeQueueOverflowStartedAt):s?.decodeQueueOverflowAgeMs,failedHardwareReleaseGeneration:lc}),Va.delete(e),Ga.add(e),Gb+=1,Kb=n,Qb=i,!0}function ea(e){e.interactivePipelineFallbackTimer!==null&&(window.clearTimeout(e.interactivePipelineFallbackTimer),e.interactivePipelineFallbackTimer=null),e.interactivePipelineFallbackFrame!==null&&(window.cancelAnimationFrame(e.interactivePipelineFallbackFrame),e.interactivePipelineFallbackFrame=null),e.interactivePipelineRecoveryFrames=[],e.interactivePipelineRecoveryBytes=0,e.interactivePipelinePaintIsCancelled=void 0,e.interactivePipelineGuardTimestampUs=null}function tv(e,t){const n=t.interactivePipelineRecoveryFrames,s=t.interactivePipelinePaintIsCancelled,a=t.onBeforePaint,i=t.onPaint;if(ea(t),n.length===0||s?.()||Vt.get(e)!==t||t.hardwareAcceleration!=="prefer-hardware"||!Su(e,t.requestedAcceleration,"interactive-pipeline-latency"))return!1;const c=t.requestedAcceleration,u=t.latencyMode;er(e);try{for(const d of n)Bp(e,d,i,c,u,s,!1,a)}catch{er(e)}return!0}function XS(e,t,n){const s=Math.max(0,Number(t.payload.byteLength||0));return e.interactivePipelineRecoveryFrames.length>=DS||e.interactivePipelineRecoveryBytes+s>LS?(ea(e),!1):(e.interactivePipelineRecoveryFrames.push({...t,payload:t.payload.slice()}),e.interactivePipelineRecoveryBytes+=s,e.interactivePipelinePaintIsCancelled=n,!0)}function JS(e,t,n,s,a=performance.now()){const i=()=>{if(!(Vt.get(e)!==t||t.interactivePipelineGuardTimestampUs!==n)){if(!t.pendingFrames.has(n)){ea(t);return}tv(e,t)}},c=u=>{if(t.interactivePipelineFallbackFrame=null,!(Vt.get(e)!==t||t.interactivePipelineGuardTimestampUs!==n)){if(!t.pendingFrames.has(n)){ea(t);return}if(u-a>=s){i();return}t.interactivePipelineFallbackFrame=window.requestAnimationFrame(c)}};t.interactivePipelineFallbackTimer=window.setTimeout(i,s),t.interactivePipelineFallbackFrame=window.requestAnimationFrame(c)}function ZS(e,t,n,s=64){try{let a=dp.get(e);a||(a={canvas:document.createElement("canvas"),lastHash:"",initialized:!1},dp.set(e,a));const i=Math.max(8,Math.min(64,Math.round(s))),c=Math.max(1,Math.round(i*Math.max(1,n)/Math.max(1,t)));(a.canvas.width!==i||a.canvas.height!==c)&&(a.canvas.width=i,a.canvas.height=c);const u=a.canvas.getContext("2d",{willReadFrequently:!0});if(!u)return{visualHash:"",visualChanged:!0};u.drawImage(e,0,0,Math.max(1,t),Math.max(1,n),0,0,i,c);const d=u.getImageData(0,0,i,c).data;let p=2166136261;for(let g=0;g<d.length;g+=4)p^=d[g],p=Math.imul(p,16777619),p^=d[g+1],p=Math.imul(p,16777619),p^=d[g+2],p=Math.imul(p,16777619);const h=(p>>>0).toString(16).padStart(8,"0"),m=!a.initialized||h!==a.lastHash;return a.initialized=!0,a.lastHash=h,{visualHash:h,visualChanged:m}}catch{return{visualHash:"",visualChanged:!0}}}function fp(e,t,n,s=$p,a=64,i){if(!US&&i)return nv(e,i);let c=pp.get(e);c||(c={lastHash:"",initialized:!1,lastCanvasSampleAt:0},pp.set(e,c));const u=performance.now();if(c.initialized&&s>0&&u-c.lastCanvasSampleAt<s)return{visualHash:c.lastHash,visualChanged:!1};const d=ZS(e,t,n,a);return c.initialized=!0,c.lastHash=d.visualHash,c.lastCanvasSampleAt=u,d}function nv(e,t){let n=su.get(e);n||(n={lastHash:"",initialized:!1},su.set(e,n));const s=String(t.contentHash||""),a=!n.initialized||!s||s!==n.lastHash;return n.initialized=!0,n.lastHash=s,{visualHash:s,visualChanged:a}}function rv(e,t,n=!1){const s=up.get(e);if(s)return s;const a=e.getContext("2d",{alpha:!1,desynchronized:t==="interactive",willReadFrequently:n});if(a){const i=a.getContextAttributes?.(),c={context:a,presentation:i?.desynchronized?"desync":"sync"};return up.set(e,c),c}return null}function eC(e){const t=String(e.frameMode||e.mode||"").toLowerCase(),n=String(e.compression||"").toLowerCase(),s=String(e.mimeType||"").toLowerCase();return t==="mode2-lzo"||n==="lzo1x"||s==="application/vnd.livedesk.lzo-rgb565"||t==="mode2-lz4"||String(e.compression||"").toLowerCase()==="lz4"||s==="application/vnd.livedesk.lz4-raw"}function tC(e){return String(e.frameMode||e.mode||"").toLowerCase()==="mode3-h264-hw"||String(e.codec||"").toLowerCase()==="h264"||String(e.mimeType||"").toLowerCase()==="video/h264"}function nC(e){const t=String(e.frameMode||e.mode||"").toLowerCase(),n=String(e.mimeType||"").toLowerCase();return t==="mode5-lzo-delta"||n==="application/vnd.livedesk.lzo-rgb565-delta"}function Zh(e,t,n){let s=n,a=t;if(s===15){let i=255;for(;i===255;){if(a>=e.length)throw new Error("Invalid LZ4 block: length overrun.");i=e[a],a+=1,s+=i}}return{length:s,cursor:a}}function rC(e,t){const n=new Uint8Array(t);let s=0,a=0;for(;s<e.length;){const i=e[s];s+=1;const c=Zh(e,s,i>>4);s=c.cursor;const u=c.length;if(s+u>e.length||a+u>n.length)throw new Error("Invalid LZ4 block: literal overrun.");if(n.set(e.subarray(s,s+u),a),s+=u,a+=u,s>=e.length)break;if(s+2>e.length)throw new Error("Invalid LZ4 block: missing offset.");const d=e[s]|e[s+1]<<8;if(s+=2,d<=0||d>a)throw new Error("Invalid LZ4 block: bad match offset.");const p=Zh(e,s,i&15);s=p.cursor;const h=p.length+4;if(a+h>n.length)throw new Error("Invalid LZ4 block: match overrun.");let m=a-d;for(let g=0;g<h;g+=1)n[a]=n[m],a+=1,m+=1}if(a!==n.length)throw new Error("Invalid LZ4 block: incomplete output.");return n}function sC(e){const t=Math.max(1,Math.floor(e.width||0)),n=Math.max(1,Math.floor(e.height||0)),s=String(e.compression||"").toLowerCase(),a=String(e.pixelFormat||e.codec||"").toLowerCase();if(s==="lzo1x"||String(e.frameMode||e.mode||"").toLowerCase()==="mode2-lzo"||String(e.mimeType||"").toLowerCase()==="application/vnd.livedesk.lzo-rgb565"){const h=Math.max(1,Math.floor(e.bytesPerPixel||2)),m=t*n*2,g=Math.floor(e.uncompressedByteLength||m);if(h!==2||g!==m)throw new Error(`Invalid mode2 RGB565 frame size: ${g} for ${t}x${n}.`);if(a&&a!=="rgb565le"&&a!=="rgb565")throw new Error(`Unsupported mode2 pixel format: ${a}`);const w=jb(e.payload,m),v=new Uint8ClampedArray(t*n*4);for(let y=0,k=0;y<w.length;y+=2,k+=4){const N=w[y]|w[y+1]<<8,C=N>>11&31,A=N>>5&63,E=N&31;v[k]=C<<3|C>>2,v[k+1]=A<<2|A>>4,v[k+2]=E<<3|E>>2,v[k+3]=255}return new ImageData(v,t,n)}const c=Math.max(1,Math.floor(e.bytesPerPixel||4)),u=Math.max(t*n*c,Math.floor(e.uncompressedByteLength||0)),d=rC(e.payload,u);if(c!==4)throw new Error(`Unsupported mode2 pixel size: ${c}`);const p=new Uint8ClampedArray(t*n*4);if(a==="rgba32"||a==="rgba")p.set(d.subarray(0,p.length));else for(let h=0,m=0;m<p.length;h+=4,m+=4)p[m]=d[h+2],p[m+1]=d[h+1],p[m+2]=d[h],p[m+3]=d[h+3];return new ImageData(p,t,n)}function ef(e,t="smooth",n=Ts.h264DecodeAcceleration){const s=window.VideoDecoder;if(!s||!window.EncodedVideoChunk)throw new Error("WebCodecs H.264 decode is not supported in this browser.");const a=Vt.get(e);if(a&&a.decoder.state!=="closed"&&a.latencyMode===t)return a;a&&er(e);let i;const c=new s({output:u=>{if(Vt.get(e)!==i){u.close();return}const d=Number(u.timestamp||0),p=performance.now();i.outputSerial+=1,xu(i,p);let h=yu(i,d);if(!h&&d>i.pendingFrameEvictedThroughTimestamp&&i.pendingFrames.size>0&&(h=KS(i),i.timestampFallbacks+=1),!h){i.pendingFrameUnmatchedOutputCount+=1,i.droppedForLatency+=1,i.lastOutputAt=p,u.close();return}const m=i.interactivePipelineGuardTimestampUs===d;if(Xb(h)){m&&ea(i),i.droppedForLatency+=1,i.lastOutputAt=p,u.close();return}const g=u.displayWidth||u.codedWidth||e.width||960,w=u.displayHeight||u.codedHeight||e.height||540,v=Number(h?.frame.durationUs||0),y=Number(u.duration||0),k=Math.max(16,Math.min(250,(v>0?v:y||83333)/1e3));i.targetPaintIntervalMs=k;const N=Math.max(0,p-h.queuedAt),A=Yb(h.frame,v>0?v:Math.round(k*1e3))?_b:Lb;if(i.latencyMode==="interactive"&&i.hardwareAcceleration==="prefer-hardware"&&m&&i.interactivePipelineRecoveryFrames.length>0&&N>A){u.close(),i.droppedForLatency+=1,tv(e,i);return}m&&ea(i),Math.abs(i.interactiveBurstOutputCadenceMs-k)>1&&(i.interactiveBurstOutputTimeCursor=0,i.interactiveBurstOutputTimeCount=0,i.interactiveBurstOutputCadenceMs=k,i.interactiveBurstOutputWindowMs=0),i.interactiveBurstOutputTimes[i.interactiveBurstOutputTimeCursor]=p,i.interactiveBurstOutputTimeCursor=(i.interactiveBurstOutputTimeCursor+1)%Qi,i.interactiveBurstOutputTimeCount=Math.min(Qi,i.interactiveBurstOutputTimeCount+1);const E=i.interactiveBurstOutputTimeCount>=Qi?p-i.interactiveBurstOutputTimes[i.interactiveBurstOutputTimeCursor]:0;for(i.interactiveBurstOutputWindowMs=Math.max(0,E),i.decodedFrames.push({videoFrame:u,pending:h,decodedAt:p,width:g,height:w,durationMs:k}),i.latencyMode==="interactive"&&i.targetPaintIntervalMs>20&&i.interactiveBurstOutputTimeCount>=Qi&&E<=Math.min(zS,Math.max(WS,i.targetPaintIntervalMs-5))&&(i.interactiveBurstTailHoldArmed=!0),i.lastOutputAt=p;i.decodedFrames.length>Op(i);)au(i,i.decodedFrames.shift(),"capacity");i.renderQueueHighWaterMark=Math.max(i.renderQueueHighWaterMark,i.decodedFrames.length),av(i),i.renderTimer!==null&&i.renderScheduledAt>0&&performance.now()-i.renderScheduledAt>HS&&(typeof document>"u"||document.visibilityState==="visible")&&(window.cancelAnimationFrame(i.renderTimer),i.renderTimer=null,i.renderScheduledAt=0),i.renderTimer!==null&&i.decodedFrames.length>=Fb&&(window.cancelAnimationFrame(i.renderTimer),i.renderTimer=null,i.renderScheduledAt=0),iu(e,i)},error:()=>{Vt.get(e)===i&&(Su(e,i.requestedAcceleration,"decoder-error"),er(e))}});return Wb+=1,no.has(e)||no.set(e,Hb++),i={decoder:c,configured:!1,configKey:"",codec:"",requestedAcceleration:n,hardwareAcceleration:hp(e,n),latencyMode:t,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,interactiveBurstTailHoldArmed:!1,interactiveBurstTailHoldCount:0,interactiveBurstOutputTimes:new Float64Array(Qi),interactiveBurstOutputTimeCursor:0,interactiveBurstOutputTimeCount:0,interactiveBurstOutputCadenceMs:0,interactiveBurstOutputWindowMs:0,interactivePipelineFallbackTimer:null,interactivePipelineFallbackFrame:null,interactivePipelineGuardTimestampUs:null,interactivePipelineRecoveryFrames:[],interactivePipelineRecoveryBytes:0,interactivePipelinePaintIsCancelled:void 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},Vt.set(e,i),Xa.add(e),mp=Math.max(mp,Xa.size),uc("create",e),i}function sv(e){ea(e),e.renderTimer!==null&&(window.cancelAnimationFrame(e.renderTimer),e.renderTimer=null),e.renderScheduledAt=0,e.flushTimer!==null&&(window.clearTimeout(e.flushTimer),e.flushTimer=null),e.flushInFlight=!1;const t=e.decodedFrames;e.decodedFrames=[];for(const n of t)try{n.videoFrame.close()}catch{}e.interactiveBufferPrimed=!1,e.interactiveBufferStartedAt=0,e.interactiveBurstTailHoldArmed=!1,e.interactiveBurstOutputTimeCursor=0,e.interactiveBurstOutputTimeCount=0,e.interactiveBurstOutputCadenceMs=0,e.interactiveBurstOutputWindowMs=0}function au(e,t,n="other"){t&&(t.videoFrame.close(),e.droppedForLatency+=1,n==="capacity"?e.renderQueueCapacityDropCount+=1:n==="age"&&(e.renderQueueAgeDropCount+=1))}function Op(e){return e.latencyMode==="interactive"?e.targetPaintIntervalMs<=20?MS:Qi:String(e.decodedFrames[0]?.pending?.frame.frameMode||e.decodedFrames[0]?.pending?.frame.mode||"").toLowerCase()==="mode4-h264-atlas"?kS:Fb}function av(e,t=performance.now()){const n=Op(e);for(;e.decodedFrames.length>n;)au(e,e.decodedFrames.shift(),"capacity");const s=e.latencyMode==="interactive"?Db:TS;let a=e.decodedFrames[0];for(;e.decodedFrames.length>0&&a&&t-a.decodedAt>s;)au(e,e.decodedFrames.shift(),"age"),a=e.decodedFrames[0]}function iv(e,t){if(t.hardwareAcceleration!=="prefer-hardware"||t.latencyMode==="interactive"||t.flushTimer!==null||t.flushInFlight)return;const n=IS;t.flushTimer=window.setTimeout(async()=>{t.flushTimer=null;const s=performance.now();if(xu(t,s),Vt.get(e)!==t||t.decoder.state!=="configured"||t.pendingFrames.size===0||t.inputSerial<=t.lastFlushInputSerial||t.lastOutputAt>0&&s-t.lastOutputAt<n)return;const a=t.inputSerial;t.flushInFlight=!0,t.flushCount+=1,t.keyFrameSeen=!1;try{await t.decoder.flush(),t.lastFlushInputSerial=Math.max(t.lastFlushInputSerial,a)}catch{Vt.get(e)===t&&Kl(t)}finally{t.flushInFlight=!1,Vt.get(e)===t&&t.inputSerial>a&&t.pendingFrames.size>0&&performance.now()-t.lastOutputAt>=n&&iv(e,t)}},n)}function aC(e,t,n,s){const a=performance.now();if(t.interactiveBackingWidth>0&&t.interactiveBackingHeight>0&&a-t.interactiveBackingMeasuredAt<CS)return{width:Math.min(n,t.interactiveBackingWidth),height:Math.min(s,t.interactiveBackingHeight)};const i=typeof e.getBoundingClientRect=="function"?e.getBoundingClientRect():{width:Number(e.clientWidth||e.width||0),height:Number(e.clientHeight||e.height||0)},c=Math.max(1,Math.min(2,Number(globalThis.devicePixelRatio)||1)),u=Math.max(0,Number(e.width||0)),d=Math.max(0,Number(e.height||0)),p=i.width>0?Math.round(i.width*c):u||Xh,h=i.height>0?Math.round(i.height*c):d||Jh,m=Math.min(1,p/n,h/s),g=Math.min(1,Math.max(Xh/n,Jh/s)),w=Math.min(1,xS/n,SS/s),v=Math.max(.01,Math.min(w,Math.max(g,m)));return t.interactiveBackingWidth=Math.max(1,Math.round(n*v)),t.interactiveBackingHeight=Math.max(1,Math.round(s*v)),t.interactiveBackingMeasuredAt=a,{width:t.interactiveBackingWidth,height:t.interactiveBackingHeight}}function tf(e,t,n){const s=performance.now();try{if(!n.pending||Xb(n.pending)){t.droppedForLatency+=1;return}let a=1;try{const h=t.onBeforePaint?.(n.pending.frame);typeof h=="number"&&Number.isFinite(h)&&(a=Math.max(.05,Math.min(1,h)))}catch{}const i=t.latencyMode==="interactive"?aC(e,t,n.width,n.height):{width:n.width,height:n.height},c=i.width,u=i.height,d=e.width!==c||e.height!==u;d&&(e.width=c,e.height=u);const p=rv(e,t.latencyMode,t.hardwareAcceleration==="prefer-software");if(p){const h=p.context.globalAlpha;p.context.globalAlpha=d||t.lastPaintAt<=0||t.hardwareAcceleration!=="prefer-hardware"?1:a;try{p.context.drawImage(n.videoFrame,0,0,n.width,n.height,0,0,c,u)}finally{p.context.globalAlpha=h}}if(n.pending){const h=performance.now(),g=t.latencyMode==="interactive"?nv(e,n.pending.frame):fp(e,n.width,n.height,$p,64,n.pending.frame),w=GS(n.pending.frame);try{t.onPaint?.(w,{deviceId:w.deviceId,frameSeq:w.frameSeq,mode:w.frameMode||w.mode||w.codec||w.mimeType,width:n.width,height:n.height,byteLength:w.byteLength,queuedForMs:Math.max(0,s-n.pending.queuedAt),decodedForMs:Math.max(0,n.decodedAt-n.pending.queuedAt),scheduledForMs:Math.max(0,s-n.decodedAt),drawMs:Math.max(0,h-s),queueSize:n.pending.queueSize,renderQueueSize:t.decodedFrames.length,droppedForLatency:t.droppedForLatency,h264DecodeAcceleration:t.hardwareAcceleration,decoderLabel:t.hardwareAcceleration,decoderFlushCount:t.flushCount,decoderTimestampFallbacks:t.timestampFallbacks,decoderInputCount:t.inputSerial,decoderOutputCount:t.outputSerial,targetPaintIntervalMs:t.targetPaintIntervalMs,canvasPresentation:p?.presentation||"sync",interactiveBufferWaitCount:t.interactiveBufferWaitCount,interactiveBufferWaitMs:t.interactiveBufferWaitMs,interactiveQueueDrainCount:t.interactiveQueueDrainCount,interactiveBurstOutputWindowMs:t.interactiveBurstOutputWindowMs,interactiveBurstTailHoldCount:t.interactiveBurstTailHoldCount,visualHash:g.visualHash,visualChanged:g.visualChanged,paintedAt:h})}catch{}}t.lastPaintAt=performance.now()}finally{n.videoFrame.close()}}function iu(e,t){if(t.renderTimer!==null||t.decodedFrames.length===0)return;const n=Math.max(16,Math.min(250,t.targetPaintIntervalMs||1e3/12)),s=()=>{if(t.renderTimer=null,t.renderScheduledAt=0,t.decodedFrames.length===0)return;const a=performance.now();if(av(t,a),t.decodedFrames.length===0){t.interactiveBurstTailHoldArmed=!1;return}if(t.latencyMode==="interactive"){const d=t.targetPaintIntervalMs<=20;if(d&&!t.interactiveBufferPrimed){t.interactiveBufferStartedAt<=0&&(t.interactiveBufferStartedAt=a,t.interactiveBufferWaitCount+=1);const h=t.decodedFrames.length>=AS,m=a-t.interactiveBufferStartedAt>=NS;if(!h&&!m){t.renderScheduledAt=performance.now(),t.renderTimer=window.requestAnimationFrame(s);return}t.interactiveBufferWaitMs+=Math.max(0,a-t.interactiveBufferStartedAt),t.interactiveBufferPrimed=!0}else d||(t.interactiveBufferPrimed=!0);if(!d&&t.interactiveBurstTailHoldArmed&&t.decodedFrames.length===1&&a-t.decodedFrames[0].decodedAt<=Db-qS){t.interactiveBurstTailHoldArmed=!1,t.interactiveBurstTailHoldCount+=1,t.renderScheduledAt=performance.now(),t.renderTimer=window.requestAnimationFrame(s);return}const p=t.decodedFrames.shift();if(p)try{tf(e,t,p)}catch{}t.decodedFrames.length===0&&(t.interactiveQueueDrainCount+=1,t.interactiveBufferPrimed=!1,t.interactiveBufferStartedAt=0,t.interactiveBurstTailHoldArmed=!1),iu(e,t);return}const i=t.lastPaintAt>0?t.lastPaintAt+n:a+RS;if(!(a+PS>=i||t.decodedFrames.length>=Math.max(1,Op(t)-1))){t.renderScheduledAt=performance.now(),t.renderTimer=window.requestAnimationFrame(s);return}const u=t.decodedFrames.shift();if(u)try{tf(e,t,u)}catch{}iu(e,t)};t.renderScheduledAt=performance.now(),t.renderTimer=window.requestAnimationFrame(s)}function ov(e,t){if(Vt.get(e)!==t||t.decoder.state==="closed")return!1;for(t.renderTimer!==null&&(window.cancelAnimationFrame(t.renderTimer),t.renderTimer=null),t.renderScheduledAt=0;t.decodedFrames.length>1;)au(t,t.decodedFrames.shift());return t.lastPaintAt=0,t.interactiveBufferPrimed=!1,t.interactiveBufferStartedAt=0,t.interactiveBurstTailHoldArmed=!1,t.interactiveBurstOutputTimeCursor=0,t.interactiveBurstOutputTimeCount=0,t.interactiveBurstOutputCadenceMs=0,t.interactiveBurstOutputWindowMs=0,iu(e,t),!0}function Ad(){if(!(typeof document>"u"||document.visibilityState!=="visible"))for(const e of Xa){const t=Vt.get(e);if(!t||t.decoder.state==="closed"){Xa.delete(e);continue}ov(e,t)}}typeof document<"u"&&typeof window<"u"&&(document.addEventListener("visibilitychange",Ad),window.addEventListener("focus",Ad),window.addEventListener("pageshow",Ad));function er(e){ev(e),Xa.delete(e),su.delete(e);const t=Vt.get(e);if(t){Vt.delete(e),zb+=1,Jb(t),t.onBeforePaint=void 0,t.onPaint=void 0,sv(t);try{t.decoder.state!=="closed"&&t.decoder.reset()}catch{}try{t.decoder.state!=="closed"&&t.decoder.close()}catch{}uc("close",e)}}function Wi(e){e&&(Zs.delete(e),Ga.delete(e),up.delete(e),pp.delete(e),dp.delete(e),su.delete(e),ac.delete(e),er(e))}function iC(e,t){const n=Vt.get(e),s=Zs.get(e);if(!n&&!s)return null;const a=c=>c>0?Math.max(0,t-c):void 0,i=n?.pendingFrames.values().next().value;return{canvasId:no.get(e)||0,canvasWidth:Math.max(0,Number(e.width||0)),canvasHeight:Math.max(0,Number(e.height||0)),decoderState:n?.decoder.state||"fallback-pending",configured:n?.configured||!1,keyFrameSeen:n?.keyFrameSeen||!1,codec:n?.codec||s?.codec||"",requestedAcceleration:n?.requestedAcceleration||s?.requested||Ts.h264DecodeAcceleration,configuredAcceleration:n?.hardwareAcceleration||s?.actual||Ts.h264DecodeAcceleration,latencyMode:n?.latencyMode||s?.latencyMode||"smooth",decodeQueueSize:Math.max(0,Number(n?.decoder.decodeQueueSize||0)),decodeQueueHighWaterMark:Math.max(0,Number(n?.decodeQueueHighWaterMark??0),Number(s?.decodeQueueHighWaterMark??0)),decodeQueueOverflowSamples:Math.max(0,Number(n?.decodeQueueOverflowSamples??0),Number(s?.decodeQueueOverflowSamples??0)),decodeQueueOverflowAgeMs:n?.decodeQueueOverflowStartedAt?Math.max(0,t-n.decodeQueueOverflowStartedAt):s?.decodeQueueOverflowAgeMs,pendingFrameCount:n?.pendingFrames.size||0,pendingFrameBytes:n?.pendingFrameBytes||0,pendingFrameHighWaterMark:n?.pendingFrameHighWaterMark||0,pendingFrameByteHighWaterMark:n?.pendingFrameByteHighWaterMark||0,pendingFrameEvictionCount:n?.pendingFrameEvictionCount||0,pendingFrameUnmatchedOutputCount:n?.pendingFrameUnmatchedOutputCount||0,pendingFrameOldestAgeMs:i?Math.max(0,t-i.queuedAt):void 0,pendingFrameMaxCount:$b,pendingFrameMaxBytes:Ob,pendingFrameMaxAgeMs:_p,renderQueueSize:n?.decodedFrames.length||0,renderQueueHighWaterMark:n?.renderQueueHighWaterMark||0,renderQueueCapacityDropCount:n?.renderQueueCapacityDropCount||0,renderQueueAgeDropCount:n?.renderQueueAgeDropCount||0,interactiveBurstTailHoldCount:n?.interactiveBurstTailHoldCount||0,interactiveBurstOutputWindowMs:Math.max(0,Number(n?.interactiveBurstOutputWindowMs||0)),interactivePipelineRecoveryBytes:Math.max(0,Number(n?.interactivePipelineRecoveryBytes||0)),targetPaintIntervalMs:Math.max(0,Number(n?.targetPaintIntervalMs||0)),droppedForLatency:Math.max(0,Number(n?.droppedForLatency||0)),inputCount:n?.inputSerial??s?.inputCount??0,outputCount:n?.outputSerial??s?.outputCount??0,lastInputAgeMs:a(n?.lastInputAt??s?.lastInputAt??0),lastOutputAgeMs:a(n?.lastOutputAt??s?.lastOutputAt??0),lastPaintAgeMs:a(n?.lastPaintAt??s?.lastPaintAt??0),softwareFallbackReason:s?.reason,softwareFallbackAt:s?.failedAt,softwareFallbackCount:s?.failureCount||0}}function Ml(e,t={}){const n=performance.now(),a=(e?[e]:[...new Set([...Xa,...Ga])]).map(u=>iC(u,n)).filter(u=>u!==null),i=a.reduce((u,d)=>u+d.pendingFrameCount,0),c=a.reduce((u,d)=>u+d.pendingFrameBytes,0);return{capturedAt:Date.now(),hardwareRequestPolicy:"all-active",activeDecoderCount:a.filter(u=>u.decoderState!=="fallback-pending").length,hardwareLeaseCount:Va.size,hardwareReleaseGeneration:lc,hardwareRecoveryProbeCount:Ub,lastHardwareRecoveryProbeAt:Vb,activeSoftwareFallbackCount:a.filter(u=>u.configuredAcceleration==="prefer-software"&&u.requestedAcceleration==="prefer-hardware").length,decoderCreateCount:Wb,decoderCloseCount:zb,activeDecoderHighWaterMark:mp,decoderLifecycleSequence:qb,decoderLifecycleEvents:t.includeLifecycleEvents===!1?[]:Vo.map(u=>({...u})),softwareFallbackEventCount:Gb,lastSoftwareFallbackReason:Kb,lastSoftwareFallbackAt:Qb,pendingFrameCount:i,pendingFrameBytes:c,canvases:a}}function Kl(e,t=1){try{e.decoder.state!=="closed"&&e.decoder.reset()}catch{}e.configured=!1,e.configKey="",e.keyFrameSeen=!1,Jb(e),sv(e),e.lastPaintAt=0,e.lastOutputAt=0,e.lastInputAt=0,e.interactiveBufferPrimed=!1,e.interactiveBufferStartedAt=0,e.lastInputFrameSeq=void 0,e.nextChunkTimestampUs=0,e.healthSampleStartedAt=performance.now(),e.healthInputSerial=e.inputSerial,e.healthOutputSerial=e.outputSerial,e.decodeQueueOverflowStartedAt=0,e.decodeQueueOverflowSamples=0,e.droppedForLatency+=Math.max(1,Math.min(1e4,Math.floor(t)))}function oC(e,t,n=performance.now()){const s=Math.max(0,Number.isFinite(t)?t:0);if(e.decodeQueueHighWaterMark=Math.max(e.decodeQueueHighWaterMark,s),s<=_S)return e.decodeQueueOverflowStartedAt=0,e.decodeQueueOverflowSamples=0,!1;e.decodeQueueOverflowStartedAt<=0?(e.decodeQueueOverflowStartedAt=n,e.decodeQueueOverflowSamples=1):e.decodeQueueOverflowSamples+=1;const a=Math.max(0,n-e.decodeQueueOverflowStartedAt);return s>=$S||e.decodeQueueOverflowSamples>=BS&&a>=OS}function cC(e,t,n,s,a,i){t.decoder.configure(n),t.configured=!0,t.configKey=s,t.codec=n.codec,t.requestedAcceleration=i,t.hardwareAcceleration=a,t.keyFrameSeen=!1,t.nextChunkTimestampUs=0,t.lastInputFrameSeq=void 0,uc("configure",e)}function lC(e,t){if(t.latencyMode!=="interactive"||t.hardwareAcceleration!=="prefer-hardware")return!1;const n=performance.now();if(n-t.healthSampleStartedAt<jS)return!1;const s=t.inputSerial-t.healthInputSerial,a=t.outputSerial-t.healthOutputSerial;return t.healthSampleStartedAt=n,t.healthInputSerial=t.inputSerial,t.healthOutputSerial=t.outputSerial,s<ES||a/Math.max(1,s)>=FS?!1:(Su(e,t.requestedAcceleration,"interactive-health"),er(e),!0)}function zi(e,t=1){if(!e)return!1;const n=Vt.get(e);return n?(n.droppedForLatency+=Math.max(1,Math.min(1e4,Math.floor(t))),er(e),!0):!1}function uC(e){if(!e)return!1;const t=Vt.get(e);return t?ov(e,t):!1}function dC(e,t,n,s="interactive",a){er(e);const i=performance.now(),c=vS(t.payload,t.uncompressedByteLength||0),u=String(t.streamId||"mode5");let d=ac.get(e);if(!d||d.streamId!==u||d.width!==c.width||d.height!==c.height){const k=new Uint8ClampedArray(c.width*c.height*4);for(let N=3;N<k.length;N+=4)k[N]=255;d={streamId:u,width:c.width,height:c.height,rgba:k,imageData:new ImageData(k,c.width,c.height),keyFrameSeen:!1,inputSerial:0,outputSerial:0},ac.set(e,d)}if(!d)throw new Error("Mode 5 canvas state could not be initialized.");d.inputSerial+=1;const h=Number(t.streamFrameSeq||0);if(h>0&&(d.lastStreamFrameSeq=h),!c.keyFrame&&!d.keyFrameSeen)return;c.keyFrame&&(d.keyFrameSeen=!0);const m=wS(d.rgba,d.width,d.height,c),g=performance.now();try{a?.(t)}catch{}(e.width!==d.width||e.height!==d.height)&&(e.width=d.width,e.height=d.height);const w=rv(e,s),v=performance.now();m&&w?.context.putImageData(d.imageData,0,0,m.x,m.y,m.width,m.height);const y=performance.now();d.outputSerial+=1,n?.(t,{deviceId:t.deviceId,frameSeq:t.frameSeq,mode:t.frameMode||t.mode||t.mimeType,width:d.width,height:d.height,byteLength:t.byteLength,queuedForMs:Math.max(0,y-i),decodedForMs:Math.max(0,g-i),scheduledForMs:0,drawMs:Math.max(0,y-v),queueSize:0,renderQueueSize:0,droppedForLatency:0,h264DecodeAcceleration:"prefer-software",decoderLabel:"lzo-rgb565-delta",decoderFlushCount:0,decoderTimestampFallbacks:0,decoderInputCount:d.inputSerial,decoderOutputCount:d.outputSerial,targetPaintIntervalMs:Math.max(1,Number(t.durationUs||0)/1e3||1e3/30),canvasPresentation:w?.presentation||"sync",interactiveBufferWaitCount:0,interactiveBufferWaitMs:0,interactiveQueueDrainCount:0,visualHash:String(t.contentHash||""),visualChanged:Number(t.deltaVisualTileCount||0)>0,paintedAt:y})}const Nd=[{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 nf(e,t){for(let n=Math.max(0,t);n+3<e.length;n+=1)if(!(e[n]!==0||e[n+1]!==0)){if(e[n+2]===1)return{index:n,length:3};if(e[n+2]===0&&e[n+3]===1)return{index:n,length:4}}return null}function pC(e){let t=0;for(;t<e.length;){const n=nf(e,t);if(!n)break;const s=n.index+n.length,a=nf(e,s),i=a?.index??e.length;if(s<i&&(e[s]&31)===7){const c=[];let u=0;for(let d=s+1;d<i;d+=1){const p=e[d];if(u>=2&&p===3){u=0;continue}c.push(p),u=p===0?u+1:0}if(c.length>=3)return`avc1.${c.slice(0,3).map(d=>d.toString(16).toUpperCase().padStart(2,"0")).join("")}`}t=a?a.index:e.length}return""}function mC(e,t,n,s,a=""){const i=Math.ceil(e/16)*Math.ceil(t/16),c=n>0?1e6/n:30,u=i*c,d=Nd.find(p=>i<=p.maxFrameSize&&u<=p.maxMacroblocksPerSecond)||Nd[Nd.length-1];return pC(s)||a||`avc1.42E0${d.code.toString(16).toUpperCase().padStart(2,"0")}`}function Bp(e,t,n,s,a="smooth",i=()=>!1,c=!0,u){ac.delete(e);const d=String(t.h264Format||"").toLowerCase()==="avc"?"avc":"annexb",p=Math.max(1,Math.floor(t.width||960)),h=Math.max(1,Math.floor(t.height||540)),m=Math.max(1,Math.floor(t.durationUs||1e6/12)),g=s||Ts.h264DecodeAcceleration,w=t.isKeyFrame===!0||String(t.chunkType||"").toLowerCase()==="key";YS(e,g,w);let v=ef(e,a,g);const y=mC(p,h,m,t.payload,v.codec);let k=hp(e,g),N="";const C=()=>{N=[t.streamId||"",t.commandId||"",p,h,y,d,g,k,a].join("|")};C(),v.onBeforePaint=u,v.onPaint=n,v.configured&&v.decoder.state!=="configured"&&(v.configured=!1,v.configKey=""),v.configured&&v.configKey!==N&&(er(e),v=ef(e,a,g),v.onBeforePaint=u,v.onPaint=n,k=hp(e,g),C());const A=()=>({codec:y,codedWidth:p,codedHeight:h,hardwareAcceleration:k,optimizeForLatency:!0,avc:{format:d}}),E=re=>v.hardwareAcceleration!=="prefer-hardware"||!Su(e,v.requestedAcceleration,re)?!1:(er(e),c&&w&&Bp(e,t,n,g,a,i,!1,u),!0),I=()=>{try{return cC(e,v,A(),N,k,g),!0}catch(re){if(E("configure-error"))return!1;throw er(e),re}};if(!v.configured&&!I())return;const F=Number(t.streamFrameSeq||0);if(F>0&&v.lastInputFrameSeq!==void 0&&(F<=v.lastInputFrameSeq&&(!w||F===v.lastInputFrameSeq||(Kl(v,v.lastInputFrameSeq-F+1),!I()))||F>v.lastInputFrameSeq+1&&(Kl(v,F-v.lastInputFrameSeq-1),!w||!I()))||(F>0&&(v.lastInputFrameSeq=F),!w&&!v.keyFrameSeen))return;w&&(v.keyFrameSeen=!0);const M=Number(v.decoder.decodeQueueSize||0);if(oC(v,M)){if(v.latencyMode==="interactive"&&v.hardwareAcceleration==="prefer-hardware"){E("decode-queue-overflow");return}if(Kl(v),!w||!I())return;v.keyFrameSeen=!0}const H=v.nextChunkTimestampUs;v.nextChunkTimestampUs+=m,QS(v,H,t,M,i),Zb(e,v),v.inputSerial+=1,v.lastInputAt=performance.now(),v.inputSerial===1&&uc("first-input",e);const V=t.payload.buffer,P=V instanceof ArrayBuffer?[V]:[],D=Yb(t,m),O=!D&&v.outputSerial>0,X=w&&v.latencyMode==="interactive"&&v.hardwareAcceleration==="prefer-hardware"&&(D||O),G=D?_b:Lb;X&&(ea(v),v.interactivePipelineGuardTimestampUs=H);const U=v.interactivePipelineGuardTimestampUs!==null&&v.interactivePipelineRecoveryFrames.length>0,ie=X||U?XS(v,t,i):!1,j=new EncodedVideoChunk({type:w?"key":"delta",timestamp:H,duration:m,data:t.payload,transfer:P});t.payload=Bb;try{v.decoder.decode(j)}catch(re){if(E("decode-error"))return;throw er(e),re}ie&&Vt.get(e)===v&&v.interactivePipelineGuardTimestampUs===H&&X&&JS(e,v,H,G),iv(e,v),lC(e,v)}async function Rd(e,t,n,s,a,i="smooth",c=n,u){if(nC(t)){n()||dC(e,t,s,i,u);return}if(tC(t)){n()||Bp(e,t,s,a,i,c,!0,u);return}if(ac.delete(e),eC(t)){er(e);const w=sC(t);if(n())return;try{u?.(t)}catch{}(e.width!==w.width||e.height!==w.height)&&(e.width=w.width,e.height=w.height);const v=e.getContext("2d"),y=performance.now();v?.putImageData(w,0,0);const k=performance.now(),N=fp(e,w.width,w.height,$p,64,t);s?.(t,{deviceId:t.deviceId,frameSeq:t.frameSeq,mode:t.frameMode||t.mode||t.codec||t.mimeType,width:w.width,height:w.height,byteLength:t.byteLength,queuedForMs:0,decodedForMs:0,scheduledForMs:0,drawMs:Math.max(0,k-y),queueSize:0,renderQueueSize:0,droppedForLatency:0,h264DecodeAcceleration:Ts.h264DecodeAcceleration,decoderLabel:"lzo-rgb565",decoderFlushCount:0,decoderTimestampFallbacks:0,decoderInputCount:0,decoderOutputCount:0,targetPaintIntervalMs:0,canvasPresentation:"sync",interactiveBufferWaitCount:0,interactiveBufferWaitMs:0,interactiveQueueDrainCount:0,visualHash:N.visualHash,visualChanged:N.visualChanged,paintedAt:k});return}er(e);const d=new Blob([t.payload],{type:t.mimeType}),p=await createImageBitmap(d);if(n()){p.close();return}const h=t.width||p.width||960,m=t.height||p.height||540;try{u?.(t)}catch{}(e.width!==h||e.height!==m)&&(e.width=h,e.height=m);const g=e.getContext("2d");if(g){const w=performance.now();g.clearRect(0,0,h,m),g.drawImage(p,0,0,h,m);const v=performance.now(),y=fp(e,h,m);s?.(t,{deviceId:t.deviceId,frameSeq:t.frameSeq,mode:t.frameMode||t.mode||t.codec||t.mimeType,width:h,height:m,byteLength:t.byteLength,queuedForMs:0,decodedForMs:0,scheduledForMs:0,drawMs:Math.max(0,v-w),queueSize:0,renderQueueSize:0,droppedForLatency:0,h264DecodeAcceleration:Ts.h264DecodeAcceleration,decoderLabel:"image",decoderFlushCount:0,decoderTimestampFallbacks:0,decoderInputCount:0,decoderOutputCount:0,targetPaintIntervalMs:0,canvasPresentation:"sync",interactiveBufferWaitCount:0,interactiveBufferWaitMs:0,interactiveQueueDrainCount:0,visualHash:y.visualHash,visualChanged:y.visualChanged,paintedAt:v})}p.close()}function hC(e){queueMicrotask(e)}function fC(e){return e?(e.width=0,e.height=0,!0):!1}function Cu(e,t){if(!e)return!1;try{t?.(e)}finally{fC(e)}return!0}function Hp(e,t){if(!e||!t)return 0;const n=Math.max(0,Number(e.get(t)||0))+1;return e.set(t,n),n}function gC(e,t){if(!e||!t)return 0;const n=Number(e.get(t)||0);return Number.isSafeInteger(n)&&n>0?n:Hp(e,t)}function rf(e,t){return Hp(e,t)}function sf(e,t,n){return!!e&&!!t&&Number(n)>0&&Number(e.get(t)||0)===Number(n)}function bC(e,t,n){if(!e||!e.has(t))return!1;const s=e.get(t);return e.delete(t),Cu(s,n)}function vC(e,t,n){const s=new Set;for(const a of e||[])if(a){for(const i of a.values())i&&s.add(i);a.clear()}for(const a of t||[])a&&s.add(a);for(const a of s)Cu(a,n);return s.size}function wC(e,{isCurrent:t,dispose:n,schedule:s=hC}){return!e||typeof t!="function"?!1:(s(()=>{t(e)||Cu(e,n)}),!0)}const yC=new Uint8Array(0);function za(e){if(!e||typeof e!="object")return e;const t=e.payload;return t instanceof Uint8Array&&t.byteLength===0?e:{...e,payload:yC}}function xC(e,t){const n=za(t);return e.set(t.deviceId,n),n}function SC(e,t){for(const[n,s]of t.entries())e.set(n,za(s));return t.clear(),new Map(e)}const CC=1500;function kC(e={}){const t=Math.max(10,Math.min(1e4,Number(e.closeDeadlineMs)||CC)),n=typeof e.setTimeout=="function"?e.setTimeout:setTimeout,s=typeof e.clearTimeout=="function"?e.clearTimeout:clearTimeout,a=new Set,i=new WeakMap;let c=0,u=0;const d=(p,h)=>{if(!p||p.settled)return!1;p.settled=!0,p.timer!==null&&(s(p.timer),p.timer=null);try{p.socket.removeEventListener?.("close",p.handleClose)}catch{}return a.delete(p),i.delete(p.entry),h&&(c+=1),!0};return Object.freeze({beginClosing(p,h="livedesk-frame-socket-release"){if(!p?.socket||i.has(p))return!1;const m=p.socket;if(Number(m.readyState)===3)return!1;const g={entry:p,socket:m,timer:null,settled:!1,handleClose:null};g.handleClose=()=>d(g,!1),i.set(p,g),a.add(g),u=Math.max(u,a.size);try{m.addEventListener?.("close",g.handleClose)}catch{}g.timer=n(()=>{if(!g.settled){try{m.close()}catch{}d(g,Number(m.readyState)!==3)}},t);try{Number(m.readyState)===0||Number(m.readyState)===1?m.close(1e3,h):m.close()}catch{try{m.close()}catch{}}return Number(m.readyState)===3&&d(g,!1),!0},snapshot(){return{closingSocketCount:a.size,closingSocketTimerCount:[...a].filter(p=>p.timer!==null).length,closingSocketTimeoutCount:c,maximumClosingSocketCount:u}}})}function MC(e,t="livedesk-frame-socket-release",n=null){if(!e)return 0;const s=[e],a=new Set;let i=0;for(;s.length>0;){const c=s.pop();if(!c||a.has(c))continue;a.add(c);const u=c.handoffFrom;c.handoffFrom=void 0,u&&!a.has(u)&&s.push(u);const d=c.disposed===!0;c.disposed=!0,c.handoffCompleted=!0;const p=c.detachListeners;c.detachListeners=void 0;try{p?.()}catch{}const h=c.releaseOwnedState;c.releaseOwnedState=void 0;try{h?.()}catch{}if(!d){if(n?.beginClosing)n.beginClosing(c,t);else try{c.socket.readyState===0||c.socket.readyState===1?c.socket.close(1e3,t):c.socket.close()}catch{try{c.socket.close()}catch{}}i+=1}}return i}const af=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"]),AC=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 NC(e){return[String(e?.deviceId||""),String(e?.sessionId||""),String(e?.streamId||""),String(e?.commandId||""),String(Number(e?.captureGeneration||0)||0),String(Number.isFinite(Number(e?.monitorIndex))?Number(e.monitorIndex):-1),String(e?.streamPurpose||"")].join("\0")}function RC(e,t){return!!t&&String(e?.deviceId||"")===String(t.deviceId||"")&&String(e?.sessionId||"")===String(t.sessionId||"")&&String(e?.streamId||"")===String(t.streamId||"")&&String(e?.commandId||"")===String(t.commandId||"")&&(Number(e?.captureGeneration||0)||0)===(Number(t.captureGeneration||0)||0)&&(Number.isFinite(Number(e?.monitorIndex))?Number(e.monitorIndex):-1)===(Number.isFinite(Number(t.monitorIndex))?Number(t.monitorIndex):-1)&&String(e?.streamPurpose||"")===String(t.streamPurpose||"")}function TC(){return{ownerKey:"",values:Object.create(null)}}function of(e){e&&(e.ownerKey="",e.values=Object.create(null))}function PC(e,t,n){if(!e||!t||!RC(e,n))return!1;const s=NC(n);if(t.ownerKey!==s&&(t.ownerKey=s,t.values=Object.create(null)),e.nativeCaptureTelemetryAvailable===!1){for(const a of af)a!=="nativeCaptureTelemetryAvailable"&&(delete t.values[a],delete e[a]);return t.values.nativeCaptureTelemetryAvailable=!1,!0}if(e.nativeCaptureResourceTelemetryAvailable===!1)for(const a of AC)delete t.values[a],delete e[a];for(const a of af)Object.prototype.hasOwnProperty.call(e,a)?t.values[a]=e[a]:Object.prototype.hasOwnProperty.call(t.values,a)&&(e[a]=t.values[a]);return!0}const cv=new ArrayBuffer(0);function IC(e){return`${String(e?.streamId||"")}:${Number(e?.frameSeq||0)}`}function jC(e){return!e||typeof e!="object"||e.payload instanceof ArrayBuffer&&e.payload.byteLength===0?e:{...e,payload:cv}}function EC(){let e=null,t="";return{accept(n){e=jC(n)},publish(){const n=e;if(e=null,!n)return null;const s=IC(n);return s===t?null:(t=s,n)},clear(){e=null,t=""},inspect(){return{pending:e?1:0,pendingPayloadBytes:Number(e?.payload?.byteLength||0),publishedKey:t}}}}const FC=0,DC=1,cf=3;function Tn(e){return Math.max(0,Math.floor(Number(e)||0))}function jr(e,t){return!t||t.active||t.socket!==null||t.audioContext!==null||t.statsTimer!==null||t.scheduledSourceCount!==0||t.pendingDecodeCount!==0||t.workletNodeCount!==0||t.workletPortCount!==0||t.pcmRingCapacityBytes!==0||t.pcmRingBufferedBytes!==0||t.pendingWorkletPacketCount!==0||t.pendingWorkletPacketBytes!==0||t.retainedFrameCount!==0||t.retainedPayloadBytes!==0?!1:e.delete(t)}function LC(){const e=new Set;let t=null;const n={ownerCount:0,socketCount:0,audioContextCount:0,workletNodeCount:0,workletPortCount:0},s=()=>{let a=0,i=0,c=0,u=0;for(const d of e){const p=Number(d.socket?.readyState);a+=d.socket&&p!==cf?1:0,i+=d.audioContext===null?0:1,c+=Tn(d.workletNodeCount),u+=Tn(d.workletPortCount)}n.ownerCount=Math.max(n.ownerCount,e.size),n.socketCount=Math.max(n.socketCount,a),n.audioContextCount=Math.max(n.audioContextCount,i),n.workletNodeCount=Math.max(n.workletNodeCount,c),n.workletPortCount=Math.max(n.workletPortCount,u)};return{createOwner({deviceId:a,socket:i,audioContext:c,statsTimer:u=null}){t=null;const d={deviceId:String(a||""),active:!0,socket:i||null,audioContext:c||null,statsTimer:u,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 e.add(d),s(),d},recordTerminalFailure(a,i,c="playback"){return e.has(a)?(t={deviceId:a.deviceId,phase:String(c||"playback").slice(0,64),message:String(i||"Remote audio playback failed.").slice(0,512)},!0):!1},deactivate(a){return e.has(a)?(a.active=!1,jr(e,a)):!1},setSocket(a,i){return e.has(a)?(a.socket=i||null,s(),jr(e,a)):!1},setAudioContext(a,i){return e.has(a)?(a.audioContext=i||null,s(),jr(e,a)):!1},setStatsTimer(a,i){return e.has(a)?(a.statsTimer=i??null,jr(e,a)):!1},setScheduledSourceCount(a,i){return e.has(a)?(a.scheduledSourceCount=Tn(i),jr(e,a)):!1},setPendingDecodeCount(a,i){return e.has(a)?(a.pendingDecodeCount=Tn(i),jr(e,a)):!1},setWorkletNode(a,i,c,u=a?.workletNodeCreateCount){return e.has(a)?(a.workletNodeCount=Tn(i),a.workletPortCount=Tn(c),a.workletNodeCreateCount=Tn(u),s(),jr(e,a)):!1},setPcmRing(a,i,c){return e.has(a)?(a.pcmRingCapacityBytes=Tn(i),a.pcmRingBufferedBytes=Math.min(a.pcmRingCapacityBytes,Tn(c)),jr(e,a)):!1},setPendingWorkletPackets(a,i,c,u=a?.pendingWorkletPacketHighWater,d=a?.pendingWorkletByteHighWater){return e.has(a)?(a.pendingWorkletPacketCount=Tn(i),a.pendingWorkletPacketBytes=Tn(c),a.pendingWorkletPacketHighWater=Math.max(a.pendingWorkletPacketHighWater,Tn(u)),a.pendingWorkletByteHighWater=Math.max(a.pendingWorkletByteHighWater,Tn(d)),jr(e,a)):!1},setRetainedFrame(a,i,c=0){return e.has(a)?(a.retainedFrameCount=Tn(i),a.retainedPayloadBytes=Tn(c),jr(e,a)):!1},releaseIfDrained(a){return jr(e,a)},hasOwner(a){return e.has(a)},snapshot(){const a=[...e].map(c=>{const u=Number(c.socket?.readyState),d=c.socket&&u!==cf?1:0;return{deviceId:c.deviceId,active:c.active,socketCount:d,openSocketCount:u===DC?1:0,connectingSocketCount:u===FC?1:0,audioContextCount:c.audioContext===null?0:1,statsTimerCount:c.statsTimer===null?0:1,scheduledSourceCount:c.scheduledSourceCount,pendingDecodeCount:c.pendingDecodeCount,workletNodeCount:c.workletNodeCount,workletPortCount:c.workletPortCount,workletNodeCreateCount:c.workletNodeCreateCount,pcmRingCapacityBytes:c.pcmRingCapacityBytes,pcmRingBufferedBytes:c.pcmRingBufferedBytes,pendingWorkletPacketCount:c.pendingWorkletPacketCount,pendingWorkletPacketBytes:c.pendingWorkletPacketBytes,pendingWorkletPacketHighWater:c.pendingWorkletPacketHighWater,pendingWorkletByteHighWater:c.pendingWorkletByteHighWater,retainedFrameCount:c.retainedFrameCount,retainedPayloadBytes:c.retainedPayloadBytes}}),i=c=>a.reduce((u,d)=>u+Tn(d[c]),0);return{ownerCount:a.length,activeOwnerCount:a.filter(c=>c.active).length,socketCount:i("socketCount"),openSocketCount:i("openSocketCount"),connectingSocketCount:i("connectingSocketCount"),audioContextCount:i("audioContextCount"),statsTimerCount:i("statsTimerCount"),scheduledSourceCount:i("scheduledSourceCount"),pendingDecodeCount:i("pendingDecodeCount"),workletNodeCount:i("workletNodeCount"),workletPortCount:i("workletPortCount"),workletNodeCreateCount:i("workletNodeCreateCount"),pcmRingCapacityBytes:i("pcmRingCapacityBytes"),pcmRingBufferedBytes:i("pcmRingBufferedBytes"),pendingWorkletPacketCount:i("pendingWorkletPacketCount"),pendingWorkletPacketBytes:i("pendingWorkletPacketBytes"),pendingWorkletPacketHighWater:i("pendingWorkletPacketHighWater"),pendingWorkletByteHighWater:i("pendingWorkletByteHighWater"),retainedFrameCount:i("retainedFrameCount"),retainedPayloadBytes:i("retainedPayloadBytes"),ownerHighWater:n.ownerCount,socketHighWater:n.socketCount,audioContextHighWater:n.audioContextCount,workletNodeHighWater:n.workletNodeCount,workletPortHighWater:n.workletPortCount,lastTerminalFailure:t,owners:a}}}}const Xt=LC();function _C(){let e=Promise.resolve(),t=0,n=0,s=0;return{acquire(a){const i=++s;let c=!1,u=!1,d=!1,p;const h=new Promise(v=>{p=v}),m=Promise.resolve(e).catch(()=>{});e=m.then(()=>h);const g=()=>d?!1:(d=!0,c&&(t=Math.max(0,t-1)),p(),!0),w=m.then(async()=>{if(u||d)return g(),null;c=!0,t+=1,n=Math.max(n,t);try{return await a({ownerId:i,release:g})}catch(v){throw g(),v}});return{ownerId:i,ready:w,release:g,cancel(){u=!0,c||g()}}},snapshot(){return{activeOwnerCount:t,ownerHighWater:n,nextOwnerId:s}}}}const $C=_C(),lf=1e3;function OC({enabled:e,now:t,lastPublishedAt:n,intervalMs:s=lf}){if(!e)return!1;const a=Math.max(0,Number(t)||0),i=Math.max(0,Number(n)||0),c=Math.max(1,Number(s)||lf);return i<=0||a-i>=c}const lv="livedesk-remote-audio-v1",BC=250,HC=160,gp=4;function WC(e){const t=String(e||"").toLowerCase();return t.includes("audio/pcm")||t.includes("f32le")||t.includes("s16le")}function bp(e={},t={}){const n=String(t.deviceId||""),s=String(t.streamId||"");return!!n&&!!s&&String(e.deviceId||"")===n&&String(e.streamId||"")===s}function zC(e={},t={}){if(!bp(e,t))return{accepted:!1,reason:"owner-mismatch",nextFrameSeq:Math.max(0,Math.floor(Number(t.lastFrameSeq)||0))};const n=Math.max(0,Math.floor(Number(e.frameSeq)||0)),s=Math.max(0,Math.floor(Number(t.lastFrameSeq)||0));return n>0&&n<=s?{accepted:!1,reason:"sequence-not-newer",nextFrameSeq:s}:{accepted:!0,reason:"",nextFrameSeq:n}}function qC(e={}){const t=String(e.capturePhase||"").toLowerCase(),n=String(e.backendKind||"").toLowerCase(),s=e.captureAlive===!0?!0:e.captureAlive===!1?!1:null,a=e.helperAlive===!0?!0:e.helperAlive===!1?!1:null,i=Math.max(0,Math.floor(Number(e.helperPid)||0)),c=n==="windows-wasapi-in-process",u=n==="macos-screencapturekit-helper"||n==="linux-system-audio-helper",d=c||u,p=e.helperRequired===!0?!0:e.helperRequired===!1?!1:u?!0:c?!1:null,h=p===!1?!0:p===!0?a===!0&&i>0:!1,m=t==="starting"||t==="capture-active-awaiting-current-pcm",g=t==="active"&&s===!0&&d&&h,w=t==="failed"||t==="stopped"||s===!1||t==="active"&&(!d||!h);let v="";return m?v="awaiting-current-pcm":!c&&!u?v="backend-unknown":t!=="active"?v=t?`phase-${t}`:"phase-unknown":s!==!0?v="capture-not-alive":p===!0&&a!==!0?v="external-helper-not-alive":p===!0&&i<=0&&(v="external-helper-pid-missing"),{capturePhase:t,backendKind:n,captureAlive:s,helperAlive:a,helperPid:i,helperRequired:p,inProcessBackend:c,externalHelperBackend:u,backendKnown:d,helperReady:h,awaitingCurrentPcm:m,healthy:g,failed:w,reason:v}}function ta(e,t){const n=Math.floor(Number(e));return Number.isFinite(n)&&n>0?n:t}function Wp(e={}){const t=Math.max(8e3,Math.min(192e3,ta(e.sampleRate,48e3))),n=Math.max(1,Math.min(8,ta(e.channels,2))),s=String(e.mimeType||"").toLowerCase(),i=String(e.sampleFormat||"").toLowerCase()==="s16le"||s.includes("s16le")||s.includes("audio/l16")?"s16le":"f32le";return{sampleRate:t,channels:n,sampleFormat:i}}function zp(e={}){const t=Wp(e),n=Math.max(1,Math.min(250,ta(e.maxDurationMs,250))),s=Math.max(1,Math.ceil(t.sampleRate*n/1e3));return{...t,maxDurationMs:n,capacityFrames:s,capacityBytes:s*t.channels*Float32Array.BYTES_PER_ELEMENT}}function UC(e={}){const t=zp(e),n=Math.max(0,Math.min(t.maxDurationMs,ta(e.targetLeadMs,160))),s=Math.min(t.capacityFrames,Math.max(1,Math.ceil(t.sampleRate*n/1e3)));let a=new Float32Array(t.capacityFrames*t.channels),i=0,c=0,u=0,d=0,p=!1,h=!1,m=0,g=0,w=0;const v={acceptedFrames:0,droppedFrames:0},y=()=>(w+=1,{sampleRate:t.sampleRate,channels:t.channels,sampleFormat:t.sampleFormat,maxDurationMs:t.maxDurationMs,targetLeadMs:n,capacityFrames:h?0:t.capacityFrames,capacityBytes:h?0:t.capacityBytes,bufferedFrames:h?0:u,bufferedBytes:h?0:u*t.channels*Float32Array.BYTES_PER_ELEMENT,bufferedMs:h?0:u*1e3/t.sampleRate,droppedFrames:m,underflowCount:g,started:!h&&p,disposed:h}),k=()=>{i=0,c=0,u=0,d=0,p=!1},N=()=>{h||(k(),a=new Float32Array(0),h=!0)},C=(I,F=0,M,H=t.sampleFormat)=>{if(v.acceptedFrames=0,v.droppedFrames=0,h||!(I instanceof ArrayBuffer))return v;const V=Math.max(0,Math.floor(Number(F)||0)),P=Math.max(0,I.byteLength-V),D=Math.min(P,Math.max(0,Math.floor(Number(M??P)||0))),O=H==="s16le",X=O?2:4,G=X*t.channels,U=Math.floor(D/G);if(U<=0)return v;const ie=Math.min(U,t.capacityFrames),j=U-ie,re=Math.max(0,u+ie-t.capacityFrames);re>0&&(i=(i+re)%t.capacityFrames,u-=re);const de=j+re;m+=de;const Q=new DataView(I,V,D);for(let ge=j;ge<U;ge+=1){const oe=c*t.channels,me=ge*t.channels;for(let Ae=0;Ae<t.channels;Ae+=1){const Pe=(me+Ae)*X,Se=O?Q.getInt16(Pe,!0)/32768:Q.getFloat32(Pe,!0);a[oe+Ae]=Number.isFinite(Se)?Math.max(-1,Math.min(1,Se)):0}c=(c+1)%t.capacityFrames}return u+=ie,!p&&u>=s&&(p=!0),v.acceptedFrames=ie,v.droppedFrames=de,v};return{writePcm:(I={})=>C(I.buffer,I.byteOffset,I.byteLength,I.sampleFormat),writePcmBuffer:C,readToChannels:(I,F=t.sampleRate)=>{if(!Array.isArray(I)||I.length===0)return;let M=Number.POSITIVE_INFINITY;for(let P=0;P<I.length;P+=1){const D=I[P];M=Math.min(M,D?.length||0)}if(h||!Number.isFinite(M)||M<=0||!p){for(let P=0;P<I.length;P+=1)I[P]?.fill?.(0);return}const H=Math.max(8e3,Math.min(192e3,ta(F,t.sampleRate))),V=t.sampleRate/H;for(let P=0;P<M;P+=1){if(u<=0){p=!1,g+=1,d=0;for(let X=0;X<I.length;X+=1)I[X].fill(0,P);break}const D=i*t.channels;for(let X=0;X<I.length;X+=1){const G=Math.min(X,t.channels-1);I[X][P]=a[D+G]}d+=V;const O=Math.min(u,Math.floor(d));O>0&&(i=(i+O)%t.capacityFrames,u-=O,d-=O)}},flush:k,dispose:N,snapshot:y,getSnapshotCount:()=>w}}function VC(e={}){const t=Math.max(1,Math.min(gp,ta(e.maxPendingPackets,gp))),n=Math.max(1,ta(e.maxPendingBytes,1)),s=new Map;let a=0,i=0,c=0,u=0,d=0,p=!1;const h=()=>({terminal:p,maxPendingPackets:t,maxPendingBytes:n,pendingPacketCount:s.size,pendingPacketBytes:a,pendingPacketHighWater:i,pendingByteHighWater:c,acceptedCount:u,droppedCount:d});return{claim(m,g){const w=typeof m=="number"&&Number.isFinite(m)?m:String(m||""),v=Math.max(0,Math.floor(Number(g)||0));return p||!w||v<=0||s.has(w)||s.size>=t||a+v>n?(d+=1,!1):(s.set(w,v),a+=v,i=Math.max(i,s.size),c=Math.max(c,a),u+=1,!0)},acknowledge(m){const g=typeof m=="number"&&Number.isFinite(m)?m:String(m||""),w=s.get(g);return w===void 0?!1:(s.delete(g),a=Math.max(0,a-w),!0)},terminate(){return s.clear(),a=0,p=!0,h()},getPendingPacketCount:()=>s.size,getPendingPacketBytes:()=>a,getPendingPacketHighWater:()=>i,getPendingByteHighWater:()=>c,snapshot:h}}function ku(e,t){const n=String(e?.name||"");if(!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(n)||!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t))throw new Error("Remote Audio worklet function binding name is invalid.");const s=`const ${n} = ${Function.prototype.toString.call(e)};`;return n===t?s:`${s}
4
- const ${t} = ${n};`}const GC=ku(ta,"positiveInteger"),KC=ku(Wp,"normalizeRemoteAudioPcmFormat"),QC=ku(zp,"remoteAudioPcmRingCapacity"),YC=ku(UC,"createRemoteAudioPcmRing"),XC=`
5
- const REMOTE_AUDIO_PCM_RING_MAX_MS = ${BC};
6
- const REMOTE_AUDIO_PCM_TARGET_LEAD_MS = ${HC};
7
- ${GC}
8
- ${KC}
9
- ${QC}
1
+ import{j as r,M as cb,w as lb,D as an,r as Ya,g as Ul,i as eu,h as Oe,c as fu,a as gu,n as ub,b as $y,d as Oy,e as Vl,f as db,k as pb,l as By,m as Fh,p as Ms,P as Ho,F as yl}from"./index-CSz9F86o.js";import{a as o,m as Zo,k as Zt,n as Xa,B as Hy,P as np,X as xn,o as ac,l as Rs,F as Dh,p as Ns,q as mb,s as Wy,t as Lh,u as _h,v as zy,D as ic,b as En,w as qy,x as hb,y as Uy,z as Vy,g as ls,c as pn,H as tu,I as ec,J as nu,K as Qs,O as fb,Q as Gy,U as gb,V as $h,Y as Ky,Z as Qy,_ as Ua,W as bu,$ as Yy,a0 as Xy,a1 as Ji,a2 as Zi,a3 as Jy,a4 as rp,S as Zs,a5 as bb,a6 as vb,a7 as Zy,a8 as ex,a9 as tx,aa as Dp,ab as nx,N as Lp,ac as wb,ad as rx,ae as er,af as Oh,C as _p,ag as vu,ah as oc,ai as tc,aj as yb,ak as sx,al as xb,am as ax,an as Sb,ao as ix,ap as sp,aq as ox,ar as ap,as as Cb,at as cx,au as lx,av as ux,aw as dx,ax as kb,ay as px,az as Bh,aA as mx,aB as hx,aC as fx,aD as Mb,f as Ko,T as Gl,A as gx,E as bx,aE as Hh,aF as yd,aG as vx,aH as xd,aI as Wh,aJ as zh,aK as wx,aL as Ab,aM as yx,G as xx}from"./icons-DwJmccVC.js";import{c as Sx}from"./supabase-C7qjtLN3.js";import{r as Cx}from"./react-DOZUPHF8.js";const kx="https://otbyfkjxrkngvjziawki.supabase.co",Mx="sb_publishable_NpUs0RDJH2YnllsqTKO6TQ_1jTdSsNQ",Ax={getItem:()=>null,setItem:()=>{},removeItem:()=>{}},Sd=typeof window<"u"&&!!window.liveDesk,pt=Sx(kx,Mx,{auth:{autoRefreshToken:!Sd,persistSession:!Sd,storage:Sd?Ax:void 0,detectSessionInUrl:!0,flowType:"pkce",storageKey:"livedesk.mindexec.supabase.auth"}}),Nx=new Set(["browserLanguage","platform","online","viewport","timezone","screen"]),Rx={id:"browser-safe-v1",collect(){if(typeof navigator>"u")return{};const e={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(e).filter(([t,n])=>Nx.has(t)&&n!==void 0))}};function Tx(e,t="Support request failed."){if(e&&typeof e=="object"&&"message"in e){const n=String(e.message||"").trim();if(n)return n.replace(/^.*Support request failed:\s*/i,"")}return e instanceof Error?e.message:t}function Px(e=Rx){return e.collect()}async function Ix(e,t="livedesk"){const{data:n,error:s}=await pt.from("app_admins").select("role").eq("user_id",e).limit(1);if(s)throw s;const a=n?.[0]?.role||"user";if(a!=="owner"){const{error:w}=await pt.rpc("register_product_access",{p_product_key:t,p_access_type:"free"});if(w)throw w}const[i,c,u]=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",e),pt.from("user_products").select("product_id").eq("user_id",e).eq("is_active",!0)]);if(i.error)throw i.error;if(c.error)throw c.error;if(u.error)throw u.error;const d=i.data||[],p=(c.data||[]).map(w=>String(w.product_id)),h=(u.data||[]).map(w=>String(w.product_id)),m=a==="owner",g=m?d.map(w=>w.id):[...new Set([...p,...h])];return{products:d,access:{userId:e,globalRole:a,accessibleProductIds:g,managedProductIds:m?d.map(w=>w.id):p,canViewAllProducts:m,canViewAllPrivatePosts:m,canManageAllProducts:m,canCreateAnnouncements:m||p.length>0}}}async function jx(e=""){const{data:t,error:n}=await pt.rpc("search_support_posts",{p_query:e.trim()||null,p_limit:250});if(n)throw n;return t||[]}async function Ex(e){const{data:t,error:n}=await pt.from("support_attachments").select("*").eq("post_id",e).order("created_at");if(n)throw n;const s=t||[];return Promise.all(s.map(async a=>{const i=await pt.storage.from("support-attachments").createSignedUrl(a.storage_path,3600);return{...a,signed_url:i.data?.signedUrl||void 0}}))}async function Fx(){const{data:e,error:t}=await pt.from("support_notifications").select("*").order("created_at",{ascending:!1}).limit(30);if(t)throw t;return e||[]}async function Dx(e){const{error:t}=await pt.rpc("mark_support_notification_read",{p_notification_id:e});if(t)throw t}async function qh(e){const{data:t,error:n}=await pt.from("support_comments").select("*").eq("post_id",e).order("created_at");if(n)throw n;return t||[]}async function Lx(e){const{data:t,error:n}=await pt.from("support_votes").select("post_id").eq("user_id",e);if(n)throw n;return new Set((t||[]).map(s=>String(s.post_id)))}async function _x(e){const{data:t,error:n}=await pt.rpc("create_support_post",{p_product_id:e.productId,p_post_type:e.postType,p_title:e.title,p_body:e.body,p_visibility:e.visibility,p_app_version:e.appVersion||null,p_platform:typeof navigator>"u"?null:navigator.platform||null,p_os_version:typeof navigator>"u"?null:navigator.platform||null,p_environment:e.includeEnvironment?Px():{}});if(n)throw n;const s=Array.isArray(t)?t[0]?.post_id:t?.post_id;if(!s)throw new Error("Support post was not created.");return String(s)}const $x=new Set(["image/png","image/jpeg","image/webp","text/plain","text/markdown","application/json","application/pdf"]);async function Ox(e,t){if(!$x.has(t.type))throw new Error("This file type is not allowed.");if(t.size<=0||t.size>10*1024*1024)throw new Error("Attachments must be smaller than 10 MB.");const n=t.name.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"attachment",s=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`,a=`${e}/${s}-${n}`,i=await pt.storage.from("support-attachments").upload(a,t,{contentType:t.type,upsert:!1});if(i.error)throw i.error;const{data:c,error:u}=await pt.rpc("add_support_attachment",{p_post_id:e,p_storage_path:a,p_file_name:n,p_mime_type:t.type,p_size_bytes:t.size});if(u)throw await pt.storage.from("support-attachments").remove([a]),u;const d=Array.isArray(c)?c[0]?.attachment_id:c?.attachment_id;if(!d)throw new Error("Attachment metadata was not created.");return String(d)}async function Bx(e,t,n,s){const{error:a}=await pt.rpc("update_support_post",{p_post_id:e,p_title:t,p_body:n,p_visibility:s});if(a)throw a}async function Hx(e,t){const{error:n}=await pt.rpc("add_support_comment",{p_post_id:e,p_body:t});if(n)throw n}async function Wx(e){const{data:t,error:n}=await pt.rpc("toggle_support_vote",{p_post_id:e});if(n)throw n;const s=Array.isArray(t)?t[0]:t;return{voted:!!s?.voted,totalVotes:Number(s?.total_votes||0)}}async function zx(e,t){const{error:n}=await pt.rpc("change_support_post_status",{p_post_id:e,p_target_status:t});if(n)throw n}async function qx(e){const{error:t}=await pt.rpc("set_support_post_hidden",{p_post_id:e,p_hidden:!0});if(t)throw t}async function Ux(e,t){const{error:n}=await pt.rpc("set_support_post_locked",{p_post_id:e,p_locked:t});if(n)throw n}async function Vx(e,t){const{error:n}=await pt.rpc("set_support_post_pinned",{p_post_id:e,p_pinned:t});if(n)throw n}async function Gx(e,t){const{error:n}=await pt.rpc("mark_support_duplicate",{p_post_id:e,p_duplicate_of_post_id:t});if(n)throw n}async function Kx(e,t){const{error:n}=await pt.rpc("accept_support_answer",{p_post_id:e,p_comment_id:t});if(n)throw n}async function Qx(e,t=!0){const{error:n}=await pt.rpc("hide_support_comment",{p_comment_id:e,p_hidden:t});if(n)throw n}const ip=[{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"}],Yx=[{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"}],Xx={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"]},Jx={type:"all",product:"",status:"all",visibility:"all",sort:"recent",query:""};function Cd(){if(typeof window>"u")return Jx;const e=new URLSearchParams(window.location.search),t=window.location.pathname.match(/^\/support\/(questions|issues|features|announcements)$/)?.[1],n=e.get("type")||t||"",s=n==="questions"||n==="question"?"question":n==="issues"||n==="issue"?"issue":n==="features"||n==="feature"?"feature":n==="announcements"||n==="announcement"?"announcement":"all",a=e.get("visibility"),i=e.get("sort");return{type:s,product:e.get("product")||"",status:e.get("status")||"all",visibility:a==="public"||a==="private"?a:"all",sort:i==="votes"||i==="newest"?i:"recent",query:e.get("q")||""}}function Zx(e){return e==="all"?"":e==="question"?"questions":e==="issue"?"issues":e==="feature"?"features":"announcements"}function eS(e,t){const n={...e,...t},s=new URLSearchParams;n.product&&s.set("product",n.product),n.status!=="all"&&s.set("status",n.status),n.visibility!=="all"&&s.set("visibility",n.visibility),n.sort!=="recent"&&s.set("sort",n.sort),n.query&&s.set("q",n.query);const a=Zx(n.type),i=s.toString();return`/support${a?`/${a}`:""}${i?`?${i}`:""}`}function xl(e){const t=new Date(e);return Number.isFinite(t.getTime())?t.toLocaleString(void 0,{dateStyle:"medium",timeStyle:"short"}):e}function kd(e){return e.replaceAll("-"," ").replace(/\b\w/g,t=>t.toUpperCase())}function Uh(e){return e==="question"?qy:e==="issue"?hb:e==="feature"?Uy:Vy}function Vh(e){return ip.find(t=>t.id===e)?.shortLabel||e}function Jn(e){const t=Tx(e);return/relation .* does not exist|function .* does not exist|schema cache/i.test(t)?"Support Board database is not installed yet. Apply the latest Supabase migration first.":/not-authenticated|jwt/i.test(t)?"Sign in again to use Support.":/product-access-denied|product-not-found/i.test(t)?"You do not have access to this product.":t}function Nb({session:e,currentProductKey:t="livedesk",appVersion:n="",onSignIn:s}){const[a,i]=o.useState(()=>Cd()),[c,u]=o.useState(null),[d,p]=o.useState([]),[h,m]=o.useState([]),[g,w]=o.useState(""),[v,y]=o.useState([]),[k,N]=o.useState([]),[C,A]=o.useState([]),[E,I]=o.useState(()=>new Set),[F,M]=o.useState(!0),[H,V]=o.useState(""),[P,D]=o.useState(""),[O,X]=o.useState(!1),[G,U]=o.useState(!1),[ie,j]=o.useState(""),[re,de]=o.useState(()=>Cd().query),[Q,ge]=o.useState(!1),[oe,me]=o.useState(!1),[Ae,Te]=o.useState(""),[Pe,Se]=o.useState(""),[te,Ce]=o.useState("free"),[Fe,Le]=o.useState(""),[Ue,ne]=o.useState(""),[ae,le]=o.useState("admin"),[ce,J]=o.useState(""),[ye,ue]=o.useState(""),[Ee,nt]=o.useState([]),[T,ve]=o.useState({productId:"",postType:"question",title:"",body:"",visibility:"public",includeEnvironment:!0,files:[]}),De=o.useCallback(_=>{const je={...a,..._};i(je),typeof window<"u"&&window.history.pushState({},"",eS(a,_))},[a]);o.useEffect(()=>{const _=()=>i(Cd());return window.addEventListener("popstate",_),()=>window.removeEventListener("popstate",_)},[]);const qe=o.useCallback(async()=>{const _=await jx(a.query);return m(_),e?.user.id&&I(await Lx(e.user.id)),_},[a.query,e?.user.id]),_e=o.useCallback(async()=>{if(!e?.user.id){u(null),p([]),m([]),w(""),A([]),M(!1);return}M(!0),D("");try{const _=await Ix(e.user.id,t);u(_.access),p(_.products),await qe(),A(await Fx())}catch(_){D(Jn(_))}finally{M(!1)}},[t,qe,e?.user.id]);o.useEffect(()=>{_e()},[_e]);const $e=o.useMemo(()=>{if(!c)return[];const _=d.find(je=>je.product_key===t);return _?c.canViewAllProducts||c.accessibleProductIds.includes(_.id)?[_]:[]:[]},[c,t,d]),mt=$e[0]?.id||"",ct=o.useMemo(()=>{const _=new Map(d.map(Qe=>[Qe.id,Qe.product_key]));return[...h.filter(Qe=>a.type!=="all"&&Qe.post_type!==a.type||!mt||Qe.product_id!==mt||a.status==="needs-response"&&!["open","needs-info"].includes(Qe.status)||a.status!=="all"&&a.status!=="needs-response"&&Qe.status!==a.status||a.visibility!=="all"&&Qe.visibility!==a.visibility?!1:_.has(Qe.product_id))].sort((Qe,Ye)=>a.sort==="votes"?Ye.vote_count-Qe.vote_count||Ye.updated_at.localeCompare(Qe.updated_at):a.sort==="newest"?Ye.created_at.localeCompare(Qe.created_at):Number(Ye.is_pinned)-Number(Qe.is_pinned)||Ye.updated_at.localeCompare(Qe.updated_at))},[h,d,a.sort,a.status,a.type,a.visibility,mt]),z=ct.find(_=>_.id===g)||ct[0]||null,pe=!!(z&&c&&(c.canViewAllProducts||c.managedProductIds.includes(z.product_id))),Y=!!(z&&e?.user.id===z.author_id)||pe;o.useEffect(()=>{if(!z){w(""),y([]),U(!1);return}z.id!==g&&w(z.id)},[z,g]),o.useEffect(()=>{let _=!0;return g?(qh(g).then(je=>{_&&y(je)}).catch(je=>{_&&D(Jn(je))}),Ex(g).then(je=>{_&&N(je)}).catch(je=>{_&&D(Jn(je))}),()=>{_=!1}):(y([]),N([]),()=>{_=!1})},[g]),o.useEffect(()=>{!T.productId&&$e[0]&&ve(_=>({..._,productId:mt||$e[0].id}))},[$e,T.productId,mt]),o.useEffect(()=>{de(a.query)},[a.query]),o.useEffect(()=>{!Pe&&$e[0]&&Se($e[0].id),!Ue&&$e[0]&&ne($e[0].id)},[$e,Pe,Ue]);const K=_=>{z&&m(je=>je.map(Qe=>Qe.id===z.id?{...Qe,..._}:Qe))},ee=async _=>{if(_.preventDefault(),!(!e||!T.productId)){V("create"),D("");try{const je=await _x({productId:T.productId,postType:T.postType,title:T.title,body:T.body,visibility:T.postType==="announcement"?"public":T.visibility,appVersion:n,includeEnvironment:T.postType==="issue"&&T.includeEnvironment});for(const Ye of Ee)await Ox(je,Ye);const Qe=await qe();X(!1),nt([]),ve(Ye=>({...Ye,title:"",body:"",files:[]})),w(je),Qe.some(Ye=>Ye.id===je)||await _e()}catch(je){D(Jn(je))}finally{V("")}}},R=async _=>{if(_.preventDefault(),!!z){V("edit"),D("");try{await Bx(z.id,z.title,z.body,z.visibility),U(!1),await qe()}catch(je){D(Jn(je))}finally{V("")}}},se=async _=>{if(_.preventDefault(),!(!z||!ie.trim())){V("comment"),D("");try{await Hx(z.id,ie),j(""),y(await qh(z.id)),await qe()}catch(je){D(Jn(je))}finally{V("")}}},Ie=async()=>{if(!(!z||z.post_type!=="feature")){V("vote"),D("");try{const _=await Wx(z.id);I(je=>{const Qe=new Set(je);return _.voted?Qe.add(z.id):Qe.delete(z.id),Qe}),K({vote_count:_.totalVotes})}catch(_){D(Jn(_))}finally{V("")}}},He=async _=>{if(z){V("status"),D("");try{await zx(z.id,_),K({status:_}),await qe()}catch(je){D(Jn(je))}finally{V("")}}},Be=async()=>{if(!(!z||!window.confirm("Hide this Support post from the board?"))){V("hide"),D("");try{await qx(z.id),w(""),await qe()}catch(_){D(Jn(_))}finally{V("")}}},xe=async()=>{if(z){V("lock"),D("");try{await Ux(z.id,!z.is_locked),K({is_locked:!z.is_locked}),await qe()}catch(_){D(Jn(_))}finally{V("")}}},Ge=async()=>{if(z){V("pin"),D("");try{await Vx(z.id,!z.is_pinned),K({is_pinned:!z.is_pinned}),await qe()}catch(_){D(Jn(_))}finally{V("")}}},rt=async _=>{if(z){V(`accept-${_}`),D("");try{await Kx(z.id,_),K({accepted_comment_id:_,status:z.post_type==="question"?"answered":z.status}),await qe()}catch(je){D(Jn(je))}finally{V("")}}},Ke=async()=>{if(!(!z||!ce||ce===z.id)){V("duplicate"),D("");try{await Gx(z.id,ce),w(""),J(""),await qe()}catch(_){D(Jn(_))}finally{V("")}}},gt=async _=>{if(!_.read_at)try{await Dx(_.id),A(je=>je.map(Qe=>Qe.id===_.id?{...Qe,read_at:new Date().toISOString()}:Qe))}catch(je){D(Jn(je))}_.post_id&&w(_.post_id),ge(!1)};return e?F&&!c?r.jsxs("section",{className:"support-page support-loading",children:[r.jsx(Xa,{className:"support-spin",size:23})," Loading Support Board..."]}):r.jsxs("section",{className:"support-page",children:[r.jsx("header",{className:"support-page-header support-page-actions-only",children:r.jsxs("div",{className:"support-header-actions",children:[r.jsxs("div",{className:"support-notification-wrap",children:[r.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>ge(_=>!_),title:"Notifications",children:[r.jsx(Hy,{size:16})," ",C.filter(_=>!_.read_at).length>0&&r.jsx("b",{children:C.filter(_=>!_.read_at).length})]}),Q&&r.jsxs("div",{className:"support-notification-popover",children:[r.jsx("strong",{children:"Notifications"}),C.length===0?r.jsx("span",{className:"support-muted",children:"No notifications yet."}):C.map(_=>r.jsxs("button",{type:"button",className:_.read_at?"":"unread",onClick:()=>{gt(_)},children:[r.jsx("b",{children:_.title}),r.jsx("span",{children:_.body}),r.jsx("small",{children:xl(_.created_at)})]},_.id))]})]}),c?.canViewAllProducts&&r.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>me(_=>!_),children:[r.jsx(Zt,{size:16})," Admin"]}),r.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>{_e()},disabled:F,children:[r.jsx(Xa,{size:16,className:F?"support-spin":""})," Refresh"]}),r.jsxs("button",{className:"support-primary-button",type:"button",onClick:()=>X(!0),disabled:$e.length===0,children:[r.jsx(np,{size:17})," New request"]})]})}),P&&r.jsxs("div",{className:"support-error",role:"alert",children:[r.jsx(xn,{size:17})," ",r.jsx("span",{children:P}),r.jsx("button",{type:"button",onClick:()=>D(""),"aria-label":"Dismiss error",children:r.jsx(xn,{size:15})})]}),O&&r.jsxs("form",{className:"support-composer",onSubmit:_=>{ee(_)},children:[r.jsxs("div",{className:"support-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"New Support request"}),r.jsx("strong",{children:"Describe one actionable problem or idea."})]}),r.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>X(!1),"aria-label":"Close composer",children:r.jsx(xn,{size:18})})]}),r.jsxs("div",{className:"support-form-grid",children:[r.jsxs("label",{children:[r.jsx("span",{children:"Type"}),r.jsx("select",{value:T.postType,onChange:_=>ve(je=>({...je,postType:_.target.value})),children:ip.filter(_=>_.id!=="announcement"||c?.canCreateAnnouncements).map(_=>r.jsx("option",{value:_.id,children:_.label},_.id))})]}),r.jsxs("label",{className:"support-form-wide",children:[r.jsx("span",{children:"Title"}),r.jsx("input",{required:!0,minLength:3,maxLength:180,value:T.title,onChange:_=>ve(je=>({...je,title:_.target.value})),placeholder:"A short, searchable summary"})]}),r.jsxs("label",{className:"support-form-wide",children:[r.jsx("span",{children:T.postType==="issue"?"What happened?":T.postType==="feature"?"Describe the desired behavior":T.postType==="announcement"?"Announcement":"Question"}),r.jsx("textarea",{required:!0,value:T.body,onChange:_=>ve(je=>({...je,body:_.target.value})),placeholder:"Include the context another person needs to respond.",rows:6})]}),r.jsxs("label",{children:[r.jsx("span",{children:"Visibility"}),r.jsxs("select",{value:T.visibility,disabled:T.postType==="announcement",onChange:_=>ve(je=>({...je,visibility:_.target.value})),children:[r.jsx("option",{value:"public",children:"Public"}),r.jsx("option",{value:"private",children:"Private"})]})]}),T.postType==="issue"&&r.jsxs("label",{className:"support-checkbox",children:[r.jsx("input",{type:"checkbox",checked:T.includeEnvironment,onChange:_=>ve(je=>({...je,includeEnvironment:_.target.checked}))}),r.jsx("span",{children:"Attach safe browser/runtime details"})]}),r.jsxs("label",{className:"support-form-wide",children:[r.jsx("span",{children:"Attachments"}),r.jsx("input",{type:"file",multiple:!0,accept:"image/png,image/jpeg,image/webp,text/plain,text/markdown,application/json,application/pdf",onChange:_=>nt(Array.from(_.target.files||[]).slice(0,5))}),r.jsx("small",{className:"support-muted",children:"Up to 5 files, 10 MB each. Images, text, JSON, Markdown, and PDF."})]})]}),r.jsxs("div",{className:"support-composer-footer",children:[r.jsx("span",{children:Ee.length>0?`${Ee.length} attachment${Ee.length===1?"":"s"} selected.`:"Private posts are visible only to you and LiveDesk Support."}),r.jsxs("button",{className:"support-primary-button",type:"submit",disabled:H==="create",children:[r.jsx(ac,{size:16})," ",H==="create"?"Submitting...":"Submit request"]})]})]}),r.jsxs("div",{className:"support-tabs",role:"tablist","aria-label":"Support post type",children:[r.jsx("button",{className:a.type==="all"?"active":"",type:"button",onClick:()=>De({type:"all"}),children:"All"}),ip.map(_=>{const je=Uh(_.id);return r.jsxs("button",{className:a.type===_.id?"active":"",type:"button",onClick:()=>De({type:_.id}),children:[r.jsx(je,{size:15})," ",_.label]},_.id)})]}),oe&&c?.canViewAllProducts&&r.jsxs("section",{className:"support-admin-panel",children:[r.jsxs("div",{className:"support-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"LiveDesk owner controls"}),r.jsx("strong",{children:"Manage LiveDesk support access and staff roles by email."})]}),r.jsx(Zt,{size:19})]}),r.jsxs("div",{className:"support-admin-grid",children:[r.jsxs("form",{onSubmit:_=>{},children:[r.jsx("strong",{children:"Grant LiveDesk access"}),r.jsx("input",{type:"email",required:!0,placeholder:"User email",value:Ae,onChange:_=>Te(_.target.value)}),r.jsxs("select",{value:te,onChange:_=>Ce(_.target.value),children:[r.jsx("option",{value:"free",children:"Free"}),r.jsx("option",{value:"user",children:"User"}),r.jsx("option",{value:"paid",children:"Paid"}),r.jsx("option",{value:"beta",children:"Beta"}),r.jsx("option",{value:"staff",children:"Staff"})]}),r.jsxs("button",{className:"support-secondary-button",type:"submit",disabled:ye==="access",children:[r.jsx(Rs,{size:15})," Grant access"]})]}),r.jsxs("form",{onSubmit:_=>{},children:[r.jsx("strong",{children:"Assign LiveDesk staff"}),r.jsx("input",{type:"email",required:!0,placeholder:"Staff email",value:Fe,onChange:_=>Le(_.target.value)}),r.jsxs("select",{value:ae,onChange:_=>le(_.target.value),children:[r.jsx("option",{value:"admin",children:"Admin"}),r.jsx("option",{value:"support",children:"Support"}),r.jsx("option",{value:"moderator",children:"Moderator"})]}),r.jsxs("button",{className:"support-secondary-button",type:"submit",disabled:ye==="product-admin",children:[r.jsx(Zt,{size:15})," Assign staff"]})]})]})]}),r.jsxs("form",{className:"support-search-bar",onSubmit:_=>{_.preventDefault(),De({query:re.trim()})},children:[r.jsxs("label",{children:[r.jsx("span",{children:"Search Support"}),r.jsx("input",{value:re,onChange:_=>de(_.target.value),placeholder:"Search titles and request details"})]}),r.jsxs("button",{className:"support-secondary-button",type:"submit",children:[r.jsx(Dh,{size:15})," Search"]}),a.query&&r.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>{de(""),De({query:""})},"aria-label":"Clear search",children:r.jsx(xn,{size:16})})]}),r.jsxs("div",{className:"support-filter-bar",children:[r.jsxs("div",{className:"support-filter-title",children:[r.jsx(Dh,{size:16}),r.jsx("span",{children:"Filter"})]}),r.jsxs("label",{children:[r.jsx("span",{children:"Status"}),r.jsx("select",{value:a.status,onChange:_=>De({status:_.target.value}),children:Yx.map(_=>r.jsx("option",{value:_.id,children:_.label},_.id))})]}),r.jsxs("label",{children:[r.jsx("span",{children:"Visibility"}),r.jsxs("select",{value:a.visibility,onChange:_=>De({visibility:_.target.value}),children:[r.jsx("option",{value:"all",children:"All visibility"}),r.jsx("option",{value:"public",children:"Public"}),r.jsx("option",{value:"private",children:"Private"})]})]}),r.jsxs("label",{children:[r.jsx("span",{children:"Sort"}),r.jsxs("select",{value:a.sort,onChange:_=>De({sort:_.target.value}),children:[r.jsx("option",{value:"recent",children:"Recently updated"}),r.jsx("option",{value:"newest",children:"Newest"}),r.jsx("option",{value:"votes",children:"Most votes"})]})]})]}),c?.canViewAllProducts&&r.jsxs("div",{className:"support-admin-shortcuts",children:[r.jsxs("span",{children:[r.jsx(Zt,{size:15})," LiveDesk owner"]}),r.jsx("button",{type:"button",onClick:()=>De({status:"needs-response"}),children:"Needs response"}),r.jsx("button",{type:"button",onClick:()=>De({visibility:"private"}),children:"Private requests"}),r.jsx("button",{type:"button",onClick:()=>De({type:"feature",status:"all",sort:"votes"}),children:"High-vote features"})]}),r.jsxs("div",{className:"support-board-layout",children:[r.jsxs("section",{className:"support-post-list","aria-label":"Support posts",children:[r.jsxs("div",{className:"support-list-heading",children:[r.jsxs("span",{children:[ct.length," request",ct.length===1?"":"s"]}),r.jsx("small",{children:"LiveDesk"})]}),ct.length===0?r.jsxs("div",{className:"support-list-empty",children:[r.jsx(Zo,{size:25}),r.jsx("strong",{children:"No posts match these filters."}),r.jsx("span",{children:"Start with a focused question, issue report, or feature request."}),$e.length>0&&r.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>X(!0),children:[r.jsx(np,{size:16})," Create the first request"]})]}):ct.map(_=>{const je=Uh(_.post_type);return r.jsxs("button",{type:"button",className:`support-post-row ${_.id===z?.id?"active":""}`,onClick:()=>{w(_.id),U(!1)},children:[r.jsx("span",{className:"support-post-row-icon",children:r.jsx(je,{size:17})}),r.jsxs("span",{className:"support-post-row-copy",children:[r.jsxs("span",{className:"support-post-row-meta",children:[r.jsx("em",{children:Vh(_.post_type)}),_.visibility==="private"&&r.jsx(Ns,{size:13})]}),r.jsx("strong",{children:_.title}),r.jsxs("small",{children:[kd(_.status)," · ",xl(_.updated_at)," · ",_.comment_count," comments"]})]}),_.post_type==="feature"&&r.jsxs("span",{className:"support-vote-count",children:[r.jsx(mb,{size:14})," ",_.vote_count]})]},_.id)})]}),r.jsx("section",{className:"support-post-detail","aria-label":"Support post detail",children:z?r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"support-detail-head",children:[r.jsxs("div",{className:"support-detail-badges",children:[r.jsx("span",{className:"support-type-badge",children:Vh(z.post_type)}),r.jsx("span",{className:`support-status-badge status-${z.status}`,children:kd(z.status)}),z.visibility==="private"&&r.jsxs("span",{className:"support-private-badge",children:[r.jsx(Ns,{size:13})," Private"]})]}),r.jsxs("div",{className:"support-detail-actions",children:[Y&&r.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>U(_=>!_),title:"Edit post",children:r.jsx(Wy,{size:16})}),pe&&r.jsxs(r.Fragment,{children:[r.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>{Ge()},disabled:H==="pin",title:z.is_pinned?"Unpin post":"Pin post",children:r.jsx(Lh,{size:16})}),r.jsx("button",{className:"support-icon-button",type:"button",onClick:()=>{xe()},disabled:H==="lock",title:z.is_locked?"Unlock post":"Lock post",children:r.jsx(Ns,{size:16})}),r.jsx("button",{className:"support-icon-button danger",type:"button",onClick:()=>{Be()},disabled:H==="hide",title:"Hide post",children:r.jsx(_h,{size:16})})]})]})]}),G?r.jsxs("form",{className:"support-edit-form",onSubmit:_=>{R(_)},children:[r.jsx("input",{value:z.title,onChange:_=>K({title:_.target.value}),minLength:3,maxLength:180,required:!0}),r.jsx("textarea",{value:z.body,onChange:_=>K({body:_.target.value}),rows:9,required:!0}),r.jsxs("div",{className:"support-edit-actions",children:[r.jsxs("select",{value:z.visibility,onChange:_=>K({visibility:_.target.value}),children:[r.jsx("option",{value:"public",children:"Public"}),r.jsx("option",{value:"private",children:"Private"})]}),r.jsxs("button",{className:"support-primary-button",type:"submit",disabled:H==="edit",children:[r.jsx(Rs,{size:16})," Save changes"]})]})]}):r.jsxs(r.Fragment,{children:[r.jsx("h3",{children:z.title}),r.jsx("div",{className:"support-detail-body",children:z.body.split(`
2
+ `).map((_,je)=>r.jsx("p",{children:_||" "},`${z.id}-body-${je}`))})]}),r.jsxs("div",{className:"support-detail-meta",children:[r.jsxs("span",{children:["Opened ",xl(z.created_at)]}),z.app_version&&r.jsxs("span",{children:["Version ",z.app_version]}),z.platform&&r.jsx("span",{children:z.platform}),z.is_locked&&r.jsxs("span",{children:[r.jsx(Ns,{size:13})," Locked"]}),z.is_pinned&&r.jsxs("span",{children:[r.jsx(Lh,{size:13})," Pinned"]})]}),r.jsxs("div",{className:"support-detail-controls",children:[z.post_type==="feature"&&r.jsxs("button",{className:`support-vote-button ${E.has(z.id)?"voted":""}`,type:"button",onClick:()=>{Ie()},disabled:H==="vote",children:[r.jsx(zy,{size:16})," ",E.has(z.id)?"Voted":"Vote"," ",r.jsx("b",{children:z.vote_count})]}),pe&&r.jsxs("label",{className:"support-status-control",children:[r.jsx("span",{children:"Change status"}),r.jsx("select",{value:z.status,onChange:_=>{He(_.target.value)},disabled:H==="status",children:(Xx[z.post_type]||[]).map(_=>r.jsx("option",{value:_,children:kd(_)},_))})]}),pe&&r.jsxs(r.Fragment,{children:[r.jsxs("select",{className:"support-status-control",value:ce,onChange:_=>J(_.target.value),children:[r.jsx("option",{value:"",children:"Duplicate of..."}),ct.filter(_=>_.id!==z.id&&_.product_id===z.product_id).map(_=>r.jsx("option",{value:_.id,children:_.title.slice(0,55)},_.id))]}),r.jsx("button",{className:"support-secondary-button",type:"button",onClick:()=>{Ke()},disabled:!ce||H==="duplicate",children:"Merge duplicate"})]})]}),k.length>0&&r.jsxs("div",{className:"support-attachments",children:[r.jsx("div",{className:"support-section-heading",children:r.jsxs("div",{children:[r.jsx("span",{children:"Attachments"}),r.jsxs("strong",{children:[k.length," file",k.length===1?"":"s"]})]})}),k.map(_=>r.jsxs("a",{href:_.signed_url,target:"_blank",rel:"noreferrer",children:[r.jsx(ic,{size:14})," ",_.file_name,r.jsxs("small",{children:[Math.ceil(_.size_bytes/1024)," KB"]})]},_.id))]}),r.jsxs("div",{className:"support-comments",children:[r.jsxs("div",{className:"support-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Discussion"}),r.jsxs("strong",{children:[v.length," comment",v.length===1?"":"s"]})]}),z.is_locked&&r.jsxs("span",{className:"support-locked-label",children:[r.jsx(Ns,{size:14})," Locked"]})]}),v.length===0?r.jsx("p",{className:"support-muted",children:"No response yet. Keep the conversation focused on this request."}):r.jsx("div",{className:"support-comment-list",children:v.map(_=>r.jsxs("article",{className:`support-comment ${_.is_staff_answer?"staff":""} ${z.accepted_comment_id===_.id?"accepted":""}`,children:[r.jsxs("div",{className:"support-comment-head",children:[r.jsx("strong",{children:_.is_staff_answer?"LiveDesk Support":_.author_id===e.user.id?"You":"Support user"}),_.is_staff_answer&&r.jsxs("span",{children:[r.jsx(Zt,{size:13})," Staff answer"]}),z.accepted_comment_id===_.id&&r.jsxs("span",{children:[r.jsx(En,{size:13})," Accepted"]}),r.jsx("time",{children:xl(_.created_at)})]}),r.jsx("p",{children:_.body}),r.jsxs("div",{className:"support-comment-actions",children:[(e.user.id===z.author_id||pe)&&z.post_type==="question"&&z.accepted_comment_id!==_.id&&r.jsxs("button",{className:"support-secondary-button",type:"button",onClick:()=>{rt(_.id)},disabled:H===`accept-${_.id}`,children:[r.jsx(Rs,{size:14})," Accept answer"]}),pe&&r.jsx("button",{className:"support-icon-button danger",type:"button",onClick:()=>{Qx(_.id)},title:"Hide comment",children:r.jsx(_h,{size:14})})]})]},_.id))}),!z.is_locked&&r.jsxs("form",{className:"support-comment-form",onSubmit:_=>{se(_)},children:[r.jsx("textarea",{value:ie,onChange:_=>j(_.target.value),placeholder:"Add a focused reply...",rows:3}),r.jsxs("button",{className:"support-primary-button",type:"submit",disabled:H==="comment"||!ie.trim(),children:[r.jsx(ac,{size:15})," Reply"]})]})]})]}):r.jsxs("div",{className:"support-detail-empty",children:[r.jsx(Zo,{size:28}),r.jsx("strong",{children:"Select a Support request"}),r.jsx("span",{children:"Its discussion and staff actions will appear here."})]})})]})]}):r.jsx("section",{className:"support-page support-auth-page",children:r.jsxs("div",{className:"support-empty-hero",children:[r.jsx("span",{className:"support-hero-icon",children:r.jsx(Zo,{size:28})}),r.jsx("p",{className:"support-eyebrow",children:"LiveDesk Support"}),r.jsx("h2",{children:"Get help, report issues, and shape the product."}),r.jsx("p",{children:"Sign in to view LiveDesk support and submit a private or public request."}),r.jsxs("button",{className:"support-primary-button",type:"button",onClick:s,children:[r.jsx(Zt,{size:17})," Sign in with Google"]})]})})}function tS(e){if(!e)return"Reading the installed version...";switch(e.state){case"checking":return"Checking for a newer LiveDesk version...";case"available":return`Version ${e.availableVersion||""} is available.`;case"downloading":return`Downloading version ${e.availableVersion||""} (${Math.round(e.progress||0)}%).`;case"downloaded":return`Version ${e.availableVersion||""} is ready. Restart to install it.`;case"installing":return"Closing LiveDesk safely and starting the update...";case"current":return"This computer has the latest LiveDesk version.";case"error":return"The update server could not be reached. This version will keep running.";case"development":return"Desktop updates are available in an installed LiveDesk build.";case"unavailable":return"Updates are not available for this desktop build.";default:return"LiveDesk checks once when the desktop app starts."}}function Rb(){const e=window.liveDesk?.updates,[t,n]=o.useState(null),[s,a]=o.useState(!1);if(o.useEffect(()=>{if(!e)return;let d=!0;e.getStatus?.().then(h=>{d&&n(h)});const p=e.onStatus?.(h=>{d&&n(h)});return()=>{d=!1,p?.()}},[e]),!e)return null;const i=t?.state==="downloaded"||t?.downloaded===!0,c=s||t?.state==="checking"||t?.state==="downloading"||t?.state==="installing",u=async()=>{a(!0);try{const d=i?await e.install?.():await e.check?.();d&&n(d)}finally{a(!1)}};return r.jsxs("section",{className:"settings-section-card desktop-update-card",children:[r.jsxs("div",{className:"settings-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Desktop app"}),r.jsx("h3",{children:"LiveDesk updates"})]}),r.jsx(ic,{size:20})]}),r.jsx("p",{className:"settings-help","aria-live":"polite",children:tS(t)}),r.jsxs("div",{className:"desktop-update-meta",children:[r.jsx("span",{children:"Installed"}),r.jsx("strong",{children:t?.currentVersion||"Unknown"}),t?.availableVersion&&r.jsxs(r.Fragment,{children:[r.jsx("span",{children:"Available"}),r.jsx("strong",{children:t.availableVersion})]})]}),r.jsxs("button",{className:"settings-reset desktop-update-action",onClick:()=>{u()},disabled:c,type:"button",children:[r.jsx(Xa,{size:15,className:c?"desktop-update-spin":""}),i?"Restart and update":c?"Updating...":"Check for updates"]})]})}function Sl(e){return!!e&&typeof e=="object"}function Tb(e){let t=e;return Sl(t)&&"data"in t&&(t=t.data),Sl(t)&&"session"in t&&(t=t.session),!Sl(t)||typeof t.access_token!="string"||!t.access_token||!Sl(t.user)||typeof t.user.id!="string"||!t.user.id?null:t}function Gh(e){return e?.access_token?e.refresh_token?"":"refresh-token-required":"access-token-required"}const Pb={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."},op={en:Pb,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 wu(e){const t=e?[e]:typeof navigator>"u"?["en"]:navigator.languages?.length?navigator.languages:[navigator.language];for(const n of t){const s=String(n||"").trim(),a=s.toLowerCase();if(!a)continue;if(a.startsWith("zh-tw")||a.startsWith("zh-hk"))return"zh-TW";if(a.startsWith("zh"))return"zh";if(a.startsWith("pt"))return"pt-BR";const i=a.split("-")[0];if(op[s])return s;if(op[i])return i}return"en"}function ru(e,t){const n=wu(t);return op[n]?.[e]||Pb[e]}function cp(e,t,n){return`${e}
3
+ ${ru(t,n)}`}const Ib={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"},nS={en:Ib,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"}},jb={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"},rS={en:jb,ko:{eyebrow:"컴퓨터 역할",title:"이 컴퓨터를 Hub로 사용할까요?",description:"Hub는 Client 컴퓨터를 연결하고 관리합니다.",restartNotice:"다른 컴퓨터가 Hub라면 이 컴퓨터가 새 Hub가 됩니다.",cancel:"취소",confirm:"Hub로 설정",closeLabel:"Hub 설정 확인 닫기"}};function sS(e){const t=wu(e);return nS[t]||Ib}function aS(e){const t=wu(e);return rS[t]||jb}function iS(e=[]){return[...new Set(e.filter(t=>typeof t=="string").map(t=>t.trim()).filter(Boolean))]}function oS(e=[],t=new Set){return e.find(n=>!t.has(n))||""}const cS=[{id:"docs",label:"Doc",icon:tu},{id:"support",label:"Support",icon:Zo},{id:"pricing",label:"Pricing",icon:ec},{id:"settings",label:"Settings",icon:nu}],Kh=[0,1e3,2e3,5e3,1e4,2e4,3e4],lS=15e3;function uS(e=""){const t=e.trim().replace(/\/+$/,"");return t||(typeof window>"u"?"":window.location.port==="5179"?window.location.origin:"http://127.0.0.1:5179")}async function $a(e,t=!1){const n=t?"":sessionStorage.getItem("livedesk.client.csrf");if(n)return n;const s=await fetch(`${e}/api/runtime/status`,{cache:"no-store"}),a=await s.json().catch(()=>({}));if(!s.ok)throw new Error(a.error||`Client runtime returned HTTP ${s.status}.`);const i=String(a.csrfToken||"");return i&&sessionStorage.setItem("livedesk.client.csrf",i),i}function lp(e){return`${Math.max(0,Math.min(100,Number(e||0))).toFixed(0)}%`}function Md(e){return Number.isFinite(e)?`${Math.max(0,Math.min(100,Number(e))).toFixed(0)}%`:"—"}function Eb(e){return Number.isFinite(e)?lp(Number(e)):"0%"}function Va(e){const t=Number(e);return!Number.isFinite(t)||t<0?"—":t>=1024**4?`${(t/1024**4).toFixed(t>=10*1024**4?0:1)} TB`:t>=1024**3?`${(t/1024**3).toFixed(t>=10*1024**3?0:1)} GB`:`${(t/1024**2).toFixed(0)} MB`}function Qh(e){const t=Math.max(0,Number(e||0));return t>=1024**3?`${(t/1024**3).toFixed(1)} GB/s`:t>=1024**2?`${(t/1024**2).toFixed(1)} MB/s`:t>=1024?`${(t/1024).toFixed(1)} KB/s`:`${t.toFixed(0)} B/s`}function dS(e,t){const n=Number(e||0)/1073741824,s=Number(t||0)/1024**3;return s>0?`${n.toFixed(1)} / ${s.toFixed(1)} GB`:"Checking..."}function pS(e,t){return!Number.isFinite(t)||Number(t)<=0?"Dedicated memory unavailable":Number.isFinite(e)?`${Va(e)} / ${Va(t)}`:`${Va(t)} available`}function mS(e){const t=Math.max(0,Math.floor(Number(e||0)/60)),n=Math.floor(t/1440),s=Math.floor(t%1440/60),a=t%60;return n>0?`${n}d ${s}h`:s>0?`${s}h ${a}m`:`${a}m`}function Cl({icon:e,label:t,value:n,detail:s,percent:a}){return r.jsxs("article",{className:"client-resource-metric",children:[r.jsxs("div",{className:"client-resource-metric-head",children:[r.jsx(e,{size:17}),r.jsx("span",{children:t}),r.jsx("strong",{children:n})]}),r.jsx("small",{title:s,children:s}),r.jsx("i",{"aria-hidden":"true",children:r.jsx("b",{style:{width:Eb(a)}})})]})}function hS(e,t){const n=e?.user.user_metadata||{},s=n.full_name||n.name||n.preferred_username||e?.user.email||e?.user.id||t?.userName||t?.auth?.name||t?.userEmail||t?.userId||"Account";return String(s).trim()||"Account"}function fS(e,t){const n=e?.user.user_metadata||{};return iS([n.avatar_url,n.picture,t?.userAvatarUrl,t?.auth?.avatarUrl])}function gS({page:e,status:t}){const s={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."}}[e];return r.jsxs("section",{className:"client-service-page",children:[r.jsx("span",{className:"client-unified-section-label",children:s.label}),r.jsx("h2",{children:s.title}),r.jsx("p",{children:s.body}),r.jsxs("div",{className:"client-service-page-card",children:[e==="docs"&&r.jsxs(r.Fragment,{children:[r.jsx("strong",{children:"Automatic connection"}),r.jsx("span",{children:"Start LiveDesk. This computer signs in, finds the Hub, and becomes available without another action."})]}),e==="pricing"&&r.jsxs(r.Fragment,{children:[r.jsx("strong",{children:"One plan, managed at the Hub"}),r.jsx("span",{children:"Computer access follows the account and plan used by the Hub."})]}),e==="settings"&&r.jsxs(r.Fragment,{children:[r.jsx("strong",{children:"Saved sign-in"}),r.jsx("span",{children:t?.auth?.persisted?"Enabled on this computer":"Sign in once to enable automatic reconnection"})]})]}),e==="settings"&&r.jsx(Rb,{})]})}function bS({session:e,status:t,pin:n,roleChangeMessage:s,videoAccelerationBusy:a,slotInput:i,slotBusy:c,onSignIn:u,onPinChange:d,onSubmitPin:p,onSlotInputChange:h,onSaveSlot:m,onEnableVideoAcceleration:g}){const w=t?.connectionState==="connected",v=t?.videoAcceleration,y=a||v?.busy||v?.state==="installing",k=v?.ready?`${v.encoder||"H.264"} · ${v.driver||"VAAPI"}`:y?"Setting up…":v?.message||"Setup available",N=t?.system?.memoryTotalBytes?Number(t.system.memoryUsedBytes||0)/t.system.memoryTotalBytes*100:0,C=t?.system?.gpus||[],A=C.find(O=>Number.isFinite(O.usagePercent)||Number.isFinite(O.memoryTotalBytes))||C[0],E=Number.isFinite(A?.usagePercent)?Number(A?.usagePercent):null,I=Number.isFinite(A?.memoryTotalBytes)&&Number(A?.memoryTotalBytes)>0&&Number.isFinite(A?.memoryUsedBytes)?Number(A?.memoryUsedBytes)/Number(A?.memoryTotalBytes)*100:null,F=t?.system?.disks||[],M=t?.system?.network,H=!!M?.sampledAt,V=M?.interfaces||[],P=[...new Set(V.map(O=>O.name).filter(Boolean))],D=V.map(O=>O.address).filter(Boolean);return r.jsxs("section",{className:"client-home-page",children:[r.jsxs("header",{className:"client-home-heading",children:[r.jsxs("div",{children:[r.jsx("p",{className:"client-unified-eyebrow",children:"THIS COMPUTER"}),r.jsx("h2",{children:t?.deviceName||"This Computer"})]}),r.jsxs("span",{className:`client-unified-role-chip ${w?"connected":""}`,children:[r.jsx(pn,{size:15})," ",w?"Online":"Connecting"]})]}),r.jsxs("div",{className:"client-home-layout",children:[r.jsxs("section",{className:"client-main-surface","aria-label":"Client computer",children:[r.jsxs("div",{className:"client-main-surface-head",children:[r.jsxs("div",{children:[r.jsx("span",{className:"client-unified-section-label",children:"SYSTEM STATUS"}),r.jsx("strong",{children:"Hardware at a glance"})]}),r.jsxs("small",{children:[r.jsx(gb,{size:14})," Uptime ",mS(t?.system?.uptimeSeconds)]})]}),r.jsxs("div",{className:"client-system-dashboard",children:[r.jsxs("section",{className:"client-performance-panel","aria-label":"Performance",children:[r.jsxs("div",{className:"client-system-subhead",children:[r.jsxs("div",{children:[r.jsx("span",{className:"client-unified-section-label",children:"PERFORMANCE"}),r.jsx("strong",{children:"Live resources"})]}),r.jsx("small",{children:"Live updates"})]}),r.jsxs("div",{className:"client-live-metrics",children:[r.jsx(Cl,{icon:$h,label:"CPU",value:lp(t?.system?.cpuUsagePercent),detail:t?.system?.cpuLogicalCores?`${t.system.cpuLogicalCores} logical cores · Current processor usage`:"Current processor usage",percent:t?.system?.cpuUsagePercent}),r.jsx(Cl,{icon:Ky,label:"Memory",value:lp(N),detail:dS(t?.system?.memoryUsedBytes,t?.system?.memoryTotalBytes),percent:N}),r.jsx(Cl,{icon:Qy,label:"GPU",value:Md(E),detail:A?.name||(t?.system?.hardwareCollecting?"Detecting graphics hardware…":"Graphics usage unavailable"),percent:E}),r.jsx(Cl,{icon:ls,label:"VRAM",value:Md(I),detail:pS(A?.memoryUsedBytes,A?.memoryTotalBytes),percent:I})]})]}),r.jsxs("section",{className:"client-storage-panel","aria-label":"Local storage",children:[r.jsxs("div",{className:"client-system-subhead",children:[r.jsxs("div",{children:[r.jsx("span",{className:"client-unified-section-label",children:"STORAGE"}),r.jsx("strong",{children:"Local drives"})]}),r.jsx("small",{children:F.length>0?`${F.length} ${F.length===1?"drive":"drives"}`:t?.system?.hardwareCollecting?"Detecting…":"Unavailable"})]}),r.jsxs("div",{className:"client-disk-list",children:[F.map(O=>r.jsxs("article",{className:"client-disk-row",children:[r.jsxs("div",{className:"client-disk-row-head",children:[r.jsxs("span",{children:[r.jsx(Ua,{size:16}),r.jsx("strong",{children:O.mount||"Disk"}),r.jsx("small",{children:O.name||"Local disk"})]}),r.jsx("strong",{children:Md(O.usedPercent)})]}),r.jsxs("small",{children:[Va(O.freeBytes)," free · ",Va(O.totalBytes)," total"]}),r.jsx("i",{"aria-hidden":"true",children:r.jsx("b",{style:{width:Eb(O.usedPercent)}})})]},`${O.mount}-${O.name||""}`)),F.length===0&&r.jsxs("div",{className:"client-disk-empty",children:[r.jsx(Ua,{size:18}),r.jsx("span",{children:t?.system?.hardwareCollecting?"Detecting local drives…":"Storage information is not available."})]})]})]}),r.jsxs("section",{className:"client-network-panel","aria-label":"Network activity",children:[r.jsxs("div",{className:"client-system-subhead",children:[r.jsxs("div",{children:[r.jsx("span",{className:"client-unified-section-label",children:"NETWORK"}),r.jsx("strong",{children:"Live traffic"})]}),r.jsx("small",{children:P.length>0?P.join(", "):"Detecting adapter"})]}),r.jsxs("div",{className:"client-network-live",children:[r.jsxs("div",{className:"client-network-adapter",children:[r.jsx(bu,{size:18}),r.jsxs("span",{children:[r.jsx("strong",{children:P.join(", ")||"Network"}),r.jsx("small",{children:D.join(" / ")||"Checking active connection"})]})]}),r.jsxs("div",{className:"client-network-rate download",children:[r.jsx(Yy,{size:17}),r.jsxs("span",{children:[r.jsx("small",{children:"Receive"}),r.jsx("strong",{children:Qh(H?M?.receiveBytesPerSecond:void 0)})]})]}),r.jsxs("div",{className:"client-network-rate upload",children:[r.jsx(Xy,{size:17}),r.jsxs("span",{children:[r.jsx("small",{children:"Send"}),r.jsx("strong",{children:Qh(H?M?.sendBytesPerSecond:void 0)})]})]}),r.jsx("small",{className:"client-network-total",children:H?`Total ${Va(M?.receivedBytes)} received / ${Va(M?.sentBytes)} sent`:"Traffic has not been measured yet."})]})]})]})]}),r.jsxs("aside",{className:"client-connection-panel",children:[r.jsx("span",{className:"client-unified-section-label",children:"LIVEDESK SERVICES"}),r.jsx("h3",{children:w?"Connected to the Hub":t?.authenticated?"Finding the Hub":"Connect this computer"}),w?r.jsxs(r.Fragment,{children:[r.jsx("p",{className:"client-unified-copy",children:"This computer is available from the LiveDesk Hub."}),r.jsxs("div",{className:"client-service-status-list",children:[r.jsxs("div",{children:[r.jsx(pn,{size:17}),r.jsxs("span",{children:[r.jsx("strong",{children:"Screen sharing"}),r.jsx("small",{children:t?.permissions?.screenCapture?"Active":"Waiting"})]})]}),r.jsxs("div",{children:[r.jsx(Zt,{size:17}),r.jsxs("span",{children:[r.jsx("strong",{children:"Remote control"}),r.jsx("small",{children:t?.permissions?.remoteInput?"Available":"Unavailable"})]})]}),r.jsxs("div",{children:[r.jsx(Ji,{size:17}),r.jsxs("span",{children:[r.jsx("strong",{children:"File delivery"}),r.jsx("small",{children:t?.permissions?.files?"Ready to receive":"Unavailable"})]})]}),r.jsxs("div",{children:[r.jsx(Zi,{size:17}),r.jsxs("span",{children:[r.jsx("strong",{children:"Computer audio"}),r.jsx("small",{children:t?.permissions?.audio?"Available":"Unavailable"})]})]})]})]}):r.jsxs(r.Fragment,{children:[r.jsx("p",{className:"client-unified-copy",children:t?.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."}),!e&&!t?.authenticated?r.jsxs("button",{className:"client-unified-primary",type:"button",onClick:u,children:[r.jsx(Qs,{size:16})," Sign in with Google"]}):r.jsxs("p",{className:"client-unified-success",children:[r.jsx(En,{size:16})," Signed in as ",e?.user.email||e?.user.id||t?.userEmail||t?.userId||"saved account"]}),r.jsxs("div",{className:"client-unified-pin-row",children:[r.jsx(Jy,{size:16}),r.jsx("input",{value:n,onChange:O=>d(O.target.value),placeholder:"6-digit Hub PIN",inputMode:"numeric","aria-label":"6-digit Hub PIN"}),r.jsx("button",{className:"client-unified-secondary",type:"button",onClick:p,disabled:n.length!==6,children:"Connect"})]})]}),v?.supported&&r.jsxs("div",{className:`client-video-acceleration state-${v.ready?"ready":v.state||"setup-required"}`,children:[r.jsx($h,{size:17}),r.jsxs("span",{children:[r.jsx("strong",{children:"Hardware video"}),r.jsx("small",{children:k})]}),!v.ready&&v.canInstall&&r.jsx("button",{type:"button",onClick:g,disabled:y,title:"Install and verify Linux FFmpeg hardware video support",children:y?"Setting up":"Enable"})]}),s&&r.jsx("p",{className:"client-unified-success",children:s}),r.jsxs("div",{className:"client-slot-setting",children:[r.jsxs("label",{htmlFor:"client-slot-number",children:[r.jsx("span",{children:"Slot"}),r.jsx("input",{id:"client-slot-number",value:i,onChange:O=>h(O.target.value),inputMode:"numeric",pattern:"[0-9]*",placeholder:"1-999","aria-label":"Wall slot number",disabled:!w||c})]}),r.jsxs("button",{type:"button",onClick:m,disabled:!w||c||!i,"aria-label":"Save slot number",title:"Save slot number",children:[r.jsx(nu,{size:17}),r.jsx("span",{children:c?"Saving":"Set"})]})]})]})]})]})}function vS({runtimeBaseUrl:e=""}){const[t,n]=o.useState(null),[s,a]=o.useState(null),[i,c]=o.useState(!1),[u,d]=o.useState(""),[p,h]=o.useState(""),[m,g]=o.useState(""),[w,v]=o.useState(!1),[y,k]=o.useState(!1),[N,C]=o.useState(""),[A,E]=o.useState(!1),[I,F]=o.useState(null),[M,H]=o.useState(!1),[V,P]=o.useState("computer"),[D,O]=o.useState(!1),X=o.useRef(null),G=o.useRef(null),U=o.useRef(!1),ie=o.useRef(null),j=o.useRef(null),re=o.useRef(!1),de=o.useRef(!1),Q=o.useRef(0),ge=o.useRef(!1),oe=o.useRef(""),me=o.useMemo(()=>uS(e),[e]),Ae=o.useMemo(()=>hS(s,t),[s,t]),Te=o.useMemo(()=>fS(s,t),[s,t]),Pe=JSON.stringify(Te),[Se,te]=o.useState(()=>new Set),Ce=oS(Te,Se),Fe=Ae.slice(0,1).toUpperCase()||"L";o.useEffect(()=>{te(new Set)},[Pe]);const Le=o.useCallback(z=>{te(pe=>{if(!z||pe.has(z))return pe;const Y=new Set(pe);return Y.add(z),Y})},[]),Ue=o.useCallback(async()=>{if(h(""),window.liveDesk?.auth?.signInWithGoogle){const z=await window.liveDesk.auth.signInWithGoogle();return z?.ok===!1?(h(z.error||"LiveDesk could not open the system browser for Google sign-in."),!1):!0}return window.location.assign(`${me}/auth/google`),!0},[me]),ne=o.useCallback(async()=>{de.current||(de.current=!0,h("Your saved Google sign-in is incomplete. LiveDesk is reopening sign-in once to repair it."),await pt.auth.signOut({scope:"local"}).catch(()=>{}),a(null),await Ue()||(de.current=!1))},[Ue]),ae=o.useCallback(async z=>{const pe=Gh(z);if(pe)throw new Error(pe);if(U.current)return!1;U.current=!0;try{if(window.liveDesk?.auth?.persistSession){const Y=await window.liveDesk.auth.persistSession(z);if(Y?.ok===!1)throw new Error(Y.error||"LiveDesk could not validate the desktop session.");return h(""),!0}for(let Y=0;Y<2;Y+=1){const K=await $a(me,Y>0),ee=await fetch(`${me}/api/auth/session`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":K},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}})}),R=await ee.json().catch(()=>({}));if(ee.status===403&&Y===0){sessionStorage.removeItem("livedesk.client.csrf");continue}if(!ee.ok)throw new Error(R.error||`Client runtime returned HTTP ${ee.status}.`);return h(""),!0}throw new Error("Client runtime rejected the session transfer.")}finally{U.current=!1}},[me]),le=o.useCallback(()=>{const z=ie.current;if(z)return z;const pe=(async()=>{try{const Y=await fetch(`${me}/api/client/status`,{cache:"no-store",signal:AbortSignal.timeout(1500)}),K=await Y.json().catch(()=>({}));if(!Y.ok)throw new Error(K.error||`Client runtime returned HTTP ${Y.status}.`);if(K.csrfToken&&sessionStorage.setItem("livedesk.client.csrf",K.csrfToken),String(K.role||"").toLowerCase()==="hub")throw new Error("This computer is assigned to the Hub role.");n(K)}catch(Y){h(Y instanceof Error?Y.message:String(Y))}})();return ie.current=pe,pe.finally(()=>{ie.current===pe&&(ie.current=null)}),pe},[me]),ce=o.useCallback(()=>{const z=j.current;if(z)return z;const pe=(async()=>{const Y=await fetch(`${me}/api/client/diagnostics`,{cache:"no-store",signal:AbortSignal.timeout(8e3)}),K=await Y.json().catch(()=>({}));if(!Y.ok)throw new Error(K.error||`Client diagnostics returned HTTP ${Y.status}.`);if(String(K.role||"").toLowerCase()==="hub")throw new Error("This computer is assigned to the Hub role.");n(K)})();return j.current=pe,pe.finally(()=>{j.current===pe&&(j.current=null)}),pe},[me]);o.useEffect(()=>{let z=!1,pe=null;const Y=async()=>{await le(),z||(pe=window.setTimeout(()=>{Y()},2e3))};return Y(),()=>{z=!0,pe!==null&&window.clearTimeout(pe)}},[le]),o.useEffect(()=>{if(V!=="computer")return;let z=!1,pe=null;const Y=()=>{z||(pe=window.setTimeout(()=>{K()},lS))},K=async()=>{document.visibilityState==="visible"&&await ce().catch(()=>{}),Y()},ee=()=>{document.visibilityState==="visible"&&(pe!==null&&(window.clearTimeout(pe),pe=null),K())};return document.addEventListener("visibilitychange",ee),K(),()=>{z=!0,document.removeEventListener("visibilitychange",ee),pe!==null&&window.clearTimeout(pe)}},[V,ce]),o.useEffect(()=>{if(ge.current)return;const z=Number(t?.slotNumber||0);C(z>0?String(z):"")},[t?.slotNumber]),o.useEffect(()=>{if(!I)return;const z=window.setTimeout(()=>F(null),5e3);return()=>window.clearTimeout(z)},[I]),o.useEffect(()=>{const z=String(p||t?.lastError||"").trim();if(!z){oe.current="";return}if(oe.current===z)return;oe.current=z;const pe=/supabase-user-verification-failed:(401|403)/i.test(z)?"Saved sign-in needs refresh. LiveDesk will retry it automatically.":z;F({kind:"error",message:pe})},[p,t?.lastError]);const J=o.useCallback(async()=>{const z=Date.now();if(!(!t?.authenticated||t.connectionState==="connected"||!["waiting","reconnecting"].includes(String(t.agent?.state||""))||z-Q.current<4e3)){Q.current=z;try{const pe=await fetch(`${me}/api/client/reconnect`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await $a(me)},body:JSON.stringify({onlyIfWaiting:!0,reason:"app-active"})});if(!pe.ok)throw new Error(`Client reconnect returned HTTP ${pe.status}.`);await le()}catch(pe){h(pe instanceof Error?pe.message:String(pe))}}},[me,le,t]);o.useEffect(()=>{const z=()=>{J()},pe=()=>{J()},Y=()=>{document.visibilityState==="visible"&&J()};return window.addEventListener("online",z),window.addEventListener("focus",pe),document.addEventListener("visibilitychange",Y),()=>{window.removeEventListener("online",z),window.removeEventListener("focus",pe),document.removeEventListener("visibilitychange",Y)}},[J]),o.useEffect(()=>{if(!i||!t||!s?.access_token||t.authenticated)return;if(Gh(s)==="refresh-token-required"){ne().catch(ee=>{de.current=!1,h(ee instanceof Error?ee.message:String(ee))});return}let z=!1,pe,Y=0;const K=async()=>{if(z)return;try{const R=await ae(s);if(await le(),R)return}catch(R){h(R instanceof Error?R.message:String(R))}if(z)return;const ee=Kh[Math.min(Y,Kh.length-1)];Y+=1,pe=window.setTimeout(()=>{K()},ee)};return K(),()=>{z=!0,pe!==void 0&&window.clearTimeout(pe)}},[i,le,ne,s,t,ae]),o.useEffect(()=>{const z=new URLSearchParams(window.location.search),pe=z.get("auth_error");if(!pe)return;h(pe),z.delete("auth_error");const Y=z.toString();window.history.replaceState(window.history.state,"",`${window.location.pathname}${Y?`?${Y}`:""}${window.location.hash}`)},[]),o.useEffect(()=>{let z=!0;if(!window.liveDesk?.auth)return a(null),c(!0),le(),()=>{z=!1};const pe=window.liveDesk?.auth?.onComplete?.(K=>{K.ok&&K.session?pt.auth.setSession(K.session).catch(ee=>h(ee instanceof Error?ee.message:String(ee))):K.ok&&K.signedOut?(a(null),c(!0),pt.auth.signOut({scope:"local"})):K.error&&h(K.error)});(async()=>{try{const K=window.liveDesk?.auth?.getSession?await window.liveDesk.auth.getSession():await pt.auth.getSession();if(!z)return;const ee=Tb(K);a(ee),le()}catch(K){z&&h(K instanceof Error?K.message:String(K))}finally{z&&c(!0)}})();const{data:Y}=pt.auth.onAuthStateChange((K,ee)=>{if(z){if(!ee&&window.liveDesk?.auth){c(!0);return}a(ee),c(!0),le()}});return()=>{z=!1,pe?.(),Y.subscription.unsubscribe()}},[le]),o.useEffect(()=>{if(!i||!t||re.current||de.current||s||t.authenticated)return;const z=new URLSearchParams(window.location.search);if(!z.has("livedesk_launch"))return;re.current=!0,z.delete("livedesk_launch");const pe=z.toString();window.history.replaceState(window.history.state,"",`${window.location.pathname}${pe?`?${pe}`:""}${window.location.hash}`),Ue().catch(Y=>h(Y instanceof Error?Y.message:String(Y)))},[i,s,Ue,t]);const ye=async()=>{O(!1),window.liveDesk?.auth?.signOut?(await pt.auth.signOut(),(await window.liveDesk.auth.signOut())?.runtimeCleared===!1&&h("Signed out locally. The LiveDesk runtime could not be reached to clear its session.")):await fetch(`${me}/api/auth/session`,{method:"DELETE",headers:{"X-LiveDesk-CSRF":await $a(me)}}).catch(()=>{}),a(null),await le()};o.useEffect(()=>{if(!D)return;const z=Y=>{Y.target instanceof Element&&Y.target.closest(".account-popover, .rail-account")||O(!1)},pe=Y=>{Y.key==="Escape"&&O(!1)};return window.addEventListener("pointerdown",z),window.addEventListener("keydown",pe),()=>{window.removeEventListener("pointerdown",z),window.removeEventListener("keydown",pe)}},[D]);const ue=o.useCallback((z=!0)=>{w||(H(!1),z&&window.requestAnimationFrame(()=>G.current?.focus()))},[w]),Ee=o.useCallback(()=>{w||!t?.authenticated||(G.current=document.activeElement instanceof HTMLElement?document.activeElement:null,g(""),H(!0))},[w,t?.authenticated]);o.useEffect(()=>{if(!M)return;const z=window.requestAnimationFrame(()=>X.current?.focus()),pe=K=>{K.target instanceof Element&&K.target.closest(".client-hub-switch-popover, .client-hub-switch-trigger")||ue(!1)},Y=K=>{K.key==="Escape"&&ue()};return window.addEventListener("pointerdown",pe),window.addEventListener("keydown",Y),()=>{window.cancelAnimationFrame(z),window.removeEventListener("pointerdown",pe),window.removeEventListener("keydown",Y)}},[ue,M]);const nt=async()=>{h("");try{const z=await fetch(`${me}/api/client/pin`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await $a(me)},body:JSON.stringify({pin:u})}),pe=await z.json().catch(()=>({}));if(!z.ok||pe?.ok===!1)throw new Error(pe?.error||"PIN could not be accepted.");d(""),await le()}catch(z){h(z instanceof Error?z.message:String(z))}},T=async()=>{H(!1),v(!0),g(""),h("");try{const z=await fetch(`${me}/api/runtime/switch-role`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await $a(me)},body:JSON.stringify({role:"hub"})}),pe=await z.json().catch(()=>({}));if(!z.ok||pe?.ok===!1)throw new Error(pe?.error||`Role change failed with HTTP ${z.status}.`);g("Hub role accepted. LiveDesk is restarting this computer with the Hub Wall.");const Y=Number(t?.runtimePid||0);await lb({baseUrl:me,targetRole:"hub",previousRuntimePid:Y,allowedStates:["running"]}),window.location.reload()}catch(z){h(z instanceof Error?z.message:String(z)),v(!1)}},ve=async()=>{if(A)return;const z=Number(N);if(!Number.isInteger(z)||z<1||z>999){F({kind:"error",message:"Enter a slot number from 1 to 999."});return}E(!0),F(null);try{const pe=await fetch(`${me}/api/client/slot`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await $a(me)},body:JSON.stringify({slotNumber:z})}),Y=await pe.json().catch(()=>({}));if(!pe.ok||Y.ok===!1){if(Y.error==="slot-taken"){const K=Y.conflict?.deviceName||Y.conflict?.hostname||Y.conflict?.deviceId||"another computer";throw new Error(`Slot ${String(z).padStart(3,"0")} is already used by ${K}.`)}throw new Error(Y.error||`Slot update failed with HTTP ${pe.status}.`)}ge.current=!1,C(String(z)),n(Y),F({kind:"success",message:`Slot ${String(z).padStart(3,"0")} saved. LiveDesk is reconnecting this Client.`})}catch(pe){F({kind:"error",message:pe instanceof Error?pe.message:String(pe)})}finally{E(!1),await le()}},De=async()=>{if(!y){k(!0),h("");try{const z=await fetch(`${me}/api/client/video-acceleration/install`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await $a(me)},body:JSON.stringify({confirm:!0})}),pe=await z.json().catch(()=>({}));if(n(pe),!z.ok||pe.videoAcceleration?.ready!==!0)throw new Error(pe.videoAcceleration?.error||pe.error||"Linux hardware video setup did not complete.")}catch(z){h(z instanceof Error?z.message:String(z))}finally{k(!1),await le()}}},qe=!!(t?.authenticated||s),_e=o.useMemo(()=>wu(),[]),$e=ru("switch-to-hub",_e),mt=ru("client",_e),ct=sS(_e);return r.jsxs("main",{className:"app-shell client-unified-shell",children:[r.jsxs("aside",{className:"tool-rail","aria-label":"LiveDesk Client tools",children:[r.jsx("div",{className:"rail-brand",title:"LiveDesk",children:r.jsx(cb,{size:25})}),r.jsx("nav",{className:"rail-tools","aria-label":"Client navigation",children:r.jsxs("div",{className:"client-main-tool-slot",children:[r.jsxs("button",{className:"rail-tool client-main-tool client-hub-tool client-hub-switch-trigger accent-blue",type:"button",onClick:Ee,disabled:w||!t?.authenticated,"aria-busy":w,"aria-expanded":M,"aria-haspopup":"dialog","aria-controls":M?"client-hub-switch-popover":void 0,"aria-label":`Hub. ${$e}`,"data-tooltip":M?void 0:cp("Hub","switch-to-hub",_e),children:[r.jsx(ls,{size:19}),r.jsx("span",{children:w?"Switching…":"Hub"})]}),r.jsxs("button",{className:`rail-tool client-main-tool accent-blue ${V==="computer"?"active":""}`,type:"button",onClick:()=>P("computer"),"aria-current":V==="computer"?"page":void 0,"aria-label":`Client. ${mt}`,"data-tooltip":cp("Client","client",_e),children:[r.jsx(pn,{size:19}),r.jsx("span",{children:"Client"})]})]})}),r.jsxs("div",{className:"rail-footer",children:[cS.map(z=>{const pe=z.icon;return r.jsxs("button",{className:`rail-tool compact ${V===z.id?"active":""}`,type:"button",onClick:()=>P(z.id),title:z.label,children:[r.jsx(pe,{size:18}),r.jsx("span",{children:z.label})]},z.id)}),r.jsxs("button",{className:`rail-account ${qe?"signed-in":""}`,type:"button",onClick:()=>O(z=>!z),"aria-expanded":D,"aria-haspopup":"dialog",title:qe?"Account":"Sign in",children:[qe&&Ce?r.jsx("img",{src:Ce,alt:Ae,referrerPolicy:"no-referrer",onError:()=>Le(Ce)},Ce):qe?r.jsx("span",{className:"avatar-fallback",children:Fe}):r.jsx(Qs,{size:18}),r.jsx("span",{children:qe?"Account":"Sign in"})]})]})]}),M&&r.jsxs("section",{id:"client-hub-switch-popover",className:"client-hub-switch-popover",role:"dialog","aria-modal":"false","aria-labelledby":"client-hub-switch-title","aria-describedby":"client-hub-switch-description client-hub-switch-restart",children:[r.jsxs("header",{className:"client-hub-switch-head",children:[r.jsx("span",{className:"client-hub-switch-mark","aria-hidden":"true",children:r.jsx(ls,{size:19})}),r.jsx("span",{className:"client-hub-switch-eyebrow",children:ct.eyebrow}),r.jsx("button",{className:"client-hub-switch-close",type:"button",onClick:()=>ue(),"aria-label":ct.closeLabel,children:r.jsx(xn,{size:17})})]}),r.jsx("h2",{id:"client-hub-switch-title",children:ct.title}),r.jsx("p",{id:"client-hub-switch-description",children:ct.description}),r.jsxs("p",{id:"client-hub-switch-restart",className:"client-hub-switch-notice",children:[r.jsx(Zt,{size:16,"aria-hidden":"true"}),r.jsx("span",{children:ct.restartNotice})]}),r.jsxs("div",{className:"client-hub-switch-actions",children:[r.jsx("button",{type:"button",onClick:()=>ue(),children:ct.cancel}),r.jsxs("button",{ref:X,className:"primary",type:"button",onClick:()=>{T()},disabled:w||!t?.authenticated,children:[r.jsx(ls,{size:16}),ct.confirm]})]})]}),D&&r.jsxs("section",{className:"account-popover",role:"dialog","aria-label":"LiveDesk account",children:[r.jsxs("div",{className:"account-popover-head",children:[r.jsx("div",{className:"account-popover-avatar",children:qe&&Ce?r.jsx("img",{src:Ce,alt:Ae,referrerPolicy:"no-referrer",onError:()=>Le(Ce)},Ce):qe?r.jsx("span",{children:Fe}):r.jsx(Qs,{size:18})}),r.jsxs("div",{children:[r.jsx("strong",{children:qe?Ae:"Account"}),r.jsx("p",{children:s?.user.email||t?.userEmail||t?.userId||"Not signed in"})]})]}),r.jsxs("dl",{className:"account-popover-facts",children:[r.jsx("dt",{children:"User"}),r.jsx("dd",{children:s?.user.email||t?.userEmail||t?.userId||"Not signed in"}),r.jsx("dt",{children:"Runtime"}),r.jsx("dd",{children:t?"Local app ready":"Checking local app"}),r.jsx("dt",{children:"Session"}),r.jsx("dd",{children:t?.auth?.persisted?"Saved on this computer":qe?"Active for this run":"Not saved"}),r.jsx("dt",{children:"Role"}),r.jsx("dd",{children:"Client"})]}),qe?r.jsxs("button",{className:"account-popover-action",onClick:()=>{ye()},type:"button",children:[r.jsx(fb,{size:16}),"Logout"]}):r.jsxs("button",{className:"account-popover-action primary",onClick:()=>{O(!1),Ue()},type:"button",children:[r.jsx(Qs,{size:16}),"Sign in with Google"]})]}),r.jsx("section",{className:"desk-stage client-unified-stage",children:V==="support"?r.jsx("section",{className:"client-unified-page",children:r.jsx(Nb,{session:s,currentProductKey:"livedesk",appVersion:t?.appVersion||"",onSignIn:()=>{Ue()}})}):V!=="computer"?r.jsx("section",{className:"client-unified-page",children:r.jsx(gS,{page:V,status:t})}):r.jsx(bS,{session:s,status:t,pin:u,roleChangeMessage:m,videoAccelerationBusy:y,slotInput:N,slotBusy:A,onSignIn:()=>{Ue()},onPinChange:z=>d(z.replace(/\D/g,"").slice(0,6)),onSubmitPin:()=>{nt()},onSlotInputChange:z=>{ge.current=!0,C(z.replace(/\D/g,"").slice(0,3))},onSaveSlot:()=>{ve()},onEnableVideoAcceleration:()=>{De()}})}),I&&r.jsxs("div",{className:`client-side-toast ${I.kind}`,role:I.kind==="error"?"alert":"status",children:[I.kind==="error"?r.jsx(Gy,{size:18}):r.jsx(En,{size:18}),r.jsx("span",{children:I.message}),r.jsx("button",{type:"button",onClick:()=>F(null),"aria-label":"Dismiss notification",children:r.jsx(xn,{size:16})})]})]})}function Ks(e,t,n){if(n<0||t<0||t+n>e.length)throw new Error("Invalid LZO1X block: input overrun.")}function Ad(e,t,n){let s=0;for(;Ks(e,t.inputIndex,1),e[t.inputIndex]===0;)s+=1,t.inputIndex+=1;const a=s*255+n+e[t.inputIndex];return t.inputIndex+=1,a}function kl(e,t,n,s){if(Ks(e,t.inputIndex,s),t.outputIndex+s>n.length)throw new Error("Invalid LZO1X block: output overrun.");n.set(e.subarray(t.inputIndex,t.inputIndex+s),t.outputIndex),t.inputIndex+=s,t.outputIndex+=s}function wS(e,t,n,s){const a=t-n;if(a<=0||s<=0)throw new Error("Invalid LZO1X block: invalid match distance.");let i=Math.min(a,s);for(e.set(e.subarray(n,n+i),t);i<s;){const c=Math.min(i,s-i);e.copyWithin(t+i,t,t+c),i+=c}return t+s}function Fb(e,t){if(!(e instanceof Uint8Array)||e.length<3||t<0)throw new Error("Invalid LZO1X block.");const n=new Uint8Array(t),s={inputIndex:0,outputIndex:0};let a=0,i=0;if(e[s.inputIndex]>=22){const c=e[s.inputIndex]-17;s.inputIndex+=1,kl(e,s,n,c),a=4}else e[s.inputIndex]>=18&&(a=e[s.inputIndex]-17,s.inputIndex+=1,kl(e,s,n,a));for(;;){Ks(e,s.inputIndex,1);const c=e[s.inputIndex];s.inputIndex+=1;let u,d;if((c&192)!==0)Ks(e,s.inputIndex,1),d=s.outputIndex-((e[s.inputIndex]<<3)+(c>>2&7)+1),s.inputIndex+=1,i=(c>>5)+1,u=c&3;else if((c&32)!==0){i=(c&31)+2,i===2&&(i+=Ad(e,s,31)),Ks(e,s.inputIndex,2);const p=e[s.inputIndex]|e[s.inputIndex+1]<<8;s.inputIndex+=2,d=s.outputIndex-((p>>2)+1),u=p&3}else if((c&16)!==0){i=(c&7)+2,i===2&&(i+=Ad(e,s,7)),Ks(e,s.inputIndex,2);const p=e[s.inputIndex]|e[s.inputIndex+1]<<8;if(s.inputIndex+=2,d=s.outputIndex-(((c&8)<<11)+(p>>2)),u=p&3,d===s.outputIndex)break;d-=16384}else if(a===0){let p=c+3;p===3&&(p+=Ad(e,s,15)),kl(e,s,n,p),a=4;continue}else a!==4?(Ks(e,s.inputIndex,1),u=c&3,d=s.outputIndex-((c>>2)+(e[s.inputIndex]<<2)+1),s.inputIndex+=1,i=2):(Ks(e,s.inputIndex,1),u=c&3,d=s.outputIndex-((c>>2)+(e[s.inputIndex]<<2)+2049),s.inputIndex+=1,i=3);if(d<0||s.outputIndex+i+u>n.length)throw new Error("Invalid LZO1X block: lookbehind overrun.");s.outputIndex=wS(n,s.outputIndex,d,i),a=u,kl(e,s,n,u)}if(i!==3||s.inputIndex!==e.length||s.outputIndex!==n.length)throw new Error("Invalid LZO1X block: incomplete output.");return n}const Yh=16,Xh=8,yS=24*1024*1024,Db=new Uint8Array(new Uint32Array([16909060]).buffer)[0]===4,up=new Uint32Array(65536);for(let e=0;e<up.length;e+=1){const t=Math.round((e>>11&31)*255/31),n=Math.round((e>>5&63)*255/63),s=Math.round((e&31)*255/31);up[e]=Db?(t|n<<8|s<<16|4278190080)>>>0:(t<<24|n<<16|s<<8|255)>>>0}function qs(e,t){return e[t]|e[t+1]<<8}function xS(e,t){const n=Number(t);if(!Number.isSafeInteger(n)||n<Yh||n>yS)throw new Error(`Invalid Mode 5 packet length: ${t}.`);const s=e instanceof Uint8Array?e:new Uint8Array(e),a=Fb(s,n);if(a[0]!==76||a[1]!==68||a[2]!==53||a[3]!==68)throw new Error("Invalid Mode 5 packet magic.");if(a[4]!==1)throw new Error(`Unsupported Mode 5 packet version: ${a[4]}.`);const i=(a[5]&1)!==0,c=qs(a,6),u=qs(a,8),d=qs(a,10),p=qs(a,12);if(c<=0||u<=0||c>3840||u>2160)throw new Error(`Invalid Mode 5 frame size: ${c}x${u}.`);if(d<=0||d>256||p>8192)throw new Error(`Invalid Mode 5 tile header: ${d}/${p}.`);const h=[];let m=Yh;for(let g=0;g<p;g+=1){if(m+Xh>a.length)throw new Error("Mode 5 tile header is truncated.");const w=qs(a,m),v=qs(a,m+2),y=qs(a,m+4),k=qs(a,m+6);m+=Xh;const N=y*k*2;if(y<=0||k<=0||y>d||k>d||w+y>c||v+k>u||m+N>a.length)throw new Error(`Invalid Mode 5 tile ${g}.`);h.push({x:w,y:v,width:y,height:k,pixels:a.subarray(m,m+N)}),m+=N}if(m!==a.length)throw new Error(`Mode 5 packet has ${a.length-m} trailing bytes.`);return{keyFrame:i,width:c,height:u,tileSize:d,tiles:h}}function SS(e,t,n,s){if(!(e instanceof Uint8ClampedArray)||e.length!==t*n*4||s.width!==t||s.height!==n)throw new Error("Mode 5 canvas state does not match the packet dimensions.");let a=t,i=n,c=0,u=0;const d=new Uint32Array(e.buffer,e.byteOffset,e.byteLength>>>2);for(const p of s.tiles){const h=Db&&(p.pixels.byteOffset&1)===0?new Uint16Array(p.pixels.buffer,p.pixels.byteOffset,p.pixels.byteLength>>>1):null;let m=0;for(let g=0;g<p.height;g+=1){let w=(p.y+g)*t+p.x;for(let v=0;v<p.width;v+=1){const y=m<<1,k=h?h[m]:p.pixels[y]|p.pixels[y+1]<<8;d[w]=up[k],m+=1,w+=1}}a=Math.min(a,p.x),i=Math.min(i,p.y),c=Math.max(c,p.x+p.width),u=Math.max(u,p.y+p.height)}return s.tiles.length>0?{x:a,y:i,width:c-a,height:u-i}:null}function CS(e){if(!e)return!0;const t=Vt.get(e);return!t||t.hardwareAcceleration==="prefer-hardware"}const Vt=new WeakMap,Jh=854,Zh=480,kS=3840,MS=2160,AS=500,cc=new WeakMap,dp=new WeakMap,Ja=new Set,Ga=new Set,ta=new WeakMap,Ka=new Set,ro=new WeakMap,pp=new WeakMap,mp=new WeakMap,su=new WeakMap,Lb=4,NS=2,Yi=4,RS=2,TS=2,PS=18,IS=0,jS=250,_b=80,ES=5,FS=150,DS=1200,LS=18,_S=.65,$b=80,Ob=125,$S=4,OS=2*1024*1024,BS=8,HS=16,WS=180,zS=3,$p=2e3,Bb=64,Hb=32*1024*1024,qS=500,US=25,VS=45,GS=20,Wb=new Uint8Array(0),Op=250,KS=globalThis.LIVEDESK_ENABLE_CANVAS_VISUAL_SAMPLING===!0;let zb=1,qb=0,Ub=0,hp=0,Vb=0;const Qo=[];let pc=0,Gb=0,Kb,Qb=0,Yb,Xb;function mc(e,t){Qo.push({sequence:++Vb,type:e,canvasId:ro.get(t)||0,observedAt:Date.now(),activeDecoderCount:Ja.size,hardwareLeaseCount:Ga.size,hardwareReleaseGeneration:pc}),Qo.length>256&&Qo.splice(0,Qo.length-256)}let Ps={h264DecodeAcceleration:"prefer-hardware"};function QS(e){e.h264DecodeAcceleration&&(Ps={...Ps,h264DecodeAcceleration:e.h264DecodeAcceleration})}function YS(e){return e.payload.byteLength===0?e:{...e,payload:Wb}}function Jb(e,t){const n=String(e.streamPurpose||"").trim().toLowerCase();return n==="wall"?!0:n==="control"?!1:t>=45e3}function Zb(e){try{return e.paintIsCancelled()}catch{return!0}}function yu(e,t){const n=e.pendingFrames.get(t);if(n)return e.pendingFrames.delete(t),e.pendingFrameBytes=Math.max(0,e.pendingFrameBytes-n.encodedByteLength),e.pendingFrames.size===0&&e.pendingTrimTimer!==null&&(window.clearTimeout(e.pendingTrimTimer),e.pendingTrimTimer=null),n}function XS(e){const t=e.pendingFrames.entries().next().value;return t?yu(e,t[0]):void 0}function ev(e){e.pendingTrimTimer!==null&&(window.clearTimeout(e.pendingTrimTimer),e.pendingTrimTimer=null),e.pendingFrames.clear(),e.pendingFrameBytes=0,e.pendingFrameEvictedThroughTimestamp=-1}function xu(e,t=performance.now()){for(;e.pendingFrames.size>0;){const n=e.pendingFrames.entries().next().value;if(!n)break;const s=t-n[1].queuedAt>$p,a=e.pendingFrames.size>Bb,i=e.pendingFrameBytes>Hb;if(!s&&!a&&!i)break;e.pendingFrameEvictedThroughTimestamp=Math.max(e.pendingFrameEvictedThroughTimestamp,n[0]),yu(e,n[0]),e.pendingFrameEvictionCount+=1}}function JS(e,t,n,s,a,i=performance.now()){yu(e,t);const c={frame:n,queuedAt:i,queueSize:s,encodedByteLength:Math.max(0,Math.floor(Number(n.payload.byteLength||0))),paintIsCancelled:a};e.pendingFrames.set(t,c),e.pendingFrameBytes+=c.encodedByteLength,xu(e,i),e.pendingFrameHighWaterMark=Math.max(e.pendingFrameHighWaterMark,e.pendingFrames.size),e.pendingFrameByteHighWaterMark=Math.max(e.pendingFrameByteHighWaterMark,e.pendingFrameBytes)}function tv(e,t){if(t.pendingTrimTimer!==null||t.pendingFrames.size===0)return;const n=t.pendingFrames.values().next().value;if(!n)return;const s=Math.max(1,$p-(performance.now()-n.queuedAt)+1);t.pendingTrimTimer=window.setTimeout(()=>{t.pendingTrimTimer=null,Vt.get(e)===t&&(xu(t),tv(e,t))},s)}function nv(e){return Ga.delete(e)?(pc+=1,mc("hardware-release",e),!0):!1}function ZS(e,t,n){if(t!=="prefer-hardware"||!n)return!1;const s=ta.get(e);return!s||s.requested!==t||s.actual!=="prefer-software"||pc<=s.failedHardwareReleaseGeneration?!1:(ta.delete(e),Ka.delete(e),Gb+=1,Kb=Date.now(),!0)}function fp(e,t=Ps.h264DecodeAcceleration){const n=ta.get(e);return n?.requested===t?(n.actual!=="prefer-hardware"&&(Ga.delete(e),Ka.add(e)),n.actual):(n&&(ta.delete(e),Ka.delete(e)),t!=="prefer-hardware"?(nv(e),Ka.delete(e),t):(Ga.has(e)||Ga.add(e),"prefer-hardware"))}function Su(e,t,n){if(t!=="prefer-hardware")return!1;const s=ta.get(e),a=Vt.get(e),i=Date.now();return ro.has(e)||ro.set(e,zb++),ta.set(e,{requested:t,actual:"prefer-software",reason:n,failedAt:i,failureCount:(s?.requested===t?s.failureCount:0)+1,codec:a?.codec||s?.codec||"",latencyMode:a?.latencyMode||s?.latencyMode||"smooth",inputCount:a?.inputSerial??s?.inputCount??0,outputCount:a?.outputSerial??s?.outputCount??0,lastInputAt:a?.lastInputAt??s?.lastInputAt??0,lastOutputAt:a?.lastOutputAt??s?.lastOutputAt??0,lastPaintAt:a?.lastPaintAt??s?.lastPaintAt??0,decodeQueueHighWaterMark:Math.max(a?.decodeQueueHighWaterMark??0,s?.decodeQueueHighWaterMark??0),decodeQueueOverflowSamples:Math.max(a?.decodeQueueOverflowSamples??0,s?.decodeQueueOverflowSamples??0),decodeQueueOverflowAgeMs:a?.decodeQueueOverflowStartedAt?Math.max(0,performance.now()-a.decodeQueueOverflowStartedAt):s?.decodeQueueOverflowAgeMs,failedHardwareReleaseGeneration:pc}),Ga.delete(e),Ka.add(e),Qb+=1,Yb=n,Xb=i,!0}function na(e){e.interactivePipelineFallbackTimer!==null&&(window.clearTimeout(e.interactivePipelineFallbackTimer),e.interactivePipelineFallbackTimer=null),e.interactivePipelineFallbackFrame!==null&&(window.cancelAnimationFrame(e.interactivePipelineFallbackFrame),e.interactivePipelineFallbackFrame=null),e.interactivePipelineRecoveryFrames=[],e.interactivePipelineRecoveryBytes=0,e.interactivePipelinePaintIsCancelled=void 0,e.interactivePipelineGuardTimestampUs=null}function rv(e,t){const n=t.interactivePipelineRecoveryFrames,s=t.interactivePipelinePaintIsCancelled,a=t.onBeforePaint,i=t.onPaint;if(na(t),n.length===0||s?.()||Vt.get(e)!==t||t.hardwareAcceleration!=="prefer-hardware"||!Su(e,t.requestedAcceleration,"interactive-pipeline-latency"))return!1;const c=t.requestedAcceleration,u=t.latencyMode;tr(e);try{for(const d of n)Hp(e,d,i,c,u,s,!1,a)}catch{tr(e)}return!0}function eC(e,t,n){const s=Math.max(0,Number(t.payload.byteLength||0));return e.interactivePipelineRecoveryFrames.length>=$S||e.interactivePipelineRecoveryBytes+s>OS?(na(e),!1):(e.interactivePipelineRecoveryFrames.push({...t,payload:t.payload.slice()}),e.interactivePipelineRecoveryBytes+=s,e.interactivePipelinePaintIsCancelled=n,!0)}function tC(e,t,n,s,a=performance.now()){const i=()=>{if(!(Vt.get(e)!==t||t.interactivePipelineGuardTimestampUs!==n)){if(!t.pendingFrames.has(n)){na(t);return}rv(e,t)}},c=u=>{if(t.interactivePipelineFallbackFrame=null,!(Vt.get(e)!==t||t.interactivePipelineGuardTimestampUs!==n)){if(!t.pendingFrames.has(n)){na(t);return}if(u-a>=s){i();return}t.interactivePipelineFallbackFrame=window.requestAnimationFrame(c)}};t.interactivePipelineFallbackTimer=window.setTimeout(i,s),t.interactivePipelineFallbackFrame=window.requestAnimationFrame(c)}function nC(e,t,n,s=64){try{let a=pp.get(e);a||(a={canvas:document.createElement("canvas"),lastHash:"",initialized:!1},pp.set(e,a));const i=Math.max(8,Math.min(64,Math.round(s))),c=Math.max(1,Math.round(i*Math.max(1,n)/Math.max(1,t)));(a.canvas.width!==i||a.canvas.height!==c)&&(a.canvas.width=i,a.canvas.height=c);const u=a.canvas.getContext("2d",{willReadFrequently:!0});if(!u)return{visualHash:"",visualChanged:!0};u.drawImage(e,0,0,Math.max(1,t),Math.max(1,n),0,0,i,c);const d=u.getImageData(0,0,i,c).data;let p=2166136261;for(let g=0;g<d.length;g+=4)p^=d[g],p=Math.imul(p,16777619),p^=d[g+1],p=Math.imul(p,16777619),p^=d[g+2],p=Math.imul(p,16777619);const h=(p>>>0).toString(16).padStart(8,"0"),m=!a.initialized||h!==a.lastHash;return a.initialized=!0,a.lastHash=h,{visualHash:h,visualChanged:m}}catch{return{visualHash:"",visualChanged:!0}}}function gp(e,t,n,s=Op,a=64,i){if(!KS&&i)return sv(e,i);let c=mp.get(e);c||(c={lastHash:"",initialized:!1,lastCanvasSampleAt:0},mp.set(e,c));const u=performance.now();if(c.initialized&&s>0&&u-c.lastCanvasSampleAt<s)return{visualHash:c.lastHash,visualChanged:!1};const d=nC(e,t,n,a);return c.initialized=!0,c.lastHash=d.visualHash,c.lastCanvasSampleAt=u,d}function sv(e,t){let n=su.get(e);n||(n={lastHash:"",initialized:!1},su.set(e,n));const s=String(t.contentHash||""),a=!n.initialized||!s||s!==n.lastHash;return n.initialized=!0,n.lastHash=s,{visualHash:s,visualChanged:a}}function av(e,t,n=!1){const s=dp.get(e);if(s)return s;const a=e.getContext("2d",{alpha:!1,desynchronized:t==="interactive",willReadFrequently:n});if(a){const i=a.getContextAttributes?.(),c={context:a,presentation:i?.desynchronized?"desync":"sync"};return dp.set(e,c),c}return null}function rC(e){const t=String(e.frameMode||e.mode||"").toLowerCase(),n=String(e.compression||"").toLowerCase(),s=String(e.mimeType||"").toLowerCase();return t==="mode2-lzo"||n==="lzo1x"||s==="application/vnd.livedesk.lzo-rgb565"||t==="mode2-lz4"||String(e.compression||"").toLowerCase()==="lz4"||s==="application/vnd.livedesk.lz4-raw"}function sC(e){return String(e.frameMode||e.mode||"").toLowerCase()==="mode3-h264-hw"||String(e.codec||"").toLowerCase()==="h264"||String(e.mimeType||"").toLowerCase()==="video/h264"}function aC(e){const t=String(e.frameMode||e.mode||"").toLowerCase(),n=String(e.mimeType||"").toLowerCase();return t==="mode5-lzo-delta"||n==="application/vnd.livedesk.lzo-rgb565-delta"}function ef(e,t,n){let s=n,a=t;if(s===15){let i=255;for(;i===255;){if(a>=e.length)throw new Error("Invalid LZ4 block: length overrun.");i=e[a],a+=1,s+=i}}return{length:s,cursor:a}}function iC(e,t){const n=new Uint8Array(t);let s=0,a=0;for(;s<e.length;){const i=e[s];s+=1;const c=ef(e,s,i>>4);s=c.cursor;const u=c.length;if(s+u>e.length||a+u>n.length)throw new Error("Invalid LZ4 block: literal overrun.");if(n.set(e.subarray(s,s+u),a),s+=u,a+=u,s>=e.length)break;if(s+2>e.length)throw new Error("Invalid LZ4 block: missing offset.");const d=e[s]|e[s+1]<<8;if(s+=2,d<=0||d>a)throw new Error("Invalid LZ4 block: bad match offset.");const p=ef(e,s,i&15);s=p.cursor;const h=p.length+4;if(a+h>n.length)throw new Error("Invalid LZ4 block: match overrun.");let m=a-d;for(let g=0;g<h;g+=1)n[a]=n[m],a+=1,m+=1}if(a!==n.length)throw new Error("Invalid LZ4 block: incomplete output.");return n}function oC(e){const t=Math.max(1,Math.floor(e.width||0)),n=Math.max(1,Math.floor(e.height||0)),s=String(e.compression||"").toLowerCase(),a=String(e.pixelFormat||e.codec||"").toLowerCase();if(s==="lzo1x"||String(e.frameMode||e.mode||"").toLowerCase()==="mode2-lzo"||String(e.mimeType||"").toLowerCase()==="application/vnd.livedesk.lzo-rgb565"){const h=Math.max(1,Math.floor(e.bytesPerPixel||2)),m=t*n*2,g=Math.floor(e.uncompressedByteLength||m);if(h!==2||g!==m)throw new Error(`Invalid mode2 RGB565 frame size: ${g} for ${t}x${n}.`);if(a&&a!=="rgb565le"&&a!=="rgb565")throw new Error(`Unsupported mode2 pixel format: ${a}`);const w=Fb(e.payload,m),v=new Uint8ClampedArray(t*n*4);for(let y=0,k=0;y<w.length;y+=2,k+=4){const N=w[y]|w[y+1]<<8,C=N>>11&31,A=N>>5&63,E=N&31;v[k]=C<<3|C>>2,v[k+1]=A<<2|A>>4,v[k+2]=E<<3|E>>2,v[k+3]=255}return new ImageData(v,t,n)}const c=Math.max(1,Math.floor(e.bytesPerPixel||4)),u=Math.max(t*n*c,Math.floor(e.uncompressedByteLength||0)),d=iC(e.payload,u);if(c!==4)throw new Error(`Unsupported mode2 pixel size: ${c}`);const p=new Uint8ClampedArray(t*n*4);if(a==="rgba32"||a==="rgba")p.set(d.subarray(0,p.length));else for(let h=0,m=0;m<p.length;h+=4,m+=4)p[m]=d[h+2],p[m+1]=d[h+1],p[m+2]=d[h],p[m+3]=d[h+3];return new ImageData(p,t,n)}function tf(e,t="smooth",n=Ps.h264DecodeAcceleration){const s=window.VideoDecoder;if(!s||!window.EncodedVideoChunk)throw new Error("WebCodecs H.264 decode is not supported in this browser.");const a=Vt.get(e);if(a&&a.decoder.state!=="closed"&&a.latencyMode===t)return a;a&&tr(e);let i;const c=new s({output:u=>{if(Vt.get(e)!==i){u.close();return}const d=Number(u.timestamp||0),p=performance.now();i.outputSerial+=1,xu(i,p);let h=yu(i,d);if(!h&&d>i.pendingFrameEvictedThroughTimestamp&&i.pendingFrames.size>0&&(h=XS(i),i.timestampFallbacks+=1),!h){i.pendingFrameUnmatchedOutputCount+=1,i.droppedForLatency+=1,i.lastOutputAt=p,u.close();return}const m=i.interactivePipelineGuardTimestampUs===d;if(Zb(h)){m&&na(i),i.droppedForLatency+=1,i.lastOutputAt=p,u.close();return}const g=u.displayWidth||u.codedWidth||e.width||960,w=u.displayHeight||u.codedHeight||e.height||540,v=Number(h?.frame.durationUs||0),y=Number(u.duration||0),k=Math.max(16,Math.min(250,(v>0?v:y||83333)/1e3));i.targetPaintIntervalMs=k;const N=Math.max(0,p-h.queuedAt),A=Jb(h.frame,v>0?v:Math.round(k*1e3))?Ob:$b;if(i.latencyMode==="interactive"&&i.hardwareAcceleration==="prefer-hardware"&&m&&i.interactivePipelineRecoveryFrames.length>0&&N>A){u.close(),i.droppedForLatency+=1,rv(e,i);return}m&&na(i),Math.abs(i.interactiveBurstOutputCadenceMs-k)>1&&(i.interactiveBurstOutputTimeCursor=0,i.interactiveBurstOutputTimeCount=0,i.interactiveBurstOutputCadenceMs=k,i.interactiveBurstOutputWindowMs=0),i.interactiveBurstOutputTimes[i.interactiveBurstOutputTimeCursor]=p,i.interactiveBurstOutputTimeCursor=(i.interactiveBurstOutputTimeCursor+1)%Yi,i.interactiveBurstOutputTimeCount=Math.min(Yi,i.interactiveBurstOutputTimeCount+1);const E=i.interactiveBurstOutputTimeCount>=Yi?p-i.interactiveBurstOutputTimes[i.interactiveBurstOutputTimeCursor]:0;for(i.interactiveBurstOutputWindowMs=Math.max(0,E),i.decodedFrames.push({videoFrame:u,pending:h,decodedAt:p,width:g,height:w,durationMs:k}),i.latencyMode==="interactive"&&i.targetPaintIntervalMs>20&&i.interactiveBurstOutputTimeCount>=Yi&&E<=Math.min(VS,Math.max(US,i.targetPaintIntervalMs-5))&&(i.interactiveBurstTailHoldArmed=!0),i.lastOutputAt=p;i.decodedFrames.length>Bp(i);)au(i,i.decodedFrames.shift(),"capacity");i.renderQueueHighWaterMark=Math.max(i.renderQueueHighWaterMark,i.decodedFrames.length),ov(i),i.renderTimer!==null&&i.renderScheduledAt>0&&performance.now()-i.renderScheduledAt>qS&&(typeof document>"u"||document.visibilityState==="visible")&&(window.cancelAnimationFrame(i.renderTimer),i.renderTimer=null,i.renderScheduledAt=0),i.renderTimer!==null&&i.decodedFrames.length>=Lb&&(window.cancelAnimationFrame(i.renderTimer),i.renderTimer=null,i.renderScheduledAt=0),iu(e,i)},error:()=>{Vt.get(e)===i&&(Su(e,i.requestedAcceleration,"decoder-error"),tr(e))}});return qb+=1,ro.has(e)||ro.set(e,zb++),i={decoder:c,configured:!1,configKey:"",codec:"",requestedAcceleration:n,hardwareAcceleration:fp(e,n),latencyMode:t,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,interactiveBurstTailHoldArmed:!1,interactiveBurstTailHoldCount:0,interactiveBurstOutputTimes:new Float64Array(Yi),interactiveBurstOutputTimeCursor:0,interactiveBurstOutputTimeCount:0,interactiveBurstOutputCadenceMs:0,interactiveBurstOutputWindowMs:0,interactivePipelineFallbackTimer:null,interactivePipelineFallbackFrame:null,interactivePipelineGuardTimestampUs:null,interactivePipelineRecoveryFrames:[],interactivePipelineRecoveryBytes:0,interactivePipelinePaintIsCancelled:void 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},Vt.set(e,i),Ja.add(e),hp=Math.max(hp,Ja.size),mc("create",e),i}function iv(e){na(e),e.renderTimer!==null&&(window.cancelAnimationFrame(e.renderTimer),e.renderTimer=null),e.renderScheduledAt=0,e.flushTimer!==null&&(window.clearTimeout(e.flushTimer),e.flushTimer=null),e.flushInFlight=!1;const t=e.decodedFrames;e.decodedFrames=[];for(const n of t)try{n.videoFrame.close()}catch{}e.interactiveBufferPrimed=!1,e.interactiveBufferStartedAt=0,e.interactiveBurstTailHoldArmed=!1,e.interactiveBurstOutputTimeCursor=0,e.interactiveBurstOutputTimeCount=0,e.interactiveBurstOutputCadenceMs=0,e.interactiveBurstOutputWindowMs=0}function au(e,t,n="other"){t&&(t.videoFrame.close(),e.droppedForLatency+=1,n==="capacity"?e.renderQueueCapacityDropCount+=1:n==="age"&&(e.renderQueueAgeDropCount+=1))}function Bp(e){return e.latencyMode==="interactive"?e.targetPaintIntervalMs<=20?RS:Yi:String(e.decodedFrames[0]?.pending?.frame.frameMode||e.decodedFrames[0]?.pending?.frame.mode||"").toLowerCase()==="mode4-h264-atlas"?NS:Lb}function ov(e,t=performance.now()){const n=Bp(e);for(;e.decodedFrames.length>n;)au(e,e.decodedFrames.shift(),"capacity");const s=e.latencyMode==="interactive"?_b:jS;let a=e.decodedFrames[0];for(;e.decodedFrames.length>0&&a&&t-a.decodedAt>s;)au(e,e.decodedFrames.shift(),"age"),a=e.decodedFrames[0]}function cv(e,t){if(t.hardwareAcceleration!=="prefer-hardware"||t.latencyMode==="interactive"||t.flushTimer!==null||t.flushInFlight)return;const n=FS;t.flushTimer=window.setTimeout(async()=>{t.flushTimer=null;const s=performance.now();if(xu(t,s),Vt.get(e)!==t||t.decoder.state!=="configured"||t.pendingFrames.size===0||t.inputSerial<=t.lastFlushInputSerial||t.lastOutputAt>0&&s-t.lastOutputAt<n)return;const a=t.inputSerial;t.flushInFlight=!0,t.flushCount+=1,t.keyFrameSeen=!1;try{await t.decoder.flush(),t.lastFlushInputSerial=Math.max(t.lastFlushInputSerial,a)}catch{Vt.get(e)===t&&Kl(t)}finally{t.flushInFlight=!1,Vt.get(e)===t&&t.inputSerial>a&&t.pendingFrames.size>0&&performance.now()-t.lastOutputAt>=n&&cv(e,t)}},n)}function cC(e,t,n,s){const a=performance.now();if(t.interactiveBackingWidth>0&&t.interactiveBackingHeight>0&&a-t.interactiveBackingMeasuredAt<AS)return{width:Math.min(n,t.interactiveBackingWidth),height:Math.min(s,t.interactiveBackingHeight)};const i=typeof e.getBoundingClientRect=="function"?e.getBoundingClientRect():{width:Number(e.clientWidth||e.width||0),height:Number(e.clientHeight||e.height||0)},c=Math.max(1,Math.min(2,Number(globalThis.devicePixelRatio)||1)),u=Math.max(0,Number(e.width||0)),d=Math.max(0,Number(e.height||0)),p=i.width>0?Math.round(i.width*c):u||Jh,h=i.height>0?Math.round(i.height*c):d||Zh,m=Math.min(1,p/n,h/s),g=Math.min(1,Math.max(Jh/n,Zh/s)),w=Math.min(1,kS/n,MS/s),v=Math.max(.01,Math.min(w,Math.max(g,m)));return t.interactiveBackingWidth=Math.max(1,Math.round(n*v)),t.interactiveBackingHeight=Math.max(1,Math.round(s*v)),t.interactiveBackingMeasuredAt=a,{width:t.interactiveBackingWidth,height:t.interactiveBackingHeight}}function nf(e,t,n){const s=performance.now();try{if(!n.pending||Zb(n.pending)){t.droppedForLatency+=1;return}let a=1;try{const h=t.onBeforePaint?.(n.pending.frame);typeof h=="number"&&Number.isFinite(h)&&(a=Math.max(.05,Math.min(1,h)))}catch{}const i=t.latencyMode==="interactive"?cC(e,t,n.width,n.height):{width:n.width,height:n.height},c=i.width,u=i.height,d=e.width!==c||e.height!==u;d&&(e.width=c,e.height=u);const p=av(e,t.latencyMode,t.hardwareAcceleration==="prefer-software");if(p){const h=p.context.globalAlpha;p.context.globalAlpha=d||t.lastPaintAt<=0||t.hardwareAcceleration!=="prefer-hardware"?1:a;try{p.context.drawImage(n.videoFrame,0,0,n.width,n.height,0,0,c,u)}finally{p.context.globalAlpha=h}}if(n.pending){const h=performance.now(),g=t.latencyMode==="interactive"?sv(e,n.pending.frame):gp(e,n.width,n.height,Op,64,n.pending.frame),w=YS(n.pending.frame);try{t.onPaint?.(w,{deviceId:w.deviceId,frameSeq:w.frameSeq,mode:w.frameMode||w.mode||w.codec||w.mimeType,width:n.width,height:n.height,byteLength:w.byteLength,queuedForMs:Math.max(0,s-n.pending.queuedAt),decodedForMs:Math.max(0,n.decodedAt-n.pending.queuedAt),scheduledForMs:Math.max(0,s-n.decodedAt),drawMs:Math.max(0,h-s),queueSize:n.pending.queueSize,renderQueueSize:t.decodedFrames.length,droppedForLatency:t.droppedForLatency,h264DecodeAcceleration:t.hardwareAcceleration,decoderLabel:t.hardwareAcceleration,decoderFlushCount:t.flushCount,decoderTimestampFallbacks:t.timestampFallbacks,decoderInputCount:t.inputSerial,decoderOutputCount:t.outputSerial,targetPaintIntervalMs:t.targetPaintIntervalMs,canvasPresentation:p?.presentation||"sync",interactiveBufferWaitCount:t.interactiveBufferWaitCount,interactiveBufferWaitMs:t.interactiveBufferWaitMs,interactiveQueueDrainCount:t.interactiveQueueDrainCount,interactiveBurstOutputWindowMs:t.interactiveBurstOutputWindowMs,interactiveBurstTailHoldCount:t.interactiveBurstTailHoldCount,visualHash:g.visualHash,visualChanged:g.visualChanged,paintedAt:h})}catch{}}t.lastPaintAt=performance.now()}finally{n.videoFrame.close()}}function iu(e,t){if(t.renderTimer!==null||t.decodedFrames.length===0)return;const n=Math.max(16,Math.min(250,t.targetPaintIntervalMs||1e3/12)),s=()=>{if(t.renderTimer=null,t.renderScheduledAt=0,t.decodedFrames.length===0)return;const a=performance.now();if(ov(t,a),t.decodedFrames.length===0){t.interactiveBurstTailHoldArmed=!1;return}if(t.latencyMode==="interactive"){const d=t.targetPaintIntervalMs<=20;if(d&&!t.interactiveBufferPrimed){t.interactiveBufferStartedAt<=0&&(t.interactiveBufferStartedAt=a,t.interactiveBufferWaitCount+=1);const h=t.decodedFrames.length>=TS,m=a-t.interactiveBufferStartedAt>=PS;if(!h&&!m){t.renderScheduledAt=performance.now(),t.renderTimer=window.requestAnimationFrame(s);return}t.interactiveBufferWaitMs+=Math.max(0,a-t.interactiveBufferStartedAt),t.interactiveBufferPrimed=!0}else d||(t.interactiveBufferPrimed=!0);if(!d&&t.interactiveBurstTailHoldArmed&&t.decodedFrames.length===1&&a-t.decodedFrames[0].decodedAt<=_b-GS){t.interactiveBurstTailHoldArmed=!1,t.interactiveBurstTailHoldCount+=1,t.renderScheduledAt=performance.now(),t.renderTimer=window.requestAnimationFrame(s);return}const p=t.decodedFrames.shift();if(p)try{nf(e,t,p)}catch{}t.decodedFrames.length===0&&(t.interactiveQueueDrainCount+=1,t.interactiveBufferPrimed=!1,t.interactiveBufferStartedAt=0,t.interactiveBurstTailHoldArmed=!1),iu(e,t);return}const i=t.lastPaintAt>0?t.lastPaintAt+n:a+IS;if(!(a+ES>=i||t.decodedFrames.length>=Math.max(1,Bp(t)-1))){t.renderScheduledAt=performance.now(),t.renderTimer=window.requestAnimationFrame(s);return}const u=t.decodedFrames.shift();if(u)try{nf(e,t,u)}catch{}iu(e,t)};t.renderScheduledAt=performance.now(),t.renderTimer=window.requestAnimationFrame(s)}function lv(e,t){if(Vt.get(e)!==t||t.decoder.state==="closed")return!1;for(t.renderTimer!==null&&(window.cancelAnimationFrame(t.renderTimer),t.renderTimer=null),t.renderScheduledAt=0;t.decodedFrames.length>1;)au(t,t.decodedFrames.shift());return t.lastPaintAt=0,t.interactiveBufferPrimed=!1,t.interactiveBufferStartedAt=0,t.interactiveBurstTailHoldArmed=!1,t.interactiveBurstOutputTimeCursor=0,t.interactiveBurstOutputTimeCount=0,t.interactiveBurstOutputCadenceMs=0,t.interactiveBurstOutputWindowMs=0,iu(e,t),!0}function Nd(){if(!(typeof document>"u"||document.visibilityState!=="visible"))for(const e of Ja){const t=Vt.get(e);if(!t||t.decoder.state==="closed"){Ja.delete(e);continue}lv(e,t)}}typeof document<"u"&&typeof window<"u"&&(document.addEventListener("visibilitychange",Nd),window.addEventListener("focus",Nd),window.addEventListener("pageshow",Nd));function tr(e){nv(e),Ja.delete(e),su.delete(e);const t=Vt.get(e);if(t){Vt.delete(e),Ub+=1,ev(t),t.onBeforePaint=void 0,t.onPaint=void 0,iv(t);try{t.decoder.state!=="closed"&&t.decoder.reset()}catch{}try{t.decoder.state!=="closed"&&t.decoder.close()}catch{}mc("close",e)}}function zi(e){e&&(ta.delete(e),Ka.delete(e),dp.delete(e),mp.delete(e),pp.delete(e),su.delete(e),cc.delete(e),tr(e))}function lC(e,t){const n=Vt.get(e),s=ta.get(e);if(!n&&!s)return null;const a=c=>c>0?Math.max(0,t-c):void 0,i=n?.pendingFrames.values().next().value;return{canvasId:ro.get(e)||0,canvasWidth:Math.max(0,Number(e.width||0)),canvasHeight:Math.max(0,Number(e.height||0)),decoderState:n?.decoder.state||"fallback-pending",configured:n?.configured||!1,keyFrameSeen:n?.keyFrameSeen||!1,codec:n?.codec||s?.codec||"",requestedAcceleration:n?.requestedAcceleration||s?.requested||Ps.h264DecodeAcceleration,configuredAcceleration:n?.hardwareAcceleration||s?.actual||Ps.h264DecodeAcceleration,latencyMode:n?.latencyMode||s?.latencyMode||"smooth",decodeQueueSize:Math.max(0,Number(n?.decoder.decodeQueueSize||0)),decodeQueueHighWaterMark:Math.max(0,Number(n?.decodeQueueHighWaterMark??0),Number(s?.decodeQueueHighWaterMark??0)),decodeQueueOverflowSamples:Math.max(0,Number(n?.decodeQueueOverflowSamples??0),Number(s?.decodeQueueOverflowSamples??0)),decodeQueueOverflowAgeMs:n?.decodeQueueOverflowStartedAt?Math.max(0,t-n.decodeQueueOverflowStartedAt):s?.decodeQueueOverflowAgeMs,pendingFrameCount:n?.pendingFrames.size||0,pendingFrameBytes:n?.pendingFrameBytes||0,pendingFrameHighWaterMark:n?.pendingFrameHighWaterMark||0,pendingFrameByteHighWaterMark:n?.pendingFrameByteHighWaterMark||0,pendingFrameEvictionCount:n?.pendingFrameEvictionCount||0,pendingFrameUnmatchedOutputCount:n?.pendingFrameUnmatchedOutputCount||0,pendingFrameOldestAgeMs:i?Math.max(0,t-i.queuedAt):void 0,pendingFrameMaxCount:Bb,pendingFrameMaxBytes:Hb,pendingFrameMaxAgeMs:$p,renderQueueSize:n?.decodedFrames.length||0,renderQueueHighWaterMark:n?.renderQueueHighWaterMark||0,renderQueueCapacityDropCount:n?.renderQueueCapacityDropCount||0,renderQueueAgeDropCount:n?.renderQueueAgeDropCount||0,interactiveBurstTailHoldCount:n?.interactiveBurstTailHoldCount||0,interactiveBurstOutputWindowMs:Math.max(0,Number(n?.interactiveBurstOutputWindowMs||0)),interactivePipelineRecoveryBytes:Math.max(0,Number(n?.interactivePipelineRecoveryBytes||0)),targetPaintIntervalMs:Math.max(0,Number(n?.targetPaintIntervalMs||0)),droppedForLatency:Math.max(0,Number(n?.droppedForLatency||0)),inputCount:n?.inputSerial??s?.inputCount??0,outputCount:n?.outputSerial??s?.outputCount??0,lastInputAgeMs:a(n?.lastInputAt??s?.lastInputAt??0),lastOutputAgeMs:a(n?.lastOutputAt??s?.lastOutputAt??0),lastPaintAgeMs:a(n?.lastPaintAt??s?.lastPaintAt??0),softwareFallbackReason:s?.reason,softwareFallbackAt:s?.failedAt,softwareFallbackCount:s?.failureCount||0}}function Ml(e,t={}){const n=performance.now(),a=(e?[e]:[...new Set([...Ja,...Ka])]).map(u=>lC(u,n)).filter(u=>u!==null),i=a.reduce((u,d)=>u+d.pendingFrameCount,0),c=a.reduce((u,d)=>u+d.pendingFrameBytes,0);return{capturedAt:Date.now(),hardwareRequestPolicy:"all-active",activeDecoderCount:a.filter(u=>u.decoderState!=="fallback-pending").length,hardwareLeaseCount:Ga.size,hardwareReleaseGeneration:pc,hardwareRecoveryProbeCount:Gb,lastHardwareRecoveryProbeAt:Kb,activeSoftwareFallbackCount:a.filter(u=>u.configuredAcceleration==="prefer-software"&&u.requestedAcceleration==="prefer-hardware").length,decoderCreateCount:qb,decoderCloseCount:Ub,activeDecoderHighWaterMark:hp,decoderLifecycleSequence:Vb,decoderLifecycleEvents:t.includeLifecycleEvents===!1?[]:Qo.map(u=>({...u})),softwareFallbackEventCount:Qb,lastSoftwareFallbackReason:Yb,lastSoftwareFallbackAt:Xb,pendingFrameCount:i,pendingFrameBytes:c,canvases:a}}function Kl(e,t=1){try{e.decoder.state!=="closed"&&e.decoder.reset()}catch{}e.configured=!1,e.configKey="",e.keyFrameSeen=!1,ev(e),iv(e),e.lastPaintAt=0,e.lastOutputAt=0,e.lastInputAt=0,e.interactiveBufferPrimed=!1,e.interactiveBufferStartedAt=0,e.lastInputFrameSeq=void 0,e.nextChunkTimestampUs=0,e.healthSampleStartedAt=performance.now(),e.healthInputSerial=e.inputSerial,e.healthOutputSerial=e.outputSerial,e.decodeQueueOverflowStartedAt=0,e.decodeQueueOverflowSamples=0,e.droppedForLatency+=Math.max(1,Math.min(1e4,Math.floor(t)))}function uC(e,t,n=performance.now()){const s=Math.max(0,Number.isFinite(t)?t:0);if(e.decodeQueueHighWaterMark=Math.max(e.decodeQueueHighWaterMark,s),s<=BS)return e.decodeQueueOverflowStartedAt=0,e.decodeQueueOverflowSamples=0,!1;e.decodeQueueOverflowStartedAt<=0?(e.decodeQueueOverflowStartedAt=n,e.decodeQueueOverflowSamples=1):e.decodeQueueOverflowSamples+=1;const a=Math.max(0,n-e.decodeQueueOverflowStartedAt);return s>=HS||e.decodeQueueOverflowSamples>=zS&&a>=WS}function dC(e,t,n,s,a,i){t.decoder.configure(n),t.configured=!0,t.configKey=s,t.codec=n.codec,t.requestedAcceleration=i,t.hardwareAcceleration=a,t.keyFrameSeen=!1,t.nextChunkTimestampUs=0,t.lastInputFrameSeq=void 0,mc("configure",e)}function pC(e,t){if(t.latencyMode!=="interactive"||t.hardwareAcceleration!=="prefer-hardware")return!1;const n=performance.now();if(n-t.healthSampleStartedAt<DS)return!1;const s=t.inputSerial-t.healthInputSerial,a=t.outputSerial-t.healthOutputSerial;return t.healthSampleStartedAt=n,t.healthInputSerial=t.inputSerial,t.healthOutputSerial=t.outputSerial,s<LS||a/Math.max(1,s)>=_S?!1:(Su(e,t.requestedAcceleration,"interactive-health"),tr(e),!0)}function qi(e,t=1){if(!e)return!1;const n=Vt.get(e);return n?(n.droppedForLatency+=Math.max(1,Math.min(1e4,Math.floor(t))),tr(e),!0):!1}function mC(e){if(!e)return!1;const t=Vt.get(e);return t?lv(e,t):!1}function hC(e,t,n,s="interactive",a){tr(e);const i=performance.now(),c=xS(t.payload,t.uncompressedByteLength||0),u=String(t.streamId||"mode5");let d=cc.get(e);if(!d||d.streamId!==u||d.width!==c.width||d.height!==c.height){const k=new Uint8ClampedArray(c.width*c.height*4);for(let N=3;N<k.length;N+=4)k[N]=255;d={streamId:u,width:c.width,height:c.height,rgba:k,imageData:new ImageData(k,c.width,c.height),keyFrameSeen:!1,inputSerial:0,outputSerial:0},cc.set(e,d)}if(!d)throw new Error("Mode 5 canvas state could not be initialized.");d.inputSerial+=1;const h=Number(t.streamFrameSeq||0);if(h>0&&(d.lastStreamFrameSeq=h),!c.keyFrame&&!d.keyFrameSeen)return;c.keyFrame&&(d.keyFrameSeen=!0);const m=SS(d.rgba,d.width,d.height,c),g=performance.now();try{a?.(t)}catch{}(e.width!==d.width||e.height!==d.height)&&(e.width=d.width,e.height=d.height);const w=av(e,s),v=performance.now();m&&w?.context.putImageData(d.imageData,0,0,m.x,m.y,m.width,m.height);const y=performance.now();d.outputSerial+=1,n?.(t,{deviceId:t.deviceId,frameSeq:t.frameSeq,mode:t.frameMode||t.mode||t.mimeType,width:d.width,height:d.height,byteLength:t.byteLength,queuedForMs:Math.max(0,y-i),decodedForMs:Math.max(0,g-i),scheduledForMs:0,drawMs:Math.max(0,y-v),queueSize:0,renderQueueSize:0,droppedForLatency:0,h264DecodeAcceleration:"prefer-software",decoderLabel:"lzo-rgb565-delta",decoderFlushCount:0,decoderTimestampFallbacks:0,decoderInputCount:d.inputSerial,decoderOutputCount:d.outputSerial,targetPaintIntervalMs:Math.max(1,Number(t.durationUs||0)/1e3||1e3/30),canvasPresentation:w?.presentation||"sync",interactiveBufferWaitCount:0,interactiveBufferWaitMs:0,interactiveQueueDrainCount:0,visualHash:String(t.contentHash||""),visualChanged:Number(t.deltaVisualTileCount||0)>0,paintedAt:y})}const Rd=[{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 rf(e,t){for(let n=Math.max(0,t);n+3<e.length;n+=1)if(!(e[n]!==0||e[n+1]!==0)){if(e[n+2]===1)return{index:n,length:3};if(e[n+2]===0&&e[n+3]===1)return{index:n,length:4}}return null}function fC(e){let t=0;for(;t<e.length;){const n=rf(e,t);if(!n)break;const s=n.index+n.length,a=rf(e,s),i=a?.index??e.length;if(s<i&&(e[s]&31)===7){const c=[];let u=0;for(let d=s+1;d<i;d+=1){const p=e[d];if(u>=2&&p===3){u=0;continue}c.push(p),u=p===0?u+1:0}if(c.length>=3)return`avc1.${c.slice(0,3).map(d=>d.toString(16).toUpperCase().padStart(2,"0")).join("")}`}t=a?a.index:e.length}return""}function gC(e,t,n,s,a=""){const i=Math.ceil(e/16)*Math.ceil(t/16),c=n>0?1e6/n:30,u=i*c,d=Rd.find(p=>i<=p.maxFrameSize&&u<=p.maxMacroblocksPerSecond)||Rd[Rd.length-1];return fC(s)||a||`avc1.42E0${d.code.toString(16).toUpperCase().padStart(2,"0")}`}function Hp(e,t,n,s,a="smooth",i=()=>!1,c=!0,u){cc.delete(e);const d=String(t.h264Format||"").toLowerCase()==="avc"?"avc":"annexb",p=Math.max(1,Math.floor(t.width||960)),h=Math.max(1,Math.floor(t.height||540)),m=Math.max(1,Math.floor(t.durationUs||1e6/12)),g=s||Ps.h264DecodeAcceleration,w=t.isKeyFrame===!0||String(t.chunkType||"").toLowerCase()==="key";ZS(e,g,w);let v=tf(e,a,g);const y=gC(p,h,m,t.payload,v.codec);let k=fp(e,g),N="";const C=()=>{N=[t.streamId||"",t.commandId||"",p,h,y,d,g,k,a].join("|")};C(),v.onBeforePaint=u,v.onPaint=n,v.configured&&v.decoder.state!=="configured"&&(v.configured=!1,v.configKey=""),v.configured&&v.configKey!==N&&(tr(e),v=tf(e,a,g),v.onBeforePaint=u,v.onPaint=n,k=fp(e,g),C());const A=()=>({codec:y,codedWidth:p,codedHeight:h,hardwareAcceleration:k,optimizeForLatency:!0,avc:{format:d}}),E=re=>v.hardwareAcceleration!=="prefer-hardware"||!Su(e,v.requestedAcceleration,re)?!1:(tr(e),c&&w&&Hp(e,t,n,g,a,i,!1,u),!0),I=()=>{try{return dC(e,v,A(),N,k,g),!0}catch(re){if(E("configure-error"))return!1;throw tr(e),re}};if(!v.configured&&!I())return;const F=Number(t.streamFrameSeq||0);if(F>0&&v.lastInputFrameSeq!==void 0&&(F<=v.lastInputFrameSeq&&(!w||F===v.lastInputFrameSeq||(Kl(v,v.lastInputFrameSeq-F+1),!I()))||F>v.lastInputFrameSeq+1&&(Kl(v,F-v.lastInputFrameSeq-1),!w||!I()))||(F>0&&(v.lastInputFrameSeq=F),!w&&!v.keyFrameSeen))return;w&&(v.keyFrameSeen=!0);const M=Number(v.decoder.decodeQueueSize||0);if(uC(v,M)){if(v.latencyMode==="interactive"&&v.hardwareAcceleration==="prefer-hardware"){E("decode-queue-overflow");return}if(Kl(v),!w||!I())return;v.keyFrameSeen=!0}const H=v.nextChunkTimestampUs;v.nextChunkTimestampUs+=m,JS(v,H,t,M,i),tv(e,v),v.inputSerial+=1,v.lastInputAt=performance.now(),v.inputSerial===1&&mc("first-input",e);const V=t.payload.buffer,P=V instanceof ArrayBuffer?[V]:[],D=Jb(t,m),O=!D&&v.outputSerial>0,X=w&&v.latencyMode==="interactive"&&v.hardwareAcceleration==="prefer-hardware"&&(D||O),G=D?Ob:$b;X&&(na(v),v.interactivePipelineGuardTimestampUs=H);const U=v.interactivePipelineGuardTimestampUs!==null&&v.interactivePipelineRecoveryFrames.length>0,ie=X||U?eC(v,t,i):!1,j=new EncodedVideoChunk({type:w?"key":"delta",timestamp:H,duration:m,data:t.payload,transfer:P});t.payload=Wb;try{v.decoder.decode(j)}catch(re){if(E("decode-error"))return;throw tr(e),re}ie&&Vt.get(e)===v&&v.interactivePipelineGuardTimestampUs===H&&X&&tC(e,v,H,G),cv(e,v),pC(e,v)}async function Td(e,t,n,s,a,i="smooth",c=n,u){if(aC(t)){n()||hC(e,t,s,i,u);return}if(sC(t)){n()||Hp(e,t,s,a,i,c,!0,u);return}if(cc.delete(e),rC(t)){tr(e);const w=oC(t);if(n())return;try{u?.(t)}catch{}(e.width!==w.width||e.height!==w.height)&&(e.width=w.width,e.height=w.height);const v=e.getContext("2d"),y=performance.now();v?.putImageData(w,0,0);const k=performance.now(),N=gp(e,w.width,w.height,Op,64,t);s?.(t,{deviceId:t.deviceId,frameSeq:t.frameSeq,mode:t.frameMode||t.mode||t.codec||t.mimeType,width:w.width,height:w.height,byteLength:t.byteLength,queuedForMs:0,decodedForMs:0,scheduledForMs:0,drawMs:Math.max(0,k-y),queueSize:0,renderQueueSize:0,droppedForLatency:0,h264DecodeAcceleration:Ps.h264DecodeAcceleration,decoderLabel:"lzo-rgb565",decoderFlushCount:0,decoderTimestampFallbacks:0,decoderInputCount:0,decoderOutputCount:0,targetPaintIntervalMs:0,canvasPresentation:"sync",interactiveBufferWaitCount:0,interactiveBufferWaitMs:0,interactiveQueueDrainCount:0,visualHash:N.visualHash,visualChanged:N.visualChanged,paintedAt:k});return}tr(e);const d=new Blob([t.payload],{type:t.mimeType}),p=await createImageBitmap(d);if(n()){p.close();return}const h=t.width||p.width||960,m=t.height||p.height||540;try{u?.(t)}catch{}(e.width!==h||e.height!==m)&&(e.width=h,e.height=m);const g=e.getContext("2d");if(g){const w=performance.now();g.clearRect(0,0,h,m),g.drawImage(p,0,0,h,m);const v=performance.now(),y=gp(e,h,m);s?.(t,{deviceId:t.deviceId,frameSeq:t.frameSeq,mode:t.frameMode||t.mode||t.codec||t.mimeType,width:h,height:m,byteLength:t.byteLength,queuedForMs:0,decodedForMs:0,scheduledForMs:0,drawMs:Math.max(0,v-w),queueSize:0,renderQueueSize:0,droppedForLatency:0,h264DecodeAcceleration:Ps.h264DecodeAcceleration,decoderLabel:"image",decoderFlushCount:0,decoderTimestampFallbacks:0,decoderInputCount:0,decoderOutputCount:0,targetPaintIntervalMs:0,canvasPresentation:"sync",interactiveBufferWaitCount:0,interactiveBufferWaitMs:0,interactiveQueueDrainCount:0,visualHash:y.visualHash,visualChanged:y.visualChanged,paintedAt:v})}p.close()}function bC(e){queueMicrotask(e)}function vC(e){return e?(e.width=0,e.height=0,!0):!1}function Cu(e,t){if(!e)return!1;try{t?.(e)}finally{vC(e)}return!0}function Wp(e,t){if(!e||!t)return 0;const n=Math.max(0,Number(e.get(t)||0))+1;return e.set(t,n),n}function wC(e,t){if(!e||!t)return 0;const n=Number(e.get(t)||0);return Number.isSafeInteger(n)&&n>0?n:Wp(e,t)}function sf(e,t){return Wp(e,t)}function af(e,t,n){return!!e&&!!t&&Number(n)>0&&Number(e.get(t)||0)===Number(n)}function yC(e,t,n){if(!e||!e.has(t))return!1;const s=e.get(t);return e.delete(t),Cu(s,n)}function xC(e,t,n){const s=new Set;for(const a of e||[])if(a){for(const i of a.values())i&&s.add(i);a.clear()}for(const a of t||[])a&&s.add(a);for(const a of s)Cu(a,n);return s.size}function SC(e,{isCurrent:t,dispose:n,schedule:s=bC}){return!e||typeof t!="function"?!1:(s(()=>{t(e)||Cu(e,n)}),!0)}const CC=new Uint8Array(0);function qa(e){if(!e||typeof e!="object")return e;const t=e.payload;return t instanceof Uint8Array&&t.byteLength===0?e:{...e,payload:CC}}function kC(e,t){const n=qa(t);return e.set(t.deviceId,n),n}function MC(e,t){for(const[n,s]of t.entries())e.set(n,qa(s));return t.clear(),new Map(e)}const AC=1500;function NC(e={}){const t=Math.max(10,Math.min(1e4,Number(e.closeDeadlineMs)||AC)),n=typeof e.setTimeout=="function"?e.setTimeout:setTimeout,s=typeof e.clearTimeout=="function"?e.clearTimeout:clearTimeout,a=new Set,i=new WeakMap;let c=0,u=0;const d=(p,h)=>{if(!p||p.settled)return!1;p.settled=!0,p.timer!==null&&(s(p.timer),p.timer=null);try{p.socket.removeEventListener?.("close",p.handleClose)}catch{}return a.delete(p),i.delete(p.entry),h&&(c+=1),!0};return Object.freeze({beginClosing(p,h="livedesk-frame-socket-release"){if(!p?.socket||i.has(p))return!1;const m=p.socket;if(Number(m.readyState)===3)return!1;const g={entry:p,socket:m,timer:null,settled:!1,handleClose:null};g.handleClose=()=>d(g,!1),i.set(p,g),a.add(g),u=Math.max(u,a.size);try{m.addEventListener?.("close",g.handleClose)}catch{}g.timer=n(()=>{if(!g.settled){try{m.close()}catch{}d(g,Number(m.readyState)!==3)}},t);try{Number(m.readyState)===0||Number(m.readyState)===1?m.close(1e3,h):m.close()}catch{try{m.close()}catch{}}return Number(m.readyState)===3&&d(g,!1),!0},snapshot(){return{closingSocketCount:a.size,closingSocketTimerCount:[...a].filter(p=>p.timer!==null).length,closingSocketTimeoutCount:c,maximumClosingSocketCount:u}}})}function RC(e,t="livedesk-frame-socket-release",n=null){if(!e)return 0;const s=[e],a=new Set;let i=0;for(;s.length>0;){const c=s.pop();if(!c||a.has(c))continue;a.add(c);const u=c.handoffFrom;c.handoffFrom=void 0,u&&!a.has(u)&&s.push(u);const d=c.disposed===!0;c.disposed=!0,c.handoffCompleted=!0;const p=c.detachListeners;c.detachListeners=void 0;try{p?.()}catch{}const h=c.releaseOwnedState;c.releaseOwnedState=void 0;try{h?.()}catch{}if(!d){if(n?.beginClosing)n.beginClosing(c,t);else try{c.socket.readyState===0||c.socket.readyState===1?c.socket.close(1e3,t):c.socket.close()}catch{try{c.socket.close()}catch{}}i+=1}}return i}const of=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"]),TC=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 PC(e){return[String(e?.deviceId||""),String(e?.sessionId||""),String(e?.streamId||""),String(e?.commandId||""),String(Number(e?.captureGeneration||0)||0),String(Number.isFinite(Number(e?.monitorIndex))?Number(e.monitorIndex):-1),String(e?.streamPurpose||"")].join("\0")}function IC(e,t){return!!t&&String(e?.deviceId||"")===String(t.deviceId||"")&&String(e?.sessionId||"")===String(t.sessionId||"")&&String(e?.streamId||"")===String(t.streamId||"")&&String(e?.commandId||"")===String(t.commandId||"")&&(Number(e?.captureGeneration||0)||0)===(Number(t.captureGeneration||0)||0)&&(Number.isFinite(Number(e?.monitorIndex))?Number(e.monitorIndex):-1)===(Number.isFinite(Number(t.monitorIndex))?Number(t.monitorIndex):-1)&&String(e?.streamPurpose||"")===String(t.streamPurpose||"")}function jC(){return{ownerKey:"",values:Object.create(null)}}function cf(e){e&&(e.ownerKey="",e.values=Object.create(null))}function EC(e,t,n){if(!e||!t||!IC(e,n))return!1;const s=PC(n);if(t.ownerKey!==s&&(t.ownerKey=s,t.values=Object.create(null)),e.nativeCaptureTelemetryAvailable===!1){for(const a of of)a!=="nativeCaptureTelemetryAvailable"&&(delete t.values[a],delete e[a]);return t.values.nativeCaptureTelemetryAvailable=!1,!0}if(e.nativeCaptureResourceTelemetryAvailable===!1)for(const a of TC)delete t.values[a],delete e[a];for(const a of of)Object.prototype.hasOwnProperty.call(e,a)?t.values[a]=e[a]:Object.prototype.hasOwnProperty.call(t.values,a)&&(e[a]=t.values[a]);return!0}const uv=new ArrayBuffer(0);function FC(e){return`${String(e?.streamId||"")}:${Number(e?.frameSeq||0)}`}function DC(e){return!e||typeof e!="object"||e.payload instanceof ArrayBuffer&&e.payload.byteLength===0?e:{...e,payload:uv}}function LC(){let e=null,t="";return{accept(n){e=DC(n)},publish(){const n=e;if(e=null,!n)return null;const s=FC(n);return s===t?null:(t=s,n)},clear(){e=null,t=""},inspect(){return{pending:e?1:0,pendingPayloadBytes:Number(e?.payload?.byteLength||0),publishedKey:t}}}}const _C=0,$C=1,lf=3;function Tn(e){return Math.max(0,Math.floor(Number(e)||0))}function Er(e,t){return!t||t.active||t.socket!==null||t.audioContext!==null||t.statsTimer!==null||t.scheduledSourceCount!==0||t.pendingDecodeCount!==0||t.workletNodeCount!==0||t.workletPortCount!==0||t.pcmRingCapacityBytes!==0||t.pcmRingBufferedBytes!==0||t.pendingWorkletPacketCount!==0||t.pendingWorkletPacketBytes!==0||t.retainedFrameCount!==0||t.retainedPayloadBytes!==0?!1:e.delete(t)}function OC(){const e=new Set;let t=null;const n={ownerCount:0,socketCount:0,audioContextCount:0,workletNodeCount:0,workletPortCount:0},s=()=>{let a=0,i=0,c=0,u=0;for(const d of e){const p=Number(d.socket?.readyState);a+=d.socket&&p!==lf?1:0,i+=d.audioContext===null?0:1,c+=Tn(d.workletNodeCount),u+=Tn(d.workletPortCount)}n.ownerCount=Math.max(n.ownerCount,e.size),n.socketCount=Math.max(n.socketCount,a),n.audioContextCount=Math.max(n.audioContextCount,i),n.workletNodeCount=Math.max(n.workletNodeCount,c),n.workletPortCount=Math.max(n.workletPortCount,u)};return{createOwner({deviceId:a,socket:i,audioContext:c,statsTimer:u=null}){t=null;const d={deviceId:String(a||""),active:!0,socket:i||null,audioContext:c||null,statsTimer:u,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 e.add(d),s(),d},recordTerminalFailure(a,i,c="playback"){return e.has(a)?(t={deviceId:a.deviceId,phase:String(c||"playback").slice(0,64),message:String(i||"Remote audio playback failed.").slice(0,512)},!0):!1},deactivate(a){return e.has(a)?(a.active=!1,Er(e,a)):!1},setSocket(a,i){return e.has(a)?(a.socket=i||null,s(),Er(e,a)):!1},setAudioContext(a,i){return e.has(a)?(a.audioContext=i||null,s(),Er(e,a)):!1},setStatsTimer(a,i){return e.has(a)?(a.statsTimer=i??null,Er(e,a)):!1},setScheduledSourceCount(a,i){return e.has(a)?(a.scheduledSourceCount=Tn(i),Er(e,a)):!1},setPendingDecodeCount(a,i){return e.has(a)?(a.pendingDecodeCount=Tn(i),Er(e,a)):!1},setWorkletNode(a,i,c,u=a?.workletNodeCreateCount){return e.has(a)?(a.workletNodeCount=Tn(i),a.workletPortCount=Tn(c),a.workletNodeCreateCount=Tn(u),s(),Er(e,a)):!1},setPcmRing(a,i,c){return e.has(a)?(a.pcmRingCapacityBytes=Tn(i),a.pcmRingBufferedBytes=Math.min(a.pcmRingCapacityBytes,Tn(c)),Er(e,a)):!1},setPendingWorkletPackets(a,i,c,u=a?.pendingWorkletPacketHighWater,d=a?.pendingWorkletByteHighWater){return e.has(a)?(a.pendingWorkletPacketCount=Tn(i),a.pendingWorkletPacketBytes=Tn(c),a.pendingWorkletPacketHighWater=Math.max(a.pendingWorkletPacketHighWater,Tn(u)),a.pendingWorkletByteHighWater=Math.max(a.pendingWorkletByteHighWater,Tn(d)),Er(e,a)):!1},setRetainedFrame(a,i,c=0){return e.has(a)?(a.retainedFrameCount=Tn(i),a.retainedPayloadBytes=Tn(c),Er(e,a)):!1},releaseIfDrained(a){return Er(e,a)},hasOwner(a){return e.has(a)},snapshot(){const a=[...e].map(c=>{const u=Number(c.socket?.readyState),d=c.socket&&u!==lf?1:0;return{deviceId:c.deviceId,active:c.active,socketCount:d,openSocketCount:u===$C?1:0,connectingSocketCount:u===_C?1:0,audioContextCount:c.audioContext===null?0:1,statsTimerCount:c.statsTimer===null?0:1,scheduledSourceCount:c.scheduledSourceCount,pendingDecodeCount:c.pendingDecodeCount,workletNodeCount:c.workletNodeCount,workletPortCount:c.workletPortCount,workletNodeCreateCount:c.workletNodeCreateCount,pcmRingCapacityBytes:c.pcmRingCapacityBytes,pcmRingBufferedBytes:c.pcmRingBufferedBytes,pendingWorkletPacketCount:c.pendingWorkletPacketCount,pendingWorkletPacketBytes:c.pendingWorkletPacketBytes,pendingWorkletPacketHighWater:c.pendingWorkletPacketHighWater,pendingWorkletByteHighWater:c.pendingWorkletByteHighWater,retainedFrameCount:c.retainedFrameCount,retainedPayloadBytes:c.retainedPayloadBytes}}),i=c=>a.reduce((u,d)=>u+Tn(d[c]),0);return{ownerCount:a.length,activeOwnerCount:a.filter(c=>c.active).length,socketCount:i("socketCount"),openSocketCount:i("openSocketCount"),connectingSocketCount:i("connectingSocketCount"),audioContextCount:i("audioContextCount"),statsTimerCount:i("statsTimerCount"),scheduledSourceCount:i("scheduledSourceCount"),pendingDecodeCount:i("pendingDecodeCount"),workletNodeCount:i("workletNodeCount"),workletPortCount:i("workletPortCount"),workletNodeCreateCount:i("workletNodeCreateCount"),pcmRingCapacityBytes:i("pcmRingCapacityBytes"),pcmRingBufferedBytes:i("pcmRingBufferedBytes"),pendingWorkletPacketCount:i("pendingWorkletPacketCount"),pendingWorkletPacketBytes:i("pendingWorkletPacketBytes"),pendingWorkletPacketHighWater:i("pendingWorkletPacketHighWater"),pendingWorkletByteHighWater:i("pendingWorkletByteHighWater"),retainedFrameCount:i("retainedFrameCount"),retainedPayloadBytes:i("retainedPayloadBytes"),ownerHighWater:n.ownerCount,socketHighWater:n.socketCount,audioContextHighWater:n.audioContextCount,workletNodeHighWater:n.workletNodeCount,workletPortHighWater:n.workletPortCount,lastTerminalFailure:t,owners:a}}}}const Xt=OC();function BC(){let e=Promise.resolve(),t=0,n=0,s=0;return{acquire(a){const i=++s;let c=!1,u=!1,d=!1,p;const h=new Promise(v=>{p=v}),m=Promise.resolve(e).catch(()=>{});e=m.then(()=>h);const g=()=>d?!1:(d=!0,c&&(t=Math.max(0,t-1)),p(),!0),w=m.then(async()=>{if(u||d)return g(),null;c=!0,t+=1,n=Math.max(n,t);try{return await a({ownerId:i,release:g})}catch(v){throw g(),v}});return{ownerId:i,ready:w,release:g,cancel(){u=!0,c||g()}}},snapshot(){return{activeOwnerCount:t,ownerHighWater:n,nextOwnerId:s}}}}const HC=BC(),uf=1e3;function WC({enabled:e,now:t,lastPublishedAt:n,intervalMs:s=uf}){if(!e)return!1;const a=Math.max(0,Number(t)||0),i=Math.max(0,Number(n)||0),c=Math.max(1,Number(s)||uf);return i<=0||a-i>=c}const dv="livedesk-remote-audio-v1",zC=250,qC=160,bp=4;function UC(e){const t=String(e||"").toLowerCase();return t.includes("audio/pcm")||t.includes("f32le")||t.includes("s16le")}function vp(e={},t={}){const n=String(t.deviceId||""),s=String(t.streamId||"");return!!n&&!!s&&String(e.deviceId||"")===n&&String(e.streamId||"")===s}function VC(e={},t={}){if(!vp(e,t))return{accepted:!1,reason:"owner-mismatch",nextFrameSeq:Math.max(0,Math.floor(Number(t.lastFrameSeq)||0))};const n=Math.max(0,Math.floor(Number(e.frameSeq)||0)),s=Math.max(0,Math.floor(Number(t.lastFrameSeq)||0));return n>0&&n<=s?{accepted:!1,reason:"sequence-not-newer",nextFrameSeq:s}:{accepted:!0,reason:"",nextFrameSeq:n}}function GC(e={}){const t=String(e.capturePhase||"").toLowerCase(),n=String(e.backendKind||"").toLowerCase(),s=e.captureAlive===!0?!0:e.captureAlive===!1?!1:null,a=e.helperAlive===!0?!0:e.helperAlive===!1?!1:null,i=Math.max(0,Math.floor(Number(e.helperPid)||0)),c=n==="windows-wasapi-in-process",u=n==="macos-screencapturekit-helper"||n==="linux-system-audio-helper",d=c||u,p=e.helperRequired===!0?!0:e.helperRequired===!1?!1:u?!0:c?!1:null,h=p===!1?!0:p===!0?a===!0&&i>0:!1,m=t==="starting"||t==="capture-active-awaiting-current-pcm",g=t==="active"&&s===!0&&d&&h,w=t==="failed"||t==="stopped"||s===!1||t==="active"&&(!d||!h);let v="";return m?v="awaiting-current-pcm":!c&&!u?v="backend-unknown":t!=="active"?v=t?`phase-${t}`:"phase-unknown":s!==!0?v="capture-not-alive":p===!0&&a!==!0?v="external-helper-not-alive":p===!0&&i<=0&&(v="external-helper-pid-missing"),{capturePhase:t,backendKind:n,captureAlive:s,helperAlive:a,helperPid:i,helperRequired:p,inProcessBackend:c,externalHelperBackend:u,backendKnown:d,helperReady:h,awaitingCurrentPcm:m,healthy:g,failed:w,reason:v}}function ra(e,t){const n=Math.floor(Number(e));return Number.isFinite(n)&&n>0?n:t}function zp(e={}){const t=Math.max(8e3,Math.min(192e3,ra(e.sampleRate,48e3))),n=Math.max(1,Math.min(8,ra(e.channels,2))),s=String(e.mimeType||"").toLowerCase(),i=String(e.sampleFormat||"").toLowerCase()==="s16le"||s.includes("s16le")||s.includes("audio/l16")?"s16le":"f32le";return{sampleRate:t,channels:n,sampleFormat:i}}function qp(e={}){const t=zp(e),n=Math.max(1,Math.min(250,ra(e.maxDurationMs,250))),s=Math.max(1,Math.ceil(t.sampleRate*n/1e3));return{...t,maxDurationMs:n,capacityFrames:s,capacityBytes:s*t.channels*Float32Array.BYTES_PER_ELEMENT}}function KC(e={}){const t=qp(e),n=Math.max(0,Math.min(t.maxDurationMs,ra(e.targetLeadMs,160))),s=Math.min(t.capacityFrames,Math.max(1,Math.ceil(t.sampleRate*n/1e3)));let a=new Float32Array(t.capacityFrames*t.channels),i=0,c=0,u=0,d=0,p=!1,h=!1,m=0,g=0,w=0;const v={acceptedFrames:0,droppedFrames:0},y=()=>(w+=1,{sampleRate:t.sampleRate,channels:t.channels,sampleFormat:t.sampleFormat,maxDurationMs:t.maxDurationMs,targetLeadMs:n,capacityFrames:h?0:t.capacityFrames,capacityBytes:h?0:t.capacityBytes,bufferedFrames:h?0:u,bufferedBytes:h?0:u*t.channels*Float32Array.BYTES_PER_ELEMENT,bufferedMs:h?0:u*1e3/t.sampleRate,droppedFrames:m,underflowCount:g,started:!h&&p,disposed:h}),k=()=>{i=0,c=0,u=0,d=0,p=!1},N=()=>{h||(k(),a=new Float32Array(0),h=!0)},C=(I,F=0,M,H=t.sampleFormat)=>{if(v.acceptedFrames=0,v.droppedFrames=0,h||!(I instanceof ArrayBuffer))return v;const V=Math.max(0,Math.floor(Number(F)||0)),P=Math.max(0,I.byteLength-V),D=Math.min(P,Math.max(0,Math.floor(Number(M??P)||0))),O=H==="s16le",X=O?2:4,G=X*t.channels,U=Math.floor(D/G);if(U<=0)return v;const ie=Math.min(U,t.capacityFrames),j=U-ie,re=Math.max(0,u+ie-t.capacityFrames);re>0&&(i=(i+re)%t.capacityFrames,u-=re);const de=j+re;m+=de;const Q=new DataView(I,V,D);for(let ge=j;ge<U;ge+=1){const oe=c*t.channels,me=ge*t.channels;for(let Ae=0;Ae<t.channels;Ae+=1){const Pe=(me+Ae)*X,Se=O?Q.getInt16(Pe,!0)/32768:Q.getFloat32(Pe,!0);a[oe+Ae]=Number.isFinite(Se)?Math.max(-1,Math.min(1,Se)):0}c=(c+1)%t.capacityFrames}return u+=ie,!p&&u>=s&&(p=!0),v.acceptedFrames=ie,v.droppedFrames=de,v};return{writePcm:(I={})=>C(I.buffer,I.byteOffset,I.byteLength,I.sampleFormat),writePcmBuffer:C,readToChannels:(I,F=t.sampleRate)=>{if(!Array.isArray(I)||I.length===0)return;let M=Number.POSITIVE_INFINITY;for(let P=0;P<I.length;P+=1){const D=I[P];M=Math.min(M,D?.length||0)}if(h||!Number.isFinite(M)||M<=0||!p){for(let P=0;P<I.length;P+=1)I[P]?.fill?.(0);return}const H=Math.max(8e3,Math.min(192e3,ra(F,t.sampleRate))),V=t.sampleRate/H;for(let P=0;P<M;P+=1){if(u<=0){p=!1,g+=1,d=0;for(let X=0;X<I.length;X+=1)I[X].fill(0,P);break}const D=i*t.channels;for(let X=0;X<I.length;X+=1){const G=Math.min(X,t.channels-1);I[X][P]=a[D+G]}d+=V;const O=Math.min(u,Math.floor(d));O>0&&(i=(i+O)%t.capacityFrames,u-=O,d-=O)}},flush:k,dispose:N,snapshot:y,getSnapshotCount:()=>w}}function QC(e={}){const t=Math.max(1,Math.min(bp,ra(e.maxPendingPackets,bp))),n=Math.max(1,ra(e.maxPendingBytes,1)),s=new Map;let a=0,i=0,c=0,u=0,d=0,p=!1;const h=()=>({terminal:p,maxPendingPackets:t,maxPendingBytes:n,pendingPacketCount:s.size,pendingPacketBytes:a,pendingPacketHighWater:i,pendingByteHighWater:c,acceptedCount:u,droppedCount:d});return{claim(m,g){const w=typeof m=="number"&&Number.isFinite(m)?m:String(m||""),v=Math.max(0,Math.floor(Number(g)||0));return p||!w||v<=0||s.has(w)||s.size>=t||a+v>n?(d+=1,!1):(s.set(w,v),a+=v,i=Math.max(i,s.size),c=Math.max(c,a),u+=1,!0)},acknowledge(m){const g=typeof m=="number"&&Number.isFinite(m)?m:String(m||""),w=s.get(g);return w===void 0?!1:(s.delete(g),a=Math.max(0,a-w),!0)},terminate(){return s.clear(),a=0,p=!0,h()},getPendingPacketCount:()=>s.size,getPendingPacketBytes:()=>a,getPendingPacketHighWater:()=>i,getPendingByteHighWater:()=>c,snapshot:h}}function ku(e,t){const n=String(e?.name||"");if(!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(n)||!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t))throw new Error("Remote Audio worklet function binding name is invalid.");const s=`const ${n} = ${Function.prototype.toString.call(e)};`;return n===t?s:`${s}
4
+ const ${t} = ${n};`}const YC=ku(ra,"positiveInteger"),XC=ku(zp,"normalizeRemoteAudioPcmFormat"),JC=ku(qp,"remoteAudioPcmRingCapacity"),ZC=ku(KC,"createRemoteAudioPcmRing"),e0=`
5
+ const REMOTE_AUDIO_PCM_RING_MAX_MS = ${zC};
6
+ const REMOTE_AUDIO_PCM_TARGET_LEAD_MS = ${qC};
10
7
  ${YC}
8
+ ${XC}
9
+ ${JC}
10
+ ${ZC}
11
11
 
12
12
  class LiveDeskRemoteAudioProcessor extends AudioWorkletProcessor {
13
13
  constructor() {
@@ -158,13 +158,13 @@ class LiveDeskRemoteAudioProcessor extends AudioWorkletProcessor {
158
158
  }
159
159
 
160
160
  registerProcessor(
161
- '${lv}',
161
+ '${dv}',
162
162
  LiveDeskRemoteAudioProcessor
163
163
  );
164
- `;function JC({eligibleCandidates:e,fallbackHubBaseUrl:t,publicConsole:n,authenticated:s}){const a=[...new Set((Array.isArray(e)?e:[]).map(c=>String(c||"").trim()).filter(Boolean))];if(a.length>0)return Object.freeze({candidates:Object.freeze(a),transport:"auto",reason:"direct-candidate"});const i=String(t||"").trim();return Object.freeze(n&&s&&i?{candidates:Object.freeze([i]),transport:"relay",reason:"authenticated-public-console-fallback"}:{candidates:Object.freeze([]),transport:"auto",reason:"unavailable"})}const ZC=new Set(["not-connected","device-not-connected"]);function uf(e,t=!1){const n=String(e||"").trim().toLowerCase();return n==="capture_transition_in_progress".toLowerCase()?t===!0:ZC.has(n)}const df="livedesk_remote_host_targets",e0="livedesk_entitlements",pf=4e3,t0=2500,qp=new TextDecoder,vp=new Set;function n0(){const e=[...vp].map(n=>n()),t=n=>e.reduce((s,a)=>s+Number(a[n]||0),0);return{ownerCount:e.length,activeOwnerCount:e.filter(n=>n.active).length,socketCount:t("socketCount"),openSocketCount:t("openSocketCount"),connectingSocketCount:t("connectingSocketCount"),closingSocketCount:t("closingSocketCount"),closingSocketTimerCount:t("closingSocketTimerCount"),closingSocketTimeoutCount:t("closingSocketTimeoutCount"),expectedBindingCount:t("expectedBindingCount"),reconnectTimerCount:t("reconnectTimerCount"),statsTimerCount:t("statsTimerCount"),configurationRefreshTimerCount:t("configurationRefreshTimerCount"),restartTokenCount:t("restartTokenCount"),retainedFrameCount:t("retainedFrameCount"),retainedPayloadBytes:t("retainedPayloadBytes"),owners:e}}function r0(){return Xt.snapshot()}function s0(e){const n=(Array.isArray(e)?e:[e||an]).map(s=>cb(s||an));return[...new Set(n.filter(Boolean))]}function a0(){const[e,t]=o.useState(null),[n,s]=o.useState(!0),a=o.useRef(null);return o.useEffect(()=>{let i=!0,c=0;const u=async(g=!1)=>{try{const w=await(window.liveDesk?.auth?.getSession?.()||pt.auth.getSession());if(!i)return;const v=Nb(w);(g||v)&&t(v)}finally{i&&s(!1)}},d=()=>{if(document.visibilityState==="hidden")return;const g=Date.now();g-c<1e3||(c=g,Qa(a,()=>u(!1)).catch(()=>{}))},p=window.liveDesk?.auth?.onComplete?.(g=>{g.ok&&g.session?pt.auth.setSession(g.session):g.ok&&g.signedOut&&(t(null),s(!1),pt.auth.signOut({scope:"local"}).catch(()=>{}))});u(!0).catch(()=>{});const{data:{subscription:h}}=pt.auth.onAuthStateChange((g,w)=>{if(!w&&window.liveDesk?.auth){s(!1);return}t(w),s(!1),w&&window.liveDesk?.auth?.persistSession?.(w)}),m=()=>d();return window.addEventListener("pageshow",d),window.addEventListener("online",d),window.addEventListener("focus",d),document.addEventListener("visibilitychange",m),()=>{i=!1,p?.(),h.unsubscribe(),window.removeEventListener("pageshow",d),window.removeEventListener("online",d),window.removeEventListener("focus",d),document.removeEventListener("visibilitychange",m)}},[]),{session:e,loading:n}}function i0(e,t=!0,n=""){const[s,a]=o.useState(null),[i,c]=o.useState([]),[u,d]=o.useState(""),[p,h]=o.useState(""),m=o.useRef(new Map),g=o.useRef(null),w=Array.isArray(e)?e.join(`
165
- `):String(e||""),v=o.useMemo(()=>s0(e),[w]),y=o.useMemo(()=>v.find(C=>Ul(C)==="loopback")||v[0]||an,[v]),k=o.useCallback(async C=>{if(!t){a(null),c([]),h(""),d("");return}let A=null;const E=Date.now(),I=v.filter(M=>(m.current.get(M)||0)<=E),F=JC({eligibleCandidates:I,fallbackHubBaseUrl:y,publicConsole:eu(),authenticated:!!n});if(F.candidates.length===0)throw new Error("No LiveDesk Hub endpoint is reachable. Retrying shortly.");for(const M of F.candidates)try{const[H,V]=await Promise.all([Oe("/api/remote/status",{signal:C,timeoutMs:pf,transport:F.transport},M),Oe("/api/remote/devices",{signal:C,timeoutMs:pf,transport:F.transport},M)]);if(C?.aborted)throw C.reason||new Error("LiveDesk Hub snapshot cancelled.");if(!Array.isArray(V.devices))throw new Error("Invalid Hub devices response.");m.current.delete(M),a(H),c(V.devices),h(M),d("");return}catch(H){if(C?.aborted)throw H;A=H,F.transport==="auto"&&m.current.set(M,Date.now()+1e4)}throw h(""),A||new Error("No LiveDesk Hub endpoint is reachable.")},[n,t,y,v]),N=o.useCallback(()=>{m.current.clear(),Qa(g,()=>k()).catch(C=>{d(C instanceof Error?C.message:String(C))})},[k]);return o.useEffect(()=>{if(m.current.clear(),!t){a(null),c([]),h(""),d("");return}let C=!0,A=null;const E=new AbortController,I=()=>{Qa(g,()=>k(E.signal)).catch(M=>{C&&!E.signal.aborted&&d(M instanceof Error?M.message:String(M))}).finally(()=>{C&&!E.signal.aborted&&(A=window.setTimeout(I,t0))})};return I(),()=>{C=!1,E.abort(new Error("LiveDesk Hub snapshot polling stopped.")),A!==null&&window.clearTimeout(A)}},[t,k]),o.useEffect(()=>{if(!t)return;let C=0;const A=()=>{if(document.visibilityState==="hidden")return;const I=Date.now();I-C<1e3||(C=I,m.current.clear(),eu()&&Dy(),N())},E=()=>A();return window.addEventListener("pageshow",A),window.addEventListener("online",A),window.addEventListener("focus",A),document.addEventListener("visibilitychange",E),()=>{window.removeEventListener("pageshow",A),window.removeEventListener("online",A),window.removeEventListener("focus",A),document.removeEventListener("visibilitychange",E)}},[t,N]),{status:s,devices:i,error:u,refresh:N,hubBaseUrl:p||y,hubCandidates:v}}function o0(e){const[t,n]=o.useState(null),[s,a]=o.useState(""),i=e?.user?.id||"",c=o.useRef(null),u=o.useCallback(async()=>{if(!i){n(null);return}const{data:d,error:p}=await pt.from(df).select("*").eq("user_id",i).maybeSingle();if(p){a(p.message);return}n(d),a("")},[i]);return o.useEffect(()=>{Qa(c,u).catch(()=>{})},[u]),o.useEffect(()=>{if(!i)return;let d=0;const p=()=>{if(document.visibilityState==="hidden")return;const m=Date.now();m-d<1e3||(d=m,Qa(c,u).catch(()=>{}))},h=()=>p();return window.addEventListener("pageshow",p),window.addEventListener("online",p),window.addEventListener("focus",p),document.addEventListener("visibilitychange",h),()=>{window.removeEventListener("pageshow",p),window.removeEventListener("online",p),window.removeEventListener("focus",p),document.removeEventListener("visibilitychange",h)}},[u,i]),o.useEffect(()=>{if(!i)return;const d=pt.channel(`livedesk-remote-host-targets-${i.replace(/[^a-zA-Z0-9]/g,"")}`).on("postgres_changes",{event:"*",schema:"public",table:df,filter:`user_id=eq.${i}`},p=>n(p.new)).subscribe();return()=>{pt.removeChannel(d)}},[i]),{target:t,error:s,refresh:u}}function c0(e){const[t,n]=o.useState(null),[s,a]=o.useState(!1),[i,c]=o.useState(""),u=e?.user?.id||"",d=o.useCallback(async()=>{if(!u){n(null),c(""),a(!1);return}a(!0);const{data:h,error:m}=await pt.from(e0).select("*").eq("user_id",u).eq("product_key","livedesk").maybeSingle();if(m){c(m.message),a(!1);return}n(h),c(""),a(!1)},[u]);o.useEffect(()=>{d()},[d]);const p=o.useMemo(()=>!t||t.status!=="active"?!1:t.expires_at?new Date(t.expires_at).getTime()>Date.now():!0,[t]);return{entitlement:t,licensed:p,loading:s,error:i,refresh:d}}const Zo={totalFrames:0,totalBytes:0,framesPerSecond:0,bytesPerSecond:0,sampleMs:0,lastUpdatedAt:0},l0=2500,u0=3e4,d0=64*1024,p0=64*1024,m0=6,h0=m0,uv=new Map;function f0(e){return uv.get(e)}const mf={totalSent:0,totalDropped:0,sentPerSecond:0,droppedPerSecond:0,bufferedAmount:0,lastInputType:"",lastInputSeq:0,lastRoundTripMs:0,lastAgentApplyMs:0,lastUpdatedAt:0};function g0(e,t,n){const s=Number(t);if(!Number.isFinite(s)||s<=0)return 0;const a=n-s,i=e.minimumHubClockOffsetMs;if(!Number.isFinite(i)||a<Number(i))return e.minimumHubClockOffsetMs=a,0;const c=Math.max(0,a-Number(i));return c>u0?(e.minimumHubClockOffsetMs=a,0):c}function Ve(e){if(e==null||e==="")return;const t=Number(e);return Number.isFinite(t)?t:void 0}const b0=["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 v0(e){return Number(e.nativeCaptureTelemetryVersion)>=5&&b0.every(t=>Ve(e[t])!==void 0)&&typeof e.nativeOutputQueueAwaitingKeyFrame=="boolean"&&e.nativeCopyTelemetryAvailable===!0}function w0(e,t,n){if(!e||typeof e!="object")return null;const s=e,a=String(s.deviceId||t||"").trim(),i=String(s.sessionId||"").trim(),c=String(s.streamId||"").trim(),u=s.streamPurpose==="control"?"control":s.streamPurpose==="wall"?"wall":null,d=String(s.commandId||"").trim(),p=Number(s.captureGeneration||0),h=Number(s.monitorIndex??-1);return!a||a!==t||!u||u!==n||!i||!c||!d||!Number.isSafeInteger(p)||p<=0||!Number.isSafeInteger(h)||h<0?null:{deviceId:a,sessionId:i,streamId:c,streamPurpose:u,commandId:d,captureGeneration:p,monitorIndex:h}}function hf(e,t,n=an,s={}){const[a,i]=o.useState(new Map),[c,u]=o.useState("idle"),[d,p]=o.useState(""),[h,m]=o.useState(Zo),g=o.useRef(new Map),w=o.useRef(new Map),v=o.useRef(new Map),y=o.useRef(null);y.current===null&&(y.current=kC());const k=o.useRef(0),N=o.useRef(new Map),C=o.useRef({enabled:!1,token:"",reason:""}),A=o.useRef(new Map),E=o.useRef(null),I=o.useRef(new Map),[F,M]=o.useState(0),H=o.useRef(s.onFrame),V=o.useRef(s.onStreamReady),P=o.useRef({totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0}),D=o.useMemo(()=>[...e].sort().join(","),[e]),O=t&&D.length>0,X=o.useRef(!1);o.useLayoutEffect(()=>(X.current=O,()=>{X.current=!1}),[O]);const G=Number.isFinite(s.fps)?Number(s.fps):2,U=Number.isFinite(s.maxWidth)?Number(s.maxWidth):640,ie=Number.isFinite(s.maxHeight)?Number(s.maxHeight):360,j=Number.isFinite(s.quality)?Number(s.quality):45,re=Number.isFinite(s.configurationRefreshMs)?Math.max(0,Math.round(Number(s.configurationRefreshMs))):0,de=String(s.frameMode||s.mode||"mode3-h264-hw").trim()||"mode3-h264-hw",Q=s.streamPurpose==="control"?"control":"wall",ge=s.forceRestart===!0,oe=String(s.forceRestartToken||"").trim(),me=String(s.restartReason||"").trim();C.current={enabled:ge,token:oe,reason:me};const Ae=o.useMemo(()=>{const ce=Object.entries(s.monitorSelections||{}).filter(([J])=>!!J).sort(([J],[ye])=>J.localeCompare(ye));return JSON.stringify(Object.fromEntries(ce))},[s.monitorSelections]),Te=o.useMemo(()=>{const ce=Object.entries(s.connectionSessionIds||{}).filter(([J])=>!!J).map(([J,ye])=>[J,String(ye||"").trim()]).sort(([J],[ye])=>J.localeCompare(ye));return JSON.stringify(Object.fromEntries(ce))},[s.connectionSessionIds]);o.useEffect(()=>{H.current=s.onFrame},[s.onFrame]),o.useEffect(()=>{V.current=s.onStreamReady},[s.onStreamReady]);const Pe=o.useCallback((ce,J="livedesk-frame-socket-release")=>{MC(ce,J,y.current)},[]),Se=o.useCallback(ce=>{const J=A.current.get(ce);J!==void 0&&(window.clearTimeout(J),A.current.delete(ce))},[]),te=o.useCallback(ce=>{const J=I.current.get(ce);J!==void 0&&(window.clearTimeout(J),I.current.delete(ce))},[]),Ce=o.useCallback((ce,J=!0)=>{for(const ye of A.current.values())window.clearTimeout(ye);A.current.clear();for(const ye of I.current.values())window.clearTimeout(ye);I.current.clear();for(const ye of v.current.values())ye.expectedBinding=void 0,Pe(ye,ce);v.current.clear(),N.current.clear(),g.current=new Map,w.current.clear(),P.current={totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0},J&&(i(new Map),p(""),m(Zo),u("idle"))},[Pe]),Fe=o.useCallback(()=>{const ce=[...v.current.values()].map(J=>J.socket);if(ce.length===0){u("idle");return}if(ce.some(J=>J.readyState===WebSocket.OPEN)){u("open");return}if(ce.some(J=>J.readyState===WebSocket.CONNECTING)){u("connecting");return}u("closed")},[]),Le=o.useCallback((ce,J,ye,ue)=>{if(J.disposed||J.socket.readyState!==WebSocket.OPEN)return!1;try{return J.socket.send(JSON.stringify({...J.payload,type:"restart-live",deviceIds:[ce],forceRestart:!0,restartReason:ye,restartToken:ue})),J.expectedBinding=void 0,of(J.sparseTelemetry),!0}catch{return!1}},[]),Ue=o.useCallback((ce,J)=>{if(J.disposed||v.current.get(ce)!==J||J.socket.readyState!==WebSocket.OPEN)return!1;try{return J.socket.send(JSON.stringify({...J.payload,type:"refresh-live",deviceIds:[ce],forceRestart:!1,reuseExisting:!0,reason:"initial-configuration-settle"})),!0}catch{try{J.socket.close(4003,"configuration-refresh-failed")}catch{}return!1}},[]),ne=o.useCallback((ce,J)=>{if(!X.current||J.disposed||!ce||ce.byteLength<5)return;const ye=Date.now(),Ee=new DataView(ce).getUint32(0,!1);if(Ee<=0||Ee+4>ce.byteLength)return;const nt=new Uint8Array(ce,4,Ee),T=JSON.parse(qp.decode(nt));PC(T,J.sparseTelemetry,J.expectedBinding);const ve=Ve(T.hubPacketEpochMs),De=ve!==void 0&&ve>0?ve:void 0,qe=g0(J,De,ye);if(qe>l0)return;const _e=new Uint8Array(ce,4+Ee),$e=Ve(T.nativeCaptureTelemetryVersion),mt=Ve(T.nativeCaptureTelemetryAgeMs),ct=Ve(T.hubClientDropped),z=Ve(T.hubClientQueueDepth),pe=Ve(T.hubClientQueueLimit),Y=Ve(T.hubClientBufferedBytes),K=ct!==void 0&&z!==void 0&&pe!==void 0&&Y!==void 0,ee={deviceId:String(T.deviceId||""),kind:T.kind==="thumbnail"?"thumbnail":"live",frameSeq:Number(T.frameSeq||0),streamFrameSeq:Number(T.streamFrameSeq||0)||void 0,streamId:String(T.streamId||""),commandId:T.commandId?String(T.commandId):void 0,sessionId:T.sessionId?String(T.sessionId):void 0,captureGeneration:Number(T.captureGeneration||0)||void 0,currentGenerationVerified:!1,streamPurpose:T.streamPurpose?String(T.streamPurpose):void 0,width:Number(T.width||0),height:Number(T.height||0),sourceWidth:Number(T.sourceWidth||0)||void 0,sourceHeight:Number(T.sourceHeight||0)||void 0,mimeType:String(T.mimeType||"image/jpeg"),mode:T.mode?String(T.mode):void 0,frameMode:T.frameMode?String(T.frameMode):void 0,frameProfile:T.frameProfile?String(T.frameProfile):void 0,encoding:T.encoding?String(T.encoding):void 0,codec:T.codec?String(T.codec):void 0,compression:T.compression?String(T.compression):void 0,pixelFormat:T.pixelFormat?String(T.pixelFormat):void 0,bytesPerPixel:Number(T.bytesPerPixel||0)||0,uncompressedByteLength:Number(T.uncompressedByteLength||0)||0,h264Format:T.h264Format?String(T.h264Format):void 0,isKeyFrame:T.isKeyFrame===!0,chunkType:T.chunkType?String(T.chunkType):void 0,timestampUs:Number(T.timestampUs||0)||0,durationUs:Number(T.durationUs||0)||0,sourceGapMs:Number(T.sourceGapMs||0)||0,agentSendGapMs:Number(T.agentSendGapMs||0)||0,agentSendDurationMs:Number(T.agentSendDurationMs||0)||0,agentSendDurationFrameSeq:Number(T.agentSendDurationFrameSeq||0)||0,agentPaceMs:Number(T.agentPaceMs||0)||0,agentQueueBeforePaceMs:Number(T.agentQueueBeforePaceMs||0)||0,agentFrameAgeMs:Number(T.agentFrameAgeMs||0)||0,inputFeedbackEventId:T.inputFeedbackEventId?String(T.inputFeedbackEventId):void 0,inputFeedbackInputSeq:Ve(T.inputFeedbackInputSeq),inputFeedbackInputType:T.inputFeedbackInputType?String(T.inputFeedbackInputType):void 0,inputFeedbackIssuedAtEpochMs:Ve(T.inputFeedbackIssuedAtEpochMs),inputFeedbackHubReceivedAtEpochMs:Ve(T.inputFeedbackHubReceivedAtEpochMs),inputFeedbackHubForwardedAtEpochMs:Ve(T.inputFeedbackHubForwardedAtEpochMs),inputFeedbackAgentReceivedAtEpochMs:Ve(T.inputFeedbackAgentReceivedAtEpochMs),inputFeedbackAppliedAtEpochMs:Ve(T.inputFeedbackAppliedAtEpochMs),inputFeedbackAgentApplyMs:Ve(T.inputFeedbackAgentApplyMs),inputFeedbackApplyToCaptureMs:Ve(T.inputFeedbackApplyToCaptureMs),inputFeedbackCaptureTimestampAvailable:typeof T.inputFeedbackCaptureTimestampAvailable=="boolean"?T.inputFeedbackCaptureTimestampAvailable:void 0,nativeCaptureTelemetryAvailable:typeof T.nativeCaptureTelemetryAvailable=="boolean"?T.nativeCaptureTelemetryAvailable:void 0,nativeCaptureTelemetryVersion:$e===void 0?void 0:Math.max(0,$e),nativeCaptureTelemetryAgeMs:mt===void 0?void 0:Math.max(0,mt),nativeEncoderHardwareAccelerationKnown:typeof T.nativeEncoderHardwareAccelerationKnown=="boolean"?T.nativeEncoderHardwareAccelerationKnown:void 0,nativeEncoderHardwareAccelerated:typeof T.nativeEncoderHardwareAccelerated=="boolean"?T.nativeEncoderHardwareAccelerated:void 0,nativeEncoderHardwareQueryStatus:T.nativeEncoderHardwareQueryStatus?String(T.nativeEncoderHardwareQueryStatus):void 0,nativeCaptureDisplayId:Ve(T.nativeCaptureDisplayId),nativeCaptureFps:Ve(T.nativeCaptureFps),nativeCompressionFps:Ve(T.nativeCompressionFps),nativeEncodedFps:Ve(T.nativeEncodedFps),nativeCaptureSampleCount:Ve(T.nativeCaptureSampleCount),nativeEncodableFrameCount:Ve(T.nativeEncodableFrameCount),nativeSkippedFrameCount:Ve(T.nativeSkippedFrameCount),nativeCompressionOutputCount:Ve(T.nativeCompressionOutputCount),nativeEncodedFrameCount:Ve(T.nativeEncodedFrameCount),nativeEncodeFramesInFlight:Ve(T.nativeEncodeFramesInFlight),nativeEncodePendingFrameCount:Ve(T.nativeEncodePendingFrameCount),nativeEncodeTimestampOwnerCount:Ve(T.nativeEncodeTimestampOwnerCount),nativeEncodeTimestampOwnerHighWatermark:Ve(T.nativeEncodeTimestampOwnerHighWatermark),nativeBackpressureCoalescedFrameCount:Ve(T.nativeBackpressureCoalescedFrameCount),nativeBackpressureSkippedFrameCount:Ve(T.nativeBackpressureSkippedFrameCount),nativeEncodePendingReplacedFrameCount:Ve(T.nativeEncodePendingReplacedFrameCount),nativeIdleSkippedFrameCount:Ve(T.nativeIdleSkippedFrameCount),nativeVideoToolboxActiveSessionCount:Ve(T.nativeVideoToolboxActiveSessionCount),nativeVideoToolboxSessionHighWatermark:Ve(T.nativeVideoToolboxSessionHighWatermark),nativeOutputQueueDepth:Ve(T.nativeOutputQueueDepth),nativeOutputQueueBytes:Ve(T.nativeOutputQueueBytes),nativeOutputQueueOldestAgeMs:Ve(T.nativeOutputQueueOldestAgeMs),nativeOutputQueueHighWatermark:Ve(T.nativeOutputQueueHighWatermark),nativeOutputQueueDroppedCount:Ve(T.nativeOutputQueueDroppedCount),nativeOutputQueueAwaitingKeyFrame:typeof T.nativeOutputQueueAwaitingKeyFrame=="boolean"?T.nativeOutputQueueAwaitingKeyFrame:void 0,nativeCopyTelemetryAvailable:typeof T.nativeCopyTelemetryAvailable=="boolean"?T.nativeCopyTelemetryAvailable:void 0,nativeAnnexBAccessUnitAllocationCount:Ve(T.nativeAnnexBAccessUnitAllocationCount),nativeAnnexBPayloadCopyCount:Ve(T.nativeAnnexBPayloadCopyCount),nativeAnnexBPayloadCopiedBytes:Ve(T.nativeAnnexBPayloadCopiedBytes),nativeAndPipeResidenceAgeMs:Ve(T.nativeAndPipeResidenceAgeMs),pipePayloadAllocationCount:Ve(T.pipePayloadAllocationCount),pipePayloadCopyCount:Ve(T.pipePayloadCopyCount),pipePayloadCopiedBytes:Ve(T.pipePayloadCopiedBytes),handoffDroppedFrameCount:Ve(T.handoffDroppedFrameCount),handoffRecoveryKeyFrameRequestCount:Ve(T.handoffRecoveryKeyFrameRequestCount),handoffOldestFrameAgeMs:Ve(T.handoffOldestFrameAgeMs),nativeCaptureResourceTelemetryAvailable:T.nativeCaptureResourceTelemetryAvailable===!0?v0(T):T.nativeCaptureResourceTelemetryAvailable===!1?!1:void 0,nativeCaptureTelemetryAt:T.nativeCaptureTelemetryAt?String(T.nativeCaptureTelemetryAt):void 0,droppedByAgent:Number(T.droppedByAgent||0)||0,hubIngressDropped:Number(T.hubIngressDropped||0)||0,hubClientDropped:ct,transport:T.transport?String(T.transport):void 0,videoTransport:T.videoTransport?String(T.videoTransport):void 0,frameTransportActive:T.frameTransportActive?String(T.frameTransportActive):void 0,frameTransportProtocol:T.frameTransportProtocol?String(T.frameTransportProtocol):void 0,frameTransportState:T.frameTransportState?String(T.frameTransportState):void 0,frameTransportReason:T.frameTransportReason?String(T.frameTransportReason):void 0,frameTransportChangedAt:T.frameTransportChangedAt?String(T.frameTransportChangedAt):void 0,frameTransportSwitchCount:Number(T.frameTransportSwitchCount||0)||0,frameTransportTcpFailureCount:Number(T.frameTransportTcpFailureCount||0)||0,frameTransportP2pReady:T.frameTransportP2pReady===!0,hubClientQueueTelemetryAvailable:K,hubClientQueueDepth:z,hubClientQueueLimit:pe,hubClientBufferedBytes:Y,udpIncompleteFrames:Number(T.udpIncompleteFrames||0)||0,hardwareEncoder:T.hardwareEncoder?String(T.hardwareEncoder):void 0,platformProfile:T.platformProfile?String(T.platformProfile):void 0,monitorIndex:Number.isFinite(Number(T.monitorIndex))?Number(T.monitorIndex):void 0,monitorCount:Number.isFinite(Number(T.monitorCount))?Number(T.monitorCount):void 0,requestedFps:Number(T.requestedFps||0)||0,effectiveFps:Number(T.effectiveFps||0)||0,captureTimingAvailable:T.captureTimingAvailable===!0,captureAverageMs:Ve(T.captureAverageMs),captureP95Ms:Ve(T.captureP95Ms),slowFrameCount:Number(T.slowFrameCount||0)||0,captureHelperRestarts:Number(T.captureHelperRestarts||0)||0,capturedAt:String(T.capturedAt||""),receivedAt:String(T.receivedAt||""),hubPacketAt:T.hubPacketAt?String(T.hubPacketAt):void 0,hubPacketEpochMs:De,browserReceivedEpochMs:ye,hubPacketTransitAgeMs:De!==void 0?qe:void 0,byteLength:Number(T.byteLength||_e.byteLength),contentHash:T.contentHash?String(T.contentHash):void 0,captureMs:Ve(T.captureMs),captureStageMs:Ve(T.captureStageMs),convertMs:Number(T.convertMs||0)||0,compressMs:Number(T.compressMs||0)||0,captureSourceSerial:Number(T.captureSourceSerial||0)||0,captureSourceSkipped:Number(T.captureSourceSkipped||0)||0,deltaTileSize:Number(T.deltaTileSize||0)||0,deltaTileCount:Number(T.deltaTileCount||0)||0,deltaVisualTileCount:Number(T.deltaVisualTileCount||0)||0,deltaRefreshTileCount:Number(T.deltaRefreshTileCount||0)||0,deltaTotalTiles:Number(T.deltaTotalTiles||0)||0,payload:_e};if(!ee.deviceId)return;const R=J.expectedBinding;if(!R)return;const se=ee.deviceId===R.deviceId&&String(ee.sessionId||"")===R.sessionId&&ee.streamId===R.streamId&&String(ee.commandId||"")===R.commandId&&Number(ee.captureGeneration||0)===R.captureGeneration&&Number(ee.monitorIndex??-1)===R.monitorIndex&&String(ee.streamPurpose||"")===R.streamPurpose;if(!se)return;ee.currentGenerationVerified=se;const Ie=Number(J.payload.monitorSelections?.[ee.deviceId]);if(Number.isFinite(Ie)&&Number.isFinite(Number(ee.monitorIndex))&&Number(ee.monitorIndex)!==Ie)return;const He={streamId:J.lastFrameStreamId,commandId:J.lastFrameCommandId,order:J.lastFrameOrder},Be=Number(ee.streamFrameSeq||ee.frameSeq||0),xe=!!He.commandId&&!!ee.commandId,Ge=He.streamId===ee.streamId&&(!xe||He.commandId===ee.commandId),rt=He.order;if(Ge&&rt>=Be&&(rt===Be||xe))return;J.lastFrameStreamId=ee.streamId,J.lastFrameCommandId=ee.commandId||"",J.lastFrameOrder=Be;const Ke=P.current;Ke.totalFrames+=1,Ke.totalBytes+=_e.byteLength,Ke.sampleFrames+=1,Ke.sampleBytes+=_e.byteLength;const gt=!g.current.has(ee.deviceId)&&!w.current.has(ee.deviceId),_=xC(w.current,ee);gt&&(g.current.set(ee.deviceId,_),w.current.delete(ee.deviceId),i(new Map(g.current))),H.current?.(ee)},[]);o.useEffect(()=>{if(!t||!D)return;P.current.sampleStartedAt=performance.now();const ce=window.setInterval(()=>{if(!X.current)return;const J=performance.now(),ye=P.current,ue=Math.max(1,J-ye.sampleStartedAt);m({totalFrames:ye.totalFrames,totalBytes:ye.totalBytes,framesPerSecond:ye.sampleFrames*1e3/ue,bytesPerSecond:ye.sampleBytes*1e3/ue,sampleMs:ue,lastUpdatedAt:Date.now()}),i(SC(g.current,w.current)),ye.sampleFrames=0,ye.sampleBytes=0,ye.sampleStartedAt=J},2e3);return E.current=ce,()=>{window.clearInterval(ce),E.current===ce&&(E.current=null)}},[t,D]),o.useEffect(()=>{const ce=()=>{const J=new Set,ye=[...v.current.values()];for(;ye.length>0;){const T=ye.pop();!T||J.has(T)||(J.add(T),T.handoffFrom&&ye.push(T.handoffFrom))}const ue=[...g.current.values(),...w.current.values()],Ee=[...J],nt=y.current?.snapshot()||{closingSocketCount:0,closingSocketTimerCount:0,closingSocketTimeoutCount:0};return{deviceKey:D,active:X.current,socketCount:Ee.length+nt.closingSocketCount,openSocketCount:Ee.filter(T=>T.socket.readyState===WebSocket.OPEN).length,connectingSocketCount:Ee.filter(T=>T.socket.readyState===WebSocket.CONNECTING).length,closingSocketCount:nt.closingSocketCount,closingSocketTimerCount:nt.closingSocketTimerCount,closingSocketTimeoutCount:nt.closingSocketTimeoutCount,expectedBindingCount:Ee.filter(T=>!!T.expectedBinding).length,reconnectTimerCount:A.current.size,statsTimerCount:E.current===null?0:1,configurationRefreshTimerCount:I.current.size,restartTokenCount:N.current.size,retainedFrameCount:ue.length,retainedPayloadBytes:ue.reduce((T,ve)=>T+Math.max(0,Number(ve.payload?.byteLength||0)),0)}};return vp.add(ce),()=>{vp.delete(ce)}},[D]),o.useEffect(()=>{const ce=D?D.split(",").filter(Boolean):[];if(!O){Ce(t?"livedesk-no-devices":"livedesk-stream-inactive");return}const J=new Set(ce),ye=performance.now();for(const ue of A.current.keys())J.has(ue)||Se(ue);for(const ue of I.current.keys())J.has(ue)||te(ue);for(const[ue,Ee]of v.current.entries())J.has(ue)||(Se(ue),Pe(Ee,"livedesk-device-unsubscribed"),v.current.delete(ue),N.current.delete(ue),g.current.delete(ue),w.current.delete(ue));P.current.sampleStartedAt<=0&&(P.current.sampleStartedAt=ye,m({...Zo,lastUpdatedAt:Date.now()}));for(const ue of ce){Se(ue),te(ue);const Ee=Number(s.monitorSelections?.[ue]),nt=Number.isInteger(Ee)&&Ee>=0?Ee:0,T={[ue]:nt},ve={type:"subscribe",deviceIds:[ue],autoStartLive:t,fps:G,maxWidth:U,maxHeight:ie,quality:j,mode:de,frameMode:de,streamPurpose:Q,monitorSelections:T},De=String(s.connectionSessionIds?.[ue]||"").trim(),qe=JSON.stringify({subscribePayload:ve,connectionSessionId:De}),_e=v.current.get(ue),$e=Number(_e?.payload.monitorSelections?.[ue]),mt=Number(T[ue]),ct=!!_e&&Number.isFinite($e)&&Number.isFinite(mt)&&$e!==mt,z=!!_e&&_e?.connectionSessionId!==De;if(_e){const Ge=_e.socket.readyState===WebSocket.CONNECTING||_e.socket.readyState===WebSocket.OPEN;if(_e.payloadKey===qe&&Ge&&!_e.disposed)continue}const pe=_e&&(_e.socket.readyState===WebSocket.CONNECTING||_e.socket.readyState===WebSocket.OPEN)&&!_e.disposed?_e.handoffFrom&&!_e.handoffCompleted?_e.handoffFrom:_e:void 0,Y=_e&&_e!==pe?_e:void 0,K=`/api/remote/frames/ws?devices=${encodeURIComponent(ue)}`,ee=fu(gu(K,n),K);ee.binaryType="arraybuffer";const R=TC(),se={socket:ee,payload:ve,payloadKey:qe,connectionSessionId:De,generation:k.current+1,monitorRestartToken:ct?`monitor-${ue}-${mt}-${k.current+1}`:"",disposed:!1,handoffFrom:pe,handoffCompleted:!1,lastFrameStreamId:"",lastFrameCommandId:"",lastFrameOrder:-1,sparseTelemetry:R,releaseOwnedState:()=>of(R)};k.current=se.generation,(ct||z)&&(g.current.delete(ue),w.current.delete(ue),i(new Map(g.current))),v.current.set(ue,se),Y&&(Y.handoffFrom=void 0,Pe(Y,"livedesk-subscription-superseded"));const Ie=()=>{if(!X.current||se.disposed||v.current.get(ue)!==se){Pe(se,"livedesk-stale-frame-socket");return}Se(ue),p("");const Ge=C.current,rt=Ge.enabled&&(!Ge.token||N.current.get(ue)!==Ge.token),Ke=rt||se.monitorRestartToken!=="",gt=rt?Ge.token:se.monitorRestartToken,_=rt?Ge.reason:se.monitorRestartToken?"monitor-selection-change":"";if(ee.send(JSON.stringify({...se.payload,forceRestart:Ke,restartReason:Ke?_:"",restartToken:Ke?gt:""})),re>0){const Qe=window.setTimeout(()=>{I.current.get(ue)===Qe&&I.current.delete(ue),X.current&&Ue(ue,se)},Math.max(1e3,re));I.current.set(ue,Qe)}rt&&Ge.token&&N.current.set(ue,Ge.token);const je=se.handoffFrom;se.handoffFrom=void 0,se.handoffCompleted=!0,je&&!je.disposed&&Pe(je,"livedesk-subscription-replaced"),Fe()},He=Ge=>{if(!X.current||se.disposed||v.current.get(ue)!==se)return;if(typeof Ge.data=="string"){try{const Ke=JSON.parse(Ge.data),gt=(_,je=!0)=>{const Qe=w0(_,ue,Q);return Qe?(se.expectedBinding=Qe,je&&V.current?.(Qe),!0):!1};if(Ke?.type==="RemoteFrameSubscriptionError"){const _=String(Ke.error||"control-stream-start-failed");uf(_,Ke.retryScheduled===!0)?(p(""),u("connecting")):p(_)}else if(Ke?.type==="RemoteFrameLiveAutoStart"){const je=(Array.isArray(Ke.skipped)?Ke.skipped:[]).find(Qe=>Qe?.deviceId===ue);if(je)uf(je.reason,je.retryScheduled===!0)?(p(""),u("connecting")):p(String(je.reason||"control-stream-start-failed"));else if(Array.isArray(Ke.started)){const Qe=Ke.started.find(Ye=>Ye?.deviceId===ue);Qe&&(p(""),gt(Qe,Qe.ready===!0))}}else Ke?.type==="RemoteFrameStreamReady"&&Ke.deviceId===ue&&gt(Ke)&&p("")}catch{}return}const rt=Ge.data instanceof ArrayBuffer?Ge.data:null;rt&&(p(""),ne(rt,se))},Be=()=>{!X.current||se.disposed||v.current.get(ue)!==se||u("connecting")},xe=()=>{const Ge=!se.disposed;se.disposed=!0,se.handoffCompleted=!0;const rt=se.detachListeners;se.detachListeners=void 0,rt?.();const Ke=v.current.get(ue);Ke===se&&te(ue);let gt=!1;if(Ke===se){const _=se.handoffFrom;se.handoffFrom=void 0,_&&!_.disposed&&(_.socket.readyState===WebSocket.CONNECTING||_.socket.readyState===WebSocket.OPEN)?(v.current.set(ue,_),gt=!0):v.current.delete(ue)}if(Fe(),Ge&&X.current&&Ke===se&&!gt){const _=window.setTimeout(()=>{A.current.get(ue)===_&&A.current.delete(ue),X.current&&M(je=>je+1)},750);Se(ue),A.current.set(ue,_)}};se.detachListeners=()=>{ee.removeEventListener("open",Ie),ee.removeEventListener("message",He),ee.removeEventListener("error",Be),ee.removeEventListener("close",xe)},ee.addEventListener("open",Ie),ee.addEventListener("message",He),ee.addEventListener("error",Be),ee.addEventListener("close",xe)}Fe()},[t,te,Se,Pe,re,Te,D,G,de,ne,n,ie,U,Ae,s.monitorSelections,j,F,Ce,Ue,Q,O,Fe]),o.useEffect(()=>{if(!O||!ge||!oe)return;const ce=D?D.split(",").filter(Boolean):[];for(const J of ce){if(N.current.get(J)===oe)continue;const ye=v.current.get(J);!ye||!Le(J,ye,me,oe)||N.current.set(J,oe)}},[D,ge,oe,me,Le,O]),o.useEffect(()=>()=>{Ce("livedesk-hook-unmount",!1)},[Ce]);const ae=o.useCallback((ce,J="browser-stale")=>{if(!O)return!1;const ye=Array.isArray(ce)&&ce.length>0?ce:D.split(",").filter(Boolean);if(ye.length===0)return!1;let ue=!1;for(const Ee of ye){const nt=v.current.get(Ee);!nt||nt.socket.readyState!==WebSocket.OPEN||(ue=Le(Ee,nt,J,`${Date.now()}-${Math.random().toString(36).slice(2)}`)||ue)}return ue},[D,Le,O]),le=o.useCallback((ce,J="browser-reconnect")=>{if(!O)return!1;const ye=Array.isArray(ce)&&ce.length>0?ce:D.split(",").filter(Boolean);if(ye.length===0)return!1;let ue=!1;for(const Ee of ye){const nt=v.current.get(Ee);nt&&(Se(Ee),Pe(nt,`livedesk-${J}`),v.current.delete(Ee),N.current.delete(Ee),g.current.delete(Ee),w.current.delete(Ee),ue=!0)}return ue&&i(new Map(g.current)),M(Ee=>Ee+1),Fe(),!0},[Se,Pe,D,O,Fe]);return{frames:a,state:c,error:d,stats:h,restartLive:ae,reconnectLive:le}}function y0(e,t,n=an,s={}){const[a,i]=o.useState(null),[c,u]=o.useState(null),[d,p]=o.useState("idle"),[h,m]=o.useState(Zo),g=o.useRef(null),w=o.useRef(s.onFrame),v=o.useRef(null),y=o.useRef(0),k=o.useRef({totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0}),N=o.useMemo(()=>[...new Set(e.filter(Boolean))].join(","),[e]),C=o.useMemo(()=>[...new Set((s.captureDeviceIds||e).filter(Boolean))].join(","),[e,s.captureDeviceIds]),A=o.useMemo(()=>JSON.stringify(s.monitorSelections||{}),[s.monitorSelections]),E=o.useMemo(()=>{const D=Object.entries(s.connectionSessionIds||{}).filter(([O])=>!!O).map(([O,X])=>[O,String(X||"").trim()]).sort(([O],[X])=>O.localeCompare(X));return JSON.stringify(Object.fromEntries(D))},[s.connectionSessionIds]),I=o.useMemo(()=>({deviceIds:N.split(",").filter(Boolean),captureDeviceIds:C.split(",").filter(Boolean),fps:Number(s.fps||20),inputFps:Number(s.inputFps||8),width:Number(s.width||1920),height:Number(s.height||1080),tileWidth:Number(s.tileWidth||320),tileHeight:Number(s.tileHeight||180),monitorSelections:s.monitorSelections||{}}),[C,N,A,s.fps,s.height,s.inputFps,s.monitorSelections,s.tileHeight,s.tileWidth,s.width]),F=o.useMemo(()=>JSON.stringify({atlasConfiguration:I,connectionSessionKey:E}),[I,E]),M=o.useRef(I);M.current=I;const H=t&&I.deviceIds.length>0,V=o.useCallback(D=>D.readyState!==WebSocket.OPEN?!1:(D.send(JSON.stringify({type:"configure",...M.current})),!0),[]);o.useEffect(()=>{w.current=s.onFrame},[s.onFrame]),o.useEffect(()=>{if(!H)return;k.current.sampleStartedAt=performance.now();const D=window.setInterval(()=>{const O=k.current,X=performance.now(),G=Math.max(1,X-O.sampleStartedAt);m({totalFrames:O.totalFrames,totalBytes:O.totalBytes,framesPerSecond:O.sampleFrames*1e3/G,bytesPerSecond:O.sampleBytes*1e3/G,sampleMs:G,lastUpdatedAt:Date.now()});const U=v.current;U&&U.frameSeq!==y.current&&(y.current=U.frameSeq,i(U)),O.sampleFrames=0,O.sampleBytes=0,O.sampleStartedAt=X},1e3);return()=>window.clearInterval(D)},[H]),o.useEffect(()=>{if(!H){g.current?.close(),g.current=null,i(null),v.current=null,y.current=0,u(null),p("idle"),m(Zo);return}let D=!1,O=0;const X=()=>{if(D)return;const G=fu(gu("/api/remote/atlas/ws",n),"/api/remote/atlas/ws");G.binaryType="arraybuffer",g.current=G,p("connecting"),G.addEventListener("open",()=>{k.current.sampleStartedAt=performance.now(),p("open"),V(G)}),G.addEventListener("message",U=>{if(typeof U.data=="string"){try{const j=JSON.parse(U.data);j?.type==="Mode4AtlasLayout"&&u({layoutVersion:Number(j.layoutVersion||0),width:Number(j.width||1920),height:Number(j.height||1080),columns:Number(j.columns||1),rows:Number(j.rows||1),tiles:Array.isArray(j.tiles)?j.tiles:[]})}catch{}return}const ie=U.data instanceof ArrayBuffer?U.data:null;if(!(!ie||ie.byteLength<5))try{const j=Date.now(),de=new DataView(ie).getUint32(0,!1);if(de<=0||de+4>ie.byteLength)return;const Q=JSON.parse(qp.decode(new Uint8Array(ie,4,de))),ge=new Uint8Array(ie,4+de),oe=Ve(Q.hubClientDropped),me=Ve(Q.hubClientQueueDepth),Ae=Ve(Q.hubClientQueueLimit),Te=Ve(Q.hubClientBufferedBytes),Pe={deviceId:String(Q.deviceId||"__livedesk_mode4_atlas__"),kind:"live",frameSeq:Number(Q.frameSeq||0),streamFrameSeq:Number(Q.streamFrameSeq||0)||void 0,streamId:String(Q.streamId||"mode4-atlas"),commandId:Q.commandId?String(Q.commandId):void 0,width:Number(Q.width||1920),height:Number(Q.height||1080),sourceWidth:Number(Q.sourceWidth||Q.width||1920),sourceHeight:Number(Q.sourceHeight||Q.height||1080),mimeType:String(Q.mimeType||"video/h264"),mode:String(Q.mode||"mode4-h264-atlas"),frameMode:String(Q.frameMode||"mode4-h264-atlas"),frameProfile:String(Q.frameProfile||"mode4-h264-atlas-v1"),encoding:String(Q.encoding||"video-atlas"),codec:String(Q.codec||"h264"),compression:String(Q.compression||"video/h264"),h264Format:String(Q.h264Format||"annexb"),isKeyFrame:Q.isKeyFrame===!0,chunkType:String(Q.chunkType||""),timestampUs:Number(Q.timestampUs||0),durationUs:Number(Q.durationUs||0),transport:Q.transport?String(Q.transport):void 0,videoTransport:Q.videoTransport?String(Q.videoTransport):void 0,frameTransportActive:Q.frameTransportActive?String(Q.frameTransportActive):void 0,frameTransportProtocol:Q.frameTransportProtocol?String(Q.frameTransportProtocol):void 0,frameTransportState:Q.frameTransportState?String(Q.frameTransportState):void 0,frameTransportReason:Q.frameTransportReason?String(Q.frameTransportReason):void 0,frameTransportChangedAt:Q.frameTransportChangedAt?String(Q.frameTransportChangedAt):void 0,frameTransportSwitchCount:Number(Q.frameTransportSwitchCount||0)||0,frameTransportTcpFailureCount:Number(Q.frameTransportTcpFailureCount||0)||0,frameTransportP2pReady:Q.frameTransportP2pReady===!0,hubClientQueueTelemetryAvailable:oe!==void 0&&me!==void 0&&Ae!==void 0&&Te!==void 0,hubClientDropped:oe,hubClientQueueDepth:me,hubClientQueueLimit:Ae,hubClientBufferedBytes:Te,udpIncompleteFrames:Number(Q.udpIncompleteFrames||0)||0,hardwareEncoder:Q.hardwareEncoder?String(Q.hardwareEncoder):void 0,platformProfile:Q.platformProfile?String(Q.platformProfile):void 0,capturedAt:String(Q.capturedAt||""),receivedAt:String(Q.receivedAt||""),hubPacketAt:Q.hubPacketAt?String(Q.hubPacketAt):void 0,hubPacketEpochMs:Number(Q.hubPacketEpochMs||0)||void 0,browserReceivedEpochMs:j,byteLength:ge.byteLength,layoutVersion:Number(Q.layoutVersion||0),atlasComposeMs:Number(Q.atlasComposeMs||0),atlasPoolStarved:Number(Q.atlasPoolStarved||0),atlasReadyTiles:Number(Q.atlasReadyTiles||0),atlasTileCount:Number(Q.atlasTileCount||0),atlasInputRevision:Number(Q.atlasInputRevision||0),atlasSourceNewestAtEpochMs:Number(Q.atlasSourceNewestAtEpochMs||0),atlasSourceOldestAtEpochMs:Number(Q.atlasSourceOldestAtEpochMs||0),atlasSourceMaxAgeMs:Number(Q.atlasSourceMaxAgeMs||0),payload:ge},Se=k.current;Se.totalFrames+=1,Se.totalBytes+=ge.byteLength,Se.sampleFrames+=1,Se.sampleBytes+=ge.byteLength,v.current=Pe,y.current===0&&(y.current=Pe.frameSeq,i(Pe)),w.current?.(Pe)}catch{}}),G.addEventListener("error",()=>p("error")),G.addEventListener("close",()=>{g.current===G&&(g.current=null),!D&&(p("closed"),O=window.setTimeout(X,1200))})};return X(),()=>{D=!0,window.clearTimeout(O),g.current?.close(),g.current=null}},[H,n,V]),o.useEffect(()=>{if(!H)return;const D=g.current;D&&V(D)},[F,H,V]);const P=o.useCallback(()=>{const D=g.current;return D?V(D):!1},[V]);return{frame:a,layout:c,state:d,stats:h,refreshInputs:P}}function x0(e,t=an){const n=o.useRef(null),s=o.useRef(0),a=o.useRef(0),i=o.useRef(new Map),c=o.useRef(""),[u,d]=o.useState("idle"),[p,h]=o.useState(""),[m,g]=o.useState(""),[w,v]=o.useState(mf),y=o.useRef({totalSent:0,totalDropped:0,sampleSent:0,sampleDropped:0,sampleStartedAt:0,lastInputType:"",lastInputSeq:0,lastRoundTripMs:0,lastAgentApplyMs:0});o.useEffect(()=>{if(!e){n.current?.close(),n.current=null,a.current=0,c.current="",i.current.clear(),d("idle"),h(""),g(""),v(mf);return}let N=!1,C=0;const A=()=>{if(N)return;const E=fu(gu("/api/remote/input/ws",t),"/api/remote/input/ws");n.current=E,g(""),y.current.sampleStartedAt=performance.now(),d("connecting"),h(""),E.addEventListener("open",()=>{N||n.current!==E||(h(""),d("open"))}),E.addEventListener("message",I=>{if(!(N||n.current!==E||typeof I.data!="string"))try{const F=JSON.parse(I.data);if(F?.type==="RemoteInputSocketReady"){g(String(F.clientId||""));return}const M=Number(F.inputSeq||F.result?.inputSeq||0),H=String(F.deviceId||F.result?.deviceId||""),V=String(F.inputEventId||F.result?.inputEventId||""),P=i.current.get(M);if(H&&(P&&P.deviceId!==H||!P&&c.current&&c.current!==H)||P?.inputEventId&&V&&P.inputEventId!==V)return;if(F?.type==="RemoteInputError"){M>0&&i.current.delete(M),h(String(F.error||F.result?.error||"Remote input failed.")),E.readyState===WebSocket.OPEN&&d("open");return}if(F?.type!=="RemoteInputApplied")return;P&&(y.current.lastRoundTripMs=Math.max(0,performance.now()-P.sentAt),i.current.delete(M)),y.current.lastInputSeq=M,y.current.lastAgentApplyMs=Math.max(0,Number(F.agentApplyMs||0)),h(""),d("open")}catch{}}),E.addEventListener("close",()=>{N||n.current!==E||(n.current=null,g(""),d("closed"),C=window.setTimeout(A,1200))}),E.addEventListener("error",()=>{!N&&n.current===E&&d("error")})};return A(),()=>{N=!0,window.clearTimeout(C);const E=n.current;n.current=null,g(""),E?.close(),i.current.clear()}},[e,t]),o.useEffect(()=>{if(!e)return;const N=window.setInterval(()=>{const C=performance.now(),A=y.current,E=Math.max(1,C-A.sampleStartedAt);v({totalSent:A.totalSent,totalDropped:A.totalDropped,sentPerSecond:A.sampleSent*1e3/E,droppedPerSecond:A.sampleDropped*1e3/E,bufferedAmount:n.current?.bufferedAmount||0,lastInputType:A.lastInputType,lastInputSeq:A.lastInputSeq,lastRoundTripMs:A.lastRoundTripMs,lastAgentApplyMs:A.lastAgentApplyMs,lastUpdatedAt:Date.now()}),A.sampleSent=0,A.sampleDropped=0,A.sampleStartedAt=C},1e3);return()=>window.clearInterval(N)},[e]);const k=o.useCallback((N,C)=>{const A=n.current;if(!A||A.readyState!==WebSocket.OPEN||!N)return!1;const E=String(C.type||"").toLowerCase(),M=E==="pointermove"||E==="wheel",H=y.current;if(M&&A.bufferedAmount>d0)return H.totalDropped+=1,H.sampleDropped+=1,H.lastInputType=`${E}-coalescible-drop`,!1;if(!M&&A.bufferedAmount>p0){H.lastInputType=`${E||"input"}-fail-closed`,h("Remote input channel was reset because ordered input could not drain.");try{A.close(4001,"ordered-input-backpressure")}catch{}return!1}const V=s.current+1;s.current=V;const P=`${V}-${crypto.randomUUID()}`,D=Date.now(),O=!M||V-a.current>=h0;for(O&&(i.current.set(V,{sentAt:performance.now(),deviceId:N,inputEventId:P}),M&&(a.current=V)),c.current=N,uv.set(N,{inputSeq:V,inputType:E||"input",sentAt:performance.now()});i.current.size>256;){const X=i.current.keys().next().value;if(X===void 0)break;i.current.delete(X)}try{A.send(JSON.stringify({type:"input",requestId:M?"":crypto.randomUUID(),fireAndForget:M,deviceId:N,input:{...C,inputEventId:P,inputSeq:V,requestAck:O,issuedAtEpochMs:D,issuedAt:new Date(D).toISOString()}}))}catch{i.current.delete(V),h("Remote input channel closed before the ordered input was queued.");try{A.close(4002,"input-send-failed")}catch{}return!1}return H.totalSent+=1,H.sampleSent+=1,H.lastInputType=E||"input",!0},[]);return{state:u,connectionId:m,sendInput:k,stats:w,error:p}}const qi={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},S0=.25,ff=300,gf=2,Al=1500,Td=5e3,C0=2e3,bf=1e4,Oo=[0,1e3,3e3];function vf(e){const t=Date.parse(String(e||""));return Number.isFinite(t)?Math.max(0,Date.now()-t):0}function k0(e,t,n=an,s=0,a=!1,i="",c,u){const d=o.useRef(null),[p,h]=o.useState("idle"),[m,g]=o.useState(null),[w,v]=o.useState(qi),[y,k]=o.useState(""),N=o.useRef(a);return N.current=a,o.useEffect(()=>{a||(g(C=>C===null?C:null),v(C=>C===qi?C:qi))},[a]),o.useEffect(()=>{if(!t||!e){h("idle"),g(null),v(qi),k("");return}h("connecting"),g(null),v(qi),k("");const C=window.AudioContext||window.webkitAudioContext;if(!C){h("unsupported"),v(qi),k("Audio playback is not supported in this browser.");return}let A=!1,E=null;const I=$C.acquire(({release:F})=>{if(A){F();return}const M=new C({latencyHint:"interactive"});d.current=M;let H=String(i||"").trim();const V="/api/remote/audio/ws?devices="+encodeURIComponent(e)+(H?"&streamId="+encodeURIComponent(H):""),P=fu(gu(V,n),V);P.binaryType="arraybuffer";const D=Xt.createOwner({deviceId:e,socket:P,audioContext:M,statsTimer:null});let O=!1;const X=()=>{const K=Xt.releaseIfDrained(D);return(K||!Xt.hasOwner(D))&&!O&&(O=!0,F()),K},G=zp({sampleRate:192e3,channels:8}).capacityBytes,U=VC({maxPendingPackets:gp,maxPendingBytes:G}),ie=EC(),j={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(M.state),stalledCount:0,automaticRestarts:0,maximumAcceptedGapMs:0,activeStreamId:H,lastCaptureStatusAt:0,lastPcmAtEpochMs:0,workletRingCapacityBytes:0,workletRingBufferedBytes:0,workletRingBufferedMs:0,workletRingDroppedFrames:0,workletRingUnderflowCount:0};let re=!1,de=!1,Q=null,ge=0,oe=0,me="",Ae=!1,Te=()=>{},Pe="connecting",Se="";const te=K=>{re||K===Pe||(Pe=K,h(K))},Ce=K=>{re||K===Se||(Se=K,k(K))};let Fe=0,Le=!1,Ue=0,ne=0,ae=0,le=!1;const ce=()=>{Xt.setPendingWorkletPackets(D,U.getPendingPacketCount(),U.getPendingPacketBytes(),U.getPendingPacketHighWater(),U.getPendingByteHighWater())},J=K=>{j.workletRingCapacityBytes=Math.max(0,Math.min(G,Number(K.ringCapacityBytes||0)||0)),j.workletRingBufferedBytes=Math.max(0,Math.min(j.workletRingCapacityBytes,Number(K.ringBufferedBytes||0)||0)),j.workletRingBufferedMs=Math.max(0,Math.min(S0*1e3,Number(K.ringBufferedMs||0)||0)),j.workletRingDroppedFrames=Math.max(j.workletRingDroppedFrames,Number(K.ringDroppedFrames||0)||0),j.workletRingUnderflowCount=Math.max(j.workletRingUnderflowCount,Number(K.ringUnderflowCount||0)||0),Xt.setPcmRing(D,j.workletRingCapacityBytes,j.workletRingBufferedBytes)},ye=()=>{const K=Q;if(Q=null,Ae=!1,K){K.onprocessorerror=null,K.port.onmessage=null;try{K.disconnect()}catch{}try{K.port.close()}catch{}}U.terminate(),ce(),j.workletRingCapacityBytes=0,j.workletRingBufferedBytes=0,j.workletRingBufferedMs=0,Xt.setPcmRing(D,0,0),Xt.setWorkletNode(D,0,0,ge),X()},ue=K=>{const ee=K.data||{},R=String(ee.type||"");if((R==="packet-terminal"||R==="processor-error")&&(U.acknowledge(typeof ee.packetId=="number"?ee.packetId:String(ee.packetId||"")),ce()),R==="packet-terminal"){const se=Math.max(0,Number(ee.droppedFrames||0)||0);se>0&&(j.workletRingDroppedFrames+=se,j.resyncs+=1)}if(R==="ring-configured"||R==="ring-state"||R==="disposed"){const se=j.workletRingDroppedFrames;J(ee),j.workletRingDroppedFrames>se&&(j.resyncs+=1)}R==="disposed"?ye():R==="processor-error"&&Te(String(ee.error||"Remote audio worklet processing failed."))},Ee=()=>{if(!(!Q||!Ae))try{Q.port.postMessage({type:"flush"})}catch{Te("Remote audio worklet could not be flushed.")}},nt=()=>{P.readyState===WebSocket.OPEN&&P.send(JSON.stringify({type:"subscribe",deviceIds:[e],streamIdsByDeviceId:H?{[e]:H}:{}}))},T=()=>{j.audioContextState=String(M.state),!re&&(j.audioContextState==="suspended"||j.audioContextState==="interrupted"?te("suspended"):j.audioContextState==="closed"&&(te("error"),Ce("The browser audio context is closed. Toggle Remote Audio off and on to recover.")))},ve=async()=>{if(re||String(M.state)==="closed")return!1;try{if(String(M.state)!=="running"&&await M.resume(),j.audioContextState=String(M.state),!re&&!Le&&j.audioContextState==="running"){const K=j.lastAcceptedAt>0&&performance.now()-j.lastAcceptedAt<=Al,ee=j.lastCaptureStatusAt>0&&performance.now()-j.lastCaptureStatusAt<=Td&&j.captureHealthy;te(K?"playing":ee?"silent":"open")}return j.audioContextState==="running"}catch(K){return re||(te("suspended"),Ce(K instanceof Error?"Audio playback is suspended: "+K.message:"Audio playback is suspended.")),!1}},De=async()=>{if(!M.audioWorklet||typeof AudioWorkletNode>"u")throw new Error("AudioWorklet is unavailable in this browser.");const K=new Blob([XC],{type:"text/javascript"});me=URL.createObjectURL(K);try{await M.audioWorklet.addModule(me)}finally{URL.revokeObjectURL(me),me=""}if(re||String(M.state)==="closed")return;const ee=new AudioWorkletNode(M,lv,{numberOfInputs:0,numberOfOutputs:1,outputChannelCount:[gf],channelCount:gf,channelCountMode:"explicit"});ge+=1,Q=ee,ee.port.onmessage=ue,ee.onprocessorerror=()=>{Te("Remote audio worklet stopped unexpectedly.")},ee.connect(M.destination),Ae=!0,Xt.setWorkletNode(D,1,1,ge)},qe=(K,ee,R,se)=>{const Ie=Q;if(re||!Ae||!Ie||ee.byteLength<=0)return!1;const He=Wp({sampleRate:K.sampleRate,channels:K.channels,mimeType:K.mimeType}),Be=++oe;if(!U.claim(Be,ee.byteLength))return ce(),!1;ce();try{return Ie.port.postMessage({type:"pcm",packetId:Be,buffer:ee,byteOffset:R,byteLength:se,sampleRate:He.sampleRate,channels:He.channels,mimeType:K.mimeType,sampleFormat:He.sampleFormat},[ee]),!0}catch{return U.acknowledge(Be),ce(),!1}},_e=async()=>{if(re||Le||P.readyState!==WebSocket.OPEN)return;if(Ue>=Oo.length){te("error"),Ce("Remote audio stopped sending frames. Toggle Audio off and on to retry.");return}const K=Ue;Ue+=1,Le=!0,j.stalledCount+=1,j.automaticRestarts+=1,te("reconnecting");try{if(!c)throw new Error("Remote audio restart owner is unavailable.");const ee=await c(e);if(re||!ee)return;H=ee,nt();const R=performance.now();Fe=R,j.lastPacketAt=R,j.lastAcceptedAt=0,j.lastCaptureStatusAt=0,j.lastPcmAtEpochMs=0,j.captureAlive=null,j.helperAlive=null,j.helperReady=!1,j.captureHealthy=!1,j.captureStatusFailed=!1,j.captureAwaitingCurrentPcm=!1,j.captureAwaitingSinceAt=0,j.capturePhase="",j.backendKind="",j.helperRequired=!1,j.helperPid=0,j.nativeCallbackDiagnosticsAvailable=!1,j.nativeRejectedCallbackCount=0,j.nativeCurrentnessDropCount=0,j.nativeLastDropReason="",j.silentForMs=0,j.activeStreamId=H,j.lastFrameSeq=0,j.maximumAcceptedGapMs=0,Ee(),ne=R+(Oo[K+1]??3e3),Ce(""),re||te("open")}catch(ee){re||(ne=performance.now()+(Oo[K+1]??3e3),te("error"),Ce(ee instanceof Error?"Remote audio restart failed: "+ee.message:"Remote audio restart failed."))}finally{Le=!1}},$e=()=>{j.drops+=1},mt=window.setInterval(()=>{if(re)return;const K=performance.now(),ee=j.lastPacketAt>0?Math.max(0,K-j.lastPacketAt):Fe>0?Math.max(0,K-Fe):0,R=j.lastAcceptedAt>0?Math.max(0,K-j.lastAcceptedAt):0,se=j.lastCaptureStatusAt>0?Math.max(0,K-j.lastCaptureStatusAt):0,Ie=P.readyState===WebSocket.OPEN,He=j.lastCaptureStatusAt>0,Be=He&&se<=Td&&j.captureHealthy,xe=He&&j.captureStatusFailed&&se>C0,Ge=He&&se>Td,rt=!He&&Fe>0&&K-Fe>bf,Ke=j.captureAwaitingCurrentPcm&&j.captureAwaitingSinceAt>0&&K-j.captureAwaitingSinceAt>bf,gt=Fe>0&&(j.lastAcceptedAt<=0?K-Fe>Al:R>Al);if(Ie&&Fe>0&&(xe||Ge||rt||Ke)?Ue>=Oo.length&&!Le?(te("error"),Ce("Remote audio capture heartbeat stopped. Toggle Audio off and on to retry.")):!Le&&K>=ne?_e():Le||te("stalled"):Ie&&gt&&!Le&&j.audioContextState!=="suspended"&&j.audioContextState!=="interrupted"&&te(Be?"silent":"open"),OC({enabled:N.current,now:K,lastPublishedAt:ae})){ae=K,v({queuedMs:j.workletRingBufferedMs,browserAgeMs:j.browserAgeMs,captureAgeMs:j.captureAgeMs,captureStatusAgeMs:se,silentForMs:j.silentForMs,captureAlive:j.captureAlive,helperAlive:j.helperAlive,helperReady:j.helperReady,captureHealthy:j.captureHealthy,captureAwaitingCurrentPcm:j.captureAwaitingCurrentPcm,capturePhase:j.capturePhase,backendKind:j.backendKind,helperRequired:j.helperRequired,helperPid:j.helperPid,captureRestartCount:j.captureRestartCount,nativeCallbackDiagnosticsAvailable:j.nativeCallbackDiagnosticsAvailable,nativeRejectedCallbackCount:j.nativeRejectedCallbackCount,nativeCurrentnessDropCount:j.nativeCurrentnessDropCount,nativeLastDropReason:j.nativeLastDropReason,localProcessingAgeMs:j.localProcessingAgeMs,lastPacketAgeMs:ee,lastAcceptedAgeMs:R,framesReceived:j.framesReceived,drops:j.drops,resyncs:j.resyncs,pendingDecodes:j.pendingDecodes,lastFrameSeq:j.lastFrameSeq,audioContextState:j.audioContextState,stalledCount:j.stalledCount,automaticRestarts:j.automaticRestarts,maximumAcceptedGapMs:j.maximumAcceptedGapMs,workletRingCapacityBytes:j.workletRingCapacityBytes,workletRingBufferedBytes:j.workletRingBufferedBytes,workletRingDroppedFrames:j.workletRingDroppedFrames,workletRingUnderflowCount:j.workletRingUnderflowCount,lastUpdatedAt:Date.now()});const _=ie.publish();_&&(le=!0,Xt.setRetainedFrame(D,1,_.payload.byteLength),g(_))}else!N.current&&le&&(le=!1,ie.clear(),Xt.setRetainedFrame(D,0,0))},250);Xt.setStatsTimer(D,mt);const ct=()=>{T(),(String(M.state)==="suspended"||String(M.state)==="interrupted")&&ve()},z=()=>{document.visibilityState==="visible"&&ve()},pe=()=>{ve()};M.addEventListener("statechange",ct),document.addEventListener("visibilitychange",z),window.addEventListener("pageshow",pe),window.addEventListener("pointerdown",pe),window.addEventListener("keydown",pe),te("connecting"),Ce(""),T();const Y=(K,ee,R,se,Ie)=>{if(j.localProcessingAgeMs=Math.max(0,performance.now()-Ie),re||j.localProcessingAgeMs>ff||!bp(K,{deviceId:e,streamId:H}))return $e(),!1;j.activeStreamId!==H&&(j.activeStreamId=H,j.lastFrameSeq=0,j.maximumAcceptedGapMs=0,Ee());const He=zC(K,{deviceId:e,streamId:H,lastFrameSeq:j.lastFrameSeq});if(!He.accepted||!qe(K,ee,R,se))return $e(),!1;j.browserAgeMs=vf(K.receivedAt),j.captureAgeMs=vf(K.capturedAt);const Be=performance.now();j.lastAcceptedAt>0&&(j.maximumAcceptedGapMs=Math.max(j.maximumAcceptedGapMs,Be-j.lastAcceptedAt)),j.lastAcceptedAt=Be,j.framesReceived+=1,j.lastFrameSeq=He.nextFrameSeq,Ue=0,ne=0,N.current&&(ie.accept(K),le=!0,Xt.setRetainedFrame(D,1,0)),String(M.state)!=="running"&&ve();const xe=String(M.state)==="running";return xe&&Ce(""),te(xe?"playing":"suspended"),!0};Te=(K="")=>{if(!de){if(de=!0,K&&(Xt.recordTerminalFailure(D,K,K.includes("setup failed")?"setup":"processor"),te(K.includes("AudioWorklet is unavailable")?"unsupported":"error"),Ce(K),u?.(e,H,"browser-audio-playback-failed").catch(()=>{})),re=!0,Xt.deactivate(D),window.clearInterval(mt),Xt.setStatsTimer(D,null),M.removeEventListener("statechange",ct),document.removeEventListener("visibilitychange",z),window.removeEventListener("pageshow",pe),window.removeEventListener("pointerdown",pe),window.removeEventListener("keydown",pe),ie.clear(),Xt.setRetainedFrame(D,0,0),Q)try{Q.port.postMessage({type:"dispose"})}catch{}try{P.close()}catch{}P.readyState===WebSocket.CLOSED&&Xt.setSocket(D,null),M.close().catch(()=>{}).finally(()=>{ye(),String(M.state)==="closed"&&Xt.setAudioContext(D,null),X()}),d.current===M&&(d.current=null),X()}},De().catch(K=>{Te(K instanceof Error?`Remote audio worklet setup failed: ${K.message}`:"Remote audio worklet setup failed.")}),P.addEventListener("open",()=>{re||(Fe=performance.now(),j.lastPacketAt=Fe,j.lastAcceptedAt=0,j.lastCaptureStatusAt=0,j.lastPcmAtEpochMs=0,j.captureAlive=null,j.helperAlive=null,j.helperReady=!1,j.captureHealthy=!1,j.captureStatusFailed=!1,j.captureAwaitingCurrentPcm=!1,j.captureAwaitingSinceAt=0,j.capturePhase="",j.backendKind="",j.helperRequired=!1,j.helperPid=0,j.maximumAcceptedGapMs=0,j.silentForMs=0,te("open"),nt(),ve())}),P.addEventListener("message",K=>{if(typeof K.data=="string")return;const ee=K.data instanceof ArrayBuffer?K.data:null;if(!ee||ee.byteLength<5)return;const R=performance.now();j.lastPacketAt=R;try{const Ie=new DataView(ee).getUint32(0,!1);if(Ie<=0||Ie+4>ee.byteLength){$e();return}const He=new Uint8Array(ee,4,Ie),Be=JSON.parse(qp.decode(He)),xe=new Uint8Array(ee,4+Ie),Ge=String(Be.deviceId||""),rt=String(Be.streamId||"");if(!bp({deviceId:Ge,streamId:rt},{deviceId:e,streamId:H})){$e();return}const Ke=String(Be.frameKind||Be.kind||"").toLowerCase();if(Be.type==="remote.audio.status"||Ke==="audio-status"){j.lastCaptureStatusAt=R;const _=qC(Be);if(j.captureAlive=_.captureAlive,j.helperAlive=_.helperAlive,j.helperReady=_.helperReady,j.captureHealthy=_.healthy,j.captureStatusFailed=_.failed,j.captureAwaitingCurrentPcm=_.awaitingCurrentPcm,_.awaitingCurrentPcm?j.captureAwaitingSinceAt||=R:j.captureAwaitingSinceAt=0,j.capturePhase=_.capturePhase,j.backendKind=_.backendKind,j.helperRequired=_.helperRequired===!0,j.helperPid=_.helperPid,j.captureRestartCount=Math.max(0,Number(Be.restartCount||0)||0),j.nativeCallbackDiagnosticsAvailable=Be.callbackDiagnosticsAvailable===!0,j.nativeRejectedCallbackCount=j.nativeCallbackDiagnosticsAvailable?Math.max(0,Number(Be.rejectedCallbackCount||0)||0):0,j.nativeCurrentnessDropCount=j.nativeCallbackDiagnosticsAvailable?Math.max(0,Number(Be.currentnessDropCount||0)||0):0,j.nativeLastDropReason=j.nativeCallbackDiagnosticsAvailable?String(Be.lastDropReason||""):"",j.lastPcmAtEpochMs=Math.max(0,Number(Be.lastPcmAtEpochMs||0)||0),j.silentForMs=Math.max(0,Number(Be.silentForMs||0)||0),j.captureAgeMs=j.lastPcmAtEpochMs>0?Math.max(0,Date.now()-j.lastPcmAtEpochMs):j.silentForMs,j.captureHealthy){if(Ue=0,ne=0,!Le){Ce("");const je=String(M.state)==="running",Qe=j.lastAcceptedAt>0&&performance.now()-j.lastAcceptedAt<=Al;te(je?Qe?"playing":"silent":"suspended")}}else j.captureAwaitingCurrentPcm&&!Le?te("open"):j.captureStatusFailed&&!Le&&te("stalled");return}const gt={deviceId:Ge,frameSeq:Number(Be.frameSeq||0),streamId:rt,mimeType:String(Be.mimeType||"audio/webm;codecs=opus"),sampleRate:Number(Be.sampleRate||48e3),channels:Number(Be.channels||2),capturedAt:String(Be.capturedAt||""),receivedAt:String(Be.receivedAt||""),byteLength:Number(Be.byteLength||xe.byteLength),payload:cv};if(!gt.deviceId||re)return;if(performance.now()-R>ff){$e();return}if(WC(gt.mimeType)){Y(gt,ee,xe.byteOffset,xe.byteLength,R);return}$e(),te("error"),Ce(`Unsupported remote audio format "${gt.mimeType}". Requesting a bounded PCM restart.`),!Le&&Ue<Oo.length&&(ne=0,_e());return}catch(se){re||(te("error"),Ce(se instanceof Error?se.message:String(se)))}}),P.addEventListener("error",()=>{re||(te("error"),Ce("Remote audio WebSocket error."))}),P.addEventListener("close",()=>{Xt.setSocket(D,null),X(),re||te("closed")}),E=()=>{Te()}});return I.ready.catch(F=>{A||(h("error"),k(F instanceof Error?`Remote audio owner setup failed: ${F.message}`:"Remote audio owner setup failed."))}),()=>{A=!0,E?E():I.cancel()}},[e,t,n,s,c,u]),{state:p,lastFrame:m,stats:w,error:y}}const Ql=384e3,M0=1024*1024,A0=24*1024*1024,N0=256*1024*1024,R0=24;function T0(e,t){if(!e||e.repeat||e.altKey||e.shiftKey)return"";const n=String(e.key||"").toLowerCase();return n!=="c"&&n!=="v"||!(t?e.metaKey===!0&&e.ctrlKey!==!0:e.ctrlKey===!0&&e.metaKey!==!0)?"":n==="c"?"copy":"paste"}function P0(e){return`clipboard-${e==="copy"?"copy":"paste"}-${Date.now()}-${crypto.randomUUID()}`}function wp(e,t=""){const n=e&&typeof e=="object"?e:{},s=String(n.operationId||""),a=String(n.contentKind||"").toLowerCase(),i=Array.isArray(n.items)?n.items:[];if(!s||t&&s!==t||!["text","image","files"].includes(a)||i.length<1||i.length>R0)throw new Error("clipboard-manifest-invalid");let c=0;const u=i.map((d,p)=>{const h=Number(d?.itemIndex),m=Number(d?.size),g=String(d?.kind||"").toLowerCase();if(h!==p||!Number.isSafeInteger(m)||m<0||g!=="file"&&m===0||!["text","image","file"].includes(g)||g!==(a==="files"?"file":a))throw new Error("clipboard-item-invalid");c+=m;const w=String(d?.sha256||"").toLowerCase(),v=String(d?.storageName||`item-${p}.bin`);if(!/^[a-f0-9]{64}$/.test(w)||v!==`item-${p}.bin`||String(d?.name||"").includes("\0"))throw new Error("clipboard-item-metadata-invalid");return{itemIndex:h,kind:g,name:String(d?.name||"").slice(0,240),mimeType:String(d?.mimeType||"").slice(0,160),size:m,lastModified:Math.max(0,Number(d?.lastModified||0)||0),sha256:w,storageName:v}});if(c!==Number(n.totalBytes)||c>N0||a==="text"&&c>M0||a==="image"&&c>A0)throw new Error("clipboard-size-limit");return{operationId:s,contentKind:a,totalBytes:c,items:u}}function Pd(e,t=Ql){if(!Number.isSafeInteger(e)||e<0||!Number.isSafeInteger(t)||t<1)throw new Error("clipboard-chunk-plan-invalid");if(e===0)return[{offset:0,byteLength:0,final:!0}];const n=[];for(let s=0;s<e;s+=t){const a=Math.min(t,e-s);n.push({offset:s,byteLength:a,final:s+a===e})}return n}const I0=3;function wf(e,t,n){const s=Math.max(1,Number(n)||1),a=Math.max(0,Math.min(s,Number(e)-Number(t))),i=Math.min(s/2,I0);return a<=i?0:a>=s-i?1:a/s}function j0(e,t,n){return{normalizedX:wf(e,n.left,n.width),normalizedY:wf(t,n.top,n.height)}}const yf=8,yp=320,xf=28,ic=1,dv=4;function E0(){let e=!1;return{claimNativeTouchEvents(){e=!0},shouldHandlePointerEvent(){return!e}}}function xt(e,t=0){const n=Number(e);return Number.isFinite(n)?n:t}function Up(e,t){const n=xt(e?.clientX)-xt(t?.clientX),s=xt(e?.clientY)-xt(t?.clientY);return n*n+s*s}function Yl(e,t,n){return Math.min(n,Math.max(t,e))}function pv(e,t){return{clientX:(xt(e?.clientX)+xt(t?.clientX))/2,clientY:(xt(e?.clientY)+xt(t?.clientY))/2}}function mv(e,t){return Math.sqrt(Up(e,t))}function ou(){return{scale:ic,translateX:0,translateY:0}}function F0(e,t,n,s){const a=n||ou(),i=Yl(xt(a.scale,ic),ic,dv),c={left:xt(s?.left),top:xt(s?.top),width:Math.max(1,xt(s?.width,1)),height:Math.max(1,xt(s?.height,1))},u=pv(e,t);return{startDistance:Math.max(1,mv(e,t)),startScale:i,anchorX:(u.clientX-c.left-xt(a.translateX))/i,anchorY:(u.clientY-c.top-xt(a.translateY))/i,bounds:c}}function D0(e,t,n){if(!e)return ou();const s=pv(t,n),a=Yl(xt(e.startScale,ic)*mv(t,n)/Math.max(1,xt(e.startDistance,1)),ic,dv),i=Math.max(1,xt(e.bounds?.width,1)),c=Math.max(1,xt(e.bounds?.height,1)),u=Yl(s.clientX-xt(e.bounds?.left)-xt(e.anchorX)*a,i*(1-a),0),d=Yl(s.clientY-xt(e.bounds?.top)-xt(e.anchorY)*a,c*(1-a),0);return{scale:a,translateX:u,translateY:d}}function L0(e,t,n){return{pointerId:xt(e,-1),startClientX:xt(t),startClientY:xt(n),clientX:xt(t),clientY:xt(n),dragged:!1}}function hv(e,t,n,s){if(!e||e.pointerId!==xt(t,-1))return e;const a={...e,clientX:xt(n,e.clientX),clientY:xt(s,e.clientY)},i=yf*yf;return{...a,dragged:e.dragged||Up({clientX:e.startClientX,clientY:e.startClientY},a)>=i}}function _0(e,t,n,s,a){if(!e||e.pointerId!==xt(t,-1))return{kind:"ignore",gesture:e,tap:null};const i=hv(e,t,n,s);return{kind:i.dragged?"drag":"tap",gesture:i,tap:i.dragged?null:{clientX:i.clientX,clientY:i.clientY,at:xt(a)}}}function Sf(e,t){if(!e||!t)return!1;const n=xt(t.at)-xt(e.at);if(n<0||n>yp)return!1;const s=xf*xf;return Up(e,t)<=s}const cu=Object.freeze({shiftKey:Object.freeze(["ShiftLeft","ShiftRight"]),ctrlKey:Object.freeze(["ControlLeft","ControlRight"]),altKey:Object.freeze(["AltLeft","AltRight"]),metaKey:Object.freeze(["MetaLeft","MetaRight"])}),$0=Object.freeze({shiftKey:"ShiftLeft",ctrlKey:"ControlLeft",altKey:"AltLeft",metaKey:"MetaLeft"}),Cf=Object.freeze({OSLeft:"MetaLeft",OSRight:"MetaRight"}),xp=64,O0=256,kf=Object.freeze({Backspace:Object.freeze({key:"Backspace",code:"Backspace",keyCode:8,location:0}),Tab:Object.freeze({key:"Tab",code:"Tab",keyCode:9,location:0}),Enter:Object.freeze({key:"Enter",code:"Enter",keyCode:13,location:0}),Escape:Object.freeze({key:"Escape",code:"Escape",keyCode:27,location:0}),PageUp:Object.freeze({key:"PageUp",code:"PageUp",keyCode:33,location:0}),PageDown:Object.freeze({key:"PageDown",code:"PageDown",keyCode:34,location:0}),End:Object.freeze({key:"End",code:"End",keyCode:35,location:0}),Home:Object.freeze({key:"Home",code:"Home",keyCode:36,location:0}),ArrowLeft:Object.freeze({key:"ArrowLeft",code:"ArrowLeft",keyCode:37,location:0}),ArrowUp:Object.freeze({key:"ArrowUp",code:"ArrowUp",keyCode:38,location:0}),ArrowRight:Object.freeze({key:"ArrowRight",code:"ArrowRight",keyCode:39,location:0}),ArrowDown:Object.freeze({key:"ArrowDown",code:"ArrowDown",keyCode:40,location:0}),Delete:Object.freeze({key:"Delete",code:"Delete",keyCode:46,location:0})}),Mf=Object.freeze({deleteContentBackward:"Backspace",deleteWordBackward:"Backspace",deleteSoftLineBackward:"Backspace",deleteHardLineBackward:"Backspace",deleteContentForward:"Delete",deleteWordForward:"Delete",deleteSoftLineForward:"Delete",deleteHardLineForward:"Delete",insertLineBreak:"Enter",insertParagraph:"Enter"});function Vp(e,t=80){return String(e||"").replace(/[\u0000-\u001f\u007f]/g,"").trim().slice(0,t)}function fv(e){const t=String(e??"");return t===" "?" ":Vp(t)}function Sp(e){const t=Vp(e);return Object.prototype.hasOwnProperty.call(Cf,t)?Cf[t]:t}function Id(e={}){const t=fv(e.key),n=Number(e.keyCode??e.which);if(t===" "||t==="Spacebar"||n===32)return"Space";const s=Number.isFinite(Number(e.location))?Math.max(0,Math.min(3,Math.trunc(Number(e.location)))):0,a=s===2?"Right":"Left";return t==="Shift"?`Shift${a}`:t==="Control"?`Control${a}`:t==="Alt"||t==="AltGraph"?`Alt${a}`:t==="Meta"||t==="OS"?`Meta${a}`:t?`Key:${s}:${t}`.slice(0,80):""}function Cp(e={}){const t=Sp(e.code);return["Shift","Control","Alt","AltGraph","Meta","OS"].includes(t)?Id({...e,key:t}):t==="Unidentified"?Id(e):t||Id(e)}function Xl(e){for(const[t,n]of Object.entries(cu))if(n.includes(e))return t;return""}function Ks(e,t){return cu[t].some(n=>e.has(n))}function Nl(e,t,n={},s="",a=""){for(const i of Object.keys(cu)){const c=n[i]===!0,u=cu[i];if(i===s){if(a==="keyup"&&!c)for(const d of u)t.has(d)||e.delete(d);continue}if(c){!Ks(e,i)&&e.size<xp&&e.add($0[i]);continue}for(const d of u)t.has(d)||e.delete(d)}}function B0(e,t){if(e.length!==t.size)return!1;let n=0;for(const s of t){if(e[n]!==s)return!1;n+=1}return!0}function Af(e){for(const t of[...e])Xl(t)||e.delete(t)}function kp(e){return{shiftKey:Ks(e,"shiftKey"),ctrlKey:Ks(e,"ctrlKey"),altKey:Ks(e,"altKey"),metaKey:Ks(e,"metaKey")}}function H0(e={},t={}){return{shiftKey:e.shiftKey===!0||t.shiftKey===!0,ctrlKey:e.ctrlKey===!0||t.ctrlKey===!0,altKey:e.altKey===!0||t.altKey===!0,metaKey:e.metaKey===!0||t.metaKey===!0}}function Rl(e){const t=String(e||""),n=Object.prototype.hasOwnProperty.call(Mf,t)?Mf[t]:t;return Object.prototype.hasOwnProperty.call(kf,n)?{...kf[n],repeat:!1}:null}function W0(e){const t=String(e??"").replace(/\0/g,"");if(!t)return[];const n=[];let s=t;for(;s.length>0;){let a=Math.min(O0,s.length);a<s.length&&/[\uD800-\uDBFF]/.test(s[a-1])&&/[\uDC00-\uDFFF]/.test(s[a])&&(a-=1),n.push(s.slice(0,a)),s=s.slice(a)}return n}function z0(e,t,n){const s=Cp(e),a=fv(e.key),i=Number(e.keyCode??e.which),c=Number(e.location);return{type:t,key:a,code:s,keyCode:Number.isFinite(i)?Math.max(0,Math.min(65535,Math.trunc(i))):0,location:Number.isFinite(c)?Math.max(0,Math.min(255,Math.trunc(c))):0,text:a.length===1?a:"",repeat:t==="keydown"&&e.repeat===!0,pressedCodes:[...n],...kp(n)}}function q0(){const e=new Set,t=new Set,n=()=>({pressedCodes:[...e]});return{event(s={},a=""){if(a!=="keydown"&&a!=="keyup")return null;const i=Cp(s);if(!i)return null;const c=Xl(i),u=e.has(i),d=[...e];return c?a==="keydown"?(Nl(e,t,s,c,a),e.size<xp&&e.add(i)):(t.has(i)||e.delete(i),Nl(e,t,s,c,a)):(Nl(e,t,s),a==="keydown"?e.size<xp&&e.add(i):e.delete(i)),a==="keyup"&&c==="metaKey"&&!Ks(e,"metaKey")&&Af(e),a==="keydown"&&u&&s.repeat!==!0&&B0(d,e)?null:z0(s,a,e)},modifier(s,a){const i=Sp(s),c=Xl(i);if(!c)return null;const u=t.has(i);return a===u?null:(a?(t.add(i),e.add(i)):(t.delete(i),e.delete(i),c==="metaKey"&&!Ks(e,"metaKey")&&Af(e)),{type:a?"keydown":"keyup",key:c==="metaKey"?"Meta":c==="ctrlKey"?"Control":c==="altKey"?"Alt":"Shift",code:i,keyCode:0,location:i.endsWith("Right")?2:1,text:"",repeat:!1,...n(),...kp(e)})},reset(s="keyboard-owner-reset",a=!1){const i=e.size>0;return e.clear(),t.clear(),!i&&!a?null:{type:"keyboard.reset",reason:Vp(s,120)||"keyboard-owner-reset",pressedCodes:[],shiftKey:!1,ctrlKey:!1,altKey:!1,metaKey:!1,repeat:!1}},isPressed(s={}){const a=typeof s=="string"?Sp(s):Cp(s);if(e.has(a))return!0;const i=Xl(a);return!!i&&Ks(e,i)},snapshot(){return{...n(),latchedCodes:[...t],...kp(e)}}}}const gv=64,U0=2;function bv(e){const t=Math.floor(Number(e));return Number.isFinite(t)?Math.max(1,Math.min(gv,t)):1}function Gp(e){const t=Math.floor(Number(e));return Number.isFinite(t)?Math.max(0,Math.min(gv-1,t)):0}function vv(e){const t=String(e||"").trim().toLowerCase();return t==="macos"||t==="darwin"||t==="mac"||t==="macosx"||t==="linux"||t.startsWith("linux ")}function V0(e,t,n){const s=String(t||"").trim();if(!s)return e||null;const a=String(n||"").trim();return e&&e.fingerprint===s&&(a?e.sampleId===a:e.sampleId==="")?e:{fingerprint:s,sampleId:a,consecutiveSamples:e?.fingerprint===s?e.consecutiveSamples+1:1}}function wv({platform:e,topologyFingerprint:t,consecutiveTopologySamples:n}){return vv(e)?!!String(t||"").trim()&&Number(n)>=U0:!0}function G0({requestedIndex:e,monitorCount:t,platform:n,topologyFingerprint:s,consecutiveTopologySamples:a}){const i=Gp(e),c=bv(t);return i<c||!wv({platform:n,topologyFingerprint:s,consecutiveTopologySamples:a})?i:c-1}function K0(e,t,n){const s=Gp(e),a=bv(t);return s<a||vv(n)?s:a-1}function na(e){const t=Number(e);return Number.isSafeInteger(t)&&t>0?t:0}function Jt(e){return String(e||"").trim()}function jd(e,t,n={}){return{deviceId:Jt(e),transitionGeneration:na(t),sessionId:Jt(n.sessionId),streamId:Jt(n.streamId),commandId:Jt(n.commandId),captureGeneration:na(n.captureGeneration),monitorIndex:Math.max(0,Math.floor(Number(n.monitorIndex)||0))}}function Dt(e,t){return!!e&&!!t&&Jt(e.deviceId)===Jt(t.deviceId)&&na(e.transitionGeneration)===na(t.transitionGeneration)}function Nf({deviceId:e,requestTransitionGeneration:t,currentTransitionGeneration:n,actualControlOwner:s}){const a=Jt(e),i=na(t),c=na(n);return!!a&&i>0&&i===c&&(!s||Jt(s.deviceId)===a)}function Rf(e,t){const n=Promise.resolve(e).catch(()=>{}).then(t);return{result:n,tail:n.then(()=>{},()=>{})}}function Tl(e,t,n){const s=Jt(e);return!s||!t||Jt(t.deviceId)!==s?!1:!n||Jt(n.deviceId)!==s}function Ed(e,t){if(!e||!t)return!1;const n=na(t.captureGeneration),s=Jt(t.commandId),a=Jt(t.sessionId),i=Jt(t.streamId),c=Number(e.monitorIndex);return!n||!s||!a||!i||!Number.isInteger(c)||c<0?!1:Jt(e.deviceId)===Jt(t.deviceId)&&Jt(e.sessionId)===a&&Jt(e.streamId)===i&&Jt(e.commandId)===s&&na(e.captureGeneration)===n&&Jt(e.streamPurpose).toLowerCase()==="control"&&c===t.monitorIndex}const Q0=820,Y0=500,Tf=`(max-width: ${Q0}px), (orientation: landscape) and (max-height: ${Y0}px) and (pointer: coarse)`,X0="1200px 0px 1800px 0px",J0=960,Z0=540,ek=68,Pf=24,tk=16;function nk(e,t,n,s){return/iPad|iPhone|iPod/i.test(String(e||""))||t==="MacIntel"&&Number(n)>1||typeof s=="boolean"}function rk(e,t){const n=e&&typeof e=="object"?e:{},s={fps:Math.max(1,Math.floor(Number(n.fps)||1)),maxWidth:Math.max(1,Math.floor(Number(n.maxWidth)||1)),maxHeight:Math.max(1,Math.floor(Number(n.maxHeight)||1)),quality:Math.max(1,Math.min(100,Math.floor(Number(n.quality)||1)))};return t?{...s,maxWidth:Math.min(s.maxWidth,J0),maxHeight:Math.min(s.maxHeight,Z0),quality:Math.min(s.quality,ek)}:s}function sk(e,t){return!t||!e||typeof e.closest!="function"?null:e.closest(".desk-stage")}function If(e,t,n){return!!(e||t&&n)}function ak({isIos:e,standalone:t,safeAreaTop:n,screenHeight:s,layoutViewportHeight:a}){if(!e||!t)return 0;const i=Number(s),c=Number(a);if((Number.isFinite(i)&&i>0&&Number.isFinite(c)&&c>0?Math.max(0,i-c):0)>=tk)return 0;const d=Number(n);return Number.isFinite(d)&&d>0?Math.max(Pf,Math.round(d)-20):Pf}function ik(e,t,n,s=!1,a=s){const i=Number(e?.height),c=Number(t),u=Number(e?.offsetTop),d=s&&Number.isFinite(c)&&c>0,p=d?0:Number.isFinite(u)?Math.max(0,Math.round(u)):0,h=d?c:Number.isFinite(i)&&i>0?i:Number.isFinite(c)&&c>0?c:1,m=Number(e?.width),g=Number(n),w=a&&Number.isFinite(g)&&g>0,v=w?g:Number.isFinite(m)&&m>0?m:Number.isFinite(g)&&g>0?g:1,y=Number(e?.offsetLeft);return{height:Math.max(1,Math.round(h)),width:Math.max(1,Math.round(v)),offsetTop:p,offsetLeft:w?0:Number.isFinite(y)?Math.max(0,Math.round(y)):0}}function ok(e,t){const n=Promise.resolve(e).catch(()=>{}).then(t);return{result:n,tail:n.then(()=>{},()=>{})}}function ck(){let e=Promise.resolve(),t=Promise.resolve();const n=s=>{const a=ok(e,s);return e=a.tail,a.result};return{enqueue:n,enqueueStop(s){const a=n(s);return t=a.then(()=>{}),t.catch(()=>{}),a},enqueueStart(s){const a=t;return n(async()=>(await a,s()))}}}function lk(e={}){return Number(e.generation)===Number(e.currentGeneration)&&e.enabled===!0&&String(e.deviceId||"")!==""&&String(e.deviceId||"")===String(e.currentDeviceId||"")&&e.documentVisible===!0&&e.presentationVisible===!0&&String(e.streamId||"")!==""&&String(e.streamId||"")===String(e.currentStreamId||"")}function uk(e={}){const t=e.ok!==!1,n=t&&e.staleOwner===!0;return{confirmed:t&&(n||e.captureStopConfirmed===!0||e.alreadyStopped===!0),staleOwner:n,preserveNewerOwner:n&&(e.retainedNewerOwner===!0||String(e.activeStreamId||"")!=="")}}const $t=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,controlWallReuseStarvationFactor:1.5,scalableAtlasMinInputFps:8,scalableAtlasMaxInputFps:20,scalableAtlasAggregateInputFps:120,atlasOutputFps:20,directDecodeAcceleration:"prefer-hardware",directLatencyMode:"interactive"});function Mp(e){return e==="slow"?$t.slowWallFps:$t.fastWallFps}function jf({paintStale:e,lastRecoveryAt:t,now:n,recoveryCooldownMs:s,transportRecoveryAfterMs:a}){if(e!==!0)return"none";const i=Math.max(0,Number(n)||0),c=Math.max(0,Number(t)||0),u=c>0?i-c:Number.POSITIVE_INFINITY;return c>0&&u>=Math.max(1,Number(a)||1)?"recover-transport":c<=0||u>=Math.max(1,Number(s)||1)?"reset-decoder":"wait"}function Ef({lastReceivedAt:e,lastPaintedAt:t,now:n,staleAfterMs:s}){const a=Math.max(0,Number(e)||0);if(a<=0)return!1;const i=Math.max(0,Number(t)||0),c=i>0?i:a;return Math.max(0,Number(n)||0)-c>Math.max(1,Number(s)||1)}function dk(e){return e==="share-files"||e==="agents"}function pk({captureOwnershipActive:e,localFeatureAccess:t,controlSessionDeviceId:n,planAllowed:s,sessionState:a,controlFocusVisible:i,presentationCanvasMounted:c,wallPresentationVisible:u,wallPresentationCanvasMounted:d,decoderOwnerExists:p}){const h=a==="connecting"||a==="active"||a==="warm";return e!==!0||t!==!0||!String(n||"").trim()||s!==!0||!h?!1:p===!0||i===!0&&c===!0||u===!0&&d===!0}function mk({decodeWidth:e,decodeHeight:t,presentationCssWidth:n,presentationCssHeight:s,devicePixelRatio:a,sourceWidth:i,sourceHeight:c}){const u=Math.max(0,Number(e)||0),d=Math.max(0,Number(t)||0),p=Math.max(0,Number(n)||0),h=Math.max(0,Number(s)||0),m=Math.max(1,Math.min(2,Number(a)||1)),g=Math.max(0,Number(i)||0),w=Math.max(0,Number(c)||0);if(u<=0||d<=0||p<=0||h<=0||g<=0||w<=0)return!1;const v=p*m,y=h*m,k=Math.min(1,v/g,y/w),N=Math.max(1,Math.round(g*k)),C=Math.max(1,Math.round(w*k));return u<N*.9||d<C*.9}function hk({cadenceCredit:e,targetFps:t,sourceFps:n,elapsedSincePaintMs:s=0,nowMs:a=0,scheduledPaintAtMs:i=0,force:c=!1}){const u=Math.max(1,Number(t)||1),d=Math.max(1,Number(n)||1);if(u>=d)return{shouldPaint:!0,nextCadenceCredit:0,sourceCadencePassthrough:!0,nextScheduledPaintAtMs:0};const p=Math.max(0,Number(a)||0),h=Math.max(0,Number(i)||0),m=p>0&&h>0,g=1e3/u,w=Math.min(g/3,1e3/d*.5),v=Number.isFinite(Number(e))?Math.max(0,Math.min(d-Number.EPSILON,Number(e))):0;if(c)return{shouldPaint:!0,nextCadenceCredit:v,sourceCadencePassthrough:!1,nextScheduledPaintAtMs:m?h:p>0?p+g:0};const y=v+u,k=y>=d,N=1e3/u*$t.controlWallReuseStarvationFactor,C=!k&&Number(s)>=N,A=m&&p+w>=h,E=m?A||C:k||C;let I=h;return E&&p>0&&(!m||C?I=p+g:(I=h+g,I<=p-g&&(I=p+g))),{shouldPaint:E,nextCadenceCredit:C?0:k&&E?y-d:Math.min(d-Number.EPSILON,y),sourceCadencePassthrough:!1,deadlineForced:C,scheduleSelected:A,nextScheduledPaintAtMs:I}}function fk(e,t){const n=Number.isFinite(Number(t))?Math.max(0,Math.floor(Number(t))):Number.POSITIVE_INFINITY;if(n<=0)return[];const s=(Array.isArray(e)?e:[]).filter(c=>c&&String(c.deviceId||"").trim()).slice().sort((c,u)=>{const d=Number.isFinite(Number(c.slotNumber))?Number(c.slotNumber):Number.MAX_SAFE_INTEGER,p=Number.isFinite(Number(u.slotNumber))?Number(u.slotNumber):Number.MAX_SAFE_INTEGER;return d!==p?d-p:String(c.deviceId).localeCompare(String(u.deviceId))}),a=[],i=new Set;for(const c of s){const u=String(c.deviceId).trim();if(!i.has(u)&&(i.add(u),a.push(u),a.length>=n))break}return a}function gk(e,t){const n=Math.max(0,Math.floor(Number(t)||0));return e===!0&&n>0}function Bo({mode4Enabled:e,directMode4WallEnabled:t,isMac:n}){return"direct"}function bk({mode4Enabled:e,directMode4WallEnabled:t,adaptiveFps:n,directDeviceCount:s,adaptive:a=!0}){return Math.max(1,Math.floor(Number(n)||1))}function vk({directDeviceCount:e,requestedFps:t,measuredFramesPerSecond:n,measuredPaintFramesPerSecond:s,measuredBytesPerSecond:a,maxBytesPerSecond:i,worstReceiveGapMs:c,worstPaintP95Ms:u,maxFrameGapMs:d}){const p=Math.max(1,Math.floor(Number(e)||1)),h=Math.max(1,Number(t)||1),m=Math.max(0,Number(n)||0),g=Math.max(0,Number(s)||0),w=Math.max(0,Number(a)||0),v=Math.max(1,Number(i)||1),y=Math.max(0,Number(c)||0),k=Math.max(0,Number(u)||0),N=Math.max(1,Number(d)||1),C=p*h,A=C>8&&m<C*$t.missingDeliveryRatio,E=C>8&&g<C*$t.missingDeliveryRatio,I=w>v||y>N||A||E,F=m>=C*$t.recoveryDeliveryRatio&&g>=C*$t.recoveryDeliveryRatio&&w<v*$t.recoveryByteRatio&&y<N*$t.recoveryGapRatio&&k<N*$t.recoveryGapRatio;return{expectedFramesPerSecond:C,estimatedMissingFrames:A,estimatedMissingPaints:E,overloaded:I,healthyForRecovery:F}}function wk({receiveSampleMs:e,paintSampleMs:t,currentGenerationVerified:n,frameRequestedFps:s,adaptiveFps:a}){const i=Number(e),c=Number(t),u=Number(s),d=Number(a);return n===!0&&Number.isFinite(i)&&i>=$t.adaptiveMinimumCurrentSampleMs&&Number.isFinite(c)&&c>=$t.adaptiveMinimumCurrentSampleMs&&Number.isFinite(u)&&u>0&&u===d}function yk({deviceCount:e,targetFps:t,adaptive:n=!0}){const s=Math.max(1,Math.floor(Number(e)||1)),a=Math.max(1,Math.min($t.scalableAtlasMaxInputFps,Math.floor(Number(t)||$t.scalableAtlasMaxInputFps)));if(!n)return a;const i=Math.max($t.scalableAtlasMinInputFps,Math.min($t.scalableAtlasMaxInputFps,Math.floor($t.scalableAtlasAggregateInputFps/s)));return Math.min(a,i)}function xk(e,t){return{acceleration:$t.directDecodeAcceleration,latencyMode:$t.directLatencyMode}}const lu=0,Ja=100,Sk=25,Ck=50,Ff=300,kk=560;function dc(e){return Number.isFinite(e)?Math.min(Ja,Math.max(lu,Math.round(e))):Ja}function Mk(e){const t=dc(e);return t===lu?"list":t<Ck?"medium":"large"}function Ak(e){const n=(Math.max(1,dc(e))-1)/(Ja-1);return Math.round(Ff+n*(kk-Ff))}const Wa={revision:0,settings:{connection:{showThisComputer:!1},security:{accessMode:"trusted-only"},control:{allowKeyboardMouse:!0,allowRemoteRestart:!1},filesAudio:{allowFileTransfer:!0,allowRemoteAudio:!0,rollingBufferEnabled:!1,recordingQuality:"standard",timelapseIntervalSeconds:10,includeRemoteCursor:!0}}},Df=[{id:"connection",label:"Connection",icon:bu},{id:"remote-access",label:"Remote Access",icon:Zt},{id:"capture-audio",label:"Capture & Audio",icon:np},{id:"agent",label:"Agent",icon:Xs}];function Go(e,t){return e?.settings?.[t]||Wa.settings[t]||{}}function Lf(e,t){return{...e,settings:{...e.settings,[t.section]:{...Go(e,t.section),[t.key]:t.value}}}}function Fd(e){return{revision:Number(e.revision||0),updatedAt:e.updatedAt,settings:e.settings}}function zs({icon:e,title:t,description:n,children:s,recommended:a=!1}){return r.jsxs("div",{className:"product-setting-row",children:[r.jsx("div",{className:"product-setting-control",children:s}),e&&r.jsx("span",{className:"product-setting-icon",children:r.jsx(e,{size:17})}),r.jsxs("div",{className:"product-setting-copy",children:[r.jsx("strong",{children:t}),a&&r.jsx("em",{children:"Recommended"}),r.jsx("small",{children:n})]})]})}function Ui({checked:e,onChange:t,label:n}){return r.jsxs("label",{className:"product-switch",children:[r.jsx("input",{"aria-label":n,type:"checkbox",checked:e,onChange:s=>t(s.target.checked)}),r.jsx("span",{})]})}function _f({value:e,onChange:t,options:n,label:s}){return r.jsx("select",{"aria-label":s,value:String(e),onChange:a=>t(a.target.value),children:n.map(([a,i])=>r.jsx("option",{value:a,children:i},a))})}function Nk({hubUrl:e="",mobileLayout:t=!1,runtimeRole:n="hub",runtimeDeviceId:s="",sessionAccessToken:a="",showThisComputerSetting:i=!0,onShowThisComputerChange:c,initialTab:u="connection",pin:d,agent:p,captureGallery:h,desktopUpdate:m}){const[g,w]=o.useState(()=>t&&u==="connection"?"remote-access":u),[v,y]=o.useState(null),[k,N]=o.useState("loading"),[C,A]=o.useState(""),[E,I]=o.useState("idle"),[F,M]=o.useState(""),H=o.useRef(null),V=o.useRef(null),P=o.useRef([]),D=o.useRef(Promise.resolve()),O=o.useRef(0),X=o.useRef(0);o.useEffect(()=>{const Se=++X.current;let te=!0;return P.current=[],V.current=null,H.current=null,D.current=Promise.resolve(),N("loading"),Oe("/api/settings",void 0,e).then(Ce=>{if(!te||Se!==X.current)return;const Fe=Fd(Ce);V.current=Fe,H.current=Fe,y(Fe),N("saved")}).catch(Ce=>{!te||Se!==X.current||(A(Ce instanceof Error?Ce.message:String(Ce)),V.current=Wa,H.current=Wa,y(Wa),N("failed"))}),()=>{te=!1}},[e]);const G=async(Se,te,Ce)=>{const Fe={id:++O.current,section:Se,key:te,value:Ce},Le=X.current;P.current.push(Fe);const Ue=Lf(H.current||V.current||Wa,Fe);H.current=Ue,y(Ue),N("saving"),A(""),D.current=D.current.then(async()=>{if(Le!==X.current)return;let ne=null,ae=null;for(let J=0;J<2&&!ne;J+=1){const ye=V.current||Wa;try{const ue=await Oe("/api/settings",{method:"PATCH",body:JSON.stringify({revision:ye.revision,[Fe.section]:{[Fe.key]:Fe.value}})},e);ne=Fd(ue)}catch(ue){if(ae=ue,J!==0||!String(ue instanceof Error?ue.message:ue).startsWith("409 "))break;try{const Ee=await Oe("/api/settings",void 0,e);if(Le!==X.current)return;V.current=Fd(Ee)}catch(Ee){ae=Ee;break}}}if(Le!==X.current)return;P.current=P.current.filter(J=>J.id!==Fe.id),ne&&(V.current=ne);const le=V.current||Wa,ce=P.current.reduce(Lf,le);H.current=ce,y(ce),ne?(A(""),N(P.current.length>0?"saving":"saved")):(N(P.current.length>0?"saving":"failed"),A(ae instanceof Error?ae.message:String(ae||"Settings could not be saved.")))}),await D.current},U=(Se,te)=>Ce=>{G(Se,te,Ce)},ie=async()=>{if(n!=="hub"||!s||!a){I("failed"),M("Sign in to this Hub before changing its runtime role.");return}I("changing"),M("");try{const Se=await Oe("/api/runtime/status",void 0,e);await Oe("/api/runtime/role",{method:"POST",headers:{Authorization:`Bearer ${a}`},body:JSON.stringify({role:"client"})},e),I("accepted"),await ob({baseUrl:e,targetRole:"client",previousRuntimePid:Number(Se.runtimePid||0),allowedStates:["running","waiting-auth"]}),Ly(5179)}catch(Se){I("failed"),M(Se instanceof Error?Se.message:String(Se))}},j=Go(v,"security"),re=Go(v,"control"),de=Go(v,"filesAudio"),Q=Go(v,"connection"),ge=`settings-panel-${g}`,oe=t?Df.filter(Se=>Se.id!=="connection"):Df;o.useEffect(()=>{t&&g==="connection"&&w("remote-access")},[g,t]),o.useEffect(()=>{v&&c?.(!!Q.showThisComputer)},[Q.showThisComputer,c,v]);const me=r.jsxs("div",{className:"settings-tab-content product-settings-content",children:[d,m,i&&r.jsxs("section",{className:"settings-section-card",children:[r.jsxs("div",{className:"settings-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Hub computer list"}),r.jsx("h3",{children:"This computer"})]}),r.jsx(pn,{size:20})]}),r.jsx(zs,{icon:pn,title:"Show this computer",description:"Show this Hub computer in its own Wall and computer lists. It stays available from other computers and the mobile app when hidden.",children:r.jsx(Ui,{checked:!!Q.showThisComputer,onChange:U("connection","showThisComputer"),label:"Show this computer"})})]}),r.jsxs("section",{className:"settings-section-card runtime-role-settings",children:[r.jsxs("div",{className:"settings-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Runtime role"}),r.jsx("h3",{children:"Use this computer as a Client"})]}),r.jsx(fb,{size:20})]}),r.jsx("p",{className:"settings-help",children:"Stop hosting from this computer and reconnect it to the selected Hub."}),E==="accepted"?r.jsx("p",{className:"settings-help runtime-role-success",children:"LiveDesk is restarting as Client."}):F?r.jsx("p",{className:"settings-help runtime-role-error",role:"alert",children:F}):null,r.jsx("button",{className:"settings-reset",onClick:()=>{ie()},disabled:E==="changing"||n!=="hub",type:"button",children:E==="changing"?"Switching role...":"Switch this computer to Client"})]})]}),Ae=r.jsxs("div",{className:"settings-tab-content product-settings-content",children:[r.jsxs("section",{className:"settings-section-card",children:[r.jsxs("div",{className:"settings-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Remote access"}),r.jsx("h3",{children:"Who may connect?"})]}),r.jsx(As,{size:20})]}),r.jsx(zs,{icon:Zt,title:"Access mode",description:"Choose the default permission boundary for remote sessions.",recommended:!0,children:r.jsx(_f,{value:String(j.accessMode),onChange:U("security","accessMode"),label:"Access mode",options:[["trusted-only","Trusted devices only"],["block-remote-access","Block remote access"]]})})]}),r.jsxs("section",{className:"settings-section-card",children:[r.jsxs("div",{className:"settings-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Session permissions"}),r.jsx("h3",{children:"What may remote users do?"})]}),r.jsx(pn,{size:20})]}),r.jsx(zs,{icon:pn,title:"Keyboard and mouse control",description:"Allow Control to send keyboard and pointer input.",recommended:!0,children:r.jsx(Ui,{checked:!!re.allowKeyboardMouse,onChange:U("control","allowKeyboardMouse"),label:"Keyboard and mouse control"})}),r.jsx(zs,{icon:gb,title:"Power actions",description:"Allow confirmed sleep, restart, and shut down commands from the Hub.",children:r.jsx(Ui,{checked:!!re.allowRemoteRestart,onChange:U("control","allowRemoteRestart"),label:"Power actions"})}),r.jsx(zs,{icon:np,title:"File transfer",description:"Allow files to be delivered to connected computers.",children:r.jsx(Ui,{checked:!!de.allowFileTransfer,onChange:U("filesAudio","allowFileTransfer"),label:"File transfer"})}),r.jsx(zs,{icon:Ji,title:"Remote audio",description:"Allow sound capture from connected computers.",children:r.jsx(Ui,{checked:!!de.allowRemoteAudio,onChange:U("filesAudio","allowRemoteAudio"),label:"Remote audio"})})]})]}),Te=r.jsxs("div",{className:"settings-tab-content product-settings-content",children:[r.jsxs("section",{className:"settings-section-card",children:[r.jsxs("div",{className:"settings-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Capture"}),r.jsx("h3",{children:"Recording defaults"})]}),r.jsx(np,{size:20})]}),r.jsx(zs,{icon:Ji,title:"Keep a Last 30s buffer",description:"Keep recent video in memory until you explicitly save it.",children:r.jsx(Ui,{checked:!!de.rollingBufferEnabled,onChange:U("filesAudio","rollingBufferEnabled"),label:"Keep a Last 30s buffer"})}),r.jsx(zs,{icon:Ji,title:"Timelapse interval",description:"Choose how often a timelapse frame is captured.",children:r.jsx(_f,{value:Number(de.timelapseIntervalSeconds),onChange:Se=>U("filesAudio","timelapseIntervalSeconds")(Number(Se)),label:"Timelapse interval",options:[["5","5 seconds"],["10","10 seconds"],["30","30 seconds"],["60","60 seconds"]]})})]}),h]}),Pe=g==="connection"?me:g==="remote-access"?Ae:g==="capture-audio"?Te:p;return r.jsxs("section",{className:"settings-page",children:[r.jsx("div",{className:"settings-page-tabs",role:"tablist","aria-label":"LiveDesk settings",children:oe.map(({id:Se,label:te,icon:Ce})=>r.jsxs("button",{className:g===Se?"active":"",id:`settings-tab-${Se}`,role:"tab","aria-selected":g===Se,"aria-controls":`settings-panel-${Se}`,tabIndex:g===Se?0:-1,onClick:()=>w(Se),type:"button",children:[r.jsx(Ce,{size:16}),te]},Se))}),k==="saving"&&r.jsx("div",{className:"product-save-state",role:"status",children:"Saving settings..."}),C&&r.jsx("div",{className:"agent-settings-alert error",role:"alert",children:C}),r.jsx("section",{className:"settings-page-panel",id:ge,role:"tabpanel","aria-labelledby":`settings-tab-${g}`,tabIndex:0,children:Pe})]})}function Rk({children:e}){return r.jsx("div",{className:"settings-tab-content",children:e})}const $f={enabled:!1};function Of(e){return{enabled:e?.enabled===!0}}async function Tk(e,t,n){let s=null;for(let a=0;a<2;a+=1){const i=await Oe("/api/settings",{signal:n},t);if(i.settings.agent?.enabled===e)return;try{await Oe("/api/settings",{method:"PATCH",signal:n,body:JSON.stringify({revision:i.revision,agent:{enabled:e}})},t);return}catch(c){if(s=c,a!==0||!String(c instanceof Error?c.message:c).startsWith("409 "))throw c}}throw s}function Pk({hubUrl:e,showToast:t}){const[n,s]=o.useState($f),[a,i]=o.useState(null),[c,u]=o.useState(""),[d,p]=o.useState(""),[h,m]=o.useState(""),g=o.useRef(0),w=o.useRef(null);o.useEffect(()=>{let F=!0;w.current?.abort();const M=new AbortController;w.current=M;const H=++g.current;return i(null),s($f),u(""),m(""),p(""),Oe("/api/settings/agent",{signal:M.signal},e).then(V=>{!F||M.signal.aborted||H!==g.current||(i(V.settings),s(Of(V.settings)))}).catch(V=>{F&&!M.signal.aborted&&H===g.current&&m(V instanceof Error?V.message:String(V))}),()=>{F=!1,M.abort(),w.current===M&&(w.current=null)}},[e]);const v=(F,M)=>s(H=>({...H,[F]:M})),y=F=>{i(F),s(Of(F))},k=()=>({generation:g.current,controller:w.current}),N=F=>F.generation===g.current&&F.controller!==null&&F.controller===w.current&&!F.controller.signal.aborted,C=async()=>{if(!a){m("Agent settings are not available yet.");return}const F=k();if(N(F)){u("save"),m(""),p("");try{if(await Tk(n.enabled,e,F.controller.signal),!N(F))return;const M=await Oe("/api/settings/agent",{signal:F.controller.signal},e);if(!N(F))return;y(M.settings),p("Codex Agent settings saved.")}catch(M){N(F)&&m(M instanceof Error?M.message:String(M))}finally{N(F)&&u("")}}},A=async()=>{const F=k();if(N(F)){u("test"),m(""),p("");try{const M=await Oe("/api/settings/agent/test",{method:"POST",signal:F.controller.signal,body:JSON.stringify({})},e);if(!N(F))return;const H=await Oe("/api/settings/agent",{signal:F.controller.signal},e);if(!N(F))return;y(H.settings);const V=Number.isFinite(M.connection?.latencyMs)?Math.max(0,Math.round(M.connection.latencyMs)):null;t(`Codex Agent connection verified${V!==null?` in ${V} ms.`:"."}`,"success")}catch(M){N(F)&&m(M instanceof Error?M.message:String(M))}finally{N(F)&&u("")}}},E=a?.codexInstallation==="installed"&&a.codexAuth==="signed-in",I=a!==null;return r.jsxs("div",{className:"settings-tab-content agent-settings-content",children:[r.jsx("section",{className:"settings-section-card agent-enable-card",children:r.jsxs("label",{className:"settings-toggle agent-enable-toggle",children:[r.jsx("input",{type:"checkbox",checked:n.enabled,onChange:F=>v("enabled",F.target.checked),disabled:!I||c!==""}),r.jsx("span",{children:"Enable Codex Agent"})]})}),h&&r.jsx("div",{className:"agent-settings-alert error",role:"alert",children:h}),d&&r.jsx("div",{className:"agent-settings-alert success",role:"status",children:d}),r.jsxs("section",{className:"settings-section-card",children:[r.jsxs("div",{className:"settings-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Connection"}),r.jsx("h3",{children:"Codex SDK / CLI"})]}),r.jsx(Zt,{size:20})]}),r.jsxs("div",{className:"agent-connection-row",children:[r.jsx("span",{className:`agent-connection-dot ${E?"connected":a?.codexAuth==="not-signed-in"?"unavailable":""}`}),r.jsx("span",{children:a?.codexInstallation==="not-installed"?"Codex SDK not installed":a?.codexAuth==="signed-in"?"Codex CLI signed in":a?.codexAuth==="not-signed-in"?"Codex CLI sign-in required":"Codex status not tested"}),r.jsxs("button",{className:"settings-reset",onClick:()=>{A()},disabled:c!=="",type:"button",children:[r.jsx(Yy,{size:15})," ",c==="test"?"Testing":"Test connection"]})]}),r.jsxs("p",{className:"settings-help",children:[r.jsx(Xy,{size:12})," The Hub uses the installed Codex SDK / CLI to plan approved commands and run them through LiveDesk Agent tools on selected computers."]})]}),r.jsx("div",{className:"settings-action-row agent-settings-actions",children:r.jsxs("button",{className:"text-button primary",onClick:()=>{C()},disabled:!I||c!=="",type:"button",children:[r.jsx(Jy,{size:15})," ",c==="save"?"Saving":"Save Agent settings"]})})]})}new Date().valueOf();function cs(e){const[t,n]=o.useState(e),s=o.useRef(e);return o.useEffect(()=>{if(s.current!==e){if(Array.isArray(s.current)&&Array.isArray(e)&&s.current.length===0&&e.length===0)return;s.current=e,n(e)}},[e]),[t,n]}function Kp(e,t){return typeof e=="function"?typeof t=="object"?e(t):e():e}function ro(e,t="data-id"){let n=e;for(!n.tagName&&e.target&&(n=e.target);n;){if(n.getAttribute&&n.getAttribute(t))return n;n=n.parentNode}return null}function Ik(e,t="data-id"){const n=ro(e,t);return n?n.getAttribute(t):null}function oc(e,t="data-id"){const n=ro(e,t);return n?Mu(n,t):null}function Mu(e,t="data-id"){const n=e.getAttribute(t);return n?jk(n):null}function mn(e){return typeof e=="string"?":"+e:e}function jk(e){if(e.startsWith(":"))return e.substring(1);const t=e*1;return isNaN(t)?e:t}function Ek(){return{detect:()=>!0,addEvent:function(e,t,n){return e.addEventListener(t,n),()=>e.removeEventListener(t,n)},addGlobalEvent:function(e,t){return document.addEventListener(e,t),()=>document.removeEventListener(e,t)},getTopNode:function(){return window.document.body}}}var tr=Ek();function Qp(e){Object.assign(tr,e)}function Bf(e,t,n){function s(a){const i=ro(a);if(!i)return;const c=Mu(i);if(typeof t=="function")return t(c,a);let u,d=a.target;for(;d!=i;){if(u=d.dataset?d.dataset.action:null,u&&t[u]){t[u](c,a);return}d=d.parentNode}t[n]&&t[n](c,a)}tr.addEvent(e,n,s)}function so(e,t){Bf(e,t,"click"),t.dblclick&&Bf(e,t.dblclick,"dblclick")}function Fk(e,t){for(let n=e.length-1;n>=0;n--)if(e[n]===t){e.splice(n,1);break}}function Dk(e,t,n){for(let s=0;s<Rs.length;s++){if(s===n)continue;const a=Rs[s],i=a.props.parent?.();if(i&&e.contains(i)&&a.node.contains(t))return!0}return!1}var yv=new Date,uu=!1,Pl=[],Rs=[],Hf=e=>{const t=e.target;if(uu||!t.isConnected){uu=!1;return}for(let n=Rs.length-1;n>=0;n--){const{node:s,date:a,props:i}=Rs[n];if(!(a>yv)&&!s.contains(t)&&s!==t&&(Dk(s,t,n)||(i.callback&&i.callback(e),i.modal||e.defaultPrevented)))break}},Lk=e=>{yv=new Date,uu=!0;for(let t=Rs.length-1;t>=0;t--){const{node:n}=Rs[t];if(!n.contains(e.target)&&n!==e.target){uu=!1;break}}};function ls(e,t){Pl.length||(Pl=[tr.addGlobalEvent("click",Hf,e),tr.addGlobalEvent("contextmenu",Hf,e),tr.addGlobalEvent("mousedown",Lk,e)]),typeof t!="object"&&(t={callback:t});const n={node:e,date:new Date,props:t};return Rs.push(n),{destroy(){Fk(Rs,n),Rs.length||(Pl.forEach(s=>s()),Pl=[])}}}var Il=e=>e.indexOf("bottom")!==-1,jl=e=>e.indexOf("left")!==-1,El=e=>e.indexOf("right")!==-1,Dd=e=>e.indexOf("top")!==-1,Wf=e=>e.indexOf("fit")!==-1,Ho=e=>e.indexOf("overlap")!==-1,_k=e=>e.split("-").every(t=>["center","fit"].indexOf(t)>-1),$k=e=>{const t=e.match(/(start|center|end)/);return t?t[0]:null};function Ok(e,t){let n=0;const s=tr.getTopNode(e);for(;e&&e!==s;){const a=getComputedStyle(e).position;if((a==="absolute"||a==="relative"||a==="fixed")&&(n=parseInt(getComputedStyle(e).zIndex)||0),e=e.parentNode,e===t)break}return n}var Yt,Pn,Wo,yn;function xv(e,t,n="bottom",s=0,a=0){if(!e)return null;Yt=s,Pn=a,Wo="auto";let i=0,c=0,u=n;const d=Sv(e),p=Ho(n)?tr.getTopNode(e):d;if(!d)return null;const h=d.getBoundingClientRect(),m=e.getBoundingClientRect(),g=p.getBoundingClientRect(),w=window.getComputedStyle(p),v={left:0,top:0,bottom:0,right:0};for(const E in v){const I=`border-${E}-width`;v[E]=parseFloat(w.getPropertyValue(I))}if(t){const E=Ok(t,d);i=Math.max(E+1,20)}if(t){if(yn=t.getBoundingClientRect(),Wf(n)&&(Wo=yn.width+"px"),n!=="point")if(_k(n))Wf(n)?Yt=0:(Yt=g.width/2,c=1),Pn=(g.height-m.height)/2;else{const E=Ho(n)?0:1;Yt=El(n)?yn.right+E:yn.left-E,Pn=Il(n)?yn.bottom+1:yn.top;const I=$k(n);I&&(El(n)||jl(n)?I==="center"?Pn-=(m.height-yn.height)/2:I==="end"&&(Pn-=m.height-yn.height):(Il(n)||Dd(n))&&(I==="center"?Yt-=(m.width-yn.width)/2:I==="end"&&(Yt-=m.width-yn.width),Ho(n)||(Yt+=1)))}}else yn={left:s,right:s,top:a,bottom:a};const y=(jl(n)||El(n))&&(Il(n)||Dd(n));jl(n)&&(c=2);const k=Yt-m.width-g.left;t&&jl(n)&&!y&&k<0&&(Yt=yn.right,c=0,u=u.replace("left","right"));const N=Yt+m.width*(1-c/2)-g.right;if(N>0)if(!El(n))Yt=g.right-v.right-m.width;else{const E=yn.left-g.x-m.width;t&&!y&&E>=0?(Yt=yn.left-m.width,u=u.replace("right","left")):Yt-=N+v.right}c&&(Yt=Math.round(Yt-m.width*c/2));const C=k<0||N>0||!y;Dd(n)&&(Pn=yn.top-m.height,t&&Pn<g.y&&C&&(Pn=yn.bottom,u=u.replace("top","bottom")));const A=Pn+m.height-g.bottom;return A>0&&(t&&Il(n)&&C?(Pn-=m.height+yn.height+1,u=u.replace("bottom","top")):Pn-=A+v.bottom),Yt-=h.left+v.left,Pn-=h.top+v.top,Yt=(Ho(n)?Yt:Math.max(Yt,0))+p.scrollLeft,Pn=(Ho(n)?Pn:Math.max(Pn,0))+p.scrollTop,Wo=Wo||"auto",{at:u,x:Yt,y:Pn,z:i,width:Wo}}function Sv(e){const t=tr.getTopNode(e);for(e&&(e=e.parentElement);e;){const n=getComputedStyle(e).position;if(e===t||n==="relative"||n==="absolute"||n==="fixed")return e;e=e.parentNode}return null}function Bk(e){const t=[];let n=e;const s=tr.getTopNode(e);for(;n&&n!==s&&!n.getAttribute("data-wx-portal-root");)getComputedStyle(n).position==="absolute"&&t.push(n),n=n.parentNode;return t}var zf=new Date().valueOf();function Yp(){return zf+=1,zf}function jn(e){return e<10?"0"+e:e.toString()}function Hk(e){const t=jn(e);return t.length==2?"0"+t:t}function Cv(e){const t=Math.floor(e/11)*11;return{start:t,end:t+11}}function Ld(e){const t=(e.getDay()+6)%7,n=new Date(e.valueOf());n.setDate(e.getDate()+(3-t)),n.setHours(0,0,0,0);const s=new Date(n.getFullYear(),0,1),a=Math.round((n.getTime()-s.getTime())/864e5);return 1+Math.floor(a/7)}var qf=["",""];function Wk(e,t,n){switch(e){case"%d":return jn(t.getDate());case"%m":return jn(t.getMonth()+1);case"%j":return t.getDate();case"%n":return t.getMonth()+1;case"%y":return jn(t.getFullYear()%100);case"%Y":return t.getFullYear();case"%D":return n.dayShort[t.getDay()];case"%l":return n.dayFull[t.getDay()];case"%M":return n.monthShort[t.getMonth()];case"%F":return n.monthFull[t.getMonth()];case"%h":return jn((t.getHours()+11)%12+1);case"%g":return(t.getHours()+11)%12+1;case"%G":return t.getHours();case"%H":return jn(t.getHours());case"%i":return jn(t.getMinutes());case"%a":return((t.getHours()>11?n.pm:n.am)||qf)[0];case"%A":return((t.getHours()>11?n.pm:n.am)||qf)[1];case"%s":return jn(t.getSeconds());case"%S":return Hk(t.getMilliseconds());case"%W":return jn(Ld(t));case"%w":{const s=n.weekStart??1;if(s===1)return jn(Ld(t));const a=(t.getDay()-s+7)%7,i=(1-s+7)%7,c=new Date(t.valueOf());return c.setDate(t.getDate()+(i-a)),jn(Ld(c))}case"%c":{let s=t.getFullYear()+"";return s+="-"+jn(t.getMonth()+1),s+="-"+jn(t.getDate()),s+="T",s+=jn(t.getHours()),s+=":"+jn(t.getMinutes()),s+=":"+jn(t.getSeconds()),s}case"%Q":return Math.floor(t.getMonth()/3)+1;default:return e}}var zk=/%[a-zA-Z]/g;function Zi(e,t){return typeof e=="function"?e:function(n){return n?(n.getMonth||(n=new Date(n)),e.replace(zk,s=>Wk(s,n,t))):""}}function Uf(e){return e&&typeof e=="object"&&!Array.isArray(e)}function Ap(e,t){for(const n in t){const s=t[n];Uf(e[n])&&Uf(s)?e[n]=Ap({...e[n]},t[n]):e[n]=t[n]}return e}function pc(e){return{getGroup(t){const n=e[t];return s=>n&&n[s]||s},getRaw(){return e},extend(t,n){if(!t)return this;let s;return n?s=Ap({...t},e):s=Ap({...e},t),pc(s)}}}var qk=yx();const Uk="en-US",Vk={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},Gk={ok:"OK",cancel:"Cancel",select:"Select","No data":"No data","Rows per page":"Rows per page","Total pages":"Total pages"},Kk={timeFormat:"%H:%i",dateFormat:"%m/%d/%Y",monthYearFormat:"%F %Y",yearFormat:"%Y"},kv={core:Gk,calendar:Vk,formats:Kk,lang:Uk},Xp=o.createContext(""),Mv=o.createContext({}),Lr=o.createContext(null),Av=o.createContext(null),fn=Object.freeze(Object.defineProperty({__proto__:null,fieldId:Av,helpers:Mv,i18n:Lr,theme:Xp},Symbol.toStringTag,{value:"Module"}));function Nv(e){const t=o.useContext(Av),[n]=o.useState(()=>e||t||Yp());return n}function ec({type:e="",css:t="",icon:n="",disabled:s=!1,title:a="",tooltip:i,text:c="",children:u,onClick:d}){const p=o.useMemo(()=>{let m=e?e.split(" ").filter(g=>g!=="").map(g=>"wx-"+g).join(" "):"";return t+(t?" ":"")+m},[e,t]),h=m=>{d&&d(m)};return r.jsxs("button",{title:a,className:`wx-2ZWgb4 wx-button ${p} ${n&&!u?"wx-icon":""}`,disabled:s,onClick:h,"data-tooltip-text":i,children:[n&&r.jsx("i",{className:"wx-2ZWgb4 "+n}),u||c||" "]})}function Qk({id:e,label:t="",inputValue:n="",value:s=!1,onChange:a,disabled:i=!1,css:c=""}){const u=Nv(e),[d,p]=cs(s),h=({target:m})=>{const g=m.checked;p(g),a&&a({value:g,inputValue:n})};return r.jsxs("div",{className:`wx-2IvefP wx-checkbox ${c}`,children:[r.jsx("input",{type:"checkbox",id:u,disabled:i,className:"wx-2IvefP wx-check",checked:d,value:n,onChange:h}),r.jsxs("label",{htmlFor:u,className:"wx-2IvefP wx-label",children:[r.jsx("span",{className:"wx-2IvefP wx-before"}),t&&r.jsx("span",{className:"wx-2IvefP wx-after",children:t})]})]})}function Jp({theme:e="",target:t,children:n}){const s=o.useRef(null),a=o.useRef(null),[i,c]=o.useState(null);s.current||(s.current=document.createElement("div"));const u=o.useContext(Xp);return o.useEffect(()=>{c(t||Yk(a.current)||tr.getTopNode(a.current))},[a.current]),r.jsxs(r.Fragment,{children:[r.jsx("span",{ref:a,style:{display:"none"}}),a.current&&i?qk.createPortal(r.jsx("div",{className:`wx-3ZWsT0 wx-${e||u}-theme`,children:n}),i):null]})}function Yk(e){const t=tr.getTopNode(e);for(;e&&e!==t&&!e.getAttribute("data-wx-portal-root");)e=e.parentNode;return e}function Xk({left:e=0,top:t=0,at:n="bottom",parent:s=null,width:a="auto",css:i="",onCancel:c,children:u,trackScroll:d=!1}){const[p,h]=o.useState(0),[m,g]=o.useState(0),[w,v]=o.useState("auto"),[y,k]=o.useState(!1),N=o.useRef(null),C=o.useRef(null),A=o.useRef(c);o.useEffect(()=>{A.current=c},[c]);function E(F){return s&&(a+"").indexOf("%")>-1?a.replace(/(\d+)%/,(M,H)=>(H=H*s.offsetWidth/100+"px",a.replace(M,H))):a&&a!=="auto"?a:F}const I=o.useCallback(()=>{if(!N.current)return;const F=xv(N.current,s,n,e,t);F&&(h(F.x),g(F.y),v(E(F.width)))},[N,s,n,e,t,a]);return o.useLayoutEffect(()=>{const F=H=>{A.current&&H.target!==C.current&&N.current&&!N.current.contains(H.target)&&A.current(H)};let M;return requestAnimationFrame(()=>{I(),k(!0),d&&N.current&&(C.current=Sv(N.current),C.current&&C.current.addEventListener("scroll",F,!0)),s&&(M=new ResizeObserver(I),M.observe(s))}),()=>{d&&C.current&&C.current.removeEventListener("scroll",F,!0),M?.disconnect()}},[]),o.useLayoutEffect(()=>{I()},[s,n,e,t]),o.useEffect(()=>{const F=M=>{A.current&&A.current(M)};if(N.current)return ls(N.current,{callback:F,parent:()=>s}).destroy},[s]),r.jsx("div",{ref:N,className:["wx-37M6Fj","wx-popup",i].filter(Boolean).join(" "),style:{position:"absolute",visibility:y?"visible":"hidden",top:m+"px",left:p+"px",width:w},children:u})}function Jk({position:e="bottom",align:t="start",autoFit:n=!0,onCancel:s=null,width:a="100%",css:i="",children:c}){const u=o.useRef(null),[d,p]=o.useState(e),[h,m]=o.useState(t),g=o.useRef(s);return o.useEffect(()=>{g.current=s},[s]),o.useEffect(()=>{if(n){const w=u.current;if(w){const v=w.getBoundingClientRect(),y=document.body.getBoundingClientRect();v.right>=y.right&&m("end"),v.bottom>=y.bottom&&p("top")}}},[]),o.useEffect(()=>{if(u.current){const w=v=>{g.current&&g.current(v)};return ls(u.current,w).destroy}},[]),r.jsx("div",{ref:u,className:["wx-dropdown",`wx-${d}-${h}`,i||"","wx-aaaVytZW"].filter(Boolean).join(" "),style:{width:a},children:c})}function Zp({position:e="bottom",align:t="start",autoFit:n=!0,inline:s=!1,onCancel:a,width:i="100%",children:c,...u}){const[d,p]=o.useState(void 0),h=o.useRef(null),m=o.useMemo(()=>`${e}-${t}`,[e,t]);return o.useLayoutEffect(()=>{h.current&&p(h.current.parentNode)},[]),r.jsxs(r.Fragment,{children:[d&&(s?r.jsx(Jk,{onCancel:a,position:e,align:t,autoFit:n,width:i,...u,children:c}):r.jsx(Jp,{children:r.jsx(Xk,{parent:d,at:m,onCancel:a,width:i,...u,children:c})})),r.jsx("span",{ref:h,className:"wx-portal-node wx-32GZ52"})]})}function Au(){return pc(kv)}function Zk(){let e=null,t=!1,n=!1,s,a,i,c;const u=(m,g,w,v,y)=>{s=m,a=g,i=w,c=v,n=y},d=m=>{e=m,t=e!==null,i(e)},p=(m,g)=>{if(!n&&m!==null&&s){const w=s.querySelectorAll(".wx-list > .wx-item")[m];w&&(w.scrollIntoView({block:"nearest"}),g&&g.preventDefault())}},h=(m,g)=>{const w=m===null?null:Math.max(0,Math.min(e+m,a.length-1));w!==e&&(d(w),s?p(w,g):requestAnimationFrame(()=>p(w,g)))};return{move:m=>{const g=oc(m),w=a.findIndex(v=>v.id===g);w!==e&&d(w)},keydown:(m,g)=>{switch(m.code){case"Enter":t?c():d(0);break;case"Space":t||d(0);break;case"Escape":i(e=null);break;case"Tab":i(e=null);break;case"ArrowDown":h(t?1:g||0,m);break;case"ArrowUp":h(t?-1:g||0,m);break}},init:u,navigate:h}}const Vf=10,eM=o.memo(function({data:e,checkboxes:t,itemTemplate:n,value:s}){return r.jsxs(r.Fragment,{children:[t&&r.jsx(Qk,{id:e.id,css:"wx-list-checkbox",value:s&&s.includes(e.id)}),n?Kp(n,{option:e}):e.label]})});function Gf({visibleItems:e,visibleRange:t,navIndex:n,checkboxes:s,itemTemplate:a,value:i,measureRefCallback:c}){return e.map((u,d)=>{const p=t.start+d;return r.jsx("div",{ref:d===0?c:void 0,className:`wx-233fr7 wx-item ${p===n?"wx-focus":""}`,"data-id":u.id,children:r.jsx(eM,{data:u,checkboxes:s,itemTemplate:a,value:i})},u.id)})}function Nu({items:e=[],children:t,onSelect:n,onReady:s,virtualized:a=!1,checkboxes:i,multiselect:c,value:u,...d}){const p=o.useRef(),h=o.useRef(!1),m=o.useRef(Zk()),[g,w]=o.useState(null),v=o.useRef(g),[y,k]=o.useState(0),[N,C]=o.useState(24),A=o.useRef(!1),E=(o.useContext(Lr)||Au()).getGroup("core"),I=o.useRef(e);o.useEffect(()=>{I.current=e},[e]);const F=o.useRef(u);o.useEffect(()=>{F.current=u},[u]);const M=o.useRef(0);o.useEffect(()=>{M.current=N},[N]);const H=o.useCallback(oe=>{oe&&oe.stopPropagation();const me=I.current,Ae=F.current,Te=v.current;let Pe;const Se=me[Te]?.id;c?Ae&&Ae.includes(Se)?Pe=Ae.filter(te=>te!==Se):Pe=[...Ae||[],Se]:Pe=Se,n&&n({id:Pe})},[c,n]),V=o.useRef(H);o.useEffect(()=>{V.current=H},[H]);const P=o.useCallback(oe=>{if(p.current){let me=oe*M.current-p.current.clientHeight+M.current;k(me),p.current.scrollTop=me}},[M.current]),D=o.useCallback(oe=>{p.current=oe,a&&(oe&&!h.current&&v.current!==null&&requestAnimationFrame(()=>{p.current&&(P(v.current),h.current=!0)}),oe||(h.current=!1))},[P]),O=o.useCallback(oe=>{if(!oe||A.current)return;const me=oe.getBoundingClientRect().height;me&&(C(me),M.current=me,A.current=!0)},[]);o.useEffect(()=>{m.current.init(p.current,e,oe=>{w(oe),v.current=oe},oe=>V.current(oe),a)},[e,p.current,a]),o.useEffect(()=>{const oe=(Ae,Te)=>{m.current.navigate(Ae,Te),P(v.current)},me=(Ae,Te)=>{const Pe=v.current,Se=I.current;if(Pe!==0&&Pe!==Se.length-1&&(Ae.key==="ArrowDown"||Ae.key==="ArrowUp")&&Ae.preventDefault(),m.current.keydown(Ae,Te),p.current){const te=p.current.scrollTop<=v.current*M.current,Ce=p.current.scrollTop+p.current.clientHeight>=v.current*M.current+M.current;te?Ce||P(v.current):(p.current.scrollTop=v.current*M.current,k(p.current.scrollTop))}};s&&s({navigate:a?oe:m.current.navigate,keydown:a?me:m.current.keydown,move:m.current.move})},[]);const X=o.useRef(0),G=o.useRef(e);G.current!==e&&(G.current=e,X.current+=1);const U=o.useCallback(()=>{m.current.navigate(null)},[m]),ie=o.useCallback(oe=>{a&&k(oe.target.scrollTop)},[a]),j=o.useMemo(()=>Math.ceil((p.current?.clientHeight||0)/N),[N,y]),re=o.useMemo(()=>{if(!a)return{start:0,end:e.length};if(!e.length)return{start:0,end:0};const oe=Math.floor(y/N),me=oe+j;return{start:Math.max(0,oe-Vf),end:Math.min(e.length,me+Vf)}},[a,e,y,N,j]),de=o.useMemo(()=>{if(!a)return e;const{start:oe,end:me}=re;return e.slice(oe,me).map(Ae=>({...Ae}))},[a,e,re]),Q=re.start*N,ge=e.length*N;return o.useEffect(()=>{a&&k(0)},[e,a]),o.useEffect(()=>{g===null&&(h.current=!1)},[g]),g===null?null:r.jsx(Zp,{onCancel:U,...d,children:r.jsx("div",{className:"wx-233fr7 wx-list",ref:D,onClick:H,onMouseMove:m.current.move,onScroll:ie,children:e.length?a?r.jsx("div",{className:"wx-233fr7 wx-list-wrapper",style:{height:`${ge}px`},children:r.jsx("div",{className:"wx-233fr7 wx-list-content",style:{transform:`translateY(${Q}px)`},children:r.jsx(Gf,{visibleRange:re,visibleItems:de,navIndex:g,measureRefCallback:O,checkboxes:i,itemTemplate:t,value:u})})}):r.jsx(Gf,{visibleRange:re,visibleItems:de,navIndex:g,measureRefCallback:O,checkboxes:i,itemTemplate:t,value:u}):r.jsx("div",{className:"wx-233fr7 wx-no-data",children:E("No data")})})},X.current)}function em({value:e="",id:t,readonly:n=!1,focus:s=!1,select:a=!1,type:i="text",placeholder:c="",disabled:u=!1,error:d=!1,title:p="",tooltip:h,css:m="",icon:g="",clear:w=!1,onChange:v}){const y=Nv(t),[k,N]=cs(e),C=o.useRef(null),A=o.useMemo(()=>g&&m.indexOf("wx-icon-left")===-1?"wx-icon-right "+m:m,[g,m]),E=o.useMemo(()=>g&&m.indexOf("wx-icon-left")!==-1,[g,m]);o.useEffect(()=>{const V=setTimeout(()=>{s&&C.current&&C.current.focus(),a&&C.current&&C.current.select()},1);return()=>clearTimeout(V)},[s,a]);const I=o.useCallback(V=>{const P=V.target.value;N(P),v&&v({value:P,input:!0})},[v]),F=o.useCallback(V=>v&&v({value:V.target.value}),[v]);function M(V){V.stopPropagation(),N(""),v&&v({value:""})}let H=i;return i!=="password"&&i!=="number"&&(H="text"),o.useEffect(()=>{const V=F,P=C.current;return P.addEventListener("change",V),()=>{P&&P.removeEventListener("change",V)}},[F]),r.jsxs("div",{className:`wx-hQ64J4 wx-text ${A} ${d?"wx-error":""} ${u?"wx-disabled":""} ${w?"wx-clear":""}`,"data-tooltip-text":h,children:[r.jsx("input",{className:"wx-hQ64J4 wx-input",ref:C,id:y,readOnly:n,disabled:u,placeholder:c,type:H,title:p,value:k,onInput:I}),w&&!u&&k?r.jsxs(r.Fragment,{children:[r.jsx("i",{className:"wx-hQ64J4 wx-icon wxi-close",onClick:M}),E&&r.jsx("i",{className:`wx-hQ64J4 wx-icon ${g}`})]}):g?r.jsx("i",{className:`wx-hQ64J4 wx-icon ${g}`}):null]})}function tM({date:e,type:t,part:n,onShift:s}){const{calendar:a,formats:i}=o.useContext(Lr).getRaw(),c=e.getFullYear(),u=o.useMemo(()=>{switch(t){case"month":return Zi(i.monthYearFormat,a)(e);case"year":return Zi(i.yearFormat,a)(e);case"duodecade":{const{start:p,end:h}=Cv(c),m=Zi(i.yearFormat,a);return`${m(new Date(p,0,1))} - ${m(new Date(h,11,31))}`}default:return""}},[e,t,c,a,i]);function d(){s&&s({diff:0,type:t})}return r.jsxs("div",{className:"wx-8HQVQV wx-header",children:[n!=="right"?r.jsx("i",{className:"wx-8HQVQV wx-pager wxi-angle-left",onClick:()=>s&&s({diff:-1,type:t})}):r.jsx("span",{className:"wx-8HQVQV wx-spacer"}),r.jsx("span",{className:"wx-8HQVQV wx-label",onClick:d,children:u}),n!=="left"?r.jsx("i",{className:"wx-8HQVQV wx-pager wxi-angle-right",onClick:()=>s&&s({diff:1,type:t})}):r.jsx("span",{className:"wx-8HQVQV wx-spacer"})]})}function tm({onClick:e,children:t}){return r.jsx("button",{className:"wx-3s8W4d wx-button",onClick:e,children:t})}function nM({value:e,current:t,part:n="",markers:s=null,css:a="",onCancel:i,onChange:c}){const u=(o.useContext(Lr)||Au()).getRaw().calendar,d=(u.weekStart||7)%7,p=u.dayShort.slice(d).concat(u.dayShort.slice(0,d)),h=(I,F,M)=>new Date(I.getFullYear(),I.getMonth()+(F||0),I.getDate()+(M||0));let m=n!=="normal";function g(I){const F=I.getDay();return F===0||F===6}function w(){const I=h(t,0,1-t.getDate());return I.setDate(I.getDate()-(I.getDay()-(d-7))%7),I}function v(){const I=h(t,1,-t.getDate());return I.setDate(I.getDate()+(6-I.getDay()+d)%7),I}const y=o.useRef(0);function k(I,F){F.timeStamp!==y.current&&(y.current=F.timeStamp,F.stopPropagation(),c&&c(new Date(I)),i&&i())}const N=o.useMemo(()=>n=="normal"?[e?h(e).valueOf():0]:e?[e.start?h(e.start).valueOf():0,e.end?h(e.end).valueOf():0]:[0,0],[n,e]),C=o.useMemo(()=>{const I=w(),F=v(),M=t.getMonth();let H=[];for(let V=I;V<=F;V.setDate(V.getDate()+1)){const P={day:V.getDate(),in:V.getMonth()===M,date:V.valueOf()};let D="";if(D+=P.in?"":" wx-inactive",D+=N.indexOf(P.date)>-1?" wx-selected":"",m){const O=P.date==N[0],X=P.date==N[1];O&&!X?D+=" wx-left":X&&!O&&(D+=" wx-right"),P.date>N[0]&&P.date<N[1]&&(D+=" wx-inrange")}if(D+=g(V)?" wx-weekend":"",s){const O=s(V);O&&(D+=" "+O)}H.push({...P,css:D})}return H},[t,N,m,s]),A=o.useRef(null);let E=o.useRef({});return E.current.click=k,o.useEffect(()=>{so(A.current,E.current)},[]),r.jsxs("div",{className:`wx-398RBS wx-month ${a}`,children:[r.jsx("div",{className:"wx-398RBS wx-weekdays",children:p.map(I=>r.jsx("div",{className:"wx-398RBS wx-weekday",children:I},I))}),r.jsx("div",{className:"wx-398RBS wx-days",ref:A,children:C.map(I=>r.jsx("div",{className:`wx-398RBS wx-day ${I.css} ${I.in?"":"wx-out"}`,"data-id":I.date,children:I.day},I.date))})]})}function rM({value:e,current:t,part:n,onCancel:s,onChange:a,onShift:i}){const c=o.useRef(new Date),[u,d]=cs(e||c.current),[p,h]=cs(t||c.current),m=o.useContext(Lr).getRaw().calendar,g=m.monthShort||[],w=o.useMemo(()=>p.getMonth(),[p]),v=o.useCallback((N,C)=>{if(N!=null){C.stopPropagation();const A=new Date(p);A.setMonth(N),h(A),i&&i({current:A})}n==="normal"&&d(new Date(p)),s&&s()},[p,n,i,s]),y=o.useCallback(()=>{const N=new Date(Rv(u,n)||p);N.setMonth(p.getMonth()),N.setFullYear(p.getFullYear()),a&&a(N)},[u,p,n,a]),k=o.useCallback(N=>{const C=N.target.closest("[data-id]");if(C){const A=parseInt(C.getAttribute("data-id"),10);v(A,N)}},[v]);return r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"wx-34U8T8 wx-months",onClick:k,children:g.map((N,C)=>r.jsx("div",{className:"wx-34U8T8 wx-month"+(w===C?" wx-current":""),"data-id":C,children:N},C))}),r.jsx("div",{className:"wx-34U8T8 wx-buttons",children:r.jsx(tm,{onClick:y,children:m.done})})]})}const _d="wx-1XEF33",sM=({value:e,current:t,onCancel:n,onChange:s,onShift:a,part:i})=>{const c=o.useContext(Lr).getRaw().calendar,[u,d]=cs(t),[p,h]=cs(e),m=o.useMemo(()=>u.getFullYear(),[u]),g=o.useMemo(()=>{const{start:N,end:C}=Cv(m),A=[];for(let E=N;E<=C;++E)A.push(E);return A},[m]),w={click:v};function v(N,C){if(N){C.stopPropagation();const A=new Date(u);A.setFullYear(N),d(A),a&&a({current:A})}i==="normal"&&h(new Date(u)),n&&n()}function y(){const N=new Date(Rv(p,i)||u);N.setFullYear(u.getFullYear()),s&&s(N)}const k=o.useRef(null);return o.useEffect(()=>{k.current&&so(k.current,w)},[]),r.jsxs(r.Fragment,{children:[r.jsx("div",{className:_d+" wx-years",ref:k,children:g.map((N,C)=>r.jsx("div",{className:_d+` wx-year ${m==N?"wx-current":""} ${C===0?"wx-prev-decade":""} ${C===11?"wx-next-decade":""}`,"data-id":N,children:N},C))}),r.jsx("div",{className:_d+" wx-buttons",children:r.jsx(tm,{onClick:y,children:c.done})})]})},Kf={month:{component:nM,next:iM,prev:aM},year:{component:rM,next:cM,prev:oM},duodecade:{component:sM,next:uM,prev:lM}};function aM(e){return e=new Date(e),e.setMonth(e.getMonth()-1),e}function iM(e){return e=new Date(e),e.setMonth(e.getMonth()+1),e}function oM(e){return e=new Date(e),e.setFullYear(e.getFullYear()-1),e}function cM(e){return e=new Date(e),e.setFullYear(e.getFullYear()+1),e}function lM(e){return e=new Date(e),e.setFullYear(e.getFullYear()-10),e}function uM(e){return e=new Date(e),e.setFullYear(e.getFullYear()+10),e}function Rv(e,t){let n;if(t==="normal")n=e;else{const{start:s,end:a}=e;t==="left"?n=s:t=="right"?n=a:n=s&&a}return n}const dM=["clear","today"];function pM(e){if(e==="done")return-1;if(e==="clear")return null;if(e==="today")return new Date}function mM({value:e,current:t,onCurrentChange:n,part:s="normal",markers:a=null,buttons:i,css:c="",onShift:u,onChange:d}){const p=o.useContext(Lr).getGroup("calendar"),[h,m]=o.useState("month"),g=Array.isArray(i)?i:i?dM:[],w=(C,A)=>{C.preventDefault(),d&&d({value:A})},v=()=>{h==="duodecade"?m("year"):h==="year"&&m("month")},y=C=>{const{diff:A,current:E}=C;if(A===0){h==="month"?m("year"):h==="year"&&m("duodecade");return}if(A){const I=Kf[h];n(A>0?I.next(t):I.prev(t))}else E&&n(E);u&&u()},k=C=>{m("month"),d&&d({select:!0,value:C})},N=o.useMemo(()=>Kf[h].component,[h]);return r.jsx("div",{className:`wx-2Gr4AS wx-calendar ${s!=="normal"&&s!=="both"?"wx-part":""} ${c}`,children:r.jsxs("div",{className:"wx-2Gr4AS wx-wrap",children:[r.jsx(tM,{date:t,part:s,type:h,onShift:y}),r.jsxs("div",{children:[r.jsx(N,{value:e,current:t,onCurrentChange:n,part:s,markers:a,onCancel:v,onChange:k,onShift:y}),h==="month"&&g.length>0&&r.jsx("div",{className:"wx-2Gr4AS wx-buttons",children:g.map(C=>r.jsx("div",{className:"wx-2Gr4AS wx-button-item",children:r.jsx(tm,{onClick:A=>w(A,pM(C)),children:p(C)})},C))})]})]})})}function nm(e){let{words:t=null,optional:n=!1,children:s}=e,a=o.useContext(Lr);const i=o.useMemo(()=>{let c=a;return(!c||!c.extend)&&(c=pc(kv)),t!==null&&(c=c.extend(t,n)),c},[t,n,a]);return r.jsx(Lr.Provider,{value:i,children:s})}function Qf(e,t,n,s){if(!e||s){const a=t?new Date(t):new Date;a.setDate(1),n(a)}else if(e.getDate()!==1){const a=new Date(e);a.setDate(1),n(a)}}const hM=["clear","today"];function Tv({value:e,current:t,markers:n=null,buttons:s=hM,css:a="",onChange:i}){const[c,u]=cs(e),[d,p]=cs(t);o.useEffect(()=>{Qf(d,c,p,!1)},[c,d]);const h=o.useCallback(g=>{const w=g.value;w?(u(new Date(w)),Qf(d,new Date(w),p,!0)):u(null),i&&i({value:w?new Date(w):null})},[i,d]),m=o.useCallback(g=>{p(g)},[p]);return d?r.jsx(nm,{children:r.jsx(mM,{value:c,current:d,markers:n,buttons:s,css:a,onChange:h,onCurrentChange:m})}):null}function fM(e){return e||(e={}),e.width||(e.width="unset"),e}const gM=["clear","today"];function bM({value:e,id:t,disabled:n=!1,error:s=!1,placeholder:a="",format:i="",buttons:c=gM,css:u="",title:d="",tooltip:p,editable:h=!1,clear:m=!1,onChange:g,dropdown:w={}}){const{calendar:v,formats:y}=(o.useContext(Lr)||Au()).getRaw(),k=i||y?.dateFormat;let N=typeof k=="function"?k:Zi(k,v);const[C,A]=o.useState(e),[E,I]=o.useState(!1);o.useEffect(()=>{A(e)},[e]);function F(){I(!1)}function M(P){const D=P===C||P&&C&&P.valueOf()===C.valueOf()||!P&&!C;A(P),D||g&&g({value:P}),setTimeout(F,1)}const H=o.useMemo(()=>C?N(C):"",[C,N]);function V({value:P,input:D}){if(!h&&!m||D)return;let O=typeof h=="function"?h(P):P?new Date(P):null;O=isNaN(O)?C||null:O||null,M(O)}return o.useEffect(()=>{const P=F;return window.addEventListener("scroll",P),()=>window.removeEventListener("scroll",P)},[]),r.jsxs("div",{className:"wx-1lKOFG wx-datepicker",onClick:()=>I(!0),children:[r.jsx(em,{css:`wx-date-input ${u}`,title:d,tooltip:p,value:H,id:t,readonly:!h,disabled:n,error:s,placeholder:a,onInput:F,onChange:V,icon:"wxi-calendar",clear:m}),E&&!n&&r.jsx(Zp,{onCancel:F,...fM(w),children:r.jsx(Tv,{buttons:c,value:C,onChange:P=>M(P.value)})})]})}function vM({value:e="",options:t=[],textOptions:n=null,placeholder:s="",disabled:a=!1,error:i=!1,title:c="",tooltip:u,textField:d="label",clear:p=!1,css:h="",children:m,onChange:g,dropdown:w={}}){const v=o.useRef(null),y=o.useRef(null);let[k,N]=cs(e);function C(M){v.current=M.navigate,y.current=M.keydown}const A=o.useMemo(()=>k||k===0?(n||t).find(M=>M.id===k):null,[k,n,t]),E=o.useCallback(({id:M})=>{(M||M===0)&&(N(M),v.current(null),g&&g({value:M}))},[N,g]),I=o.useCallback(M=>{M.stopPropagation(),N(""),g&&g({value:""})},[N,g]),F=o.useCallback(()=>t.findIndex(M=>M.id===k),[t,k]);return r.jsxs("div",{className:`wx-2YgblL wx-richselect ${h} ${i?"wx-2YgblL wx-error":""} ${a?"wx-2YgblL wx-disabled":""} ${m?"":"wx-2YgblL wx-nowrap"}`,title:c,onClick:()=>v.current(F()),onKeyDown:M=>y.current(M,F()),tabIndex:0,"data-tooltip-text":u,children:[r.jsx("div",{className:"wx-2YgblL wx-label",children:A?m?m(A):A[d]:s?r.jsx("span",{className:"wx-2YgblL wx-placeholder",children:s}):" "}),p&&!a&&k?r.jsx("i",{className:"wx-2YgblL wx-icon wxi-close",onClick:I}):r.jsx("i",{className:"wx-2YgblL wx-icon wxi-angle-down"}),!a&&r.jsx(Nu,{items:t,onReady:C,onSelect:E,...w,children:({option:M})=>m?m(M):M[d]})]})}const wM=({options:e=[],value:t="",css:n="",children:s,onChange:a})=>{const[i,c]=o.useState(t),u=d=>{c(d),a&&a({value:d})};return o.useEffect(()=>{c(t)},[t]),r.jsx("div",{className:`wx-0hMO7P wx-segmented ${n}`,children:e.map(d=>r.jsx("button",{className:`wx-0hMO7P wx-segment ${d.css} ${d.id===i?"wx-selected":""}`,title:d.title,onClick:()=>u(d.id),"data-tooltip-text":d.tooltip,children:s?Kp(s,{option:d}):r.jsxs(r.Fragment,{children:[d.icon&&r.jsx("i",{className:`wx-0hMO7P wx-icon ${d.icon} ${d.label?"":"wx-only"}`}),d.label&&r.jsx("span",{className:"wx-0hMO7P wx-label",children:d.label})]})},d.id))})};function yM({notice:e={}}){function t(){e.remove&&e.remove()}return r.jsxs("div",{className:`wx-11sNg5 wx-notice wx-${e.type?e.type:""}`,role:"status","aria-live":"polite",children:[r.jsx("div",{className:"wx-11sNg5 wx-text",children:e.text}),r.jsx("div",{className:"wx-11sNg5 wx-button",children:r.jsx("i",{className:"wx-11sNg5 wxi-close",onClick:t})})]})}function xM({data:e=[]}){return r.jsx("div",{className:"wx-3nwoO9 wx-notices",children:e.map(t=>r.jsx(yM,{notice:t},t.id))})}function Np({title:e="",buttons:t=["cancel","ok"],header:n,children:s,footer:a,css:i="",onConfirm:c,onCancel:u}){const d=(o.useContext(Lr)||Au()).getGroup("core"),p=o.useRef(null);o.useEffect(()=>{p.current?.focus()},[]);function h(g){switch(g.code){case"Enter":{const w=g.target.tagName;if(w==="TEXTAREA"||w==="BUTTON")return;c&&c({event:g});break}case"Escape":u&&u({event:g});break}}function m(g,w){const v={event:g,button:w};w==="cancel"?u&&u(v):c&&c(v)}return r.jsx("div",{className:`wx-1FxkZa wx-modal ${i}`,ref:p,tabIndex:0,onKeyDown:h,children:r.jsxs("div",{className:"wx-1FxkZa wx-window",children:[n||(e?r.jsx("div",{className:"wx-1FxkZa wx-header",children:e}):null),r.jsx("div",{children:s}),a||t&&r.jsx("div",{className:"wx-1FxkZa wx-buttons",children:t.map(g=>r.jsx("div",{className:"wx-1FxkZa wx-button",children:r.jsx(ec,{type:`block ${g==="ok"?"primary":"secondary"}`,onClick:w=>m(w,g),children:d(g)})},g))})]})})}function SM({children:e},t){const[n,s]=o.useState(null),[a,i]=o.useState([]);return o.useImperativeHandle(t,()=>({showModal:c=>{const u={...c};return s(u),new Promise((d,p)=>{u.resolve=h=>{s(null),d(h)},u.reject=h=>{s(null),p(h)}})},showNotice:c=>{c={...c},c.id=c.id||Yp(),c.remove=()=>i(u=>u.filter(d=>d.id!==c.id)),c.expire!=-1&&setTimeout(c.remove,c.expire||5100),i(u=>[...u,c])}}),[]),r.jsxs(r.Fragment,{children:[e,n&&r.jsx(Np,{title:n.title,buttons:n.buttons,onConfirm:n.resolve,onCancel:n.reject,children:n.message}),r.jsx(xM,{data:a})]})}const CM=o.forwardRef(SM);function kM(e){let{children:t}=e,n=o.useRef();const s=o.useMemo(()=>({showNotice:a=>n.current.showNotice(a),showModal:a=>n.current.showModal(a)}),[]);return r.jsx(Mv.Provider,{value:s,children:r.jsx(CM,{ref:n,children:t})})}const MM=({value:e=!1,type:t="",icon:n="",disabled:s=!1,iconActive:a="",onClick:i,title:c="",tooltip:u,css:d="",text:p="",textActive:h="",children:m,active:g,onChange:w})=>{const[v,y]=cs(e),k=o.useMemo(()=>(v?"pressed":"")+(t?" "+t:""),[v,t]),N=o.useCallback(C=>{let A=!v;i&&i(C),C.defaultPrevented||(y(A),w&&w({value:A}))},[v,i,w]);return v&&g?r.jsx(ec,{title:c,tooltip:u,text:v&&h||p,css:d,type:k,icon:v&&a||n,onClick:N,disabled:s,children:Kp(g,{value:v})}):m?r.jsx(ec,{title:c,tooltip:u,text:v&&h||p,css:d,type:k,icon:v&&a||n,onClick:N,disabled:s,children:m}):r.jsx(ec,{title:c,tooltip:u,text:v&&h||p,css:d,type:k,icon:v&&a||n,onClick:N,disabled:s})};function AM(){return r.jsx(r.Fragment,{})}function Yf(e){const{fonts:t=!0,children:n}=e;return r.jsx(Xp.Provider,{value:"willow",children:r.jsxs(r.Fragment,{children:[n&&n&&r.jsx("div",{className:"wx-theme wx-willow-theme",children:n}),t&&r.jsxs(r.Fragment,{children:[r.jsx("link",{rel:"preconnect",href:"https://cdn.svar.dev",crossOrigin:"true"}),r.jsx(AM,{}),r.jsx("link",{rel:"stylesheet",href:"https://cdn.svar.dev/fonts/wxi/wx-icons.css"})]})]})})}Qp(tr);const rm={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 Pv=class{constructor(e){this._nextHandler=null,this._dispatch=e,this.exec=this.exec.bind(this)}async exec(e,t){return this._dispatch(e,t),this._nextHandler&&await this._nextHandler.exec(e,t),t}setNext(e){return this._nextHandler=e}};new Date().valueOf();var NM=class{constructor(e){const t={id:0,$level:0,data:[],parent:null},n=new Map;n.set(0,t),this._pool=n,e&&e.length&&this.parse(e,0)}parse(e,t){const n=this._pool;for(let a=0;a<e.length;a++){const i=e[a];i.parent=i.parent||t,i.data=null,n.set(i.id,i)}for(let a=0;a<e.length;a++){const i=e[a],c=n.get(i.parent);c&&(c.data||(c.data=[]),c.data.push(i))}const s=n.get(t);this.setLevel(s,s.$level+1,!1)}add(e,t){const n=this._pool.get(e.parent||0);e.$level=n.$level+1,this._pool.set(e.id,e),n.data?t===-1?n.data=[...n.data,e]:Xf(n,t,e):n.data=[e]}addAfter(e,t){if(!t)return this.add(e,-1);const n=this.byId(t),s=this.byId(n.parent),a=Fl(s,n.id)+1;e.parent=s.id,e.$level=s.$level+1,this.add(e,a)}remove(e){const t=this._pool.get(e);this._remove(t);const n=this._pool.get(t.parent);n.data=n.data.filter(s=>s.id!=e),this._clearBranch(n)}_remove(e){e.data&&e.data.forEach(t=>this._remove(t)),this._pool.delete(e.id)}update(e,t){let n=this._pool.get(e);const s=this._pool.get(n.parent),a=Fl(s,n.id);n={...n,...t},s&&a>=0&&(s.data[a]=n,s.data=[...s.data]),this._pool.set(n.id,n)}move(e,t,n){const s=this._pool.get(e),a=t==="child",i=this._pool.get(n),c=i.$level+(a?1:0);if(!s||!i)return;const u=this._pool.get(s.parent),d=a?i:this._pool.get(i.parent);d.data||(d.data=[]);const p=Fl(u,s.id);RM(u,p);const h=a?d.data.length:Fl(d,i.id)+(t==="after"?1:0);if(Xf(d,h,s),u.id===d.id&&p===h)return null;s.parent=d.id,s.$level!==c&&(s.$level=c,this.setLevel(s,c+1,!0)),this.update(s.id,s),this._clearBranch(u)}_clearBranch(e){e.data&&!e.data.length&&(e.open&&delete e.open,this.update(e.id,{data:null}))}toArray(){const e=[],t=this._pool.get(0).data;return t&&Iv(t,e),e}byId(e){return this._pool.get(e)}getBranch(e){return this._pool.get(e).data}forEach(e){this._pool.forEach((t,n)=>{n!==0&&e(t)})}eachChild(e,t){const n=this.byId(t);!n||!n.data||n.data.forEach((s,a)=>{e(this.byId(s.id),a),this.eachChild(e,s.id)})}setLevel(e,t,n){e.data&&(e.data=e.data.map(s=>(n&&(s={...s},this._pool.set(s.id,s)),s.$level=t,s.data&&this.setLevel(s,t+1,n),s)))}};function Iv(e,t){e.forEach(n=>{t.push(n),n.open===!0&&Iv(n.data,t)})}function RM(e,t){const n=[...e.data];n.splice(t,1),e.data=n}function Xf(e,t,n){const s=[...e.data];s.splice(t,0,n),e.data=s}function Fl(e,t){return e?.data.findIndex(n=>n.id===t)}var jv=2,TM=class{constructor(t){t&&(this._writable=t.writable,this._async=t.async),this._values={},this._state={}}setState(t,n=0){const s={};return this._wrapProperties(t,this._state,this._values,"",s,n),s}getState(){return this._values}getReactive(){return this._state}_wrapProperties(t,n,s,a,i,c){for(const u in t){const d=n[u],p=s[u],h=t[u];if(d&&(p===h&&typeof h!="object"||h instanceof Date&&p instanceof Date&&p.getTime()===h.getTime()))continue;const m=a+(a?".":"")+u;d?(d.__parse(h,m,i,c)&&(s[u]=h),c&jv?i[m]=d.__trigger:d.__trigger()):(h&&h.__reactive?n[u]=this._wrapNested(h,h,m,i):n[u]=this._wrapWritable(h),s[u]=h),i[m]=i[m]||null}}_wrapNested(t,n,s,a){const i=this._wrapWritable(t);return this._wrapProperties(t,i,n,s,a,0),i.__parse=(c,u,d,p)=>(this._wrapProperties(c,i,n,u,d,p),!1),i}_wrapWritable(t){const n=[],s=function(){for(let a=0;a<n.length;a++)n[a](t)};return{subscribe:a=>(n.push(a),this._async?setTimeout(a,1,t):a(t),()=>{const i=n.indexOf(a);i>=0&&n.splice(i,1)}),__trigger:()=>{n.length&&(this._async?setTimeout(s,1):s())},__parse:function(a){return t=a,!0}}}};function Jf(e,t){return Object.defineProperty(e,"__reactive",{value:!0,enumerable:!1,writable:!1}),e}var PM=class{constructor(t,n,s,a){typeof t=="function"?this._setter=t:this._setter=t.setState.bind(t),this._routes=n,this._parsers=s,this._prev={},this._triggers=new Map,this._sources=new Map,this._routes.forEach(i=>{i.in.forEach(c=>{const u=this._triggers.get(c)||[];u.push(i),this._triggers.set(c,u)}),i.out.forEach(c=>{const u=this._sources.get(c)||{};i.in.forEach(d=>u[d]=!0),this._sources.set(c,u)})}),this._routes.forEach(i=>{i.length=Math.max(...i.in.map(c=>Ev(c,this._sources,1)))}),this._bus=a}init(t){const n={};for(const s in t)if(this._prev[s]!==t[s]){const a=this._parsers[s];n[s]=a?a(t[s]):t[s]}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,jv);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 s=t.signals[n];s&&s()}}}setState(t,n=[]){const s=this._setter(t);return this._triggerUpdates(s,n),s}_triggerUpdates(t,n){const s=Object.keys(t),a=!n.length;n=n||[];for(let i=0;i<s.length;i++){const c=s[i],u=this._triggers.get(c);u&&u.forEach(d=>{n.indexOf(d)==-1&&n.push(d)})}a&&this._execNext(n)}_execNext(t){for(;t.length;){t.sort((s,a)=>s.length<a.length?1:-1);const n=t[t.length-1];t.splice(t.length-1),n.exec(t)}}};function Ev(e,t,n){const s=t.get(e);if(!s)return n;const a=Object.keys(s).map(i=>Ev(i,t,n+1));return Math.max(...a)}var IM=class{constructor(){this._nextHandler=null,this._handlers={},this._tag=new WeakMap,this.exec=this.exec.bind(this)}on(t,n,s){let a=this._handlers[t];a?s&&s.intercept?a.unshift(n):a.push(n):a=this._handlers[t]=[n],s&&s.tag&&this._tag.set(n,s.tag)}intercept(t,n,s){this.on(t,n,{...s,intercept:!0})}detach(t){for(const n in this._handlers){const s=this._handlers[n];for(let a=s.length-1;a>=0;a--)this._tag.get(s[a])===t&&s.splice(a,1)}}async exec(t,n){const s=this._handlers[t];if(s)for(let a=0;a<s.length;a++){const i=s[a](n);if(i===!1||i&&i.then&&await i===!1)return}return this._nextHandler&&await this._nextHandler.exec(t,n),n}setNext(t){return this._nextHandler=t}};const Vi=1024;function cc(e){return e<Vi?`${e} B`:e<Vi**2?`${(e/Vi).toFixed(1)} KB`:e<Vi**3?`${(e/Vi**2).toFixed(1)} MB`:`${(e/Vi**3).toFixed(1)} GB`}function Zf(e,t){t||(t={key:"name",order:"asc"});const n=e.filter(c=>c.type==="folder"),s=e.filter(c=>c.type!=="folder"),a=n.sort(eg(t)),i=s.sort(eg(t));return[...a,...i]}function jM(e,t){return typeof e=="string"?e.localeCompare(t,void 0,{numeric:!0}):typeof e=="object"?e.getTime()-t.getTime():(e??0)-(t??0)}function EM(e,t){return typeof e=="string"?-e.localeCompare(t,void 0,{numeric:!0}):typeof t=="object"?t.getTime()-e.getTime():(t??0)-(e??0)}function eg({key:e,order:t}){const n=t==="asc"?jM:EM;return(s,a)=>n(s[e],a[e])}function sm(e,t){const n=e==="/"?1:e.split("/").length;return n>=t.length?null:t[n].id}function FM(e){return e.length>1?e[e.length-2].id:null}let DM=class extends NM{constructor(t){const n={id:"/",name:"My files",open:!0,$level:1,parent:0,ext:"",type:"folder"};super([n]),this.parse(t,"/")}parse(t,n,s){!t||!t.length||(t.forEach(a=>this.parseId(a,s?n:void 0)),super.parse(t,n))}parseId(t,n){if(t.parent===0)return;const s=t.id,a=s.lastIndexOf("/");if(t.parent=n??(a===0?"/":s.slice(0,a)),t.name=s.slice(a+1),t.type=t.type||"file",t.type!=="folder"){const i=t.name.lastIndexOf("."),c=i!==-1?t.name.slice(i+1):"";t.ext=c!=="new"?c?.toLocaleLowerCase():""}}getParents(t){const n=[];let s=this.byId(t);if(!s)return n;for(;s.id!==0;)n.push(s),s=this.byId(s.parent);return n.reverse()}findFiles(t,n="/"){const s=[],a=t.toLocaleLowerCase();return this.eachChild(i=>{i.name.toLowerCase().indexOf(a)!==-1&&s.push(i)},n),s}add(t,n){const s=this.byId(t.parent||"/"),a=t.data?[...t.data]:null;t.data=null,super.add(t,n??s.data?s.data.length:0),a&&a.forEach(i=>this.add(i))}renameFiles(t,n,s){const a=this.byId(t),i=this.normalizeFile(a,n),c=[];return i.data?.forEach(u=>c.push(this.renameFiles(u.id,i.id,s))),c.length&&(i.data=c),s[t]=i.id,i}copyFiles(t,n,s){const a={};return t.forEach(i=>{const c=this.renameFiles(i,n,a);this.add(c),s&&this.remove(i),a[i]=c.id}),a}moveFiles(t,n){if(this.byId(t[0]).parent!==n)return this.copyFiles(t,n,!0)}serialize(t="/"){const n=[],s=this.byId(t);return s?(s.data?.forEach(a=>{const{id:i,date:c,type:u,size:d,lazy:p}=a,h={id:i,date:c,type:u??"file"};p&&(h.lazy=p),d&&(h.size=d),n.push(h);const m=this.serialize(i);m.length&&n.push(...m)}),n):null}normalizeFile(t,n){const s=t.name,a=s.lastIndexOf("."),i=a!==-1?s.slice(a+1):"",c=i?`.${i}`:"";let u=a!==-1?s.slice(0,a):s,d=n+(n==="/"?"":"/")+u;for(;this.byId(d+c);){const p=".new";d+=p,u+=p}return{...t,id:d+c,name:u+c,parent:n,ext:i.toLocaleLowerCase()}}},LM=class extends TM{in;_router;constructor(t){super({writable:t,async:!1});const n=[];for(let i=0;i<2;i++)n.push({in:["data",`panels.${i}.path`],out:[`panels.${i}._crumbs`],exec:c=>{const{data:u,panels:d}=this.getState(),p=[];p[i]={_crumbs:u.getParents(d[i].path)},this.setState({panels:p},c)}}),n.push({in:["data",`panels.${i}.path`,`panels.${i}._sorts`,"search"],out:[`panels.${i}._files`],exec:c=>{const{data:u,panels:d,search:p}=this.getState();let h;p?h=u.findFiles(p,d[i].path):h=u.byId(d[i].path)?.data||[];const{path:m,_sorts:g}=d[i];h=Zf(h,g[m]);const w=[];w[i]={_files:h},this.setState({panels:w},c)}}),n.push({in:["data",`panels.${i}.selected`,`panels.${i}._sorts`],out:[`panels.${i}._selected`],exec:c=>{const{data:u,panels:d}=this.getState(),p=[];d[i].selected.forEach(v=>{const y=u.byId(v);y&&p.push(y)});const{path:h,_sorts:m}=d[i],g=Zf(p,m[h]),w=[];w[i]={_selected:g},this.setState({panels:w},c)}});this._router=new PM(super.setState.bind(this),n,{data:i=>new DM(i)});const s=this.in=new IM;s.on("select-file",({id:i,toggle:c,range:u,panel:d,type:p})=>{const{panels:h,activePanel:m}=this.getState();typeof d>"u"&&(d=m),i||(c=u=!1);let g=[...h[d].selected];if(c){const v=g.indexOf(i);v===-1?g.push(i):g.splice(v,1)}else if(u&&h[d]._lastSelected){const v=h[d]._files;let y=v.findIndex(C=>C.id==h[d]._lastSelected),k=v.findIndex(C=>C.id==i);k<y&&([y,k]=[k,y]);const N=v.slice(y,k+1).map(C=>C.id);g=[...new Set([...g,...N])]}else g=i?[i]:[];const w=[];w[d]={selected:g,_lastSelected:i,_selectNavigation:p==="navigation"},this.setState({panels:w})}),s.on("set-path",({id:i,panel:c,selected:u})=>{const{data:d,activePanel:p}=this.getState(),h=d.byId(i);if(h){const m=[];typeof c>"u"&&(c=p),m[c]={path:i},this.setState({panels:m}),s.exec("select-file",{panel:c}),u&&u.forEach(g=>s.exec("select-file",{id:g,panel:c,toggle:!0})),h.lazy&&s.exec("request-data",{id:i})}}),s.on("provide-data",({id:i,data:c})=>{const{mode:u,data:d}=this.getState(),p=d.byId(i);p&&(p.lazy||(p.data=[]),p.lazy=!1,d.parse(c,i,u==="search"),this.setState({data:d}))}),s.on("open-tree-folder",({id:i,mode:c})=>{const{data:u}=this.getState();u.update(i,{open:c}),this.setState({data:u})}),s.on("show-preview",({mode:i})=>{this.setState({preview:i})}),s.on("rename-file",i=>{const{id:c,name:u}=i,{data:d,panels:p}=this.getState(),h=d.byId(c);if(h.name!==u){h.name=u;const m=d.normalizeFile(h,h.parent);i.newId=m.id,m.data=null,d.add(m);let g={[c]:m.id};h.data?.forEach(v=>g={...d.moveFiles([v.id],m.id),...g});const w=p.map(v=>({selected:v.selected,_crumbs:v._crumbs,_lastSelected:v._lastSelected,_sorts:v._sorts}));d.remove(c),this._updatePanels(w,g),this.setState({data:d,panels:w})}}),s.on("create-file",i=>{const{file:c,parent:u}=i,{data:d}=this.getState(),p=d.normalizeFile(c,u);p.type=c.type||"file",i.newId=p.id,d.add(p),this.setState({data:d}),s.exec("select-file",{id:p.id})}),s.on("delete-files",({ids:i})=>{const{data:c,panels:u}=this.getState(),d=u.map(p=>({selected:p.selected,_crumbs:p._crumbs,_lastSelected:p._lastSelected,_sorts:p._sorts}));i.forEach(p=>c.remove(p)),this._updatePanels(d,{}),this.setState({data:c,panels:d})}),s.on("copy-files",i=>{const{ids:c,target:u}=i;if(this._isPlacedIntoSelf(c,u)){console.error("You cannot copy a folder into itself"),i.skipProvider=!0;return}const{data:d,panels:p,activePanel:h}=this.getState(),m=d.copyFiles(c,u);i.newIds=c.map(g=>m[g]),this.setState({data:d}),p[h].path==u&&(s.exec("select-file",{}),c.forEach(g=>{s.exec("select-file",{id:m[g],toggle:!0})}))}),s.on("move-files",i=>{const{ids:c,target:u}=i;if(this._isPlacedIntoSelf(c,u)){console.error("You cannot move a folder into itself"),i.skipProvider=!0;return}const{data:d,panels:p,activePanel:h}=this.getState(),m=d.moveFiles(c,u);if(m){i.newIds=c.map(w=>m[w]);const g=p.map(w=>({selected:w.selected,_crumbs:w._crumbs,_lastSelected:w._lastSelected,_sorts:w._sorts}));this._updatePanels(g,m,!0),this.setState({data:d,panels:g}),p[h].path==u&&(s.exec("select-file",{}),c.forEach(w=>{s.exec("select-file",{id:m[w],toggle:!0})}))}});let a=null;s.on("filter-files",({text:i})=>{if(!i){a&&this.setState({...a});return}s.exec("select-file",{});const{panels:c,mode:u}=this.getState();a||(a={panels:c,mode:u,search:""}),this.setState({mode:"search",search:i})}),s.on("set-mode",({mode:i})=>{const{activePanel:c}=this.getState(),u=[];u[c]={_selectNavigation:!1};const d={mode:i,search:"",panels:u};a=null,this.setState(d)}),s.on("set-active-panel",({panel:i})=>{this.setState({activePanel:i})}),s.on("sort-files",({key:i,order:c,panel:u,path:d})=>{const{activePanel:p,panels:h}=this.getState();u=u??p,d=d??h[u].path;const m=[];m[u]={_sorts:{...h[u]._sorts,[d]:{key:i,order:c}}},this.setState({panels:m})}),this.initOnce()}initOnce(){const t=[];for(let s=0;s<2;s++)t[s]=Jf({_crumbs:[],_files:[],_selected:[],_sorts:{},path:"/",selected:[],...t[s]});const n={panels:Jf(t),data:[],search:""};this._router.init(n)}init(t){const n={...t};this._router.init(n)}setState(t,n){return this._router.setState(t,n)}getFile(t){const{data:n}=this.getState();return n.byId(t)||null}serialize(t){const{data:n}=this.getState();return n.serialize(t)}_updatePanels(t,n,s){const{data:a}=this.getState();t.forEach(i=>{const c=[];i.selected.forEach(p=>{a.byId(p)?c.push(p):!s&&n[p]&&c.push(n[p])}),i.selected=c,a.byId(i._lastSelected)||(i._lastSelected=s?null:n[i._lastSelected]||null);const u={};Object.keys(i._sorts).forEach(p=>{a.byId(p)?u[p]=i._sorts[p]:n[p]&&!s&&(u[n[p]]=i._sorts[p])}),i._sorts=u;const d=i._crumbs[i._crumbs.length-1];d?.id!=="/"&&(n[d.id]?i.path=n[d.id]:a.byId(d.id)||(i.path="/"))})}_isPlacedIntoSelf(t,n){return t.some(s=>s===n||this.getState().data.getParents(n).some(a=>a.id===s))}};function _M(e){switch(e){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[e==="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(t=>t!==null)}}function $M(e,t="data-id"){let n=e;for(!n.tagName&&e.target&&(n=e.target);n;){if(n.getAttribute&&n.getAttribute(t))return n;n=n.parentNode}return null}function OM(e,t="data-id"){const n=$M(e,t);return n?n.getAttribute(t):null}new Date().valueOf();function BM(e,t){const{api:n}=t;function s(i,c){const u=t.getPanel(),d=u.selected,p=c.ctrlKey||c.metaKey,h=c.shiftKey;let m;const g=d?.[0]?n.getFile(d[0]):null;d?.length?d.length>1?m=t.menuOptions("multiselect"):m=t.menuOptions(g.type,g):m=t.menuOptions("body");const w=`${p?"ctrl+":""}${h?"shift+":""}${i}`,v=m?m.find(k=>k.hotkey?.toLowerCase()===w):!1,y=t.performAction;if(v)switch(w){case"ctrl+c":y("copy");break;case"ctrl+x":y("move");break;case"ctrl+v":y("paste",g);break;case"delete":y("delete");break;case"ctrl+r":c.preventDefault(),y("rename",g);break;case"ctrl+d":c.preventDefault(),y("download",g);break;default:v.handler?.({context:g})}switch(i){case"enter":{if(p||h)break;const{_crumbs:k,_selectNavigation:N}=u;if(N){const C=FM(k);if(C){const A=sm(C,k);n.exec("set-path",{id:C,selected:[A]})}}else if(d.length===1){const C=n.getFile(d[0]);C&&n.exec(C.type==="folder"?"set-path":"open-file",{id:C.id})}break}case"arrowup":case"arrowleft":{const{_files:k,_selected:N,path:C,_selectNavigation:A}=u;let E;if(N.length){const I=N.at(0).id,F=k.findIndex(M=>M.id===I);if(F!==-1){const M=F-1;k[M]?E=k[M].id:C!=="/"&&!(p||h)&&n.exec("select-file",{type:"navigation"})}}else{if(A)break;if(C!=="/"){n.exec("select-file",{type:"navigation"});break}E=k.at(0)?.id}E&&n.exec("select-file",{id:E,toggle:p,range:h});break}case"arrowdown":case"arrowright":{const{_files:k,_selected:N,path:C,_selectNavigation:A}=u;let E;if(N.length){const I=N.at(-1).id,F=k.findIndex(M=>M.id===I);if(F!==-1){const M=F+1;k[M]&&(E=k[M].id)}}else{if(C!=="/"&&!A){n.exec("select-file",{type:"navigation"});break}E=k.at(0)?.id}E&&n.exec("select-file",{id:E,toggle:p,range:h});break}}}function a(i){const c=i.code.replace("Key","").toLowerCase();s(c,i),c=="tab"&&setTimeout(()=>{const u=document.activeElement;u.className.indexOf("table")!=-1&&n.exec("set-active-panel",{panel:+OM(u,"data-panel")})})}return e.addEventListener("keydown",a),{destroy:()=>{e.removeEventListener("keydown",a)}}}function HM(e,t="data-id"){let n=e;for(!n.tagName&&e.target&&(n=e.target);n;){if(n.getAttribute&&n.getAttribute(t))return n;n=n.parentNode}return null}function WM(e,t="data-id"){const n=e.getAttribute(t);return n?zM(n):null}function zM(e){if(e.startsWith(":"))return e.substring(1);const t=e*1;return isNaN(t)?e:t}function qM(){return{detect:()=>!0,addEvent:function(e,t,n){return e.addEventListener(t,n),()=>e.removeEventListener(t,n)},addGlobalEvent:function(e,t){return document.addEventListener(e,t),()=>document.removeEventListener(e,t)},getTopNode:function(){return window.document.body}}}var UM=qM();new Date().valueOf();function Fv(e){const[t,n]=o.useState(e),s=o.useRef(e);return o.useEffect(()=>{if(s.current!==e){if(Array.isArray(s.current)&&Array.isArray(e)&&s.current.length===0&&e.length===0)return;s.current=e,n(e)}},[e]),[t,n]}function VM(e,t,n){const[s,a]=o.useState(()=>t);return e||console.warn(`Writable ${n} is not defined`),o.useEffect(()=>e?e.subscribe(c=>{a(()=>c)}):void 0,[e]),s}function dt(e,t){const n=e.getState(),s=e.getReactiveState();return VM(s[t],n[t],t)}function GM(e,t){const n=o.useRef(t);n.current=t;const[s,a]=o.useState(1);return o.useEffect(()=>e.subscribe(c=>{n.current=c,a(u=>u+1)}),[e]),[n.current,s]}function xr(e,t){const n=e.getState(),s=e.getReactiveState();return GM(s[t],n[t])}function Dv(e){const t={};return e.split(";").forEach(n=>{const[s,a]=n.split(":");if(a){let i=s.trim();i.indexOf("-")&&(i=i.replace(/-([a-z])/g,(c,u)=>u.toUpperCase())),t[i]=a.trim()}}),t}function Lv(e){let t=e,n=[];return{subscribe:u=>{n.push(u),u(t)},unsubscribe:u=>{n=n.filter(d=>d!==u)},set:u=>{t=u,n.forEach(d=>d(t))},update:u=>{t=u(t),n.forEach(d=>d(t))}}}function tg(e,t,n){function s(a){const i=HM(a);if(!i)return;const c=WM(i);if(typeof t=="function")return t(c,a);let u,d=a.target;for(;d!=i;){if(u=d.dataset?d.dataset.action:null,u&&t[u]){t[u](c,a);return}d=d.parentNode}t[n]&&t[n](c,a)}return UM.addEvent(e,n,s)}function KM(e,t){const n=[tg(e,t,"click")];return t.dblclick&&n.push(tg(e,t.dblclick,"dblclick")),()=>{n.forEach(s=>s())}}function _v(e,t){return e.map((n,s)=>{const a=t(n,s);return n.data&&n.data.length&&(a.data=_v(n.data,t)),a}).filter(Boolean)}function $v(e,t){const n=[];return e.forEach(s=>{if(s.data){const a=$v(s.data,t);a.length&&n.push({...s,data:a})}else t(s)&&n.push(s)}),n}function QM(e){return _v(e,(t,n)=>{const s={...t,id:t.id||Yp()};return s.type&&(s.comp=s.type),s.comp==="separator"&&e[n-1]?.comp==="separator"?null:s})}const Ov={};function YM(e){return Ov[e]||e}function XM(e,t){Ov[e]=t}function JM({onClick:e,onShow:t,option:n}){const s=o.useRef(null),a=o.useCallback(()=>{t(n.data?n.id:!1,s.current)},[t,n]),i=o.useCallback(u=>{if(n.data){u.stopPropagation(),t(n.id,s.current);return}e(u)},[e,t,n]),c=o.useMemo(()=>n&&n.comp?YM(n.comp):null,[n]);return r.jsxs("div",{ref:s,className:`wx-cDCz9rZQ wx-option ${n.css||""} ${n.disabled?"wx-disabled":""}`,"data-id":mn(n.id),onMouseEnter:a,onClick:i,children:[n.icon?r.jsx("i",{className:`wx-cDCz9rZQ wx-icon ${n.icon}`}):null,n.comp?c?r.jsx(c,{item:n,option:n}):null:r.jsxs("span",{className:"wx-cDCz9rZQ wx-value",children:[" ",n.text," "]}),n.subtext?r.jsx("span",{className:"wx-cDCz9rZQ wx-subtext",children:n.subtext}):null,n.data?r.jsx("i",{className:"wx-cDCz9rZQ wx-sub-icon wxi-angle-right"}):null]})}function am({options:e,left:t=0,top:n=0,at:s="bottom",parent:a=null,mount:i=null,context:c=null,css:u="",onClick:d,onCancel:p}){const[h,m]=o.useState(-1e4),[g,w]=o.useState(-1e4),[v,y]=o.useState(20),[k,N]=o.useState(),C=o.useRef(null),[A,E]=o.useState(!1),[I,F]=o.useState(null),M=o.useCallback(()=>{const G=xv(C.current,a,s,t,n);G&&(m(G.x),w(G.y),N(G.width));let U=G?.z??20;const ie=a?Bk(a):[];let j=0;for(const re of ie){const de=parseInt(getComputedStyle(re).zIndex,10);de>j&&(j=de)}j>=U&&(U=j+1),y(U)},[a,s,t,n]);o.useEffect(()=>{i&&i(M)},[]);const H=o.useCallback(()=>{E(!1)},[]),V=o.useCallback((G,U)=>{E(G),F(U)},[]),P=o.useMemo(()=>QM(e),[e]);o.useEffect(()=>{M()},[a,M]);const D=o.useRef(d),O=o.useRef(p),X=o.useRef(a);return o.useEffect(()=>{D.current=d},[d]),o.useEffect(()=>{O.current=p},[p]),o.useEffect(()=>{X.current=a},[a]),o.useEffect(()=>{if(!C.current)return;function G(U){O.current?O.current(U):D.current&&D.current({action:null,option:null})}return ls(C.current,{callback:G,modal:!0,parent:()=>X.current}).destroy},[]),r.jsx("div",{ref:C,"data-wx-menu":"true",className:`wx-XMmAGqVx wx-menu ${u}`,style:{position:"absolute",top:g+"px",left:h+"px",width:k,zIndex:v},onMouseLeave:H,children:P.map(G=>r.jsxs(o.Fragment,{children:[G.comp==="separator"?r.jsx("div",{className:"wx-XMmAGqVx wx-separator"}):r.jsx(JM,{option:G,onShow:V,onClick:U=>{if(!G.data&&!U.defaultPrevented){const ie={context:c,action:G,option:G,event:U};G.handler&&G.handler(ie),d&&d(ie),U.stopPropagation()}}}),G.data&&A===G.id?r.jsx(am,{css:u,options:G.data,at:"right-overlap",parent:I,context:c,onClick:d,onCancel:p}):null]},G.id))})}const Bv=o.forwardRef(function(e,t){const{options:n,at:s="bottom",resolver:a=null,dataKey:i="contextId",filter:c=null,css:u="",children:d,onClick:p}=e,[h,m]=o.useState(null),[g,w]=o.useState(null),[v,y]=o.useState(0),[k,N]=o.useState(0),C=o.useRef(null),A=o.useMemo(()=>`data-${i.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}`,[i]),E=o.useMemo(()=>h!==null&&c?$v(n,H=>c(H,h)):n,[h,c,n]);function I(H){w(null),p&&p(H)}function F(H){if(C.current===H){C.current=null;return}w(null),p&&p({action:null,option:null})}const M=o.useCallback((H,V)=>{if(!H){w(null);return}if(H.defaultPrevented)return;const P=H.target;if(P&&P.dataset&&P.dataset.menuIgnore)return;if(g&&g===P){w(null),H.preventDefault();return}y(H.clientX+1),N(H.clientY+1);let D=typeof V<"u"?V:oc(P,A);a&&(D=a(D,H),!D)||(m(D),w(P),C.current=H.nativeEvent||H,H.preventDefault())},[g,A,a]);return o.useImperativeHandle(t,()=>({show:M}),[M]),r.jsxs(r.Fragment,{children:[d?r.jsx("span",{onClick:M,"data-menu-ignore":"true",children:typeof d=="function"?d():d}):null,g?r.jsx(Jp,{children:r.jsx(am,{css:u,at:s,top:k,left:v,parent:g,context:h,onClick:I,onCancel:F,options:E},g)}):null]})}),ZM=o.forwardRef(function(e,t){const{options:n,at:s="bottom",css:a="",children:i,onClick:c}=e,[u,d]=o.useState(null),p=o.useRef(null);function h(v){d(null),c&&c(v)}function m(v){if(p.current===v){p.current=null;return}d(null),c&&c({action:null,option:null})}const g=o.useCallback(v=>{d(v.target),p.current=v.nativeEvent||v,v.preventDefault()},[]);o.useImperativeHandle(t,()=>({show:g}),[g]);function w(v){let y=v.target;for(;!y.dataset.menuIgnore;)d(y),y=y.parentNode}return r.jsxs(r.Fragment,{children:[r.jsx("span",{onClick:w,"data-menu-ignore":"true",children:i}),u?r.jsx(Jp,{children:r.jsx(am,{css:a,at:s,parent:u,options:n,onClick:h,onCancel:m})}):null]})}),eA=o.forwardRef(function(e,t){const{options:n,at:s="bottom",resolver:a=null,dataKey:i="contextId",filter:c=null,css:u="",children:d,onClick:p}=e,h=o.useRef(null),m=o.useCallback((g,w)=>{h.current.show(g,w)},[]);return o.useImperativeHandle(t,()=>({show:m}),[m]),r.jsxs(r.Fragment,{children:[d?r.jsx("span",{onContextMenu:m,"data-menu-ignore":"true",children:d}):null,r.jsx(Bv,{css:u,at:s,options:n,resolver:a,dataKey:i,filter:c,ref:h,onClick:p})]})}),tA={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 nA=class{constructor(t,n,s,a,i){this.setFiles=t,this.setReady=n,this.setSignal=s,this.setDrag=a,i&&i.length&&this.setFiles(i)}open(t){this.setSignal(["click",t||{}])}getState(){let t="server";const n=this.files;for(let s=0;s<n.length;s++){if(n[s].status==="client")return"client";n[s].status==="error"&&(t="error")}return t}droparea(t,n){n=n||{};const s=()=>{n.dragEnter&&n.dragEnter(),this.setDrag(!0)},a=()=>{n.dragLeave&&n.dragLeave(),this.setDrag(!1)},i=u=>{u.preventDefault()},c=u=>{u.preventDefault(),this.setDrag(!1),this.setSignal(["drop",n,u]),n.dragLeave&&n.dragLeave(),n.drop&&n.drop()};return t.addEventListener("dragenter",s),t.addEventListener("dragleave",a),t.addEventListener("dragover",i,!0),t.addEventListener("drop",c,!0),()=>{t.removeEventListener("dragenter",s),t.removeEventListener("dragleave",a),t.removeEventListener("dragover",i,!0),t.removeEventListener("drop",c,!0)}}updateFile(t,n){const s=this.files.findIndex(i=>i.id===t);if(s===-1)return;const a=[...this.files];return a[s]={...a[s],...n},this.files=a,this.setFiles(this.files),this.files[s]}deleteFile(t){this.files=this.files.filter(n=>n.id!==t),this.setFiles(this.files)}addFile(t,n){n?this.files=[...this.files,t]:this.files=[t],this.setFiles(this.files)}deleteAll(){this.files=[],this.setFiles(this.files)}};function Hv(e){const[t,n]=o.useState([]),[s,a]=o.useState(Promise.resolve(null)),[i,c]=o.useState(null),[u,d]=o.useState(!1),p=o.useRef();return p.current||(p.current=new nA(n,a,c,d,e)),p.current.files=t,p.current.ready=s,p.current.signal=i,p.current.drag=u,p.current}function rA(e,t){{if(e){const n=e.getGroup(t);if(n)return n}return pc(tA).getGroup(t)}}const sA=()=>Math.random().toString(36).substr(2,9),aA=({data:e,accept:t="",multiple:n=!0,folder:s=!1,uploadURL:a="",apiOnly:i=!1,disabled:c=!1,children:u,onChange:d,onUpload:p})=>{const h=o.useRef(null),m=o.useRef(null),[g,w]=o.useState({}),v=Hv(),y=e||v,k=o.useContext(fn.i18n),N=rA(k,"uploader");o.useEffect(()=>{h.current&&s&&(h.current.webkitdirectory=!0)},[s]),o.useEffect(()=>{if(!i&&m.current&&!c)return y.droparea(m.current)},[i,c,m]);const C=P=>{const D=new FormData;return D.append("upload",P.file),fetch(a,{method:"POST",body:D}).then(O=>O.json()).then(O=>({id:P.id,...O}),()=>({id:P.id,status:"error"})).catch(O=>(console.log(O),{id:P.id,status:"error"}))},A=(P,D)=>{const O=y.updateFile(P,D),X={...O,status:y.getState()};O&&O.uploaded&&O.uploaded(X),p&&p(X),O.temp&&y.deleteFile(O.id)},E=P=>{if(!P)return;const D=typeof a=="function"?a(P):C(P);y.setReady(D.then(O=>{O.status=O.status||"server",A(P.id,O)}).catch(O=>{A(P.id,{status:"error",error:O})}))},I=(P,D)=>{const O={...D||g,id:sA(),status:"client",name:P.name,file:P};O.selected&&O.selected(O),d&&d(O),y.addFile(O,n),E(O),h.current&&(h.current.value="")},F=(P,D,O)=>{P.isFile?P.file(X=>{I(X,O)}):P.isDirectory&&P.createReader().readEntries(X=>{X.forEach(G=>{F(G,D+G.name+"/",O)})})},M=P=>{Array.from(P.target.files).forEach(D=>I(D))},H=(P,D)=>{Array.from(P.dataTransfer.items).forEach(O=>{const X=O.webkitGetAsEntry();X&&F(X,"",D)})},V=()=>{h.current&&h.current.click()};return o.useEffect(()=>{if(y.signal){const[P,D,O]=y.signal;w(D),P==="click"?V():P==="drop"&&H(O,D),y.setSignal(null)}},[y.signal]),i?r.jsxs(r.Fragment,{children:[r.jsx("input",{type:"file",className:"wx-at1A8tb8 wx-input",ref:h,onChange:M,accept:t,multiple:n,disabled:c}),u]}):r.jsxs("div",{className:`wx-at1A8tb8 wx-label ${y.drag?"wx-active":""} ${c?"wx-disabled":""}`,ref:m,children:[r.jsx("input",{type:"file",className:"wx-at1A8tb8 wx-input",ref:h,onChange:M,accept:t,multiple:n,disabled:c}),u||r.jsx("div",{className:"wx-at1A8tb8 wx-dropzone",children:r.jsxs("span",{children:[N("Drop files here or")," ",r.jsx("span",{className:"wx-at1A8tb8 wx-action",onClick:V,children:N("select files")})]})})]})};new Date().valueOf();function iA(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(const n in t){const s=e[n],a=t[n];if(!Ru(s,a))return!1}return!0}function Ru(e,t){if(typeof e=="number"||typeof e=="string"||typeof e=="boolean"||e===null)return e===t;if(typeof e!=typeof t||(e===null||t===null)&&e!==t||e instanceof Date&&t instanceof Date&&e.getTime()!==t.getTime())return!1;if(typeof e=="object")if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let n=e.length-1;n>=0;n--)if(!Ru(e[n],t[n]))return!1;return!0}else return iA(e,t);return e===t}function Rp(e){if(typeof e!="object"||e===null)return e;if(e instanceof Date)return new Date(e);if(e instanceof Array)return e.map(Rp);const t={};for(const n in e)t[n]=Rp(e[n]);return t}var Wv=2,oA=class{constructor(e){e&&(this._writable=e.writable,this._async=e.async),this._values={},this._state={}}setState(e,t=0){const n={};return this._wrapProperties(e,this._state,this._values,"",n,t),n}getState(){return this._values}getReactive(){return this._state}_wrapProperties(e,t,n,s,a,i){for(const c in e){const u=t[c],d=n[c],p=e[c];if(u&&(d===p&&typeof p!="object"||p instanceof Date&&d instanceof Date&&d.getTime()===p.getTime()))continue;const h=s+(s?".":"")+c;u?(u.__parse(p,h,a,i)&&(n[c]=p),i&Wv?a[h]=u.__trigger:u.__trigger()):(p&&p.__reactive?t[c]=this._wrapNested(p,p,h,a):t[c]=this._wrapWritable(p),n[c]=p),a[h]=a[h]||null}}_wrapNested(e,t,n,s){const a=this._wrapWritable(e);return this._wrapProperties(e,a,t,n,s,0),a.__parse=(i,c,u,d)=>(this._wrapProperties(i,a,t,c,u,d),!1),a}_wrapWritable(e){const t=[],n=function(){for(let s=0;s<t.length;s++)t[s](e)};return{subscribe:s=>(t.push(s),this._async?setTimeout(s,1,e):s(e),()=>{const a=t.indexOf(s);a>=0&&t.splice(a,1)}),__trigger:()=>{t.length&&(this._async?setTimeout(n,1):n())},__parse:function(s){return e=s,!0}}}},cA=class{constructor(e,t,n,s){typeof e=="function"?this._setter=e:this._setter=e.setState.bind(e),this._routes=t,this._parsers=n,this._prev={},this._triggers=new Map,this._sources=new Map,this._routes.forEach(a=>{a.in.forEach(i=>{const c=this._triggers.get(i)||[];c.push(a),this._triggers.set(i,c)}),a.out.forEach(i=>{const c=this._sources.get(i)||{};a.in.forEach(u=>c[u]=!0),this._sources.set(i,c)})}),this._routes.forEach(a=>{a.length=Math.max(...a.in.map(i=>zv(i,this._sources,1)))}),this._bus=s}init(e){const t={};for(const n in e)if(this._prev[n]!==e[n]){const s=this._parsers[n];t[n]=s?s(e[n]):e[n]}this._prev=this._prev?{...this._prev,...e}:{...e},this.setState(t),this._bus&&this._bus.exec("init-state",t)}setStateAsync(e){const t=this._setter(e,Wv);return this._async?Object.assign(this._async.signals,t):this._async={signals:t,timer:setTimeout(this._applyState.bind(this),1)},t}_applyState(){const e=this._async;if(e){this._async=null,this._triggerUpdates(e.signals,[]);for(const t in e.signals){const n=e.signals[t];n&&n()}}}setState(e,t=[]){const n=this._setter(e);return this._triggerUpdates(n,t),n}_triggerUpdates(e,t){const n=Object.keys(e),s=!t.length;t=t||[];for(let a=0;a<n.length;a++){const i=n[a],c=this._triggers.get(i);c&&c.forEach(u=>{t.indexOf(u)==-1&&t.push(u)})}s&&this._execNext(t)}_execNext(e){for(;e.length;){e.sort((n,s)=>n.length<s.length?1:-1);const t=e[e.length-1];e.splice(e.length-1),t.exec(e)}}};function zv(e,t,n){const s=t.get(e);if(!s)return n;const a=Object.keys(s).map(i=>zv(i,t,n+1));return Math.max(...a)}var lA=class{constructor(){this._nextHandler=null,this._handlers={},this._tag=new WeakMap,this.exec=this.exec.bind(this)}on(e,t,n){let s=this._handlers[e];s?n&&n.intercept?s.unshift(t):s.push(t):s=this._handlers[e]=[t],n&&n.tag&&this._tag.set(t,n.tag)}intercept(e,t,n){this.on(e,t,{...n,intercept:!0})}detach(e){for(const t in this._handlers){const n=this._handlers[t];for(let s=n.length-1;s>=0;s--)this._tag.get(n[s])===e&&n.splice(s,1)}}async exec(e,t){const n=this._handlers[e];if(n)for(let s=0;s<n.length;s++){const a=n[s](t);if(a===!1||a&&a.then&&await a===!1)return}return this._nextHandler&&await this._nextHandler.exec(e,t),t}setNext(e){return this._nextHandler=e}};function uA(e){return t=>t[e]}function dA(e){return(t,n)=>t[e]=n}function ra(e,t){return(t.getter||uA(t.id))(e)}function $d(e,t,n){return(t.setter||dA(t.id))(e,n)}function pA(e,t){const n=document.createElement("a");n.href=URL.createObjectURL(e),n.download=t,document.body.appendChild(n),n.click(),document.body.removeChild(n)}function Js(e,t){let n=ra(e,t)??"";return t.template?n=t.template(n,e,t):t.optionsMap&&(Array.isArray(n)?n=n.map(s=>t.optionsMap.get(s)).join(", "):n=t.optionsMap.get(n)),typeof n>"u"?"":n+""}function mA(e,t){const n=/\n|"|;|,/;let s="";const a=t.rows||`
166
- `,i=t.cols||" ",c=e._columns,u=e.flatData;t.header!==!1&&c[0].header&&(s=ng("header",c,s,i,a));for(let d=0;d<u.length;d++){const p=[];for(let h=0;h<c.length;h++){let m=Js(u[d],c[h]);n.test(m)&&(m='"'+m.replace(/"/g,'""')+'"'),p.push(m)}s+=(s?a:"")+p.join(i)}return t.footer!==!1&&c[0].footer&&(s=ng("footer",c,s,i,a)),s}function ng(e,t,n,s,a){const i=/\n|"|;|,/;for(let c=0;c<t[0][e].length;c++){const u=[];for(let d=0;d<t.length;d++){let p=(t[d][e][c].text||"")+"";i.test(p)&&(p='"'+p.replace(/"/g,'""')+'"'),u.push(p)}n+=(n?a:"")+u.join(s)}return n}const hA="portrait",fA=100,gA="a4",bA={a3:{width:11.7,height:16.5},a4:{width:8.27,height:11.7},letter:{width:8.5,height:11}};function vA(e,t){const n=[];let s=[],a=0;const i=e.filter(u=>!u.hidden),c=wA(t);return i.forEach((u,d)=>{a+u.width<=c?(a+=u.width,s.push(u)):(s.length&&n.push(s),s=[u],a=u.width),d===i.length-1&&s.length&&n.push(s)}),n}function rg(e,t,n){const s=[];return e.forEach((a,i)=>{const c=a[t];for(let u=0;u<n.length;u++){s[u]||(s[u]=[]);const d={...c[u]};if(s[u][i]!==null){if(!i&&!d.rowspan&&!d.colspan){let p=1,h=e[i+p][t][u],m=d.width;for(;!h.rowspan&&!h.colspan;)p++,h=e[i+p][t][u],m+=h.width;d.colspan=p,d.width=m,d.height=n[u]}if(s[u].push(d),!d.collapsed&&d.colspan>1){let p=d.colspan-1;if(d.colspan+i>e.length){const h=d.colspan-(d.colspan+i-e.length);d.colspan=h,d.width=e.slice(i,i+p+1).reduce((m,g)=>m+g.width,0),h>1&&(p=h-1)}for(let h=0;h<p;h++)s[u].push(null)}if(d.rowspan>1){const p=d.rowspan;for(let h=1;h<p;h++)s[u+h]||(s[u+h]=[]),s[u+h].push(null)}}}if(a.collapsed)for(let u=0;u<s.length;u++){const d=s[u],p=d[i];if(p&&p.collapsed){if(d[i]=null,!u)break}else{const h=p||d.findLast(m=>m?.colspan>=1);h&&(h.colspan=h.colspan-1,h.width=h.width-a.width)}}}),s.map(a=>a.filter(i=>i&&i.colspan!==0))}function wA(e){const{mode:t,ppi:n,paper:s}=e,{width:a,height:i}=bA[s];return yA(t==="portrait"?a:i,n)}function yA(e,t){return e*t}function xA(e={}){const{mode:t,ppi:n,paper:s}=e;return{mode:t||hA,ppi:n||fA,paper:s||gA}}function qv(e,t){return e.flexgrow?`min-width:${t}px;width:auto`:`width:${e.width}px; max-width:${e.width}px; height:${e.height}px`}function SA(e,t,n){let s=e[n.id];if(n.filter.type==="richselect"&&s){const a=n.filter.config?.options||t.find(({id:i})=>i==n.id).options;a&&(s=a.find(({id:i})=>i==s).label)}return s??""}const sg=["resize-column","hide-column","update-cell"],CA=["delete-row","update-row","update-cell"],kA=["move-item"],MA=["resize-column","move-item"];class AA{undo=[];redo=[];progress={};in;getState;setState;_previousValues={};constructor(t,n,s){this.in=t,this.getState=n,this.setState=s,this.setHandlers(),this.resetStateHistory()}getHandlers(){return{"add-row":{handler:t=>({action:"delete-row",data:{id:t.id},source:{action:"add-row",data:t}})},"delete-row":{handler:t=>{const{id:n}=t,{data:s}=this.getPrev(),a=s.findIndex(i=>i.id===n);return{action:"add-row",data:{id:n,row:s[a],before:a<s.length-1?s[a+1].id:void 0},source:{action:"delete-row",data:t}}}},"update-cell":{handler:t=>{const{id:n,column:s}=t,a=this.getRow(n),i=this.getColumn(s),c=ra(a,i);return Ru(c,t.value)?null:{action:"update-cell",data:{id:n,column:s,value:c},source:{action:"update-cell",data:t}}}},"update-row":{handler:t=>{const{id:n,row:s}=t,a=this.getRow(n);for(const i in s)Object.keys(a).includes(i)||(a[i]=void 0);return{action:"update-row",data:{id:n,row:a},source:{action:"update-row",data:t}}}},"copy-row":{handler:t=>{const{id:n}=t,{data:s}=this.getState(),a=s.findIndex(c=>c.id===n),i=s[a];return{action:"delete-row",data:{id:n},source:{action:"add-row",data:{id:n,row:i,before:a<s.length-1?s[a+1].id:void 0}}}}},"resize-column":{handler:t=>{const{id:n,width:s}=t,a=this.getColumn(n),{_sizes:i}=this.getState();return{action:"resize-column",data:{id:n,width:a.width??i.columnWidth},source:{action:"resize-column",data:{id:n,width:s}}}}},"hide-column":{handler:t=>{const{id:n}=t,s=this.getColumn(n);return{action:"hide-column",data:{id:n,mode:s.hidden},source:{action:"hide-column",data:t}}}},"collapse-column":{handler:t=>{const{id:n,row:s,mode:a}=t;return{action:"collapse-column",data:{id:n,row:s,mode:typeof a=="boolean"?!a:a},source:{action:"collapse-column",data:t}}}},"move-item":{handler:t=>{const{id:n,target:s,mode:a}=t,{flatData:i}=this.getPrev(),c=i.findIndex(u=>u.id===n);return{action:"move-item",data:{id:n,target:i[c+(c?-1:1)].id,mode:c?"after":"before"},source:{action:"move-item",data:{id:n,target:s,mode:a}}}}},"open-row":{handler:t=>{const{id:n,nested:s}=t;return{action:"close-row",data:{id:n,nested:s},source:{action:"open-row",data:t}}}},"close-row":{handler:t=>{const{id:n,nested:s}=t;return{action:"open-row",data:{id:n,nested:s},source:{action:"close-row",data:t}}}}}}resetHistory(){this.undo=[],this.redo=[],this.progress={},this.resetStateHistory()}getPrev(){return this._previousValues}setHandlers(){const t=this.getHandlers();for(const n in t)this.in.intercept(n,s=>{if(!(s.eventSource==="undo"||s.eventSource==="redo"||s.skipUndo)){if(MA.includes(n)){(s.inProgress&&!this.progress[n]||typeof s.inProgress!="boolean")&&(kA.includes(n)&&this.setPrev("flatData"),sg.includes(n)&&this.setPrev("columns")),this.progress[n]=s.inProgress;return}CA.includes(n)&&this.setPrev("data"),sg.includes(n)&&this.setPrev("columns")}}),this.in.on(n,s=>{if(s.eventSource==="undo"||s.eventSource==="redo"||s.skipUndo||s.inProgress)return;const a=t[n].handler(s);a&&this.addToHistory(a)})}setPrev(t){this._previousValues[t]=Rp(this.getState()[t])}addToHistory(t){this.undo.push(t),this.redo=[],this.setStateHistory()}handleUndo(){if(!this.undo.length)return;const t=this.undo.pop();this.redo.push({...t.source,source:t}),this.in.exec(t.action,{...t.data,eventSource:"undo"}),this.setStateHistory()}handleRedo(){if(!this.redo.length)return;const t=this.redo.pop();this.undo.push({...t.source,source:t}),this.in.exec(t.action,{...t.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(t){const{data:n}=this.getPrev();return this.getState().tree?this.getTreeRow(n,t):n.find(s=>s.id===t)}getTreeRow(t,n){for(let s=0;s<t.length;s++){if(t[s].id===n)return t[s];if(t[s].data){const a=this.getTreeRow(t[s].data,n);if(a)return a}}return null}getColumn(t){const{columns:n}=this.getPrev();return n.find(s=>s.id===t)}}function Uv(e,t){return typeof e>"u"||e===null?-1:typeof t>"u"||t===null?1:e===t?0:e>t?1:-1}function NA(e,t){return-Uv(e,t)}function RA(e,t){if(typeof t.sort=="function")return function(s,a){const i=t.sort(s,a);return e==="asc"?i:-i};const n=e==="asc"?Uv:NA;return function(s,a){return n(ra(s,t),ra(a,t))}}function TA(e,t){if(!e||!e.length)return;const n=e.map(s=>{const a=t.find(i=>i.id==s.key);return RA(s.order,a)});return e.length===1?n[0]:function(s,a){for(let i=0;i<n.length;i++){const c=n[i](s,a);if(c!==0)return c}return 0}}const Dl=28,PA=20;function IA(){if(typeof document>"u")return"willow";const e=document.querySelector('[class^="wx"][class$="theme"]');return e?e.className.substring(3,e.className.length-6):"willow"}function du(e,t,n,s,a){const i=document.createElement("div"),c=document.createElement("div"),u=document.body;a=a?`${a}px`:"auto";let d,p;c.className=t,i.classList.add(`wx-${n}-theme`),i.style.cssText=`height:auto;position:absolute;top:0px;left:100px;overflow:hidden;width=${a};white-space:nowrap;`,i.appendChild(c),u.appendChild(i),typeof e!="object"&&(e=[e]);for(let h=0;h<e.length;h++){c.innerText=e[h]+"";const m=i.getBoundingClientRect(),g=Math.ceil(m.width)+(s&&s.length?s[h]:0),w=Math.ceil(m.height);d=Math.max(d||0,g),p=Math.max(p||0,w)}return i.remove(),{width:d,height:p}}function ag(e,t,n,s,a){const i=[];for(let c=0;c<e.length;c++){const u=e[c][t],d=u.length;for(let p=0;p<d;p++){const{text:h,vertical:m,collapsed:g,rowspan:w,css:v}=u[p];if(!h){i[p]=Math.max(i[p]||0,s);continue}let y=0;if(m&&!g){let k=`wx-measure-cell-${t}`;if(k+=v?` ${v}`:"",y=du(h,k,a).width,(w>1||!u[p+1])&&n>p+1){const N=w||n-p,C=i.slice(p,p+N).reduce((A,E)=>A+E,0);if(C<y){const A=Math.ceil((y-C)/N);for(let E=p;E<p+N;E++)i[E]=(i[E]||s)+A}continue}}i[p]=Math.max(i[p]||s,y)}}return i}function jA(e,t,n){const s=[],a=[];let i="wx-measure-cell-body";i+=e.css?` ${e.css}`:"";for(let c=0;c<t.length;c++){const u=t[c],d=Js(u,e);d&&(s.push(d),e.treetoggle?a.push(t[c].$level*Dl+(t[c].$count?Dl:0)+(e.draggable?Dl:0)):e.draggable&&a.push(Dl))}return du(s,i,n,a).width}function EA(e,t){const n="wx-measure-cell-header",s=e.sort?PA:0;let a=e.header;if(typeof a=="string")return du(a,n,t).width+s;let i;Array.isArray(a)||(a=[a]);for(let c=0;c<a.length;c++){const u=a[c],d=typeof u=="string"?u:u.text,p=n+(typeof u=="string"?"":` ${u.css}`);let h=du(d,p,t).width;c===a.length-1&&(h+=s),i=Math.max(i||0,h)}return i}const FA={text:(e,t)=>e?e.toString().toLowerCase().indexOf(t.toLowerCase())!==-1:!t,richselect:(e,t)=>typeof t!="number"&&!t?!0:e==t,datepicker:(e,t)=>t?e&&LA(e,t):!0,multiselect:(e,t)=>!t||t?.length===0?!0:Array.isArray(e)?e?.some(n=>t.includes(n)):e&&t.includes(e)};function Vv(e){return FA[e]}function DA(e,t){const n=[];for(const s in e){const a=t.find(d=>d.id==s),{config:i,type:c}=a.header.find(d=>d.filter).filter,u=e[s];n.push(d=>{const p=ra(d,a);return i?.handler?i.handler(p,u):Vv(c)(p,u)})}return s=>{for(let a=0;a<n.length;a++)if(!n[a](s))return!1;return!0}}function LA(e,t){return e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate()}let _A=class extends oA{in;_router;_branches;_xlsxWorker;_historyManager;constructor(t){super({writable:t,async:!1});const n={rowHeight:37,columnWidth:160,headerHeight:36,footerHeight:36};this._router=new cA(super.setState.bind(this),[{in:["columns","sizes","_skin"],out:["_columns","_sizes"],exec:a=>{const{columns:i,sizes:c,_skin:u}=this.getState(),d=this.copyColumns(i),p=d.reduce((g,w)=>Math.max(w.header.length,g),0),h=d.reduce((g,w)=>Math.max(w.footer.length,g),0);d.forEach(this.setCollapsibleColumns);const m=this.normalizeSizes(d,c,p,h,u);for(let g=0;g<d.length;g++)this.normalizeColumns(d,g,"header",p,m),this.normalizeColumns(d,g,"footer",h,m);this.setState({_columns:d,_sizes:m},a)}},{in:["data","tree","_filterIds"],out:["flatData","_rowHeightFromData"],exec:a=>{const{data:i,tree:c,dynamic:u,_filterIds:d}=this.getState(),p=d&&new Set(d),h=c?this.flattenRows(i,[],d):p?i.filter(g=>p.has(g.id)):i,m=!u&&h.some(g=>g.rowHeight);this.setState({flatData:h,_rowHeightFromData:m},a)}}],{sizes:a=>({...n,...a})});const s=this.in=new lA;s.on("close-editor",({ignore:a})=>{const{editor:i}=this.getState();i&&(a||s.exec("update-cell",i),this.setState({editor:null}))}),s.on("open-editor",({id:a,column:i})=>{let c=this.getState().editor;c&&s.exec("close-editor",{});const u=this.getRow(a),d=i?this.getColumn(i):this.getNextEditor(u);if(d?.editor){let p=d.editor;if(typeof p=="function"&&(p=p(u,d)),!p)return;c={column:d.id,id:a,value:ra(u,d)??"",renderedValue:Js(u,d),type:p.type||p},typeof p=="object"&&p.config&&(c.config=p.config,p.config.options&&(c.options=p.config.options)),d.options&&!c.options&&(c.options=d.options),this.setState({editor:c})}}),s.on("editor",({value:a})=>{let i=this.getState().editor;if(i){i={...i},i.value=a;const c=this.getColumn(i.column),u={...this.getRow(i.id)};$d(u,c,a),i.renderedValue=Js(u,c),this.setState({editor:i})}}),s.on("add-row",a=>{const i=this.getState();let{data:c}=i;const{select:u,_filterIds:d}=i,{row:p,before:h,after:m,select:g}=a;if(a.id=p.id=a.id||p.id||Ll(),h||m){const v=h||m,y=c.findIndex(k=>k.id===v);c=[...c],c.splice(y+(m?1:0),0,a.row)}else c=[...c,a.row];const w={data:c};d&&(w._filterIds=[...d,a.id]),this.setState(w),!(typeof g=="boolean"&&!g)&&(g||u)&&s.exec("select-row",{id:p.id,show:!0})}),s.on("delete-row",a=>{const{data:i,selectedRows:c,focusCell:u,editor:d}=this.getState(),{id:p}=a,h={data:i.filter(m=>m.id!==p)};this.isSelected(p)&&(h.selectedRows=c.filter(m=>m!==p)),d?.id===p&&(h.editor=null),this.setState(h),u?.row===p&&this.in.exec("focus-cell",{eventSource:"delete-row"})}),s.on("update-cell",a=>{const i=this.getState();let{data:c}=i;c=[...c];const{tree:u}=i,{id:d,column:p,value:h}=a,m=this.getColumn(p);if(u){const g={...this._branches[d]};$d(g,m,h);const w=this.updateTreeRow(g);g.$parent===0&&(c=w)}else{const g=c.findIndex(v=>v.id===d),w={...c[g]};$d(w,m,h),c[g]=w}this.setState({data:c})}),s.on("update-row",a=>{let{data:i}=this.getState();const{id:c,row:u}=a,d=i.findIndex(p=>p.id===c);i=[...i],i[d]={...i[d],...u},this.setState({data:i})}),s.on("select-row",({id:a,toggle:i,range:c,mode:u,show:d,column:p})=>{const h=this.getState(),{focusCell:m}=h;let{selectedRows:g}=h;if(g.length||(c=i=!1),c){const{data:w}=this.getState();let v=w.findIndex(k=>k.id===g[g.length-1]),y=w.findIndex(k=>k.id===a);v>y&&([v,y]=[y,v]),w.slice(v,y+1).forEach(k=>{this.isSelected(k.id)||g.push(k.id)})}else if(i&&this.isSelected(a)){if(u===!0)return;g=g.filter(w=>w!==a)}else if(i){if(u===!1)return;g.push(a)}else g=[a];this.setState({selectedRows:[...g]}),m?.row!==a&&this.in.exec("focus-cell",{eventSource:"select-row"}),d&&this.in.exec("scroll",{row:a,column:p})}),this.in.on("focus-cell",a=>{const{row:i,column:c,eventSource:u}=a,{_columns:d,split:p}=this.getState();i&&c?(this.setState({focusCell:{row:i,column:c}}),u!=="click"&&((!p.left||d.findIndex(h=>h.id===a.column)>=p.left)&&(!p.right||d.findIndex(h=>h.id===a.column)<d.length-p.right)?this.in.exec("scroll",{row:i,column:c}):this.in.exec("scroll",{row:i}))):this.setState({focusCell:null})}),s.on("resize-column",a=>{const{id:i,auto:c,maxRows:u,inProgress:d}=a;if(d===!1)return;let p=a.width||0;const h=[...this.getState().columns],m=this.getColumn(i);if(c){if(c==="data"||c===!0){const{flatData:g,_skin:w}=this.getState();let v=g.length;u&&(v=Math.min(u,v));const y=g.slice(0,v);p=jA(m,y,w)}if(c==="header"||c===!0){const{_skin:g}=this.getState();p=Math.max(EA(m,g),p)}}m.width=Math.max(17,p),delete m.flexgrow,this.setState({columns:h})}),s.on("hide-column",a=>{const{id:i,mode:c}=a,u=[...this.getState().columns],d=this.getColumn(i),p=u.reduce((h,m)=>h+(m.hidden?0:1),0);!c||p>1?(d.hidden=!d.hidden,this.setState({columns:u})):a.skipUndo=!0}),s.on("sort-rows",a=>{const{key:i,add:c,sort:u}=a,d=this.getState(),{columns:p,data:h,tree:m}=d;if(u){const C=[...h];C.sort(u),this.setState({data:C});return}const{order:g="asc"}=a;let w=d.sortMarks;const v=Object.keys(w),y=v.length;!c||!y||y===1&&w[i]?w={[i]:{order:g}}:(y===1&&(w[v[0]]={...w[v[0]],index:0}),w={...w,[i]:{order:g,index:typeof c=="number"?c:w[i]?.index??y}});const k=Object.keys(w).sort((C,A)=>w[C].index-w[A].index).map(C=>({key:C,order:w[C].order}));this.setState({sortMarks:w});const N=TA(k,p);if(N){const C=[...h];m?this.sortTree(C,N):C.sort(N),this.setState({data:C})}}),s.on("filter-rows",a=>{const{value:i,key:c,filter:u}=a;if(!Object.keys(a).length){this.setState({filterValues:{},_filterIds:null});return}const d=this.getState(),{data:p,tree:h,_columns:m}=d;let g=d.filterValues;const w={};c&&(g={...g,[c]:i},w.filterValues=g);const v=u??DA(g,m);let y=[];h?y=this.filterTree(p,v,y):p.forEach(k=>{v(k)&&y.push(k.id)}),w._filterIds=y,this.setState(w)}),s.on("collapse-column",a=>{const{id:i,row:c,mode:u}=a,d=[...this.getState().columns],p=this.getColumn(i).header,h=Array.isArray(p)?p[c]:p;typeof h=="object"&&(h.collapsed=u??!h.collapsed,this.setState({columns:d}))}),s.on("move-item",a=>{const{id:i,inProgress:c}=a;let{target:u,mode:d="after"}=a;const{data:p,flatData:h,tree:m}=this.getState(),g=h.findIndex(y=>y.id===i);let w;if(d==="up"||d==="down"){if(d==="up"){if(g===0)return;w=g-1,d="before"}else if(d==="down"){if(g===h.length-1)return;w=g+1,d="after"}u=h[w]&&h[w].id}else w=h.findIndex(y=>y.id===u);if(g===-1||w===-1||c===!1)return;let v;m||(v=this.moveItem(i,u,p,d)),this.setState({data:m?this.normalizeTreeRows(v):v})}),s.on("copy-row",a=>{const{id:i,target:c,mode:u="after"}=a,d=this.getState(),{flatData:p,_filterIds:h}=d;let{data:m}=d;const g=this.getRow(i);if(!g)return;const w={...g,id:Ll()};a.id=w.id;const v=p.findIndex(k=>k.id===c);if(v===-1)return;m.splice(v+(u==="after"?1:0),0,w),m=[...m];const y={data:m};h&&(y._filterIds=[...h,w.id]),this.setState(y)}),s.on("open-row",a=>{const{id:i,nested:c}=a;this.toggleBranch(i,!0,c)}),s.on("close-row",a=>{const{id:i,nested:c}=a;this.toggleBranch(i,!1,c)}),s.on("export-data",a=>new Promise((i,c)=>{const u=a.format||"csv",d=`${a.fileName||"data"}.${u}`;if(u==="csv"){const p=mA(this.getState(),a.csv||{});a.download!==!1?pA(new Blob(["\uFEFF"+p],{type:"text/csv"}),d):a.result=p,i(!0)}else c()})),s.on("hotkey",({key:a,event:i,isInput:c})=>{switch(a){case"arrowup":{const{flatData:u,focusCell:d,select:p}=this.getState();if(i.preventDefault(),c)return;const h=d?d.column:this._getFirstVisibleColumn()?.id,m=d?this.getPrevRow(d.row)?.id:u[u.length-1]?.id;h&&m&&(this.in.exec("focus-cell",{row:m,column:h,eventSource:"key"}),p&&this.in.exec("select-row",{id:m}));break}case"arrowdown":{const{flatData:u,focusCell:d,select:p}=this.getState();if(i.preventDefault(),c)return;const h=d?d.column:this._getFirstVisibleColumn()?.id,m=d?this.getNextRow(d.row)?.id:u[0]?.id;h&&m&&(this.in.exec("focus-cell",{row:m,column:h,eventSource:"key"}),p&&this.in.exec("select-row",{id:m}));break}case"arrowright":{const{focusCell:u}=this.getState();if(c)return;if(i.preventDefault(),u){const d=this.getNextColumn(u.column,!0)?.id;d&&this.in.exec("focus-cell",{row:u.row,column:d,eventSource:"key"})}break}case"arrowleft":{const{focusCell:u}=this.getState();if(c)return;if(i.preventDefault(),u){const d=this.getPrevColumn(u.column,!0)?.id;d&&this.in.exec("focus-cell",{row:u.row,column:d,eventSource:"key"})}break}case"tab":{const{editor:u,focusCell:d,select:p}=this.getState();if(u){i.preventDefault();const h=u.column;let m=u.id,g=this.getNextEditor(this.getRow(m),this.getColumn(h));if(!g){const w=this.getNextRow(m);w&&(m=w.id,g=this.getNextEditor(w))}g&&(this.in.exec("open-editor",{id:m,column:g.id}),this.in.exec("focus-cell",{row:m,column:g.id,eventSource:"key"}),p&&!this.isSelected(m)&&this.in.exec("select-row",{id:m}))}else d&&this.in.exec("focus-cell",{eventSource:"key"});break}case"shift+tab":{const{editor:u,focusCell:d,select:p}=this.getState();if(u){i.preventDefault();const h=u.column;let m=u.id,g=this.getPrevEditor(this.getRow(m),this.getColumn(h));if(!g){const w=this.getPrevRow(m);w&&(m=w.id,g=this.getPrevEditor(w))}g&&(this.in.exec("open-editor",{id:m,column:g.id}),this.in.exec("focus-cell",{row:m,column:g.id,eventSource:"key"}),p&&!this.isSelected(m)&&this.in.exec("select-row",{id:m}))}else d&&this.in.exec("focus-cell",{eventSource:"key"});break}case"escape":{const{editor:u}=this.getState();u&&(this.in.exec("close-editor",{ignore:u.type!="multiselect"}),this.in.exec("focus-cell",{row:u.id,column:u.column,eventSource:"key"}));break}case"f2":{const{editor:u,focusCell:d}=this.getState();!u&&d&&this.in.exec("open-editor",{id:d.row,column:d.column});break}case"enter":{const{focusCell:u,tree:d}=this.getState();if(!c&&d&&u&&this.getColumn(u.column).treetoggle){const p=this.getRow(u.row);if(!p.data)return;this.in.exec(p.open?"close-row":"open-row",{id:u.row,nested:!0})}break}case"home":{const{editor:u,focusCell:d}=this.getState();if(!u&&d){i.preventDefault();const p=this._getFirstVisibleColumn()?.id;this.in.exec("focus-cell",{row:d.row,column:p,eventSource:"key"})}break}case"ctrl+home":{const{editor:u,focusCell:d,flatData:p,select:h}=this.getState();if(!u&&d){i.preventDefault();const m=p[0]?.id,g=this._getFirstVisibleColumn()?.id;m&&g&&(this.in.exec("focus-cell",{row:m,column:g,eventSource:"key"}),h&&!this.isSelected(m)&&this.in.exec("select-row",{id:m}))}break}case"end":{const{editor:u,focusCell:d}=this.getState();if(!u&&d){i.preventDefault();const p=this._getLastVisibleColumn()?.id,h=d.row;this.in.exec("focus-cell",{row:h,column:p,eventSource:"key"})}break}case"ctrl+end":{const{editor:u,focusCell:d,flatData:p,select:h}=this.getState();if(!u&&d){i.preventDefault();const m=p.at(-1).id,g=this._getLastVisibleColumn()?.id;m&&g&&(this.in.exec("focus-cell",{row:m,column:g,eventSource:"key"}),h&&!this.isSelected(m)&&this.in.exec("select-row",{id:m}))}break}case"ctrl+z":{this.in.exec("undo",{});break}case"ctrl+y":{this.in.exec("redo",{});break}}}),s.on("scroll",a=>{const{_columns:i,split:c,_sizes:u,flatData:d,dynamic:p,_rowHeightFromData:h}=this.getState();let m=-1,g=-1,w=0,v=0;if(a.column){m=0;const y=i.findIndex(k=>k.id===a.column);w=i[y].width;for(let k=c.left??0;k<y;k++){const N=i[k];N.hidden||(m+=N.width)}}if(a.row&&!p){const y=d.findIndex(k=>k.id===a.row);y>=0&&(h?(g=d.slice(0,y).reduce((k,N)=>k+(N.rowHeight||u.rowHeight),0),v=d[y].rowHeight):g=u.rowHeight*y)}this.setState({scroll:{top:g,left:m,width:w,height:v||u.rowHeight}})}),s.on("scroll-to",a=>{const i={};a.top!==void 0&&(i.scrollTop=a.top),a.left!==void 0&&(i.scrollLeft=a.left),Object.keys(i).length&&this.setState(i)}),s.on("print",a=>{const i=xA(a);this.setState({_print:i}),this.setStateAsync({_print:null})}),s.on("undo",()=>{this._historyManager?.handleUndo()}),s.on("redo",()=>{this._historyManager?.handleRedo()}),this.initOnce()}getXlsxWorker(t){if(!this._xlsxWorker){const n=window.URL.createObjectURL(new Blob([`importScripts('${t}');`],{type:"text/javascript"}));this._xlsxWorker=new Promise(s=>{const a=new Worker(n);a.addEventListener("message",i=>{i.data.type==="init"&&s(a)})})}return this._xlsxWorker}initOnce(){const t={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(t)}init(t){t.hasOwnProperty("_skin")&&!t._skin&&(t._skin=IA()),t.columns&&t.columns.forEach(n=>{n.options&&(n.optionsMap=new Map(n.options.map(s=>[s.id,s.label])))}),Ru(this.getState().data,t.data)||(t.tree?t.data=this.normalizeTreeRows(t.data):t.data=this.normalizeRows(t.data),this.setState({_filterIds:null,filterValues:{},sortMarks:{},search:null}),this._historyManager&&this._historyManager.resetHistory()),t.tree&&(t.undo=!1,t.reorder=!1),t.split?.right&&(t.split.right=0),t.undo&&!this._historyManager&&(this._historyManager=new AA(this.in,this.getState.bind(this),this.setState.bind(this))),this._router.init({...t})}setState(t,n){return this._router.setState(t,n)}setStateAsync(t){this._router.setStateAsync(t)}getRow(t){const{tree:n}=this.getState();return n?this._branches[t]:this.getState().data.find(s=>s.id===t)}getRowIndex(t,n){return n||(n=this.getState().flatData),n.findIndex(s=>s.id===t)}getNextRow(t){const n=this.getState().flatData,s=this.getRowIndex(t,n);return n[s+1]}getPrevRow(t){const n=this.getState().flatData,s=this.getRowIndex(t,n);return n[s-1]}getColumn(t){return this.getState().columns.find(n=>n.id===t)}getNextColumn(t,n){const s=this.getState()._columns,a=s.findIndex(i=>i.id===t);return n?this._getFirstVisibleColumn(a+1):s[a+1]}getPrevColumn(t,n){const s=this.getState()._columns,a=s.findIndex(i=>i.id===t);return n?this._getLastVisibleColumn(a-1):s[a-1]}_getFirstVisibleColumn(t){const n=this.getState()._columns;let s=t??0;for(;s<n.length&&(n[s]?.hidden||n[s]?.collapsed);)s++;return n[s]}_getLastVisibleColumn(t){const n=this.getState()._columns;let s=t??n.length-1;for(;s<n.length&&(n[s]?.hidden||n[s]?.collapsed);)s--;return n[s]}isCellEditable(t,n){const{editor:s,hidden:a}=n;return!s||a?!1:typeof s=="function"?s(t,n):!0}getNextEditor(t,n){let s=this.getState().columns;if(n){const a=s.findIndex(i=>i.id===n.id);s=s.slice(a+1)}return s.find(a=>this.isCellEditable(t,a))}getPrevEditor(t,n){let s=this.getState().columns;if(n){const a=s.findLastIndex(i=>i.id===n.id);s=s.slice(0,a)}return s.findLast(a=>this.isCellEditable(t,a))}toggleBranch(t,n,s){let a=this._branches[t],{data:i}=this.getState();if(i=[...i],t!==0){a={...a,open:n};const c=this.updateTreeRow(a);a.$parent===0&&(i=c)}s&&a.data?.length&&a.data.forEach(c=>{const u=this.toggleKids(c,n,s);t===0&&(i=u)}),this.setState({data:i})}toggleKids(t,n,s){t={...t,open:n};const a=this.updateTreeRow(t);return s&&t.data?.length&&t.data.forEach(i=>{this.toggleKids(i,n,s)}),a}updateTreeRow(t){const n=t.id;this._branches[n]=t;const s=this._branches[t.$parent],a=s.data.findIndex(i=>i.id===n);return s.data=[...s.data],s.data[a]=t,s.data}isSelected(t){return this.getState().selectedRows.indexOf(t)!==-1}findAndRemove(t,n){for(let s=0;s<t.length;s++){if(t[s].id===n)return t.splice(s,1)[0];if(t[s].data){const a=[...t[s].data],i=this.findAndRemove(a,n);if(i)return t[s]={...t[s],data:a},i}}return null}insertItem(t,n,s,a){for(let i=0;i<t.length;i++){if(t[i].id===n){const c=t[i],u=a==="before"?i:i+1;if(c.data){if(a==="before"){const d=i>0?t[i-1]:null;return d?.data&&d.open?t[i-1]={...d,data:[...d.data,s]}:t.splice(u,0,s),!0}else if(c.open)return t[i]={...c,data:[s,...c.data]},!0}return t.splice(u,0,s),!0}if(t[i].data&&(t[i]={...t[i],data:[...t[i].data]},this.insertItem(t[i].data,n,s,a)))return!0}return!1}moveItem(t,n,s,a){const i=[...s],c=this.findAndRemove(i,t);return this.insertItem(i,n,c,a),i}copyColumns(t){const n=[];for(let s=0;s<t.length;s++){const a={...t[s]};this.copyHeaderFooter(a,"header"),this.copyHeaderFooter(a,"footer"),n[s]=a}return n}copyHeaderFooter(t,n){let s=t[n];s=Array.isArray(s)?[...s]:[s],s.forEach((a,i)=>{s[i]=typeof a=="string"?{text:a}:{...a}}),t[n]=s}setCollapsibleColumns(t,n,s){let a=t.header;for(let i=0;i<a.length;i++){const c=a[i];if(c.collapsible&&c.collapsed){if(c.collapsible!=="first"){t.collapsed=!0,t.width=36,c.vertical=!0;const d=a.length-i;a=a.slice(0,i+1),a[i].rowspan=d}const u=c.colspan;if(u){const d=a[i+1];let p=1;d&&d.colspan&&!d.collapsed&&(p=d.colspan);for(let h=p;h<u;h++){const m=s[n+h];m&&(m.hidden=!0)}}}}}normalizeColumns(t,n,s,a,i){const c=t[n];c.width||(c.width=c.flexgrow?17:i.columnWidth),c._colindex=n+1;const u=c[s],d=i[`${s}RowHeights`];for(let p=0;p<a;p++){const h=u[p];h.id=c.id,p===u.length-1&&(h.rowspan=h.rowspan?Math.min(h.rowspan,a-p):a-p);for(let m=1;m<h.rowspan;m++){u.splice(p+m,0,{_hidden:!0});for(let g=1;g<h.colspan;g++)t[n+g][s].splice(p+m,0,{})}if(h.rowspan){const m=(h.rowspan===a?d:d.slice(p,h.rowspan+p)).reduce((g,w)=>g+w,0);h.height=m,p+h.rowspan!=a&&h.height--}if(h.colspan){let m=c.width,g=c.flexgrow||0;const w=h.colspan;for(let v=1;v<w;v++){const y=t[n+v];y&&(y.hidden?h.colspan-=1:y.flexgrow?g+=y.flexgrow:m+=y.width||i.columnWidth),g?h.flexgrow=g:h.width=m}}else h.width=c.width,h.flexgrow=c.flexgrow;s==="header"&&h.filter&&typeof h.filter=="string"&&(h.filter={type:h.filter})}u.length>a&&(u.length=a),c[s]=u}normalizeRows(t){for(let n=0;n<t.length;n++)t[n].id||(t[n].id=Ll());return t}normalizeTreeRows(t,n,s){return!n&&!s&&(this._branches={0:{data:t}}),t.forEach(a=>{a.id||(a.id=Ll()),a.$level=n||0,a.$parent=s||0,this._branches[a.id]=a,a.data&&(a.data.length?(a.$count=a.data.length,this.normalizeTreeRows(a.data,a.$level+1,a.id)):(delete a.data,delete a.$count,delete a.open))}),t}sortTree(t,n){t.sort(n),t.forEach(s=>{s.data&&this.sortTree(s.data,n)})}filterTree(t,n,s){return t.forEach(a=>{n(a)&&s.push(a.id),a.data&&this.filterTree(a.data,n,s)}),s}flattenRows(t,n,s){const a=n;return t.forEach(i=>{(!s||s.includes(i.id))&&a.push(i),i.data?.length&&i.open!==!1&&this.flattenRows(i.data,a,s)}),a}createFilter(t){const{_columns:n}=this.getState(),s=[];for(const a in t){const i=n.find(p=>p.id==a),{config:c,type:u}=i.header.find(p=>p.filter).filter,d=t[a];s.push(p=>{const h=ra(p,i);return c?.handler?c.handler(h,d):Vv(u)(h,d)})}return a=>{for(let i=0;i<s.length;i++)if(!s[i](a))return!1;return!0}}searchRows(t,n){t=t.trim().toLowerCase();const s={};if(!t)return s;const{flatData:a,columns:i}=this.getState(),c=n?i.filter(u=>n[u.id]):i;return a.forEach(u=>{const d={};c.forEach(p=>{const h=Js(u,p);String(h).toLowerCase().includes(t)&&(d[p.id]=!0)}),Object.keys(d).length&&(s[u.id]=d)}),s}normalizeSizes(t,n,s,a,i){const c=ag(t,"header",s,n.headerHeight,i),u=ag(t,"footer",a,n.footerHeight,i),d=c.reduce((h,m)=>h+m,0),p=u.reduce((h,m)=>h+m,0);return{...n,headerRowHeights:c,footerRowHeights:u,headerHeight:d,footerHeight:p}}},$A=new Date().valueOf();function Ll(){return"temp://"+$A++}function OA(e,t="data-id"){let n=e;for(!n.tagName&&e.target&&(n=e.target);n;){if(n.getAttribute&&n.getAttribute(t))return n;n=n.parentNode}return null}new Date().valueOf();var BA=class{constructor(){this.store=new Map}configure(e,t){this.node=t;for(const n in e)if(e[n]){const s=n.toLowerCase().replace(/[ ]/g,""),a=e[n];this.store.set(s,a)}}},eo=[],HA={subscribe:e=>{WA();const t=new BA;return eo.push(t),e(t),()=>{const n=eo.findIndex(s=>s===t);n>=0&&eo.splice(n,1)}}},ig=!1;function WA(){ig||(ig=!0,document.addEventListener("keydown",e=>{if(eo.length&&(e.ctrlKey||e.altKey||e.metaKey||e.shiftKey||e.key.length>1||e.key===" ")){const t=[];e.ctrlKey&&t.push("ctrl"),e.altKey&&t.push("alt"),e.metaKey&&t.push("meta"),e.shiftKey&&t.push("shift");let n=e.code.replace("Key","").toLocaleLowerCase();e.key===" "&&(n="space"),t.push(n);const s=t.join("+");for(let a=eo.length-1;a>=0;a--){const i=eo[a],c=i.store.get(s)||i.store.get(n);c&&i.node.contains(e.target)&&c(e,{key:s,evKey:n})}}}))}const zA={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 qA(e,{keys:t,exec:n}){if(!t)return;function s(c){const u=c.target;return u.tagName==="INPUT"||u.tagName==="TEXTAREA"||OA(u,"data-header-id")?.classList.contains("wx-filter")||!!u.closest(".wx-cell.wx-editor")}const a={};for(const c in t){const u=t[c];typeof u<"u"&&(typeof u=="function"?a[c]=u:u&&(a[c]=d=>{const p=s(d);n({key:c,event:d,isInput:p})}))}const i=HA.subscribe(c=>{c.configure(a,e)});return{destroy:()=>{i()}}}function UA(e,t){let n=null;t.scroll.subscribe(s=>{if(!s||s===n)return;n=s;const{left:a,top:i,height:c,width:u}=s,d=t.getHeight(),p=t.getWidth(),h=t.getScrollMargin();if(i>=0){const m=e.scrollTop;i<m?e.scrollTop=i:i+c>m+d&&(e.scrollTop=i-d+c)}if(a>=0){const m=e.scrollLeft;a<m?e.scrollLeft=a:a+u>m+p-h&&(e.scrollLeft=a-p+u+h)}}),t.scrollLeft?.subscribe?.(s=>{requestAnimationFrame(()=>{Math.abs(e.scrollLeft-s)>1&&(e.scrollLeft=s)})}),t.scrollTop?.subscribe?.(s=>{requestAnimationFrame(()=>{Math.abs(e.scrollTop-s)>1&&(e.scrollTop=s)})})}const lr=o.createContext(null);function VA(e,t){const n=new ResizeObserver(s=>{requestAnimationFrame(()=>t(s[0].contentRect))});return n.observe(e.parentNode),{destroy(){n.disconnect()}}}const og=5,GA=700;function Jl(e){const t=e.getBoundingClientRect(),n=document.body,s=t.top+n.scrollTop-n.clientTop||0,a=t.left+n.scrollLeft-n.clientLeft||0;return{y:Math.round(s),x:Math.round(a),width:e.offsetWidth,height:e.offsetHeight}}function Tp(e,t){const n=Jl(t);return{x:e.clientX-n.x,y:e.clientY-n.y}}function KA(e,t){const n=t.current;let s=null,a,i,c=!1,u=!1;const d=document.createElement("DIV");d.className="wx-drag-zone",d.setAttribute("tabindex",-1);function p(){clearTimeout(a),a=null}function h(M){const H=ro(M);H&&(s={container:d,sourceNode:M.target,from:Mu(H),pos:Tp(M,e)},i=s.pos,m(M))}function m(M){if(!s)return;const H=s.pos=Tp(M,e);if(!c){if(!u&&!M?.target?.getAttribute("draggable-data")&&Math.abs(i.x-H.x)<og&&Math.abs(i.y-H.y)<og)return;if(I(M)===!1)return F()}if(u){const V=window.scrollX||document.documentElement.scrollLeft||document.body.scrollLeft,P=window.scrollY||document.documentElement.scrollTop||document.body.scrollTop;s.targetNode=document.elementFromPoint(M.pageX-V,M.pageY-P)}else s.targetNode=M.target;n.move&&n.move(M,s),d.style.left=-(s.offset?s.offset.x:0)+"px",d.style.top=s.pos.y+(s.offset?s.offset.y:0)+"px"}function g(M){d.parentNode&&d.parentNode.removeChild(d),d.innerHTML="",c&&n.end&&n.end(M,s),s=i=null,F()}function w(M){n.getReorder&&!n.getReorder()||M.button===0&&(E(M),window.addEventListener("mousemove",v),window.addEventListener("mouseup",y),h(M))}function v(M){m(M)}function y(M){g(M)}function k(M){if(n.getReorder&&!n.getReorder())return;a=setTimeout(()=>{u=!0,h(M.touches[0])},GA),E(M);function H(){a&&p(),M.target.removeEventListener("touchmove",N),M.target.removeEventListener("touchend",H),g(M)}M.target.addEventListener("touchmove",N),M.target.addEventListener("touchend",H),e.addEventListener("contextmenu",C)}function N(M){c?(M.preventDefault(),m(M.touches[0])):a&&p()}function C(M){if(c||a)return M.preventDefault(),!1}function A(M){M.preventDefault()}function E(M){if(!n.getDraggableInfo)return;const{hasDraggable:H}=n.getDraggableInfo();(!H||M.target.getAttribute("draggable-data"))&&(document.body.style.userSelect="none",document.body.style.webkitUserSelect="none")}function I(M){if(c=!0,n.start){if(n.start(M,s)===!1)return!1;e.appendChild(d),document.body.style.cursor="move"}}function F(M){c=u=!1,document.body.style.cursor="",document.body.style.userSelect="",document.body.style.webkitUserSelect="",window.removeEventListener("mousemove",v),window.removeEventListener("mouseup",y),M&&(e.removeEventListener("mousedown",w),e.removeEventListener("touchstart",k),e.removeEventListener("dragstart",A))}return e.addEventListener("mousedown",w),e.addEventListener("touchstart",k),e.addEventListener("dragstart",A),{destroy(){F(!0)}}}const QA=.004;function YA(){return{dirX:0,dirY:0,scrollSpeedFactor:1}}function XA(e,t,n,s){const{node:a,left:i,top:c,bottom:u,sense:d,xScroll:p,yScroll:h}=s,m=Tp(e,a);n.scrollState||(n.scrollState=YA());let g=0,w=0;m.x<i+d?g=-1:m.x>t.width-d&&(g=1),m.y<c+Math.round(d/2)?w=-1:m.y>t.height-u-Math.round(d/2)&&(w=1),(n.scrollState.dirX!==g||n.scrollState.dirY!==w)&&(Gv(n),n.scrollState.dirX=g,n.scrollState.dirY=w),(p&&n.scrollState.dirX!==0||h&&n.scrollState.dirY!==0)&&JA(n,s,{x:n.scrollState.dirX,y:n.scrollState.dirY})}function JA(e,t,n){e.autoScrollTimer||(e.autoScrollTimer=setTimeout(()=>{e.activeAutoScroll=setInterval(ZA,15,e,t,n)},250))}function Gv(e){e.scrollSpeedFactor=1,e.autoScrollTimer&&(e.autoScrollTimer=clearTimeout(e.autoScrollTimer),e.activeAutoScroll=clearInterval(e.activeAutoScroll))}function ZA(e,t,n){const{x:s,y:a}=n;e.scrollSpeedFactor+=QA,s!==0&&tN(e,t,s),a!==0&&eN(e,t,a)}function eN(e,t,n){const s=t.node.scrollTop;Kv(s+Math.round(t.sense/3)*e.scrollSpeedFactor*n,"scrollTop",t)}function tN(e,t,n){const s=t.node.scrollLeft;Kv(s+Math.round(t.sense/3)*e.scrollSpeedFactor*n,"scrollLeft",t)}function Kv(e,t,n){n.node[t]=e}function Tu(e,t,n,s,a,i){const c={};return e&&(c.width=`${e}px`,c.minWidth=`${e}px`),t&&(c.flexGrow=t),i&&(c.height=`${i}px`),n&&(c.position="sticky",n.left&&(c.left=`${s}px`),n.right&&(c.right=`${a}px`)),c}function Qv(e,t,n){let s="";if(e.fixed)for(const a in e.fixed){let i=e.fixed[a]===-1;!i&&e.fixed.leftSize&&t.colspan&&(i=t.colspan+e._colindex-1===e.fixed.leftSize),s+=i?"wx-shadow ":"wx-fixed "}return s+=t.rowspan>1?"wx-rowspan ":"",s+=t.colspan>1?"wx-colspan ":"",s+=t.vertical?"wx-vertical ":"",s+=n?n(e)+" ":"",s}function nN(e){const{row:t,column:n,cellStyle:s=null,columnStyle:a=null,children:i,focusable:c}=e,u=o.useContext(lr),d=dt(u,"focusCell"),p=dt(u,"search"),h=dt(u,"reorder"),m=o.useMemo(()=>p?.rows[t.id]&&p.rows[t.id][n.id],[p,t.id,n.id]),g=o.useMemo(()=>Tu(n.width,n.flexgrow,n.fixed,n.left,n.right),[n.width,n.flexgrow,n.fixed,n.left,n.right]);function w(I,F){let M="wx-cell";return M+=n.fixed?" "+(n.fixed===-1?"wx-shadow":"wx-fixed"):"",M+=I?" "+I(n):"",M+=F?" "+F(t,n):"",M+=n.treetoggle?" wx-tree-cell":"",M}const v=o.useMemo(()=>w(a,s),[a,s,n,t]),y=o.useMemo(()=>typeof n.draggable=="function"?n.draggable(t,n)!==!1:n.draggable,[n,t]),k=o.useRef(null);o.useEffect(()=>{k.current&&c&&d?.row===t.id&&d?.column===n.id&&k.current.focus()},[d,c,t.id,n.id]);const N=o.useCallback(()=>{c&&!d&&u.exec("focus-cell",{row:t.id,column:n.id,eventSource:"focus"})},[u,c,d,t.id,n.id]);function C(I){const F=new RegExp(`(${p.value.trim()})`,"gi");return String(I).split(F).map(M=>({text:M,highlight:F.test(M)}))}const A=o.useMemo(()=>{const I=n.fixed&&n.fixed.left===-1||n.fixed.right===-1,F=n.fixed&&n.fixed.right;return[v,I?"wx-shadow":"",F?"wx-fixed-right":""].filter(Boolean).join(" ")},[v,n]),E=n.cell;return r.jsxs("div",{className:"wx-TSCaXsGV "+A,ref:k,onFocus:N,style:g,"data-row-id":mn(t.id),"data-col-id":mn(n.id),tabIndex:c?"0":"-1",role:"gridcell","aria-colindex":n._colindex,"aria-readonly":n.editor?void 0:!0,children:[h&&n.draggable?y?r.jsx("i",{"draggable-data":"true",className:"wx-TSCaXsGV wx-draggable wxi-drag"}):r.jsx("i",{className:"wx-TSCaXsGV wx-draggable-stub"}):null,n.treetoggle?r.jsxs(r.Fragment,{children:[r.jsx("span",{style:{marginLeft:`${t.$level*28}px`}}),t.$count?r.jsx("i",{"data-action":"toggle-row",className:`wx-TSCaXsGV wx-table-tree-toggle wxi-menu-${t.open!==!1?"down":"right"}`}):null]}):null,E?r.jsx(E,{api:u,row:t,column:n,onAction:({action:I,data:F})=>u.exec(I,F)}):i?i():m?r.jsx("span",{children:C(Js(t,n)).map(({highlight:I,text:F},M)=>I?r.jsx("mark",{className:"wx-TSCaXsGV wx-search",children:F},M):r.jsx("span",{children:F},M))}):Js(t,n)]})}function cg(e,t){let n,s;function a(u){n=u.clientX,e.style.opacity=1,document.body.style.cursor="ew-resize",document.body.style.userSelect="none",window.addEventListener("mousemove",i),window.addEventListener("mouseup",c),t&&t.down&&t.down(e)}function i(u){s=u.clientX-n,t&&t.move&&t.move(s)}function c(){e.style.opacity="",document.body.style.cursor="",document.body.style.userSelect="",t&&t.up&&t.up(s),window.removeEventListener("mousemove",i),window.removeEventListener("mouseup",c)}return e.addEventListener("mousedown",a),{destroy(){e.removeEventListener("mousedown",a)}}}function rN({filter:e,column:t,action:n,filterValue:s}){function a({value:i}){n({value:i,key:t.id})}return r.jsx(em,{...e.config??{},value:s,onChange:a})}function sN({filter:e,column:t,action:n,filterValue:s}){const a=o.useContext(lr),i=dt(a,"flatData"),c=o.useMemo(()=>e?.config?.options||t?.options||d(),[e,t,i]),u=o.useMemo(()=>e?.config?.template,[e]);function d(){const m=[];return i.forEach(g=>{const w=ra(g,t);m.includes(w)||m.push(w)}),m.map(g=>({id:g,label:g}))}function p({value:m}){n({value:m,key:t.id})}function h(m){m.key!=="Tab"&&m.preventDefault()}return r.jsx("div",{style:{width:"100%"},onKeyDown:h,children:r.jsx(vM,{placeholder:"",clear:!0,...e?.config??{},options:c,value:s,onChange:p,children:m=>u?u(m):m.label})})}function aN({filter:e,column:t,action:n,filterValue:s}){function a({value:i}){n({value:i,key:t.id})}return r.jsx("div",{className:"wx-aaaK5VYO",style:{width:"100%"},children:r.jsx(bM,{placeholder:"",clear:!0,...e?.config??{},value:s,onChange:a})})}function Yv(e){const{value:t,options:n=[],placeholder:s="",clear:a=!1,text:i=null,template:c=null,cell:u=null,dropdown:d={},autoOpen:p=!1,onChange:h,onAction:m}=e,[g,w]=Fv(t||[]),v=o.useMemo(()=>(g||[]).map(P=>n.find(D=>D.id===P)).filter(Boolean),[g,n]),y=o.useRef(null),k=o.useRef(null),[N,C]=o.useState(null),A=()=>{const P=g||[];if(!P.length)return 0;const D=n.find(O=>P.includes(O.id));return D?n.indexOf(D):0};function E(P){k.current=P.navigate,C(()=>P.keydown),p&&P.navigate(A())}o.useEffect(()=>{p&&(y.current?.focus(),typeof window<"u"&&window.getSelection&&window.getSelection().removeAllRanges())},[]);function I({id:P}){w(P),h&&h({value:P})}function F(P){P.stopPropagation(),w([]),h&&h({value:[]})}function M(){k.current?.(A())}function H(){k.current?.(null)}function V(P){N?.(P,A())}return r.jsxs("div",{ref:y,className:"wx-multiselect wx-aadNNOwy",onClick:M,onKeyDown:V,tabIndex:0,children:[r.jsx("div",{className:"wx-label wx-aadNNOwy",children:c?c(v):u?r.jsx(u,{data:v,onAction:m}):i?r.jsx("span",{className:"wx-text wx-aadNNOwy",children:i}):v.length?r.jsx("span",{className:"wx-text wx-aadNNOwy",children:v.map(P=>P.label).join(", ")}):s?r.jsx("span",{className:"wx-placeholder wx-aadNNOwy",children:s}):" "}),a&&g?.length?r.jsx("i",{className:"wx-icon wxi-close wx-aadNNOwy",onClick:F}):r.jsx("i",{className:"wx-icon wxi-angle-down wx-aadNNOwy"}),r.jsx(Nu,{items:n,onReady:E,onSelect:I,multiselect:!0,checkboxes:!0,value:g||[],onCancel:H,...d,children:({option:P})=>r.jsx("div",{className:"wx-option wx-aadNNOwy",children:c?c(P):u?r.jsx(u,{data:P,onAction:m}):P.label})})]})}function iN({filter:e,column:t,action:n,filterValue:s}){const a=o.useContext(fn.i18n)?.getGroup("grid")||pc(rm).getGroup("grid"),i=o.useMemo(()=>({clear:!0,...e?.config||{}}),[e]),c=o.useMemo(()=>i.options||t.options,[i,t]),u=o.useMemo(()=>{const h=s?.length;return h?h<3?s.map(m=>t.optionsMap.get(m)).join(", "):h+" "+a("selected"):""},[s,t,a]);function d({value:h}){n({value:h,key:t.id})}function p(h){h.key!=="Tab"&&h.preventDefault()}return r.jsx("div",{style:{width:"100%"},onKeyDown:p,children:r.jsx(Yv,{placeholder:"",...i,options:c,value:s||[],text:u,onChange:d})})}const oN={text:rN,richselect:sN,datepicker:aN,multiselect:iN};function cN({filter:e,column:t}){const n=o.useContext(lr),s=dt(n,"filterValues");function a(c){n.exec("filter-rows",c)}const i=o.useMemo(()=>oN[e.type],[e.type]);return r.jsx(i,{filter:e,column:t,action:a,filterValue:s[t.id]})}function lN(e){const{cell:t,column:n,row:s,lastRow:a,sortRow:i,columnStyle:c,bodyHeight:u,hasSplit:d}=e,p=o.useContext(lr),h=dt(p,"sortMarks"),m=o.useMemo(()=>h?h[n.id]:void 0,[h,n.id]),g=o.useRef(),w=o.useCallback(G=>{g.current=t.flexgrow?G.parentNode.clientWidth:t.width},[t.flexgrow,t.width]),v=o.useCallback((G,U)=>{p.exec("resize-column",{id:t.id,width:Math.max(1,(g.current||0)+G),inProgress:U})},[p,t.id]),y=o.useCallback(G=>v(G,!0),[v]),k=o.useCallback(G=>v(G,!1),[v]),N=o.useCallback(G=>{if(!n.sort||t.filter)return;let U=m?.order;U&&(U=U==="asc"?"desc":"asc"),p.exec("sort-rows",{key:t.id,add:G.ctrlKey||G.metaKey,order:U})},[p,t.id,t.filter,n.sort,m?.order]),C=o.useCallback(G=>{G&&G.stopPropagation(),p.exec("collapse-column",{id:t.id,row:s})},[p,t.id,s]),A=o.useCallback(G=>{G.key==="Enter"&&C()},[C]),E=o.useCallback(G=>{G.key==="Enter"&&!t.filter&&N(G)},[N,t.filter]),I=o.useMemo(()=>t.collapsed&&n.collapsed,[t.collapsed,n.collapsed]),F=o.useMemo(()=>I&&!d&&t.collapsible!=="header",[I,d,t.collapsible]),M=o.useMemo(()=>F?{top:-u/2,position:"absolute"}:{},[F,u]),H=o.useMemo(()=>Tu(t.width,t.flexgrow,n.fixed,n.left,t.right??n.right,t.height+(I&&F?u:0)),[t.width,t.flexgrow,n.fixed,n.left,t.right,n.right,t.height,I,F,u]),V=o.useMemo(()=>Qv(n,t,c),[n,t,c]),P=o.useCallback(()=>Object.fromEntries(Object.entries(t).filter(([G])=>G!=="cell")),[t]),D=`wx-cell ${V} ${t.css||""} wx-collapsed`,O=["wx-cell",V,t.css||"",t.filter?"wx-filter":"",n.fixed&&n.fixed.right?"wx-fixed-right":""].filter(Boolean).join(" "),X=o.useRef(null);return o.useEffect(()=>{const G=X.current;if(!G)return;const U=cg(G,{down:w,move:y,up:k});return()=>{typeof U=="function"&&U()}},[w,y,k,cg]),I?r.jsx("div",{className:"wx-RsQD74qC "+D,style:H,role:"button","aria-label":`Expand column ${t.text||""}`,"aria-expanded":!t.collapsed,tabIndex:0,onKeyDown:A,onClick:C,"data-header-id":mn(n.id),children:r.jsx("div",{className:"wx-RsQD74qC wx-text",style:M,children:t.text||""})}):r.jsxs("div",{className:"wx-RsQD74qC "+O,style:H,onClick:N,"data-header-id":mn(n.id),tabIndex:!t._hidden&&n.sort&&!t.filter?0:void 0,role:"columnheader","aria-colindex":n._colindex,"aria-colspan":t.colspan>1?t.colspan:void 0,"aria-rowspan":t.rowspan>1?t.rowspan:void 0,"aria-sort":!m?.order||t.filter?"none":m?.order==="asc"?"ascending":"descending",onKeyDown:E,children:[t.collapsible?r.jsx("div",{className:"wx-RsQD74qC wx-collapse",role:"button","aria-label":t.collapsed?"Expand column":"Collapse column","aria-expanded":!t.collapsed,tabIndex:0,onKeyDown:A,onClick:C,children:r.jsx("i",{className:`wx-RsQD74qC wxi-angle-${t.collapsed?"down":"right"}`})}):null,t.cell?(()=>{const G=t.cell;return r.jsx(G,{api:p,cell:P(),column:n,row:s,onAction:({action:U,data:ie})=>p.exec(U,ie)})})():t.filter?r.jsx(cN,{filter:t.filter,column:n}):r.jsx("div",{className:"wx-RsQD74qC wx-text",children:t.text||""}),n.resize&&a&&!t._hidden?r.jsx("div",{className:"wx-RsQD74qC wx-grip",role:"presentation","aria-label":"Resize column",ref:X,onClick:G=>G.stopPropagation(),children:r.jsx("div",{})}):null,i?r.jsx("div",{className:"wx-RsQD74qC wx-sort",children:m?r.jsxs(r.Fragment,{children:[typeof m.index<"u"?r.jsx("div",{className:"wx-RsQD74qC wx-order",children:m.index+1}):null,r.jsx("i",{className:`wx-RsQD74qC wxi-arrow-${m.order==="asc"?"up":"down"}`})]}):null}):null]})}function uN({cell:e,column:t,row:n,columnStyle:s}){const a=o.useContext(lr),i=o.useMemo(()=>Tu(e?.width,e?.flexgrow,t?.fixed,t?.left,e?.right??t?.right,e?.height),[e?.width,e?.flexgrow,t?.fixed,t?.left,e?.right,t?.right,e?.height]),c=o.useMemo(()=>Qv(t,e,s),[t,e,s]),u=o.useCallback(()=>Object.fromEntries(Object.entries(e||{}).filter(([p])=>p!=="cell")),[e]),d=`wx-6Sdi3Dfd wx-cell ${c||""} ${e?.css||""}`+(t?.fixed&&t?.fixed.right?" wx-fixed-right":"");return r.jsx("div",{className:d,style:i,children:!t?.collapsed&&!e?.collapsed?e?.cell?Fp.createElement(e.cell,{api:a,cell:u(),column:t,row:n,onAction:({action:p,data:h})=>a.exec(p,h)}):r.jsx("div",{className:"wx-6Sdi3Dfd wx-text",children:e?.text||""}):null})}function lg({deltaLeft:e,contentWidth:t,columns:n,type:s="header",columnStyle:a,bodyHeight:i}){const c=o.useContext(lr),u=dt(c,"_sizes"),d=dt(c,"split"),p=o.useMemo(()=>u?.[`${s}RowHeights`],[u,s]),h=o.useMemo(()=>{let y=[];if(n&&n.length){const k=n[0][s].length;for(let N=0;N<k;N++){let C=0;y.push([]),n.forEach((A,E)=>{const I={...A[s][N]};C||y[N].push(I),I.colspan>1?C=I.colspan-1:C&&C--})}}return y},[n,s]),m=o.useMemo(()=>d?.left||d?.right,[d]);function g(y){return n.find(k=>k.id===y)}function w(y,k){let N=k;return y.rowspan&&(N+=y.rowspan-1),N===h.length-1}function v(y,k,N){if(!N.sort)return!1;for(let C=h.length-1;C>=0;C--){const A=N.header[C];if(!A.filter&&!A._hidden)return k===C}return w(y,k)}return r.jsx("div",{className:`wx-sAsPVaUK wx-${s}`,style:{paddingLeft:`${e}px`,width:`${t}px`},role:"rowgroup",children:h.map((y,k)=>r.jsx("div",{className:s==="header"?"wx-sAsPVaUK wx-h-row":"wx-sAsPVaUK wx-f-row",style:{height:`${p?.[k]}px`,display:"flex"},role:"row",children:y.map(N=>{const C=g(N.id);return s==="header"?r.jsx(lN,{cell:N,columnStyle:a,column:C,row:k,lastRow:w(N,k),bodyHeight:i,sortRow:v(N,k,C),hasSplit:m},N.id):r.jsx(uN,{cell:N,columnStyle:a,column:g(N.id),row:k},N.id)})},k))})}function dN({overlay:e}){const t=o.useContext(lr);function n(a){return typeof a=="function"}const s=e;return r.jsx("div",{className:"wx-1ty666CQ wx-overlay",children:n(e)?r.jsx(s,{onAction:({action:a,data:i})=>t.exec(a,i)}):e})}function pN(e){const{editor:t,onSave:n,onApply:s}=e,[a,i]=o.useState(t?.value||""),{type:c="text"}=o.useMemo(()=>t?.config||{},[t]),u=o.useRef(null);o.useEffect(()=>{u.current&&u.current.focus()},[]),o.useEffect(()=>{if(!u.current)return;const h=ls(u.current,()=>n(!0));return()=>h.destroy()},[n]);function d(){u.current&&(i(u.current.value),s(u.current.value))}function p({key:h}){h==="Enter"&&n()}return r.jsx("input",{className:"wx-e7Ao5ejY wx-text",onInput:d,onKeyDown:p,ref:u,type:c,value:a})}function mN({editor:e,onAction:t,onSave:n,onApply:s,onCancel:a}){const[i,c]=o.useState(e?.value),[u,d]=o.useState(e?.renderedValue),[p,h]=o.useState(e?.options||[]),m=o.useMemo(()=>e?.config?.template,[e]),g=o.useMemo(()=>e?.config?.cell,[e]),w=o.useMemo(()=>e?.config?.dropdown||{},[e]),v=o.useMemo(()=>({trackScroll:!0,...w}),[w]),y=o.useMemo(()=>(p||[]).findIndex(M=>M.id===i),[p,i]),k=o.useRef(null),N=o.useRef(null),C=o.useCallback(M=>{k.current=M.navigate,N.current=M.keydown,k.current(y)},[y,k]),A=o.useCallback(M=>{const H=M?.target?.value??"";d(H);const V=H?(e?.options||[]).filter(P=>(P.label||"").toLowerCase().includes(H.toLowerCase())):e?.options||[];h(V),V.length?k.current(-1/0):k.current(null)},[e]),E=o.useRef(null);o.useEffect(()=>{E.current&&E.current.focus()},[]);const I=o.useRef(n);o.useEffect(()=>{I.current=n},[n]),o.useEffect(()=>{if(!E.current)return;const M=ls(E.current,()=>I.current(!0));return()=>M.destroy()},[]),o.useEffect(()=>{c(e?.value),d(e?.renderedValue),h(e?.options||[])},[e]);const F=o.useCallback(({id:M})=>{s(M),n()},[s,n]);return r.jsxs(r.Fragment,{children:[r.jsx("input",{className:"wx-0UYfSd1x wx-input",ref:E,value:u??"",onChange:A,onKeyDown:M=>N.current?N.current(M,y):void 0}),r.jsx(Nu,{items:p,onReady:C,onSelect:F,...v,onCancel:a,children:({option:M})=>m?m(M):g?r.jsx(g,{data:M,onAction:t}):M.label})]})}function hN({editor:e,onAction:t,onSave:n,onApply:s,onCancel:a}){const[i]=o.useState(()=>e.value||new Date),{template:c,cell:u,dropdown:d={}}=e?.config||{},p=o.useMemo(()=>({trackScroll:!0,width:"auto",...d}),[d]);function h({value:v}){s(v),n()}const m=o.useRef(null),[g,w]=o.useState(null);return o.useEffect(()=>{m.current&&m.current.focus(),typeof window<"u"&&window.getSelection&&window.getSelection().removeAllRanges()},[]),o.useEffect(()=>{if(!g)return;const v=ls(g,()=>n(!0));return()=>v.destroy()},[g,n]),r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"wx-lNWNYUb6 wx-value",ref:m,tabIndex:0,onClick:a,onKeyDown:v=>v.preventDefault(),children:c?c(i):u?r.jsx(u,{data:e.value,onAction:t}):r.jsx("span",{className:"wx-lNWNYUb6 wx-text",children:e.renderedValue})}),r.jsx(Zp,{...p,onCancel:a,children:r.jsx("div",{ref:w,className:"wx-lNWNYUb6",children:r.jsx(Tv,{value:i,onChange:h,buttons:e.config?.buttons})})})]})}function fN(e){const{editor:t}=e,n=e.onAction??e.onaction,s=e.onSave??e.onsave,a=e.onApply??e.onapply,i=e.onCancel??e.oncancel,c=t.config||{},{dropdown:u={}}=c,d=o.useMemo(()=>({trackScroll:!0,...u}),[u]),[p]=o.useState(t.options.find(A=>A.id===t.value)),[h]=o.useState(t.value),[m]=o.useState(t.options),g=o.useMemo(()=>m.findIndex(A=>A.id===h),[m,h]);function w({id:A}){a(A),s()}let v;const[y,k]=o.useState();function N(A){v=A.navigate,k(()=>A.keydown),v(g)}const C=o.useRef(null);return o.useEffect(()=>{C.current&&C.current.focus(),typeof window<"u"&&window.getSelection&&window.getSelection().removeAllRanges()},[]),o.useEffect(()=>{if(!C.current)return;const A=ls(C.current,()=>s(!0));return()=>A.destroy()},[s]),r.jsxs(r.Fragment,{children:[r.jsx("div",{ref:C,className:"wx-ywGRk611 wx-value",tabIndex:0,onClick:i,onKeyDown:A=>{y(A,g),A.preventDefault()},children:c.template?c.template(p):c.cell?(()=>{const A=c.cell;return r.jsx(A,{data:p,onAction:n})})():r.jsx("span",{className:"wx-ywGRk611 wx-text",children:t.renderedValue})}),r.jsx(Nu,{items:m,onReady:N,onSelect:w,...d,onCancel:i,children:({option:A})=>c.template?c.template(A):c.cell?(()=>{const E=c.cell;return r.jsx(E,{data:A,onAction:n})})():A.label})]})}function gN(e){const{editor:t,onAction:n,onSave:s,onApply:a}=e,i=t?.config||{},c=t?.options??[],u=t?.value||[],d=t?.renderedValue,p=o.useMemo(()=>({trackScroll:!0,...i.dropdown||{}}),[i]);function h({value:g}){a(g)}const m=o.useRef(null);return o.useEffect(()=>{if(!m.current)return;const g=ls(m.current,()=>s(!0));return()=>g.destroy()},[s]),r.jsx("div",{ref:m,className:"wx-value wx-aacZ4gNU",onClick:()=>s(!0),children:r.jsx(Yv,{value:u,options:c,text:d,template:i.template,cell:i.cell,clear:i.clear,dropdown:p,autoOpen:!0,onChange:h,onAction:n})})}const bN={text:pN,combo:mN,datepicker:hN,richselect:fN,multiselect:gN};function vN({column:e,row:t}){const n=o.useContext(lr),s=dt(n,"editor"),a=o.useCallback((v,y)=>{n.exec("close-editor",{ignore:v}),y&&n.exec("focus-cell",{...y,eventSource:"click"})},[n]),i=o.useCallback(v=>{const y=v?null:{row:s?.id,column:s?.column};a(!1,y)},[s,a]),c=o.useCallback(()=>{a(!0,{row:s?.id,column:s?.column})},[s,a]),u=o.useCallback(v=>{n.exec("editor",{value:v})},[n]),d=o.useCallback(v=>{v.key==="Enter"&&s&&(e.editor.type==="multiselect"?u(s.value):c())},[s,e.editor,c,u]),p=o.useMemo(()=>Tu(e.width,e.flexgrow,e.fixed,e.left,e.right),[e.width,e.flexgrow,e.fixed,e.left,e.right]),h=o.useMemo(()=>{let v=e.editor;if(typeof v=="function"&&(v=v(t,e)),!v)return null;let y=typeof v=="string"?v:v.type;return bN[y]},[e,t]),m=o.useRef(null);o.useEffect(()=>{m.current&&typeof p=="string"&&m.current.setAttribute("style",p)},[p]);const g=typeof t.$parent<"u"?"gridcell":"cell",w=typeof t.$parent<"u"?!e.editor:void 0;return r.jsx("div",{className:"wx-8l724t2g wx-cell wx-editor",ref:m,style:typeof p=="object"&&p!==null?p:void 0,role:g,"aria-readonly":w,tabIndex:-1,onClick:v=>v.stopPropagation(),onDoubleClick:v=>v.stopPropagation(),onKeyDown:d,children:h?r.jsx(h,{editor:s,onSave:i,onApply:u,onCancel:c,onAction:({action:v,data:y})=>n.exec(v,y)}):null})}function ug(e){const{columns:t,type:n,columnStyle:s}=e,a=o.useContext(lr),{filterValues:i,_columns:c,_sizes:u}=a.getState();function d(p){return s?" "+s(p):""}return r.jsx(r.Fragment,{children:t.map((p,h)=>r.jsx("tr",{children:p.map(m=>{const g=c.find(y=>y.id===m.id),w=`wx-print-cell-${n}${d(g)}${m.filter?" wx-print-cell-filter":""}${m.vertical?" wx-vertical":""}`,v=m.cell;return r.jsx("th",{style:Dv(qv(m,u.columnWidth)),className:"wx-Gy81xq2u "+w,rowSpan:m.rowspan,colSpan:m.colspan,children:v?r.jsx(v,{api:a,cell:Object.fromEntries(Object.entries(m).filter(([y])=>y!=="cell")),column:g,row:h}):m.filter?r.jsx("div",{className:"wx-Gy81xq2u wx-print-filter",children:SA(i,c,m)}):r.jsx("div",{className:"wx-Gy81xq2u wx-text",children:m.text??""})},m.id)})},h))})}function wN(e){const{columns:t,rowStyle:n,columnStyle:s,cellStyle:a,header:i,footer:c,reorder:u}=e,d=o.useContext(lr),{flatData:p,_sizes:h}=d.getState(),m=i&&rg(t,"header",h.headerRowHeights),g=c&&rg(t,"footer",h.footerRowHeights);function w(y,k){let N="";return N+=s?" "+s(k):"",N+=a?" "+a(y,k):"",N}function v(y,k){return typeof k.draggable=="function"?k.draggable(y,k)!==!1:k.draggable}return r.jsxs("table",{className:`wx-8NTMLH0z wx-print-grid ${t.some(y=>y.flexgrow)?"wx-flex-columns":""}`,children:[i?r.jsx("thead",{children:r.jsx(ug,{columns:m,type:"header",columnStyle:s})}):null,r.jsx("tbody",{children:p.map((y,k)=>r.jsx("tr",{className:"wx-8NTMLH0z wx-row"+(n?" "+n(y):""),style:{height:`${y.rowHeight||h.rowHeight}px`},children:t.map(N=>N.collapsed?null:r.jsxs("td",{className:`wx-8NTMLH0z wx-print-cell wx-cell ${w(y,N)}`,style:Dv(qv(N,h.columnWidth)),children:[u&&N.draggable?r.jsx("span",{className:"wx-8NTMLH0z wx-print-draggable",children:v(y,N)?r.jsx("i",{className:"wx-8NTMLH0z wxi-drag"}):null}):null,N.treetoggle?r.jsxs(r.Fragment,{children:[r.jsx("span",{style:{marginLeft:y.$level*28+"px"}}),y.$count?r.jsx("i",{className:`wx-8NTMLH0z wx-print-grid-tree-toggle wxi-menu-${y.open!==!1?"down":"right"}`}):null]}):null,N.cell?(()=>{const C=N.cell;return r.jsx(C,{api:d,row:y,column:N})})():r.jsx("span",{children:Js(y,N)})]},N.id))},k))}),c?r.jsx("tfoot",{children:r.jsx(ug,{columns:g,type:"footer",columnStyle:s})}):null]})}function yN(e){const{config:t,...n}=e,s=o.useContext(lr),{_skin:a,_columns:i}=s.getState(),c=o.useMemo(()=>vA(i,t),[]),u=o.useRef(null);return o.useEffect(()=>{const d=document.body;d.classList.add("wx-print");const p=u.current;if(!p)return;const h=p.cloneNode(!0);d.appendChild(h);const m=`@media print { @page { size: ${t.paper} ${t.mode}; }`,g=document.createElement("style");g.setAttribute("type","text/css"),g.setAttribute("media","print"),document.getElementsByTagName("head")[0].appendChild(g),g.appendChild(document.createTextNode(m)),window.print(),g.remove(),d.classList.remove("wx-print"),h.remove()},[]),r.jsx("div",{className:`wx-4zwCKA7C wx-${a}-theme wx-print-container`,ref:u,children:c.map((d,p)=>r.jsx("div",{className:"wx-4zwCKA7C wx-print-grid-wrapper",children:r.jsx(wN,{columns:d,...n})},p))})}function xN(e){const{header:t,footer:n,overlay:s,multiselect:a,onreorder:i,rowStyle:c,columnStyle:u,cellStyle:d,autoRowHeight:p,resize:h,clientWidth:m,clientHeight:g,responsiveLevel:w,hotkeys:v}=e,y=o.useContext(lr),k=dt(y,"dynamic"),N=dt(y,"_columns"),C=dt(y,"flatData"),A=dt(y,"split"),E=dt(y,"_sizes"),[I,F]=xr(y,"selectedRows"),M=dt(y,"select"),H=dt(y,"editor"),V=dt(y,"scrollLeft"),P=dt(y,"scrollTop"),D=dt(y,"tree"),O=dt(y,"focusCell"),X=dt(y,"_print"),G=dt(y,"undo"),U=dt(y,"reorder"),ie=dt(y,"_rowHeightFromData"),[j,re]=o.useState(0);o.useEffect(()=>{re(Ye())},[]);const[de,Q]=o.useState(0),ge=o.useMemo(()=>(N||[]).some(Z=>!Z.hidden&&Z.flexgrow),[N]),oe=o.useMemo(()=>E?.rowHeight||0,[E]),me=o.useRef(null),[Ae,Te]=o.useState(null),[Pe,Se]=o.useState(null),te=o.useMemo(()=>{let Z=[],be=0;return A&&A.left&&(Z=(N||[]).slice(0,A.left).filter(We=>!We.hidden).map(We=>({...We})),Z.forEach(We=>{We.fixed={left:1,leftSize:A.left},We.left=be,be+=We.width}),Z.length&&(Z[Z.length-1].fixed.left=-1)),{columns:Z,width:be}},[A,N]),Ce=o.useMemo(()=>{let Z=[],be=0;if(A&&A.right){Z=(N||[]).slice(A.right*-1).filter(We=>!We.hidden).map(We=>({...We}));for(let We=Z.length-1;We>=0;We--){const lt=Z[We];lt.fixed={right:1},lt.right=be,be+=lt.width}Z.length&&(Z[0].fixed={right:-1})}return{columns:Z,width:be}},[A,N]),Fe=o.useMemo(()=>{const Z=(N||[]).slice(A?.left||0,(N||[]).length-(A?.right??0)).filter(be=>!be.hidden);return Z.forEach(be=>{be.fixed=0}),Z},[N,A]),Le=o.useMemo(()=>(N||[]).reduce((Z,be)=>(be.hidden||(Z+=be.width),Z),0),[N]),Ue=1;function ne(Z,be,We){let lt=be,It=Z;if(Fe.length){let At=Fe.length;for(let et=Z;et>=0;et--)Fe[et][We].forEach(Mt=>{Mt.colspan>1&&et>Z-Mt.colspan&&et<At&&(At=et)});if(At!==Fe.length&&At<Z){for(let et=At;et<Z;et++)lt-=Fe[et].width;It=At}}return{index:It,delta:lt}}const ae=o.useMemo(()=>{let Z,be,We;const lt=V||0,It=(V||0)+(m||0);let At=0,et=0,Mt=0,Cn=0;Fe.forEach((jt,tn)=>{lt>Mt&&(At=tn,Cn=Mt),Mt=Mt+jt.width,It>Mt&&(et=tn+Ue)});const zt={header:0,footer:0};for(let jt=et;jt>=At;jt--)["header","footer"].forEach(tn=>{Fe[jt]&&Fe[jt][tn].forEach(us=>{const Ps=us.colspan;if(Ps&&Ps>1){const Bt=Ps-(et-jt+1);Bt>0&&(zt[tn]=Math.max(zt[tn],Bt))}})});const kn=ne(At,Cn,"header"),Nt=ne(At,Cn,"footer"),cn=kn.delta,ht=kn.index,we=Nt.delta,Ot=Nt.index;return ge&&Le>(m||0)?Z=be=We=[...te.columns,...Fe,...Ce.columns]:(Z=[...te.columns,...Fe.slice(At,et+1),...Ce.columns],be=[...te.columns,...Fe.slice(ht,et+zt.header+1),...Ce.columns],We=[...te.columns,...Fe.slice(Ot,et+zt.footer+1),...Ce.columns]),{data:Z||[],header:be||[],footer:We||[],d:Cn,df:we,dh:cn}},[Fe,te,Ce,V,m,ge,Le]),le=o.useMemo(()=>t&&E?.headerHeight||0,[t,E]),ce=o.useMemo(()=>n&&E?.footerHeight||0,[n,E]),J=o.useMemo(()=>m&&g?Le>=m:!1,[m,g,Le]),[ye,ue]=o.useState(!1),Ee=o.useMemo(()=>(g||0)-le-ce-(J?j:0),[g,le,ce,J,j]),nt=o.useMemo(()=>Math.ceil((Ee||0)/(oe||1))+1,[Ee,oe]),T=o.useRef([]),[ve,De]=o.useState(0),[qe,_e]=o.useState(void 0),$e=o.useMemo(()=>{let Z=0,be=0;const We=2,lt=P||0;if(p){let et=lt;for(;et>0;)et-=T.current[Z]||oe,Z++;be=lt-et;for(let Mt=Math.max(0,Z-We-1);Mt<Z;Mt++)be-=T.current[Z-Mt]||oe;Z=Math.max(0,Z-We)}else{if(ie){let et=0,Mt=0;for(let Nt=0;Nt<(C||[]).length;Nt++){const cn=C[Nt].rowHeight||oe;if(Mt+cn>lt){et=Nt;break}Mt+=cn}Z=Math.max(0,et-We);for(let Nt=0;Nt<Z;Nt++)be+=C[Nt].rowHeight||oe;let Cn=0,zt=0;for(let Nt=et+1;Nt<(C||[]).length;Nt++){const cn=C[Nt].rowHeight||oe;if(Cn++,zt+cn>Ee)break;zt+=cn}const kn=Math.min(k?k.rowCount:(C||[]).length,et+Cn+We);return{d:be,start:Z,end:kn}}Z=Math.floor(lt/(oe||1)),Z=Math.max(0,Z-We),be=Z*(oe||0)}const It=k?k.rowCount:(C||[]).length,At=Math.min(It,Z+(nt||0)+We);return{d:be,start:Z,end:At}},[p,ie,P,oe,k,C,nt,Ee]),mt=o.useMemo(()=>{const Z=k?k.rowCount:(C||[]).length;if(p)return ve+$e.d+(Z-(qe||0))*(oe||0);if(!ie)return Z*(oe||0);let be=0;for(let We=0;We<Z;We++)be+=C[We]?.rowHeight||oe;return be},[k,C,oe,p,ie,ve,$e.d,qe]),ct=o.useRef({});ct.current={clientWidth:m,clientHeight:g,fullHeight:mt,headerHeight:le,footerHeight:ce,fullWidth:Le,SCROLLSIZE:j};const z=o.useCallback(()=>{const Z=ct.current;ue(Z.clientWidth&&Z.clientHeight?Z.fullHeight+Z.headerHeight+Z.footerHeight>=Z.clientHeight-(Z.fullWidth>=Z.clientWidth?Z.SCROLLSIZE:0):!1)},[]);o.useEffect(()=>{const Z=requestAnimationFrame(z);return()=>window.cancelAnimationFrame(Z)},[de,z]),o.useEffect(()=>{z()},[g,z]);const pe=o.useMemo(()=>ge&&Le<=(m||0)?(m||0)-0-(ye?j:0):Le,[ge,Le,m,ye,j,J]),Y=o.useMemo(()=>ge&&Le<=(m||0)?m||0:pe<(m||0)?Le+(ye?j:0):-1,[ge,Le,m,pe,ye,j]),K=o.useRef({});o.useEffect(()=>{if(k&&(K.current.start!==$e.start||K.current.end!==$e.end)){const{start:Z,end:be}=$e;K.current={start:Z,end:be},y&&y.exec&&y.exec("request-data",{row:{start:Z,end:be}})}},[k,$e,y]);const ee=o.useMemo(()=>k?C||[]:(C||[]).slice($e.start,$e.end),[k,C,$e]),R=o.useMemo(()=>(I||[]).filter(Z=>(ee||[]).some(be=>be.id===Z)),[F,ee]),se=o.useMemo(()=>$e.start,[$e.start]),Ie=o.useRef({top:P,left:V});Ie.current={top:P,left:V};const He=o.useCallback(Z=>{const be=Z.target.scrollTop,We=Z.target.scrollLeft,lt=Ie.current;(be!==lt.top||We!==lt.left)&&y.exec("scroll-to",{top:be,left:We})},[y]),Be=o.useCallback(Z=>{Z.shiftKey&&Z.preventDefault(),me.current&&me.current.focus&&me.current.focus()},[]),xe=o.useCallback(()=>!!(N||[]).find(Z=>!!Z.draggable),[N]),Ge=o.useRef(null),rt=o.useRef(null),Ke=o.useRef({dblclick:(Z,be)=>{const We={id:Z,column:oc(be,"data-col-id")};y.exec("open-editor",We)},click:(Z,be)=>{if(be.target.closest("input")||Ge.current)return;const We=oc(be,"data-col-id");if(O?.id!==Z&&y.exec("focus-cell",{row:Z,column:We,eventSource:"click"}),M===!1)return;const lt=a&&(be.ctrlKey||be.metaKey),It=a&&be.shiftKey;(lt||I.length>1||!I.includes(Z))&&y.exec("select-row",{id:Z,toggle:lt,range:It})},"toggle-row":Z=>{const be=y.getRow(Z);y.exec(be.open!==!1?"close-row":"open-row",{id:Z})},"ignore-click":()=>!1}),gt=o.useMemo(()=>({top:le,bottom:ce,left:te.width,xScroll:J,yScroll:ye,sense:p&&Pe?Pe.offsetHeight:Math.max(E?.rowHeight||0,40),node:me.current&&me.current.firstElementChild}),[le,ce,te.width,J,ye,p,Pe,E]);function _(Z,be){const{container:We,sourceNode:lt,from:It}=be;if(xe()&&!lt.getAttribute("draggable-data"))return!1;Te(It),D&&y.getRow(It).open&&y.exec("close-row",{id:It,nested:!0});const At=ro(lt),et=At.cloneNode(!0);et.classList.remove("wx-selected"),et.querySelectorAll("[tabindex]").forEach(kn=>kn.setAttribute("tabindex","-1")),We.appendChild(et),Se(et);const Mt=(V||0)-ae.d,Cn=ye?j:0;We.style.width=Math.min((m||0)-Cn,ge&&Le<=(m||0)?pe:pe-Cn)+Mt+"px";const zt=Jl(At);be.offset={x:Mt,y:-Math.round(zt.height/2)},rt.current||(rt.current=Z.clientY)}function je(Z,be){const{from:We}=be,lt=be.pos,It=Jl(me.current);lt.x=It.x;const At=gt.top;if(lt.y<At)lt.y=At;else{const et=It.height-(J&&j>0?j:Math.round(gt.sense/2))-gt.bottom;lt.y>et&&(lt.y=et)}if(me.current.contains(be.targetNode)){const et=ro(be.targetNode),Mt=et&&Mu(et);if(Mt&&Mt!==We){be.to=Mt;const Cn=p?Pe?.offsetHeight:E?.rowHeight;if(Pe&&((P||0)===0||lt.y>At+Cn-1)){const zt=et.getBoundingClientRect(),kn=Jl(Pe).y,Nt=zt.y,cn=kn>Nt?-1:1,ht=cn===1?"after":"before",we=y.getState().flatData,Ot=Math.abs(we.findIndex(tn=>tn.id===We)-we.findIndex(tn=>tn.id===Mt)),jt=Ot!==1?ht==="before"?"after":"before":ht;if(Ot===1&&(cn===-1&&Z.clientY>rt.current||cn===1&&Z.clientY<rt.current))return;rt.current=Z.clientY,y.exec("move-item",{id:We,target:Mt,mode:jt,inProgress:!0})}}i&&i({event:Z,context:be})}XA(Z,It,be,gt)}function Qe(Z,be){const{from:We,to:lt}=be;y.exec("move-item",{id:We,target:lt,inProgress:!1}),Ge.current=setTimeout(()=>{Ge.current=0},1),Te(null),Se(null),rt.current=null,Gv(be)}function Ye(){const Z=document.createElement("div");Z.style.cssText="position:absolute;left:-1000px;width:100px;padding:0px;margin:0px;min-height:100px;overflow-y:scroll;",document.body.appendChild(Z);const be=Z.offsetWidth-Z.clientWidth;return document.body.removeChild(Z),be}const Gt=o.useMemo(()=>Y>0?{width:`${Y}px`}:void 0,[Y]),en=o.useRef(null);function zn(){Promise.resolve().then(()=>{let Z=0,be=se;const We=en.current;We&&(Array.from(We.children).forEach((lt,It)=>{T.current[se+It]=lt.offsetHeight,Z+=lt.offsetHeight,be++}),De(Z),_e(be))})}o.useEffect(()=>{ee&&p&&zn()},[ee,p,se]);let[on,Sr]=o.useState();o.useEffect(()=>{if(O&&(!M||!R.length||R.includes(O.row)))Sr({...O});else if(ee.length&&ae.data.length){if(!on||R.length&&!R.includes(on.row)||ee.findIndex(Z=>Z.id===on.row)===-1||ae.data.findIndex(Z=>Z.id===on.column&&!Z.collapsed)===-1){const Z=R[0]||ee[0].id,be=ae.data.findIndex(We=>!We.collapsed);Sr(be!==-1?{row:Z,column:ae.data[be].id}:null)}}else Sr(null)},[O]);const qn=o.useRef(null);o.useEffect(()=>{const Z=me.current;if(!Z)return;const be=VA(Z,h);return()=>{typeof be=="function"&&be()}},[h]);const Fn=o.useRef({});Object.assign(Fn.current,{start:_,move:je,end:Qe,getReorder:()=>U,getDraggableInfo:()=>({hasDraggable:xe()})}),o.useEffect(()=>{const Z=me.current;return Z?KA(Z,Fn).destroy:void 0},[U,me.current]),o.useEffect(()=>{const Z=me.current;return Z?qA(Z,{keys:v!==!1&&{...zA,"ctrl+z":G,"ctrl+y":G,...v},exec:be=>y.exec("hotkey",be)}).destroy:void 0},[y,G,v]);const Sn=o.useRef({scroll:y.getReactiveState().scroll,scrollLeft:y.getReactiveState().scrollLeft,scrollTop:y.getReactiveState().scrollTop});Sn.current.getWidth=()=>(m||0)-(ye?j:0),Sn.current.getHeight=()=>Ee,Sn.current.getScrollMargin=()=>te.width+Ce.width,o.useEffect(()=>{UA(qn.current,Sn.current)},[]);const nr=o.useRef(null);o.useEffect(()=>{const Z=nr.current;if(!Z)return;const be=[];be.push(ls(Z,()=>O&&y.exec("focus-cell",{eventSource:"click"})).destroy),be.push(KM(Z,Ke.current)),Q(Z.clientHeight);const We=new ResizeObserver(()=>{Q(Z.clientHeight)});return We.observe(Z),be.push(()=>We.disconnect()),()=>be.forEach(lt=>lt())},[]);const bt=`wx-grid ${w?`wx-responsive-${w}`:""}`;return o.useEffect(()=>{O&&(ee.some(Z=>Z.id===O.row)&&ae.data.some(Z=>Z.id===O.column&&!Z.collapsed)||y.exec("focus-cell",{eventSource:"destroy"}))},[O,ee,ae.data,y]),r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"wx-4VuBwK2D "+bt,style:{"--header-height":`${le}px`,"--footer-height":`${ce}px`,"--split-left-width":`${te.width}px`,"--split-right-width":`${Ce.width}px`},children:r.jsx("div",{ref:me,className:"wx-4VuBwK2D wx-table-box",style:Gt,role:D?"treegrid":"grid","aria-colcount":ae.data.length,"aria-rowcount":ee.length,"aria-multiselectable":D&&a?!0:void 0,tabIndex:-1,children:r.jsxs("div",{ref:qn,className:"wx-4VuBwK2D wx-scroll",style:{overflowX:J?"scroll":"hidden",overflowY:ye?"scroll":"hidden"},onScroll:He,children:[t?r.jsx("div",{className:"wx-4VuBwK2D wx-header-wrapper",children:r.jsx(lg,{contentWidth:pe,deltaLeft:ae.dh,columns:ae.header,columnStyle:u,bodyHeight:Ee-+n})}):null,r.jsxs("div",{ref:nr,className:"wx-4VuBwK2D wx-body",style:{width:`${pe}px`,height:`${mt}px`},onMouseDown:Z=>Be(Z),children:[s?r.jsx(dN,{overlay:s}):null,r.jsx("div",{ref:en,className:"wx-4VuBwK2D wx-data",style:{paddingTop:`${$e.d}px`,paddingLeft:`${ae.d}px`},children:ee.map((Z,be)=>{const We=I.indexOf(Z.id)!==-1,lt=Ae===Z.id,It="wx-row"+(p?" wx-autoheight":"")+(c?" "+c(Z):"")+(We?" wx-selected":"")+(lt?" wx-inactive":""),At=p?{minHeight:`${Z.rowHeight||oe}px`}:{height:`${Z.rowHeight||oe}px`};return r.jsx("div",{className:"wx-4VuBwK2D "+It,"data-id":mn(Z.id),"data-context-id":mn(Z.id),style:At,role:"row","aria-rowindex":be,"aria-expanded":Z.open,"aria-level":D?Z.$level+1:void 0,"aria-selected":D?We:void 0,tabIndex:-1,children:ae.data.map(et=>et.collapsed?r.jsx("div",{className:"wx-4VuBwK2D wx-cell wx-collapsed"},et.id):H?.id===Z.id&&H.column===et.id?r.jsx(vN,{row:Z,column:et},et.id):r.jsx(nN,{row:Z,column:et,columnStyle:u,cellStyle:d,reorder:U,focusable:on?.row===Z.id&&on?.column===et.id},et.id))},Z.id)})})]}),n&&(C||[]).length?r.jsx(lg,{type:"footer",contentWidth:pe,deltaLeft:ae.df,columns:ae.footer,columnStyle:u}):null]})})}),X?r.jsx(yN,{config:X,rowStyle:c,columnStyle:u,cellStyle:d,header:t,footer:n,reorder:U}):null]})}const SN=e=>e.split("-").map(t=>t?t.charAt(0).toUpperCase()+t.slice(1):"").join(""),CN=o.forwardRef(function({data:e=[],columns:t=[],rowStyle:n=null,columnStyle:s=null,cellStyle:a=null,selectedRows:i,select:c=!0,multiselect:u=!1,header:d=!0,footer:p=!1,dynamic:h=null,overlay:m=null,reorder:g=!1,onReorder:w=null,autoRowHeight:v=!1,sizes:y,split:k,tree:N=!1,autoConfig:C=!1,init:A=null,responsive:E=null,sortMarks:I,undo:F=!1,hotkeys:M=null,filterValues:H,...V},P){const D=o.useRef();D.current=V;const O=o.useMemo(()=>new _A(Lv),[]),X=o.useMemo(()=>O.in,[O]),G=o.useRef(null);G.current===null&&(G.current=new Pv((Ce,Fe)=>{const Le="on"+SN(Ce);D.current&&D.current[Le]&&D.current[Le](Fe)}),X.setNext(G.current));const U=o.useMemo(()=>({getState:O.getState.bind(O),getReactiveState:O.getReactive.bind(O),getStores:()=>({data:O}),exec:X.exec,setNext:Ce=>(G.current=G.current.setNext(Ce),G.current),intercept:X.intercept.bind(X),on:X.on.bind(X),detach:X.detach.bind(X),getRow:O.getRow.bind(O),getColumn:O.getColumn.bind(O)}),[O,X]),[ie,j]=o.useState(0),[re,de]=o.useState(0),[Q,ge]=o.useState(null),[oe,me]=o.useState(null),Ae=o.useMemo(()=>{if(C&&!t.length&&e.length){const Ce=e[0],Fe=[];for(let Le in Ce)if(Le!=="id"&&Le[0]!=="$"){let Ue={id:Le,header:Le[0].toUpperCase()+Le.slice(1)};typeof C=="object"&&(Ue={...Ue,...C}),Fe.push(Ue)}return Fe}return(oe&&oe.columns)??t},[C,t,e,oe]),Te=o.useMemo(()=>(oe&&oe.sizes)??y,[oe,y]),Pe=o.useCallback(Ce=>{if(j(Ce.width),de(Ce.height),E){const Fe=Object.keys(E).map(Number).sort((Le,Ue)=>Le-Ue).find(Le=>Ce.width<=Le)??null;Fe!==Q&&(me(E[Fe]),ge(Fe))}},[E,Q]),Se=o.useContext(fn.theme),te=o.useRef(0);return o.useEffect(()=>{if(!te.current)A&&A(U);else{const Ce=O.getState();O.init({data:e,columns:Ae,split:k||Ce.split,sizes:Te||Ce.sizes,selectedRows:i||Ce.selectedRows,dynamic:h,tree:N,sortMarks:I||Ce.sortMarks,filterValues:H||Ce.filterValues,undo:F,reorder:g,_skin:Se,_select:c})}te.current++},[O,e,Ae,k,Te,i,h,N,I,H,F,g,Se,c,A,U]),te.current===0&&O.init({data:e,columns:Ae,split:k||{left:0},sizes:Te||{},selectedRows:i||[],dynamic:h,tree:N,sortMarks:I||{},filterValues:H||{},undo:F,reorder:g,_skin:Se,select:c}),o.useImperativeHandle(P,()=>({...U}),[U]),r.jsx(lr.Provider,{value:U,children:r.jsx(nm,{words:rm,optional:!0,children:r.jsx(xN,{header:d,footer:p,overlay:m,rowStyle:n,columnStyle:s,cellStyle:a,onReorder:w,multiselect:u,autoRowHeight:v,clientWidth:ie,clientHeight:re,responsiveLevel:Q,resize:Pe,hotkeys:M})})})});Qp(tr);const hn=o.createContext(null),im=o.createContext(null),om=o.createContext(null);function kN({children:e}){const t=o.useContext(fn.i18n),n=o.useMemo(()=>t.getGroup("filemanager"),[t]),s=o.useContext(hn),[a]=xr(s,"panels"),i=dt(s,"activePanel"),c=a[i].path,[u,d]=o.useState(null),[p,h]=o.useState(null),[m,g]=o.useState(""),[w,v]=o.useState(""),[y,k]=o.useState(!1);function N(){const I=m.trim();if(!I){k(!0);return}u.add?s.exec("create-file",{file:{...u.item,name:I},parent:c}):w!==I&&s.exec("rename-file",{id:u.item.id,name:I}),C()}function C(){d(null),k(null),v(""),g("")}function A(){s.exec("delete-files",{ids:p.selected}),h(null)}const E=o.useMemo(()=>({showPrompt(I){const F=I.item.name||(I.item.type==="folder"?n("New folder"):`${n("New file")}.txt`);v(F),g(F),d({...I})},showConfirm(I){h({...I})}}),[n]);return r.jsxs(im.Provider,{value:E,children:[r.jsx(kM,{children:e}),u?r.jsx(Np,{title:n(`Enter ${u.item.type} name`),onConfirm:N,onCancel:C,children:r.jsx(em,{error:y,select:!0,focus:!0,value:m,onChange:({value:I})=>g(I)})}):null,p?r.jsx(Np,{title:n("Are you sure you want to delete these items:"),onConfirm:A,onCancel:()=>h(null),children:p.selected?r.jsx("ul",{className:"wx-gq7BMzEP wx-list",children:p.selected.map((I,F)=>r.jsx("li",{children:I},F))}):null}):null]})}let dg={"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 MN(e){const t=e.lastIndexOf("."),n=t>0&&t<e.length-1?Math.min(10,e.length-t):Math.min(5,e.length),s=e.slice(0,-n),a=e.slice(-n);return[s,a]}function AN({item:e}){const t=o.useContext(hn),n=o.useContext(fn.i18n).getGroup("filemanager"),s=o.useContext(hn).templates,[a]=xr(t,"panels"),i=dt(t,"activePanel"),c=dt(t,"mode"),u=a[i].selected,d=o.useMemo(()=>s.preview(e,214,163),[s,e]),p=o.useMemo(()=>s.icon(e,"big"),[s,e]),[h,m]=o.useMemo(()=>MN(e.name),[e.name]);return r.jsx(r.Fragment,{children:e.id==="/wx-filemanager-parent-link"?c!=="search"?r.jsx("div",{className:"wx-GAOa4kDV wx-back-item",children:r.jsxs("div",{className:`wx-GAOa4kDV wx-back ${e.navigation?"wx-selected":""}`,"data-id":mn("/wx-filemanager-parent-link"),children:[r.jsx("i",{className:"wx-GAOa4kDV wxi-arrow-left"}),r.jsx("span",{children:n("Back to parent folder")})]})}):null:r.jsxs("div",{className:`wx-GAOa4kDV wx-item ${u?.length&&u.indexOf(e.id)>=0?"wx-selected":""}`,"data-id":mn(e.id),children:[d?r.jsx("div",{className:"wx-GAOa4kDV wx-preview wx-file-preview",children:r.jsx("img",{className:"wx-GAOa4kDV wx-card-preview",alt:n("A miniature file preview"),src:d})}):p?r.jsx("div",{className:"wx-GAOa4kDV wx-preview wx-file-icon",children:r.jsx("img",{className:"wx-GAOa4kDV wx-card-preview",alt:"",src:p})}):r.jsx("div",{className:"wx-GAOa4kDV wx-preview",children:r.jsx("i",{className:`wx-GAOa4kDV wxi-${e.type}`})}),e.type==="folder"?r.jsxs("div",{className:"wx-GAOa4kDV wx-info",children:[r.jsxs("div",{className:"wx-GAOa4kDV wx-folder-name",children:[r.jsx("span",{className:"wx-GAOa4kDV wx-type",children:n("Folder")}),r.jsxs("span",{className:"wx-GAOa4kDV wx-name",children:[r.jsx("span",{children:h}),r.jsx("span",{children:m})]})]}),r.jsx("div",{"data-action-id":mn(e.id),className:"wx-GAOa4kDV wx-more",children:r.jsx("i",{className:"wx-GAOa4kDV wxi-dots-v"})})]}):r.jsxs("div",{className:"wx-GAOa4kDV wx-info",children:[r.jsx("div",{className:"wx-GAOa4kDV wx-file-name",children:r.jsxs("span",{className:"wx-GAOa4kDV wx-name",children:[r.jsx("span",{children:h}),r.jsx("span",{children:m})]})}),r.jsx("div",{"data-action-id":mn(e.id),className:"wx-GAOa4kDV wx-more",children:r.jsx("i",{className:"wx-GAOa4kDV wxi-dots-v"})})]})]})})}function Xv(){const e=o.useContext(hn),t=o.useContext(fn.i18n),n=o.useMemo(()=>t.getGroup("filemanager"),[t]),[s]=xr(e,"panels"),a=dt(e,"activePanel"),i=dt(e,"mode"),c=s[a]._files,u=s[a].selected,d=s[a].path,p=s[a]._crumbs,h=s[a]._selectNavigation,m=o.useCallback((C,A)=>{const E=A&&(A.ctrlKey||A.metaKey),I=A&&A.shiftKey;if(C==="/wx-filemanager-parent-link"){if(u.length&&(E||I))return;e.exec("select-file",{type:"navigation"});return}let F=C==="body"&&A?null:C;const M=A.target.className.indexOf("wx-more")!==-1||A.target.className.indexOf("wxi-dots-v")!==-1;setTimeout(()=>{e.exec("select-file",{id:F,toggle:E&&!M,range:I&&!M,panel:a})},1)},[e,u,a]),g=o.useCallback(()=>{p.length>1&&e.exec("set-path",{id:p[p.length-2].id,panel:a,selected:[p[p.length-1].id]})},[e,p,a]),w=o.useCallback(C=>{if(C==="/wx-filemanager-parent-link")return g();i==="search"&&e.exec("filter-files",{text:""});const A=c.find(E=>E.id===C);A&&(A.type=="folder"?e.exec("set-path",{id:A.id,panel:a}):e.exec("open-file",{id:A.id}))},[e,g,i,c,a]),v=o.useCallback((C,A)=>{(!u?.length||!u.filter(E=>E?.id===C).length>0)&&m(C,A)},[u,m]),y=o.useMemo(()=>d!=="/"?[{id:"/wx-filemanager-parent-link",name:n("Back to parent folder"),navigation:h},...c]:c,[d,n,h,c]),k=o.useRef(null),N=o.useRef();return o.useEffect(()=>{k.current&&(N.current?(N.current.click=m,N.current._dblclick=w,N.current.context=v):(N.current={click:m,dblclick:C=>N.current._dblclick(C),_dblclick:w,context:v},so(k.current,N.current)))},[m,w,v]),i=="search"&&!y.length?r.jsx("div",{className:"wx-iyjASZCY wx-not-found",children:r.jsx("div",{className:"wx-iyjASZCY wx-not-found-text",children:n("Looks like nothing is here")})}):r.jsx("div",{tabIndex:0,className:"wx-iyjASZCY "+("wx-cards"+(d!=="/"&&i!=="search"?" wx-has-back-link":"")),"data-id":mn("body"),ref:k,children:y.map(C=>r.jsx(AN,{item:C},C.id))})}function Ka({name:e="",spin:t=!1,onClick:n}){return r.jsx("i",{"data-menu-ignore":"true",className:`wx-uwcvNSAG wx-icon wxi-${e} ${t?"wx-spin":""} ${n?"wx-clickable":""}`,onClick:()=>{n&&n()}})}function NN(){const e=o.useContext(fn.i18n).getGroup("filemanager"),t=o.useContext(hn),n=dt(t,"activePanel"),[s]=xr(t,"panels"),a=o.useMemo(()=>s[n]._crumbs,[s,n]);function i(){t.exec("filter-files",{text:""})}return r.jsxs("div",{className:"wx-GDJvtROw wx-search",children:[r.jsxs("div",{className:"wx-GDJvtROw wx-toolbar",children:[r.jsx("div",{className:"wx-GDJvtROw wx-back-icon",children:r.jsx(Ka,{name:"angle-left",onClick:i})}),r.jsxs("div",{className:"wx-GDJvtROw wx-text",children:[e("Search results in")," ",Array.isArray(a)&&a.map((c,u)=>r.jsxs(o.Fragment,{children:[u?"/":null,c.id=="/"?e(c.name):c.name]},u))]})]}),r.jsx(Xv,{})]})}function Od({narrowMode:e,extraInfo:t}){const n=o.useContext(hn),{preview:s,icon:a}=n.templates,i=o.useContext(fn.i18n),c=o.useMemo(()=>i.getGroup("filemanager"),[i]),u=o.useMemo(()=>Zi("%D, %d %F %Y, %H:%i",i.getRaw().calendar),[i]),[d,p]=xr(n,"panels"),h=dt(n,"activePanel"),m=dt(n,"preview"),g=dt(n,"search"),w=o.useMemo(()=>{const M=d&&h!=null&&d[h]?._selected?.length||0;return g&&!M},[g,p,h]),v=o.useMemo(()=>{const M=d&&h!=null?d[h]:null;return M?w?M._files:M._selected:[]},[w,p,h]),y=o.useCallback((M,H)=>(M?`${M} ${c(M>1?"folders":"folder")} `:"")+(H?`${H} ${c(H>1?"files":"file")}`:""),[c]),k=o.useCallback(()=>{n.exec("show-preview",{mode:!m})},[n,m]),N=o.useCallback(M=>M.type==="folder"?c("Folder"):M.ext||c("Unknown file"),[c]),C=o.useMemo(()=>{let M,H,V,P,D,O,X,G;if(v.length===1&&!w){H=v[0],M=H.name;const U=s(H,400,500);U?(V=U,P=""):(P=a(H,"big"),V=""),D=H.type!=="folder"}else{if(H=D=null,M="",v.length){let U=0,ie=0,j=0,re=[],de;v.forEach(ge=>{typeof ge.size>"u"&&(de=!0,U=void 0),de||(U+=ge.size),re.push(N(ge)),ge.type==="folder"?ie++:j++});const Q=new Set(re);O=Q.size>1?c("multiple"):[...Q][0],X=y(ie,j),G=U,w||(M=c("Multiple files"))}P=a({type:w?"search":v.length?"multiple":"none"},"big"),V=""}return{name:M,item:H,previewSrc:V,iconSrc:P,showDownloadIcon:D,type:O,totalCount:X,totalSize:G}},[v,w,s,a,c,N,y]),A=o.useCallback(()=>{n.exec("download-file",{id:v[0].id})},[n,v]),E=o.useCallback(async M=>{if(!t||!M)return null;try{return await t(M)}catch(H){return console.log(H),null}},[t]),[I,F]=o.useState(null);return o.useEffect(()=>{let M=!1;return F(null),Promise.resolve(E(C.item)).then(H=>{M||F(H)}).catch(()=>{M||F(null)}),()=>{M=!0}},[E,C.item]),r.jsx("div",{className:"wx-O0BTtRrH wx-wrapper",children:v&&v.length?r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"wx-O0BTtRrH wx-preview",children:[r.jsxs("div",{className:"wx-O0BTtRrH wx-toolbar",children:[r.jsx("div",{className:"wx-O0BTtRrH wx-name",children:C.name}),r.jsxs("div",{className:"wx-O0BTtRrH wx-icons",children:[C.showDownloadIcon?r.jsx(Ka,{name:"download",onClick:A}):null,e?r.jsx(Ka,{name:"close",onClick:k}):null]})]}),C.previewSrc?r.jsx("div",{className:"wx-O0BTtRrH wx-img-wrapper",children:r.jsx("img",{src:C.previewSrc,alt:c("A miniature file preview")})}):C.iconSrc?r.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:r.jsx("img",{src:C.iconSrc,alt:c("A miniature file preview")})}):r.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:C.item?r.jsx("i",{className:`wx-O0BTtRrH wx-icon wxi-${C.item.type}`}):r.jsx("i",{className:`wx-O0BTtRrH wx-icon wxi-${w?"search":"file-multiple-outline"}`})})]}),r.jsxs("div",{className:"wx-O0BTtRrH wx-info-panel",children:[r.jsx("div",{className:"wx-O0BTtRrH wx-title",children:c(w?"Found":"Information")}),r.jsxs("div",{className:"wx-O0BTtRrH wx-list",children:[C.item?r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"wx-O0BTtRrH wx-name",children:c("Type")}),r.jsx("span",{className:"wx-O0BTtRrH wx-value",children:N(C.item)}),typeof C.item.size<"u"?r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"wx-O0BTtRrH wx-name",children:c("Size")}),r.jsx("span",{className:"wx-O0BTtRrH wx-value",children:cc(C.item.size)})]}):null,r.jsx("span",{className:"wx-O0BTtRrH wx-name",children:c("Date")}),r.jsxs("span",{className:"wx-O0BTtRrH wx-value",children:[u(C.item.date)," "]})]}):r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"wx-O0BTtRrH wx-name",children:c("Count")}),r.jsx("span",{className:"wx-O0BTtRrH wx-value",children:C.totalCount}),r.jsx("span",{className:"wx-O0BTtRrH wx-name",children:c("Type")}),r.jsx("span",{className:"wx-O0BTtRrH wx-value",children:C.type}),typeof C.totalSize<"u"?r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"wx-O0BTtRrH wx-name",children:c("Size")}),r.jsx("span",{className:"wx-O0BTtRrH wx-value",children:cc(C.totalSize)})]}):null]}),I?Object.entries(I).map(([M,H])=>r.jsxs(Fp.Fragment,{children:[r.jsx("span",{className:"wx-O0BTtRrH wx-name",children:M}),r.jsx("span",{className:"wx-O0BTtRrH wx-value",children:H})]},M)):null]})]})]}):r.jsxs("div",{className:"wx-O0BTtRrH wx-no-info-panel",children:[r.jsxs("div",{className:"wx-O0BTtRrH wx-toolbar",children:[r.jsx("div",{className:"wx-O0BTtRrH wx-name",children:C.name}),r.jsx("div",{className:"wx-O0BTtRrH wx-icons",children:e?r.jsx(Ka,{name:"close",onClick:k}):null})]}),r.jsx("div",{className:"wx-O0BTtRrH wx-no-info-wrapper",children:r.jsxs("div",{className:"wx-O0BTtRrH wx-no-info",children:[C.previewSrc?r.jsx("div",{className:"wx-O0BTtRrH wx-img-wrapper",children:r.jsx("img",{src:C.previewSrc,alt:c("A miniature file preview")})}):C.iconSrc?r.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:r.jsx("img",{src:C.iconSrc,alt:c("A miniature file preview")})}):r.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:r.jsx("i",{className:`wx-O0BTtRrH wx-icon wxi-${w?"search":"message-question-outline"}`})}),r.jsx("span",{className:"wx-O0BTtRrH wx-text",children:w?"":c("Select file or folder to view details")})]})})]})})}function Jv({panel:e}){const t=o.useContext(hn),n=o.useContext(fn.i18n),s=o.useMemo(()=>n.getGroup("filemanager"),[n]),[a,i]=xr(t,"panels"),c=o.useMemo(()=>a[e]._files,[i,e]),u=o.useMemo(()=>a[e]._crumbs||[],[i,e]);function d(v){const y=sm(v,u);t.exec("set-path",{id:v,panel:e,...y&&{selected:[y]}})}const[p,h]=o.useState(null);o.useEffect(()=>{c&&h(null)},[c]);function m(){h(!0),t.exec("request-data",{id:u[u.length-1].id}),setTimeout(()=>{h(null)},5e3)}const g=o.useRef(null),w=o.useRef();return o.useEffect(()=>{w.current?w.current.click=d:(w.current={click:d},so(g.current,w.current))},[d]),r.jsxs("div",{className:"wx-SNY5LTYx wx-breadcrumbs","data-menu-ignore":"true",ref:g,children:[r.jsx("div",{className:"wx-SNY5LTYx wx-refresh-icon",children:r.jsx(Ka,{name:"refresh",spin:!!p,onClick:m})}),u.map((v,y)=>r.jsxs(Fp.Fragment,{children:[y?r.jsx(Ka,{name:"angle-right"}):null,r.jsx("div",{className:"wx-SNY5LTYx wx-item","data-id":mn(v.id),"data-menu-ignore":"true",children:v.id=="/"?s(v.name):v.name})]},y))]})}function RN({row:e}){const t=o.useContext(fn.i18n),[n]=o.useState(()=>t.getGroup("filemanager")),s=o.useContext(hn).templates,[a]=o.useState(()=>s.icon(e,"small"));return r.jsx("div",{className:"wx-qgAqG6sL wx-name-cell",children:e.id==="/wx-filemanager-parent-link"?r.jsxs(r.Fragment,{children:[r.jsx("i",{className:"wx-qgAqG6sL wxi-arrow-left"}),r.jsxs("span",{className:"wx-qgAqG6sL wx-name",children:[" ",n("Back to parent folder")]})]}):r.jsxs(r.Fragment,{children:[a?r.jsx("img",{className:"wx-qgAqG6sL wx-icon",alt:"",src:a,height:"24px",width:"24px"}):r.jsx("i",{className:`wx-qgAqG6sL wxi-${e.type}`}),r.jsxs("span",{className:"wx-qgAqG6sL wx-name",children:[" ",e.name," "]})]})})}function Zv({children:e}){const t=o.useContext(hn),n=dt(t,"activePanel"),s=o.useContext(om),a=o.useRef(null);let i=o.useRef({});return i.current.drop=()=>{const c=a.current,u=Ik(c,"data-panel");u&&u!=n&&t.exec("set-active-panel",{panel:u*1})},i.current.dragEnter=()=>{const c=a.current;c&&c.classList.toggle("wx-active")},i.current.dragLeave=()=>{const c=a.current;c&&c.classList.toggle("wx-active")},o.useEffect(()=>{const c=a.current;return s.droparea(c,i.current)},[]),r.jsx("div",{className:"wx-LT9X7tb7 wx-upload-area",ref:a,children:e})}function Pp({panel:e,active:t=!1,onClick:n,onContextMenu:s}){const a=o.useContext(hn),i=o.useContext(fn.i18n),c=o.useMemo(()=>i.getGroup("filemanager"),[i]),u=o.useMemo(()=>Zi("%d %M %Y",i.getRaw().calendar),[i]),[d]=xr(a,"panels"),p=d[e].selected,h=d[e].path,m=d[e]._crumbs,g=d[e]._sorts,w=d[e]._selectNavigation,v=d[e]._files,y=o.useMemo(()=>[{id:"name",header:c("Name"),flexgrow:3,sort:!0,resize:!0,cell:RN},{id:"size",header:c("Size"),width:100,sort:!0,resize:!0,template:O=>typeof O=="number"?cc(O):""},{id:"date",header:c("Date"),width:120,sort:!0,resize:!0,template:O=>O?u(O):""}],[c,u]),k=o.useRef(null),N=o.useRef(null),C=o.useMemo(()=>w?["/wx-filemanager-parent-link"]:[...p],[w,p]);function A(O,X){if(X&&X.target&&X.target.className&&X.target.className.indexOf("wx-grip")!==-1)return;const G=X&&(X.ctrlKey||X.metaKey),U=X&&X.shiftKey;if(O==="/wx-filemanager-parent-link"){if(p.length&&(G||U))return;a.exec("select-file",{type:"navigation"});return}let ie=O==="body"&&X?null:O;!k.current&&!N.current?a.exec("select-file",{id:ie,toggle:G,range:U,panel:e}):(k.current=null,N.current=null)}function E(){m.length>1&&a.exec("set-path",{id:m[m.length-2].id,panel:e,selected:[m[m.length-1].id]})}function I(O){if(O==="/wx-filemanager-parent-link")return E();const X=v.find(G=>G.id===O);X&&(X.type==="folder"?a.exec("set-path",{id:X.id,panel:e}):a.exec("open-file",{id:X.id}))}function F(O){const X=O.key,G=g[h];let U=G?"asc":"desc";G&&G.key===X&&(U=G.order==="asc"?"desc":"asc"),a.exec("sort-files",{key:X,order:U,panel:e,path:h})}function M(O){O.intercept("sort-rows",X=>(k.current=!0,F(X),!1)),O.intercept("select-row",()=>!1),O.on("resize-column",()=>N.current=!0),O.intercept("hotkey",()=>!1)}const H=o.useMemo(()=>h!=="/"?[{id:"/wx-filemanager-parent-link",name:c("Back to parent folder")},...v]:v,[h,v,c]),V=o.useMemo(()=>{if(H&&g&&g[h]){const{key:O,order:X}=g[h];return{[O]:{order:X}}}},[H,g,h]),P=o.useRef(null),D=o.useRef();return o.useEffect(()=>{D.current?(D.current.click=A,D.current._dblclick=I):(D.current={click:A,dblclick:O=>D.current._dblclick(O),_dblclick:I},so(P.current,D.current))},[A,I]),r.jsxs("div",{onClick:n,onContextMenu:s,className:"wx-SSaVhET7 wx-wrapper",children:[r.jsx(Jv,{panel:e}),r.jsx("div",{"data-id":mn("body"),className:`wx-SSaVhET7 wx-list ${t?"wx-active":""}`,ref:P,children:r.jsx(Zv,{children:r.jsx(CN,{init:M,data:H,columns:y,selectedRows:C,columnStyle:()=>"wx-SSaVhET7 wx-each-cell",sizes:{rowHeight:42,headerHeight:42},sortMarks:V})})})]})}function TN(){const e=o.useContext(hn),t=dt(e,"activePanel");function n(s){e.exec("set-active-panel",{panel:s})}return r.jsxs("div",{className:"wx-L55BfJa2 wx-panels","data-id":mn("body"),children:[r.jsx("div",{className:"wx-L55BfJa2 wx-item","data-panel":0,children:r.jsx(Pp,{panel:0,active:t==0,onClick:()=>n(0),onContextMenu:()=>n(0)})}),r.jsx("div",{className:"wx-L55BfJa2 wx-item","data-panel":1,children:r.jsx(Pp,{panel:1,active:t==1,onClick:()=>n(1),onContextMenu:()=>n(1)})})]})}function ew({folderIcon:e=!1,folder:t={}}){const n=o.useContext(hn),[s,a]=xr(n,"panels"),i=dt(n,"activePanel"),c=o.useMemo(()=>s[i].path,[a,i]),u=o.useContext(fn.i18n),d=o.useMemo(()=>u.getGroup("filemanager"),[u]),p=o.useMemo(()=>!!t.data?.find(w=>w.type==="folder"),[t]),h=o.useMemo(()=>t.id=="/"?d(t.name):t.name,[t,d]),m=o.useMemo(()=>t.$level>1?(t.$level-1)*20:0,[t]),g=t.open;return r.jsxs(r.Fragment,{children:[r.jsxs("li",{"data-id":mn(t.id),className:`wx-NYfhvGIt wx-folder${c===t.id?" wx-selected":""}`,style:{paddingLeft:`${m}px`},children:[p?r.jsx("i",{className:`wx-NYfhvGIt wx-toggle wxi-${g?"angle-down":"angle-right"}`,"data-action":"toggle"}):r.jsx("span",{className:"wx-NYfhvGIt wx-toggle-placeholder"}),r.jsx("i",{className:"wx-NYfhvGIt "+(e||"wxi-folder")}),r.jsxs("span",{className:"wx-NYfhvGIt wx-name",children:[" ",h," "]})]}),g&&t.data&&t.data.length&&p?r.jsx(r.Fragment,{children:t.data.map(w=>w.type==="folder"?r.jsx(ew,{folder:w},w.id):null)}):null]})}function PN(){const e=o.useContext(hn),[t,n]=xr(e,"data"),[s,a]=xr(e,"panels"),i=dt(e,"activePanel"),c=o.useMemo(()=>s[i]._crumbs,[a,i]),u=o.useCallback(w=>{e.exec("open-tree-folder",{id:w,mode:!t.byId(w).open})},[e,n]),d=o.useCallback(w=>{const v=sm(w,c);e.exec("set-path",{id:w,panel:i,...v&&{selected:[v]}})},[e,c,i]),[p,h]=o.useState([]);o.useEffect(()=>{h(t.byId(0).data)},[n]);const m=o.useRef(null),g=o.useRef();return o.useEffect(()=>{g.current?(g.current.click=d,g.current.toggle=u):(g.current={click:d,toggle:u},so(m.current,g.current))},[d,u]),r.jsx("ul",{ref:m,className:"wx-LyHJ6R6A",children:p.map(w=>w.type==="folder"?r.jsx(ew,{folder:w},w.id):null)})}function IN(){const e=o.useContext(hn),t=o.useContext(fn.i18n),n=o.useMemo(()=>t.getGroup("filemanager"),[t]),s=dt(e,"drive"),a=s?s.used:"",i=s?s.total:"";return a&&i?r.jsxs("div",{className:"wx-DetSyKGG wx-drive",children:[r.jsx("progress",{value:a,max:i,className:"wx-DetSyKGG wx-progress"}),r.jsxs("p",{children:[cc(a)," ",n("of")," ",cc(i)," ",n("used")]})]}):null}function jN({option:e}){const t=o.useContext(fn.i18n).getGroup("filemanager"),n=o.useContext(om),s=o.useCallback(()=>{n.open({})},[n]);return r.jsx("div",{className:"wx-9XiKcxq5 wx-upload-button",onClick:s,children:r.jsx("span",{children:t(e.text)})})}function EN({readonly:e,menuOptions:t}){const n=o.useContext(fn.i18n).getGroup("filemanager"),{showPrompt:s}=o.useContext(im);o.useEffect(()=>{XM("upload",jN)},[]);function a({action:c}){c&&(c.id==="add-file"?s({item:{type:"file",size:0,date:new Date},add:!0}):c.id==="add-folder"&&s({item:{type:"folder",date:new Date},add:!0}))}const i=o.useMemo(()=>t("add").map(c=>(c.text=n(c.text),c)),[t,n]);return r.jsxs("div",{className:"wx-FlucfALM wx-wrapper",children:[!e&&r.jsx("div",{className:"wx-FlucfALM wx-button",children:r.jsx(ZM,{options:i,at:"bottom-fit",onClick:a,children:r.jsx(ec,{type:"primary block",children:n("Add New")})})}),r.jsx("div",{className:"wx-FlucfALM wx-tree",children:r.jsx(PN,{})}),r.jsx(IN,{})]})}function FN({value:e="",onSearch:t}){const[n,s]=Fv(e),a=o.useContext(fn.i18n).getGroup("filemanager"),i=o.useRef(null),c=o.useMemo(()=>n!==""?"wxi-close":"wxi-search",[n]);function u(p){const h=p.target.value;s(h),t&&t({value:h})}function d(){s(""),i.current&&i.current.focus(),t&&t({value:""})}return r.jsxs("div",{className:"wx-lUZMtgT1 wx-search-input",children:[r.jsx("i",{className:`wx-lUZMtgT1 wx-icon ${c}`,onClick:d}),r.jsx("input",{type:"text",className:"wx-lUZMtgT1 wx-text",ref:i,value:n,onInput:u,placeholder:a("Search")})]})}function DN({narrowMode:e=!1,onShowTree:t}){const n=o.useContext(hn),s=o.useContext(fn.i18n).getGroup("filemanager"),a=dt(n,"mode"),i=dt(n,"preview"),c=dt(n,"search"),u=[{icon:"wxi-view-sequential",id:"table"},{icon:"wxi-view-grid",id:"cards"},{icon:"wxi-view-column",id:"panels"}];function d({value:m}){n.exec("set-mode",{mode:m})}function p(m){m.preventDefault(),n.exec("show-preview",{mode:!i})}function h(m){n.exec("filter-files",{text:m.value})}return r.jsxs("div",{className:"wx-5PZQQztG wx-toolbar",children:[r.jsxs("div",{className:"wx-5PZQQztG wx-left "+(e?"wx-left-narrow":""),children:[e?a==="panels"||a==="search"?null:r.jsx("div",{className:"wx-5PZQQztG wx-sidebar-icon","data-id":mn("toggle-tree"),children:r.jsx(Ka,{onClick:()=>t&&t(),name:"subtask"})}):r.jsx("div",{className:"wx-5PZQQztG wx-name",children:s("Files")}),r.jsx(FN,{onSearch:h,value:c})]}),r.jsxs("div",{className:"wx-5PZQQztG wx-right",children:[e?null:r.jsx("div",{className:"wx-5PZQQztG wx-preview-icon",children:r.jsx(MM,{onClick:p,value:i,children:r.jsx("i",{className:"wx-5PZQQztG wxi-eye"})})}),r.jsx("div",{className:"wx-5PZQQztG wx-modes",children:r.jsx(wM,{value:a,options:u,onChange:d})})]})]})}function LN(){const e=o.useContext(hn),t=dt(e,"activePanel");return r.jsxs("div",{className:"wx-NwohNJzN wx-wrapper",children:[r.jsx(Jv,{panel:t}),r.jsx(Zv,{children:r.jsx(Xv,{})})]})}function _N({readonly:e=!1,menuOptions:t,extraInfo:n}){const s=o.useRef(null),a=o.useRef(null),[i,c]=o.useState(void 0),[u,d]=o.useState(void 0),[p,h]=o.useState(!1),m=Hv(),g=o.useContext(hn),{showPrompt:w,showConfirm:v}=o.useContext(im),y=o.useContext(fn.i18n),k=o.useMemo(()=>y.getGroup("filemanager"),[y]),N=dt(g,"mode"),C=dt(g,"preview"),A=dt(g,"activePanel"),[E,I]=xr(g,"panels"),F=o.useMemo(()=>(E&&A!=null?E[A]:null)?.selected??[],[I,A]),M=o.useMemo(()=>(E&&A!=null?E[A]:null)?.path,[I,A]),[H,V]=o.useState([]);o.useEffect(()=>{const Q=s.current;if(!Q)return;const ge=new ResizeObserver(oe=>{const me=oe[0]?.borderBoxSize?.[0]?.inlineSize;typeof me=="number"&&d(me<768)});return ge.observe(Q),()=>{ge.disconnect()}},[]);const P=o.useCallback(()=>{h(Q=>!Q)},[]),D=o.useCallback(Q=>{u&&oc(Q)!=="toggle-tree"&&h(!1)},[u]);o.useEffect(()=>{const Q=a.current;if(Q)return ls(Q,D).destroy},[D]),o.useEffect(()=>{const Q=a.current;if(!Q)return;const ge=new ResizeObserver(()=>{Q&&c(Q.clientWidth)});return ge.observe(Q),Q&&c(Q.clientWidth),()=>{ge.disconnect()}},[]);const O=o.useMemo(()=>({icon:"wxi-eye",text:"Preview",id:"preview"}),[]),X=o.useCallback(Q=>{let ge=u?[O]:[];return Q==="file"&&(ge=[...ge,...t().filter(oe=>oe.id==="download")]),ge},[u,O,t]),G=o.useRef(null),U=o.useCallback((Q,ge,oe)=>{const me=oe?[ge.id]:F;switch(Q){case"download":g.exec("download-file",{id:ge.id});break;case"copy":case"move":G.current={action:Q,ids:me};break;case"paste":G.current&&g.exec(G.current.action==="copy"?"copy-files":"move-files",{ids:G.current.ids,target:ge?.type==="folder"?ge.id:M});break;case"rename":w({item:ge});break;case"delete":v({selected:me});break;case"preview":g.exec("show-preview",{mode:!C});break}},[g,F,M,w,v,C]),ie=o.useCallback(()=>E?.[A],[E,A]);o.useEffect(()=>{const Q=s.current;if(!Q)return;const ge=BM(Q,{api:g,menuOptions:e?X:t,performAction:U,getPanel:ie});return()=>{typeof ge=="function"?ge():ge&&typeof ge.destroy=="function"&&ge.destroy()}},[g,e,X,t,U,ie]);const j=o.useCallback((Q,ge)=>{const oe=Q?g.getFile(Q):null,me=ge.target.closest(".tree-item.folder");let Ae;if(e)Ae=X(oe?.type);else{switch(Q){case"body":Ae=t(Q);break;default:if(oe)if(!me&&F.length>1)Ae=u?[O,...t("multiselect")]:t("multiselect");else if(Q==="/")Ae=t("folder",oe).filter(Te=>Te.id==="paste");else{const Te=t(oe.type,oe);Te&&(Ae=u?[O,...Te]:Te)}}N==="search"&&(Ae=Ae?.filter(Te=>Te.id!=="paste"))}if(oe?.id&&(!F.length||!F.some(Te=>Te===oe.id))&&!me&&g.exec("select-file",{id:oe.id}),Ae?.length)return Ae.forEach(Te=>{me&&(Te.hotkey=""),Te.text&&(Te.text=k(Te.text)),Te.hotkey&&(Te.subtext=Te.hotkey)}),V(Ae),oe||{}},[g,e,X,t,F,u,O,N,k]),re=o.useCallback(Q=>{const{action:ge,context:oe}=Q;ge&&U(ge.id,oe,!ge.hotkey)},[U]);async function de(Q){await Promise.resolve();const{name:ge,size:oe}=Q.file;g.exec("create-file",{file:{name:ge,size:oe,date:new Date,file:Q.file},parent:M})}return r.jsx("div",{className:"wx-RJbNonjJ wx-filemanager wx-flex",ref:s,"data-menu-ignore":"false",children:u&&C?r.jsx("div",{className:"wx-RJbNonjJ wx-info-narrow",children:r.jsx(Od,{narrowMode:u,extraInfo:n})}):r.jsxs(r.Fragment,{children:[r.jsx(DN,{narrowMode:u,onShowTree:P}),r.jsx(eA,{dataKey:"id",at:"point",options:H,resolver:j,onClick:re,children:r.jsxs(Bv,{dataKey:"actionId",options:H,resolver:j,onClick:re,children:[r.jsx(aA,{data:m,apiOnly:!0,uploadURL:de}),r.jsx(om.Provider,{value:m,children:r.jsx("div",{className:"wx-RJbNonjJ wx-content-wrapper wx-flex",children:N!=="panels"&&N!=="search"?r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"wx-RJbNonjJ "+["wx-sidebar",u?"wx-sidebar-narrow":"",p?"wx-sidebar-visible":""].filter(Boolean).join(" "),ref:a,children:r.jsx(EN,{readonly:e,menuOptions:t})}),r.jsxs("div",{className:"wx-RJbNonjJ wx-content",style:{width:`calc(100% - ${i||0}px - 10px)`},children:[r.jsx("div",{className:`wx-RJbNonjJ wx-content-item${C?"":"-fit"}`,"data-id":mn("body"),children:N==="table"?r.jsx(Pp,{panel:A}):r.jsx(LN,{})}),C?r.jsx("div",{className:"wx-RJbNonjJ wx-info",children:r.jsx(Od,{extraInfo:n})}):null]})]}):r.jsxs(r.Fragment,{children:[r.jsx("div",{className:`wx-RJbNonjJ wx-content-item${C?"":"-fit"}`,children:N==="panels"?r.jsx(TN,{}):r.jsx(NN,{})}),C?r.jsx("div",{className:"wx-RJbNonjJ wx-info",children:r.jsx(Od,{extraInfo:n})}):null]})})})]})})]})})}const $N=e=>e.split("-").map(t=>t?t.charAt(0).toUpperCase()+t.slice(1):"").join("");function ON(e,t){const{type:n,ext:s}=e;if(n==="folder")return!1;let a;return n&&n!=="file"&&dg[n]?a=n:s?a=dg[s]?s:"file":a="unknown",`https://cdn.svar.dev/icons/filemanager/vivid/${t}/${a}.svg`}const BN=o.forwardRef(function(e,t){const{data:n=[],mode:s="cards",drive:a=null,preview:i=!1,panels:c=null,activePanel:u=0,readonly:d=!1,menuOptions:p=_M,extraInfo:h=null,init:m=null,icons:g=ON,previews:w=null,...v}=e,y=o.useRef();y.current=v;const k=o.useMemo(()=>new LM(Lv),[]),N=o.useMemo(()=>k.in,[k]),C=o.useRef(null);C.current===null&&(C.current=new Pv((I,F)=>{const M="on"+$N(I);y.current&&y.current[M]&&y.current[M](F)}),N.setNext(C.current));const A=o.useMemo(()=>({getState:k.getState.bind(k),getReactiveState:k.getReactive.bind(k),getStores:()=>({data:k}),exec:N.exec,setNext:I=>(C.current=C.current.setNext(I),C.current),intercept:N.intercept.bind(N),on:N.on.bind(N),detach:N.detach.bind(N),getFile:k.getFile.bind(k),serialize:k.serialize.bind(k),templates:{preview:w||(()=>null),icon:g==="simple"?(()=>null):g}}),[k,N]),E=o.useRef(0);return o.useEffect(()=>{if(!E.current)m&&m(A);else{const I=k.getState();k.init({data:n,mode:s,drive:a,preview:i,panels:c||I.panels||[],activePanel:u})}E.current++},[k,n,s,a,i,c,u,m,A]),E.current===0&&k.init({data:n,mode:s,drive:a,preview:i,panels:c||[],activePanel:u}),o.useImperativeHandle(t,()=>({...A}),[A]),r.jsx(hn.Provider,{value:A,children:r.jsx(nm,{words:rm,optional:!0,children:r.jsx(kN,{children:r.jsx(_N,{readonly:d,menuOptions:p,extraInfo:h})})})})});function HN({fonts:e=!0,children:t}){return t?r.jsx(Yf,{fonts:e,children:t}):r.jsx(Yf,{fonts:e})}Qp(tr);function cm(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Invalid Hub ${t} response.`);return e}function mc(e,t,n){const s=cm(e,n);if(!Array.isArray(s[t]))throw new Error(`Invalid Hub ${n} response: ${t} must be an array.`);return s[t]}function WN(e,t,n){const s=cm(e,n);if(!s[t]||typeof s[t]!="object"||Array.isArray(s[t]))throw new Error(`Invalid Hub ${n} response: ${t} must be an object.`);return s[t]}async function zN(e,t=!1){return mc(await Oe(`/api/remote/filesystem/roots${t?"?refresh=1":""}`,void 0,e),"roots","filesystem roots")}async function Bd(e,t){const n=await Oe(`/api/remote/filesystem/entries?id=${encodeURIComponent(e)}`,void 0,t);return{folder:WN(n,"folder","filesystem entries"),entries:mc(n,"entries","filesystem entries")}}async function qN(e,t){return Oe("/api/remote/filesystem/selection/scan",{method:"POST",body:JSON.stringify({itemIds:e})},t)}async function UN(e,t,n,s){return Oe("/api/remote/files/from-hub",{method:"POST",body:JSON.stringify({itemIds:e,deviceIds:t,remoteDirectory:n})},s)}async function VN(e,t=!1){const n=await Oe(`/api/remote/files/jobs?active=${t?"1":"0"}`,void 0,e);return{jobs:mc(n,"jobs","file transfer jobs")}}async function GN(e,t){return Oe(`/api/remote/files/jobs/${encodeURIComponent(e)}`,void 0,t)}async function KN(e,t){return Oe(`/api/remote/files/jobs/${encodeURIComponent(e)}/cancel`,{method:"POST"},t)}async function pg(e){return mc(await Oe("/api/remote/filesystem/shared-folders",void 0,e),"folders","shared folders")}async function QN(e,t){return Oe("/api/remote/filesystem/shared-folders",{method:"POST",body:JSON.stringify({sourceId:e})},t)}async function YN(e,t,n){return Oe(`/api/remote/filesystem/shared-folders/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)},n)}async function XN(e,t){return Oe(`/api/remote/filesystem/shared-folders/${encodeURIComponent(e)}`,{method:"DELETE"},t)}async function JN(e,t,n,s){const a=await Oe(`/api/remote/filesystem/shared-folders/${encodeURIComponent(e)}/sync`,{method:"POST",body:JSON.stringify({deviceIds:t,remoteDirectory:n})},s),i=cm(a,"shared folder sync");return{ok:i.ok===!0,jobs:mc(a,"jobs","shared folder sync"),files:Number(i.files||0),totalBytes:Number(i.totalBytes||0)}}function ZN(e){return{id:String(e.id),parentId:e.parent,name:e.name,type:e.type==="file"?"file":"folder",size:Number(e.size||0),modifiedAt:e.date?.toISOString()||null,displayPath:String(e.displayPath||e.name),hasChildren:e.lazy===!0||!!e.data?.length,locked:e.locked===!0}}function mg(e){if(!Number.isFinite(e)||e<=0)return"0 B";const t=["B","KB","MB","GB","TB"];let n=e,s=0;for(;n>=1024&&s<t.length-1;)n/=1024,s+=1;return`${n.toFixed(s===0||n>=100?0:1)} ${t[s]}`}function Zl(e){return e.driveType==="network"?"network":e.driveType==="removable"?"removable":"local"}function eR(e){const t=e.filter(n=>Zl(n)==="local");return t.find(n=>/\bC:/i.test(`${n.name} ${n.displayPath||""}`))||t[0]||e[0]||null}function tR(e){const t=String(e.displayPath||"").trim();if(t)return t;const n=String(e.name||"").match(/\(([A-Za-z]:)\)/)?.[1];return n?`${n}\\`:e.name}function nR({hubUrl:e,roots:t,loading:n,error:s,onRefreshRoots:a,onImportFiles:i,onImportFolder:c,onSelectionChange:u,onShareItem:d,onAddSyncFolder:p,onNotice:h}){const m=o.useRef(null),g=o.useRef("/"),w=o.useRef(0),v=o.useRef([]),y=o.useRef(new Map),[k,N]=o.useState(null),[C,A]=o.useState([]),[E,I]=o.useState([]),[F,M]=o.useState(0),[H,V]=o.useState(null),[P,D]=o.useState(!1),[O,X]=o.useState(""),[G,U]=o.useState(new Set),ie=t.find(ne=>ne.id===k)||null,j=C[C.length-1]||null,re=ie?j?.svarPath||`/${ie.name}`:null,de=re;o.useEffect(()=>{v.current=C,g.current=de||"/"},[de,C]);const Q=o.useMemo(()=>(y.current.clear(),!ie||!de||C.length===0?[]:(C.forEach(ne=>y.current.set(ne.svarPath,ne.hubId)),[...C.map((ne,ae)=>({id:ne.svarPath,parent:ae===0?"/":C[ae-1].svarPath,type:"folder",name:ne.name,date:ne.modifiedAt?new Date(ne.modifiedAt):void 0,lazy:!1})),...E.map(ne=>{const ae=`${de}/${ne.name}`;return y.current.set(ae,ne.id),{id:ae,parent:de,name:ne.name,type:ne.type==="file"?"file":"folder",...ne.type==="file"?{size:ne.size}:{},date:ne.modifiedAt?new Date(ne.modifiedAt):void 0,lazy:ne.type!=="file"&&ne.hasChildren===!0,displayPath:ne.displayPath,locked:ne.locked,driveType:ne.driveType,totalBytes:ne.totalBytes,freeBytes:ne.freeBytes}})])),[ie,E,de,C]),ge=ne=>y.current.get(String(ne))||String(ne),oe=ne=>ZN({...ne,id:ge(String(ne.id)),parent:ge(String(ne.parent))}),me=async(ne,ae)=>{const le=ne[ne.length-1];if(!le)return;const ce=++w.current;D(!0),X("");try{const J=await Bd(le.hubId,e);if(ce!==w.current)return;if(!Array.isArray(J.entries))throw new Error("Invalid Hub filesystem entries response.");const ye={...le,displayPath:J.folder.displayPath||le.displayPath,modifiedAt:J.folder.modifiedAt||le.modifiedAt},ue=[...ne.slice(0,-1),ye];v.current=ue,A(ue),I(J.entries),M(Ee=>Ee+1)}catch(J){if(ce!==w.current)return;console.error("[LiveDesk FS] folder navigation failed",{folderId:le.hubId,error:J}),X(J instanceof Error?`${ae}: ${J.message}`:`${ae}: Unable to read this folder.`)}finally{ce===w.current&&D(!1)}},Ae=async ne=>{const ae={svarPath:`/${ne.name}`,hubId:ne.id,name:ne.name,pathLabel:tR(ne),displayPath:ne.displayPath,modifiedAt:ne.modifiedAt},le=++w.current;N(ne.id),v.current=[ae],A([ae]),g.current=ae.svarPath,I([]),X(""),D(!0),V(ne.id),U(ce=>{const J=new Set(ce);return J.delete(ne.id),J});try{const ce=await Bd(ne.id,e);if(le!==w.current)return;if(!Array.isArray(ce.entries))throw new Error("Invalid Hub filesystem entries response.");const J={...ae,pathLabel:ce.folder.displayPath||ae.pathLabel,displayPath:ce.folder.displayPath||ae.displayPath,modifiedAt:ce.folder.modifiedAt||ae.modifiedAt};v.current=[J],A([J]),I(ce.entries),M(ye=>ye+1)}catch(ce){if(le!==w.current)return;console.error("[LiveDesk FS] getEntries failed",{rootId:ne.id,error:ce}),U(J=>new Set(J).add(ne.id)),X(ce instanceof Error?`${ne.name}: ${ce.message}`:`${ne.name}: Unable to read this drive.`),h(ce instanceof Error?`${ne.name}: ${ce.message}`:`${ne.name}: Unable to read this drive.`)}finally{le===w.current&&(V(null),D(!1))}},Te=ne=>{const ae=v.current;ne<0||ne>=ae.length||ne===ae.length-1||me(ae.slice(0,ne+1),ae[ne].name)},Pe=(ne,ae)=>{if(ne.type!=="folder")return;const le=v.current,ce=le.findIndex(ye=>ye.svarPath===ae);if(ce<0)return;const J={svarPath:`${ae}/${ne.name}`,hubId:ne.id,name:ne.name,pathLabel:ne.name,displayPath:ne.displayPath,modifiedAt:ne.modifiedAt};me([...le.slice(0,ce+1),J],ne.name)},Se=()=>Te(v.current.length-2),te=ne=>{if(ne.key!=="Enter"&&ne.code!=="Enter"&&ne.code!=="NumpadEnter"||ne.target?.closest('button, input, textarea, [contenteditable="true"]'))return;const le=m.current;if(!le)return;const ce=le.getState().panels?.flatMap(ye=>ye.selected||[])||[];if(ce.length!==1)return;const J=le.getFile(String(ce[0]));J?.type==="folder"&&(ne.preventDefault(),ne.stopPropagation(),Pe(oe(J),String(J.parent||g.current)))};o.useEffect(()=>{const ne=t.find(ae=>ae.id===k)||eR(t);if(U(ae=>new Set([...ae].filter(le=>t.some(ce=>ce.id===le)))),!ne){N(null),v.current=[],A([]),I([]);return}Ae(ne)},[t]);const Ce=ne=>{m.current=ne,ne.on("request-data",async({id:ae})=>{const le=String(ae),ce=ge(le);try{const J=await Bd(ce,e);if(!Array.isArray(J.entries))throw new Error("Invalid Hub filesystem entries response.");const ye=J.entries.map(ue=>{const Ee=`${le}/${ue.name}`;return y.current.set(Ee,ue.id),{id:Ee,parent:le,name:ue.name,type:ue.type==="file"?"file":"folder",...ue.type==="file"?{size:ue.size}:{},date:ue.modifiedAt?new Date(ue.modifiedAt):void 0,lazy:ue.type!=="file"&&ue.hasChildren===!0,displayPath:ue.displayPath,locked:ue.locked,driveType:ue.driveType,totalBytes:ue.totalBytes,freeBytes:ue.freeBytes}});await ne.exec("provide-data",{id:le,data:ye})}catch(J){console.error("[LiveDesk FS] nested getEntries failed",{id:ce,error:J}),h(J instanceof Error?J.message:"Unable to read this folder.")}}),ne.intercept("set-path",({id:ae})=>{const le=String(ae),ce=v.current.findIndex(ye=>ye.svarPath===le);if(ce>=0)return Te(ce),!1;const J=ne.getFile(le);if(J?.type==="folder")return Pe(oe(J),String(J.parent||g.current)),!1}),ne.intercept("open-file",()=>!1),ne.on("select-file",()=>{window.setTimeout(()=>{const ce=(ne.getState().panels?.flatMap(J=>J.selected||[])||[]).map(J=>ne.getFile(J)).filter(Boolean).map(J=>oe(J));u(ce.map(J=>J.id),ce)},0)})},Fe=(ne,ae)=>{const le=ae?oe(ae):null,ce=()=>{const J=le?.type==="file"?String(ae?.parent||g.current):String(ae?.id||g.current);m.current?.exec("request-data",{id:J})};return ne==="body"?[{id:"refresh",text:"Refresh",icon:"mdi mdi-refresh",handler:ce},{id:"properties",text:"Properties",icon:"mdi mdi-information-outline",handler:()=>h("Select a file or folder to view its properties.")}]:ne==="multiselect"?[{id:"share",text:"Share to Clients",icon:"mdi mdi-share-variant",handler:()=>{(m.current?.getState().panels?.flatMap(ye=>ye.selected||[])||[]).forEach(ye=>{const ue=m.current?.getFile(ye);ue&&d(oe(ue))})}},{id:"refresh",text:"Refresh",icon:"mdi mdi-refresh",handler:ce}]:le?[{id:"share",text:"Share to Clients",icon:"mdi mdi-share-variant",handler:()=>d(le)},...le.type==="folder"?[{id:"sync",text:"Add folder to Sync",icon:"mdi mdi-folder-sync-outline",handler:()=>p(le)}]:[],{id:"copy-path",text:"Copy path",icon:"mdi mdi-content-copy",handler:()=>{Vl(le.displayPath||le.name)}},{id:"refresh",text:"Refresh",icon:"mdi mdi-refresh",handler:ce},{id:"properties",text:"Properties",icon:"mdi mdi-information-outline",handler:()=>h(`${le.name}
167
- ${le.displayPath||""}`)}]:[]},Le=async()=>{try{await a()}catch(ne){h(ne instanceof Error?ne.message:"Unable to refresh Hub drives.")}},Ue=[{id:"local",label:"Local drives",icon:qa,roots:t.filter(ne=>Zl(ne)==="local")},{id:"removable",label:"Removable drives",icon:Zy,roots:t.filter(ne=>Zl(ne)==="removable")},{id:"network",label:"Network drives",icon:Dp,roots:t.filter(ne=>Zl(ne)==="network")}];return r.jsxs("section",{className:"hub-file-explorer-panel","aria-label":"Hub file explorer",children:[r.jsxs("div",{className:"hub-file-explorer-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Hub file explorer"}),r.jsxs("strong",{children:[r.jsx(qa,{size:16})," Browse files on this Hub"]})]}),r.jsxs("div",{className:"hub-file-explorer-heading-actions",children:[r.jsx("button",{className:"icon-button",onClick:i,title:"Import files from this browser",type:"button",children:r.jsx(bb,{size:16})}),r.jsx("button",{className:"icon-button",onClick:c,title:"Import folder from this browser",type:"button",children:r.jsx(ex,{size:16})}),r.jsx("button",{className:"icon-button",onClick:()=>{Le()},title:"Refresh drives",type:"button",children:r.jsx(Ya,{size:16})})]})]}),n?r.jsxs("div",{className:"hub-file-explorer-state",children:[r.jsx(qa,{size:24}),r.jsx("strong",{children:"Connecting to LiveDesk Hub file system..."})]}):s?r.jsxs("div",{className:"hub-file-explorer-state error",role:"alert",children:[r.jsx(As,{size:24}),r.jsx("strong",{children:s})]}):r.jsxs("div",{className:"hub-file-explorer-content",children:[r.jsxs("aside",{className:"hub-file-explorer-drive-sidebar","aria-label":"Hub drives",children:[r.jsxs("div",{className:"hub-drive-sidebar-title",children:[r.jsx(qa,{size:15}),r.jsx("strong",{children:"This PC"})]}),Ue.map(ne=>ne.roots.length>0&&r.jsxs("section",{className:"hub-drive-group",children:[r.jsxs("h3",{children:[r.jsx(ne.icon,{size:13}),ne.label]}),r.jsx("div",{className:"hub-drive-list",children:ne.roots.map(ae=>{const le=ne.icon,ce=G.has(ae.id)||ae.locked===!0;return r.jsxs("button",{className:`hub-drive-item ${k===ae.id?"active":""} ${ce?"unavailable":""}`,onClick:()=>{Ae(ae)},"aria-pressed":k===ae.id,type:"button",children:[r.jsx("span",{className:"hub-drive-item-icon",children:r.jsx(le,{size:16})}),r.jsxs("span",{className:"hub-drive-item-copy",children:[r.jsx("strong",{children:ae.name}),r.jsx("small",{children:ae.displayPath||ae.name}),r.jsxs("em",{children:[mg(ae.freeBytes||0)," free / ",mg(ae.totalBytes||0)]})]}),H===ae.id?r.jsx(Zn,{className:"hub-drive-item-status spin",size:15}):ce?r.jsx($h,{className:"hub-drive-item-status",size:15}):null]},ae.id)})})]},ne.id)),t.length===0&&r.jsxs("div",{className:"hub-drive-sidebar-empty",children:[r.jsx(As,{size:17}),r.jsx("span",{children:"No drives available."})]})]}),r.jsxs("div",{className:"hub-file-explorer-browser",children:[r.jsxs("div",{className:"hub-file-explorer-navigation",children:[r.jsx("nav",{className:"hub-file-explorer-breadcrumbs","aria-label":"Current Hub folder",children:C.map((ne,ae)=>r.jsxs("span",{className:"hub-file-explorer-breadcrumb-item",children:[ae>0&&r.jsx(Lp,{size:13,"aria-hidden":"true"}),r.jsx("button",{className:`hub-file-explorer-breadcrumb ${ae===C.length-1?"current":""}`,onClick:()=>Te(ae),title:ne.displayPath||ne.pathLabel,"data-hub-folder-id":ne.hubId,"aria-current":ae===C.length-1?"location":void 0,type:"button",children:ne.pathLabel})]},ne.svarPath))}),r.jsxs("div",{className:"hub-file-explorer-navigation-actions",children:[P&&r.jsx(Zn,{className:"hub-file-explorer-loading-icon spin",size:15,"aria-label":"Loading folder"}),r.jsx("button",{className:"icon-button",onClick:Se,disabled:C.length<=1||P,title:"Back to parent folder",type:"button",children:r.jsx(db,{size:16})})]})]}),O&&r.jsxs("div",{className:"hub-file-explorer-folder-error",role:"alert",children:[r.jsx($h,{size:15}),r.jsx("span",{children:O})]}),r.jsx("div",{className:"hub-file-explorer-svar",onKeyDownCapture:te,children:r.jsx(HN,{fonts:!1,children:r.jsx(BN,{data:Q,panels:re?[{path:re,selected:[]}]:void 0,readonly:!0,mode:"table",preview:!1,init:Ce,icons:"simple",menuOptions:Fe},`${ie?.id||"no-root"}:${F}`)})})]})]})]})}class rR extends o.Component{state={error:null};static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,n){console.error("[LiveDesk] Share Files runtime error",t,n.componentStack)}render(){return this.state.error?r.jsxs("section",{className:"file-share-error-boundary",role:"alert",children:[r.jsx(vu,{size:24}),r.jsx("strong",{children:"Share Files could not be opened."}),r.jsx("span",{children:this.state.error.message||"An unexpected file explorer error occurred."}),r.jsxs("button",{className:"text-button",onClick:this.props.onRetry,type:"button",children:[r.jsx(Ya,{size:15})," Retry"]})]}):this.props.children}}function sR(e){return e.deviceName||e.hostname||e.deviceId}function aR({devices:e,mode:t,selectedIds:n,onModeChange:s,onToggle:a}){const i=new Set(n);return r.jsxs("section",{className:"distribution-targets",children:[r.jsxs("div",{className:"file-share-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Target"}),r.jsx("strong",{children:t==="all"?`${e.length} connected`:`${n.length} selected`})]}),r.jsxs("div",{className:"file-share-tabs compact","aria-label":"File transfer targets",children:[r.jsxs("button",{className:t==="all"?"active":"",onClick:()=>s("all"),type:"button",children:[r.jsx(sc,{size:14})," All connected"]}),r.jsxs("button",{className:t==="selected"?"active":"",onClick:()=>s("selected"),type:"button",children:[r.jsx(pn,{size:14})," Selected"]})]})]}),r.jsx("div",{className:"file-share-device-list","aria-label":"Connected Client targets",children:e.length===0?r.jsx("div",{className:"file-share-empty-inline",children:"No connected Clients."}):e.map(c=>{const u=t==="all"||i.has(c.deviceId);return r.jsxs("label",{className:`file-share-device-option ${u?"selected":""}`,children:[r.jsx("input",{type:"checkbox",checked:u,disabled:t==="all",onChange:()=>a(c.deviceId)}),r.jsx(pn,{size:20,"aria-hidden":"true"}),r.jsxs("span",{children:[r.jsx("strong",{children:sR(c)}),r.jsxs("small",{children:["Slot ",c.slotNumber?String(c.slotNumber).padStart(3,"0"):"-"," / ",c.platform||"unknown OS"]})]}),r.jsx(En,{size:17,"aria-hidden":"true"})]},c.deviceId)})})]})}function iR(e){if(!Number.isFinite(e)||e<=0)return"0 B";const t=["B","KB","MB","GB","TB"];let n=e,s=0;for(;n>=1024&&s<t.length-1;)n/=1024,s+=1;return`${n.toFixed(s===0||n>=100?0:1)} ${t[s]}`}function oR({folders:e,loading:t,busy:n,canSync:s,onSyncAll:a,onSync:i,onToggleAuto:c,onRemove:u,onAdd:d}){return r.jsxs("section",{className:"file-share-sync-panel",children:[r.jsxs("div",{className:"file-share-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Hub folders"}),r.jsx("strong",{children:"Continuous sync"})]}),r.jsxs("button",{className:"text-button compact",onClick:a,disabled:n||!s||e.length===0,type:"button",children:[r.jsx(Jo,{size:15})," ",n?"Syncing":"Sync all"]})]}),t?r.jsx("div",{className:"file-share-empty-state",children:"Loading Hub sync folders..."}):e.length===0?r.jsxs("button",{className:"file-share-empty-state interactive",onClick:d,type:"button",children:[r.jsx(Jo,{size:28}),r.jsx("strong",{children:"Add a selected Hub folder"}),r.jsx("span",{children:"Hub keeps the manifest and can sync while this browser is closed."})]}):r.jsx("div",{className:"file-share-sync-list",children:e.map(p=>r.jsxs("article",{className:`file-share-sync-row state-${p.status}`,children:[r.jsx("div",{className:"file-share-sync-icon",children:r.jsx(Jo,{size:19})}),r.jsxs("div",{className:"file-share-sync-info",children:[r.jsx("strong",{children:p.name}),r.jsx("span",{children:p.displayPath}),r.jsxs("small",{children:[p.fileCount," files / ",iR(p.totalBytes)," · ",p.lastSyncedAt?`Last sync ${lb(p.lastSyncedAt)} ago`:p.message||"Not synced yet"]})]}),r.jsxs("label",{className:"file-share-auto-sync",children:[r.jsx("input",{type:"checkbox",checked:p.autoSync,onChange:()=>c(p)}),r.jsx("span",{children:"Auto"})]}),r.jsxs("button",{className:"text-button compact",onClick:()=>i(p),disabled:n||!s||p.status==="syncing",type:"button",children:[r.jsx(Ya,{size:14})," Sync now"]}),r.jsx("button",{className:"icon-button",onClick:()=>u(p),title:"Remove sync folder",type:"button",children:r.jsx(vb,{size:15})})]},p.id))})]})}function cR(e){const n=(e.targetMode==="all"?e.devices.map(s=>s.deviceId):e.selectedTargetIds).length>0;return r.jsxs("aside",{className:"file-share-distribution-panel",children:[r.jsxs("div",{className:"file-share-distribution-head",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Distribution"}),r.jsx("strong",{children:"Hub → Clients"})]}),r.jsx(nc,{size:18})]}),r.jsxs("div",{className:"file-share-tabs",role:"tablist","aria-label":"Distribution mode",children:[r.jsx("button",{className:e.tab==="send"?"active":"",onClick:()=>e.onTabChange("send"),role:"tab","aria-selected":e.tab==="send",type:"button",children:"Send"}),r.jsx("button",{className:e.tab==="sync"?"active":"",onClick:()=>e.onTabChange("sync"),role:"tab","aria-selected":e.tab==="sync",type:"button",children:"Sync"})]}),e.tab==="send"?r.jsxs(r.Fragment,{children:[r.jsx(aR,{devices:e.devices,mode:e.targetMode,selectedIds:e.selectedTargetIds,onModeChange:e.onTargetModeChange,onToggle:e.onTargetToggle}),r.jsxs("label",{className:"file-share-destination",children:[r.jsx("span",{children:"Destination folder"}),r.jsxs("div",{children:[r.jsx(Xi,{size:15}),r.jsx("input",{value:e.remoteDirectory,onChange:s=>e.onRemoteDirectoryChange(s.target.value),placeholder:"Desktop/LiveDeskFiles"})]}),r.jsx("small",{children:"Blank uses Desktop/LiveDeskFiles."})]}),r.jsxs("div",{className:"file-share-selection-summary",children:[r.jsx("span",{children:"Selected"}),r.jsx("strong",{children:e.selectedSummary})]}),r.jsxs("button",{className:"file-share-share-button",onClick:e.onShare,disabled:!e.canShare,type:"button",children:[r.jsx(nc,{size:17})," Share selected"]}),r.jsxs("button",{className:"file-share-secondary-button",onClick:e.onAddSync,disabled:!e.canAddSync,type:"button",children:[r.jsx(Xi,{size:16})," Add selected folder to Sync"]})]}):r.jsx(oR,{folders:e.folders,loading:e.foldersLoading,busy:e.syncBusy,canSync:n,onSyncAll:e.onSyncAll,onSync:e.onSync,onToggleAuto:e.onToggleAuto,onRemove:e.onRemove,onAdd:e.onAddFolder})]})}function lR(e){if(!Number.isFinite(e)||e<=0)return"0 B";const t=["B","KB","MB","GB","TB"];let n=e,s=0;for(;n>=1024&&s<t.length-1;)n/=1024,s+=1;return`${n.toFixed(s===0||n>=100?0:1)} ${t[s]}`}function hg(e){if(e.state==="completed")return 100;const t=e.totalBytes>0?Math.round(e.sentBytes/e.totalBytes*100):e.totalFiles>0?Math.round(e.completedFiles/e.totalFiles*100):0;return Math.max(0,Math.min(Ip(e.state)?100:99,t))}function fg(e){return e.state==="scanning"?"Scanning selected Hub items":e.state==="queued"?"Preparing transfer":e.state==="sending"?`${e.completedFiles}/${e.totalFiles} · ${e.currentPath||"sending"}`:e.state==="completed"?`Sent ${e.totalFiles} file${e.totalFiles===1?"":"s"} to ${e.targetCount} Client${e.targetCount===1?"":"s"}`:e.state==="partially-failed"?`${e.failedTargets.length} Client${e.failedTargets.length===1?"":"s"} failed`:e.state==="cancelled"?"Transfer cancelled":e.error||"Transfer failed"}function Ip(e){return["completed","partially-failed","failed","cancelled"].includes(e)}function uR({hubUrl:e,devices:t,localFeatureAccess:n,upgradeNotice:s,remoteDirectory:a,onRemoteDirectoryChange:i,targetMode:c,selectedTargetIds:u,onTargetModeChange:d,onTargetToggle:p,filePickerRef:h,folderPickerRef:m,onBrowserFileImport:g,onBrowserFolderImport:w,onNotice:v,onTransferChange:y}){const k=Array.isArray(t)?t:[],[N,C]=o.useState([]),[A,E]=o.useState(!0),[I,F]=o.useState(""),[M,H]=o.useState([]),[V,P]=o.useState([]),[D,O]=o.useState(null),[X,G]=o.useState(!1),[U,ie]=o.useState([]),[j,re]=o.useState(!0),[de,Q]=o.useState(!1),[ge,oe]=o.useState("send"),[me,Ae]=o.useState([]),Te=o.useRef(new Set),Pe=o.useRef(!1),Se=o.useMemo(()=>c==="all"?k.map(T=>T.deviceId):u.filter(T=>k.some(ve=>ve.deviceId===T)),[k,u,c]),te=me.find(T=>!Ip(T.state)),Ce=V.length===1&&V[0].type==="folder"?V[0]:null,Fe=V.length===0?"Select files or folders from the Hub explorer.":X?"Calculating selection size...":D?`${D.files} files, ${D.folders} folders · ${lR(D.totalBytes)}`:`${V.length} item${V.length===1?"":"s"} selected`,Le=T=>{y({id:T.jobId,state:T.state,progress:hg(T),message:fg(T)})},Ue=o.useCallback(async()=>{const T=await zN(e,!0);return C(T),F(""),T},[e]),ne=async()=>{if(!Pe.current){Pe.current=!0;try{const ve=(await VN(e,!0)).jobs||[],De=await Promise.all([...Te.current].map(async $e=>{try{return await GN($e,e)}catch{return null}})),qe=[...ve,...De.filter(Boolean)],_e=[...new Map(qe.map($e=>[$e.jobId,$e])).values()];Ae(_e),_e.forEach(Le),_e.filter($e=>Ip($e.state)).forEach($e=>Te.current.delete($e.jobId))}catch{}finally{Pe.current=!1}}};o.useEffect(()=>{let T=!0;E(!0),F(""),Promise.all([Ue(),pg(e).then(De=>{T&&ie(De)})]).catch(De=>{T&&(F(De instanceof Error?"Hub file system is unavailable. Make sure LiveDesk Hub is running on this computer.":"Hub file system is unavailable."),v(De instanceof Error?De.message:"Hub file system is unavailable."))}).finally(()=>{T&&(E(!1),re(!1))}),ne();const ve=window.setInterval(()=>{ne()},800);return()=>{T=!1,window.clearInterval(ve)}},[e,Ue]),o.useEffect(()=>{if(M.length===0){O(null);return}let T=!1;return G(!0),qN(M,e).then(ve=>{T||O(ve)}).catch(ve=>{T||v(ve instanceof Error?ve.message:"Unable to calculate selected size.")}).finally(()=>{T||G(!1)}),()=>{T=!0}},[e,M.join("|")]);const ae=(T,ve)=>{H(T),P(ve)},le=T=>{T.forEach(ve=>Te.current.add(ve.jobId)),Ae(ve=>[...new Map([...ve,...T].map(De=>[De.jobId,De])).values()]),T.forEach(Le)},ce=async()=>{if(!n){v(s);return}if(M.length===0){v("Select files or folders from the Hub explorer.");return}if(Se.length===0){v("Choose at least one connected Client.");return}if(te){v("A Hub transfer is already running.");return}try{const T=await UN(M,Se,a.trim(),e);Te.current.add(T.jobId),v("Hub transfer queued."),await ne()}catch(T){v(T instanceof Error?T.message:"Unable to start Hub transfer.")}},J=async T=>{const ve=T||Ce;if(!ve||ve.type!=="folder"){v("Select one folder to add it to Sync.");return}try{const De=await QN(ve.id,e);ie(qe=>[...qe.filter(_e=>_e.id!==De.folder.id),De.folder]),oe("sync"),v(`${ve.name} is ready for Hub sync.`)}catch(De){v(De instanceof Error?De.message:"Unable to add the Hub folder to Sync.")}},ye=async T=>{if(Se.length===0){v("Choose at least one connected Client.");return}Q(!0),ie(ve=>ve.map(De=>De.id===T.id?{...De,status:"syncing"}:De));try{const ve=await JN(T.id,Se,a.trim(),e);le(ve.jobs||[]),v(ve.jobs?.length?"Hub sync queued.":"No changed files to sync.");const De=await pg(e);ie(De)}catch(ve){v(ve instanceof Error?ve.message:"Unable to sync the Hub folder."),ie(De=>De.map(qe=>qe.id===T.id?{...qe,status:"error",message:"Sync failed"}:qe))}finally{Q(!1)}},ue=async()=>{Q(!0);try{for(const T of U)await ye(T)}finally{Q(!1)}},Ee=async T=>{try{const ve=await YN(T.id,{autoSync:!T.autoSync},e);ie(De=>De.map(qe=>qe.id===T.id?ve.folder:qe))}catch(ve){v(ve instanceof Error?ve.message:"Unable to update auto sync.")}},nt=async T=>{try{await XN(T.id,e),ie(ve=>ve.filter(De=>De.id!==T.id))}catch(ve){v(ve instanceof Error?ve.message:"Unable to remove the sync folder.")}};return r.jsxs("section",{className:"livedesk-file-explorer",children:[r.jsx("input",{ref:h,className:"hidden-file-input",type:"file",multiple:!0,onChange:T=>{T.currentTarget.files&&g(T.currentTarget.files),T.currentTarget.value=""}}),r.jsx("input",{ref:m,className:"hidden-file-input",type:"file",multiple:!0,webkitdirectory:"",directory:"",onChange:T=>{T.currentTarget.files&&w(T.currentTarget.files),T.currentTarget.value=""}}),r.jsx("div",{className:"file-share-workspace",children:r.jsxs(rR,{onRetry:()=>window.location.reload(),children:[r.jsx(nR,{hubUrl:e,roots:N,loading:A,error:I,onRefreshRoots:Ue,onImportFiles:()=>h.current?.click(),onImportFolder:()=>m.current?.click(),onSelectionChange:ae,onShareItem:T=>{H([T.id]),P([T]),oe("send")},onAddSyncFolder:T=>{H([T.id]),P([T]),J(T)},onNotice:v}),r.jsx(cR,{devices:k,targetMode:c,selectedTargetIds:u,onTargetModeChange:d,onTargetToggle:p,remoteDirectory:a,onRemoteDirectoryChange:i,selectedEntries:V,selectedSummary:Fe,canShare:n&&!te&&M.length>0&&Se.length>0&&!X,onShare:()=>{ce()},canAddSync:!!Ce,onAddSync:()=>{J()},tab:ge,onTabChange:oe,folders:U,foldersLoading:j,syncBusy:de,onSyncAll:()=>{ue()},onSync:T=>{ye(T)},onToggleAuto:T=>{Ee(T)},onRemove:T=>{nt(T)},onAddFolder:()=>{J()}})]})}),te&&r.jsx("footer",{className:"file-share-workspace-footer",children:r.jsxs("span",{children:[fg(te)," · ",hg(te),"% ",r.jsx("button",{className:"icon-button",onClick:()=>{KN(te.jobId,e).then(T=>{Ae(ve=>ve.map(De=>De.jobId===T.jobId?T:De)),Le(T)})},title:"Cancel transfer",type:"button",children:r.jsx(xn,{size:14})})]})})]})}const dR=o.forwardRef(function({value:t,onChange:n,onSubmit:s,onOpenSuggestedTasks:a,suggestedOpen:i=!1,suggestedTaskCount:c,disabled:u=!1,placeholder:d="Ask LiveDesk to work across your machines...",compact:p=!1},h){return r.jsxs("form",{className:"agents-composer",onSubmit:m=>{m.preventDefault(),s()},children:[r.jsx("button",{className:`agents-suggested-trigger ${i?"active":""}`,type:"button","aria-label":c===void 0?"Open Suggested tasks":`Open Suggested tasks (${c} available)`,"aria-expanded":i,onClick:a,disabled:u,children:r.jsx(tx,{size:17})}),r.jsx("textarea",{ref:h,value:t,onChange:m=>n(m.target.value.slice(0,4e3)),placeholder:d,"aria-label":"Ask LiveDesk",rows:p?1:2,disabled:u}),r.jsxs("button",{className:"agents-run-button",type:"submit",disabled:u||!t.trim(),children:[u?r.jsx(Zn,{className:"spin",size:16}):r.jsx(nc,{size:16}),u?"Running":"Run"]})]})}),pR=["read","processControl","serviceControl","applicationControl","fileRead","fileWrite","fileDelete","shell","script","softwareInstall","network","systemPower","systemConfiguration","userAccount"];function pu(e){return e.deviceName?.trim()||e.hostname?.trim()||e.deviceId}function mu(e){return e.connected!==!0?!1:e.synthetic===!0?!0:!e.channels||e.channels.control===!0}function mR(e){return e==="running"||e==="completed"||e==="failed"||e==="cancelled"?e:"queued"}function hR(e){switch(e){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 fR(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Jn(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function _l(e){const t=Jn(e);return t===null?"":t<1024**2?`${Math.round(t/1024)}K`:t<1024**3?`${(t/1024**2).toFixed(0)}M`:`${(t/1024**3).toFixed(1)}G`}function gg(e){const t=Jn(e);return t===null?"":`${Math.round((t<=1?t:t/100)*100)}%`}function gR(e){return!e||/^(?:[\w .-]+ )?collected(?:\.)?$/i.test(e.trim())?"":e.trim()}function hu(e,t){if(t.error)return t.error;const n=fR(t.data),s=gR(t.result||"");if(!n)return s||t.stage||t.status;if(e==="system.health"){const a=typeof n.machine=="string"?n.machine:"",i=gg(n.cpuUsageRatio),c=Jn(n.cores),u=_l(n.freeMemoryBytes),d=_l(n.totalMemoryBytes),p=Jn(n.totalMemoryBytes)&&Jn(n.freeMemoryBytes)!==null?`${Math.round(Jn(n.freeMemoryBytes)/Jn(n.totalMemoryBytes)*100)}% RAM free`:"";return[a,i&&`CPU ${i}`,c!==null&&`${Math.round(c)} cores`,u&&d?`RAM ${u}/${d}`:"",p,typeof n.platform=="string"?n.platform:""].filter(Boolean).join(" · ")||s||t.status}if(e==="disk.status"){const a=typeof n.root=="string"?n.root:"",i=_l(n.freeBytes),c=Jn(n.totalBytes)&&Jn(n.freeBytes)!==null?`${Math.round(Jn(n.freeBytes)/Jn(n.totalBytes)*100)}% free`:"";return[a,i&&`${i} free`,c].filter(Boolean).join(" · ")||s||t.status}if(e==="gpu.status"){const a=typeof n.name=="string"&&n.name?n.name:"No GPU detected",i=gg(n.usageRatio),c=Jn(n.temperatureC)!==null?`${Math.round(Jn(n.temperatureC))}°C`:"",u=_l(n.freeMemoryBytes);return[a,i&&`GPU ${i}`,c,u&&`${u} free`].filter(Boolean).join(" · ")||s||t.status}if(e==="process.list"){const a=Jn(n.count);return a!==null?`${a} matching process${a===1?"":"es"}`:s||t.status}if(e==="network.status"){const a=Array.isArray(n.adapters)?n.adapters.length:null;return a!==null?`${a} active adapter${a===1?"":"s"}`:s||t.status}return s||t.stage||t.status}function bg(e,t){const n=hu(e,t);return t.status==="failed"||t.status==="cancelled"||/\b(?:warning|failed|error|offline|not running|low|timeout|timed out)\b/i.test(`${t.result||""} ${n}`)}function bR({state:e,operation:t}){const n=e.status==="completed"?Ns:e.status==="failed"||e.status==="cancelled"?xn:e.status==="running"?Zn:wb,s=e.status==="running"?e.stage||"Working":e.status==="completed"?t?hu(t,e):e.result||"Completed":e.status==="failed"?e.error||"Failed":e.status==="cancelled"?"Cancelled":"Queued";return r.jsxs("div",{className:`agent-target-row status-${e.status}`,"data-agent-target-id":e.deviceId,children:[r.jsx("span",{className:"agent-target-status","aria-hidden":"true",children:r.jsx(n,{size:15})}),r.jsx("strong",{children:e.deviceName}),r.jsx("span",{className:"agent-target-state",children:e.status[0].toUpperCase()+e.status.slice(1)}),r.jsx("small",{children:s})]})}function vR({operation:e,states:t,status:n,onCancel:s,onRetry:a,busy:i=!1}){const c=["running","queued"].includes(n),[u,d]=o.useState(!1),[p,h]=o.useState("all"),m=o.useMemo(()=>({total:t.length,completed:t.filter(A=>A.status==="completed").length,failed:t.filter(A=>A.status==="failed").length,running:t.filter(A=>A.status==="running").length,queued:t.filter(A=>A.status==="queued").length,cancelled:t.filter(A=>A.status==="cancelled").length}),[t]),g=t.filter(A=>bg(e,A)),w=g.filter(A=>A.status==="completed").length,v=m.failed>0,y=g.length>0,k=t.filter(A=>p==="issues"?bg(e,A):p==="running"?A.status==="running"||A.status==="queued":p==="completed"?A.status==="completed":p==="failed"?A.status==="failed":!0),N=y&&!c||n==="completed-with-failures"?"Completed with issues":n[0]?.toUpperCase()+n.slice(1),C=t.filter(A=>A.status==="completed").map(A=>hu(e,A)).filter(Boolean).filter((A,E,I)=>I.indexOf(A)===E).slice(0,2);return r.jsxs("section",{className:"agent-task-block","aria-label":"Task execution",children:[r.jsxs("div",{className:"agent-task-head",children:[r.jsxs("div",{children:[r.jsx("span",{children:"LiveDesk Agent"}),r.jsx("strong",{children:hR(e)})]}),r.jsx("span",{className:`agent-task-status status-${y?"completed-with-failures":n}`,children:N})]}),r.jsxs("div",{className:"agent-task-summary","aria-label":"Task summary",children:[r.jsxs("strong",{children:[m.total," targets"]}),r.jsxs("span",{className:"summary-completed",children:[m.completed," completed"]}),m.running>0&&r.jsxs("span",{className:"summary-running",children:[m.running," running"]}),m.queued>0&&r.jsxs("span",{children:[m.queued," queued"]}),v&&r.jsxs("span",{className:"summary-failed",children:[m.failed," failed"]}),w>0&&r.jsxs("span",{className:"summary-cancelled",children:[w," warning"]}),m.cancelled>0&&r.jsxs("span",{className:"summary-cancelled",children:[m.cancelled," cancelled"]})]}),C.length>0&&r.jsxs("div",{className:"agent-task-result-preview",title:C.join(" · "),children:[r.jsx("span",{children:"Result"}),C.join(" · ")]}),r.jsx("div",{className:"agent-target-chips","aria-label":"Target status overview",children:t.map((A,E)=>{const I=A.status==="completed"?"✓":A.status==="failed"?"×":A.status==="cancelled"?"!":A.status==="running"?"…":"·";return r.jsxs("span",{className:`agent-target-chip status-${A.status}`,title:`${A.deviceName}: ${hu(e,A)}`,"aria-label":`${E+1}. ${A.deviceName}: ${A.status}`,children:[r.jsx("b",{children:String(E+1).padStart(2,"0")}),r.jsx("span",{children:I})]},A.deviceId)})}),t.length>0&&r.jsx("div",{className:"agent-task-details-toggle",children:r.jsxs("button",{type:"button",onClick:()=>d(A=>!A),"aria-expanded":u,children:[u?r.jsx(nx,{size:14}):r.jsx(yb,{size:14}),u?"Hide details":"Show details"]})}),u&&r.jsxs("div",{className:"agent-task-details",children:[r.jsx("div",{className:"agent-task-filters",role:"tablist","aria-label":"Task result filter",children:["all","issues","running","completed","failed"].map(A=>r.jsx("button",{className:p===A?"active":"",onClick:()=>h(A),role:"tab","aria-selected":p===A,type:"button",children:A==="all"?"All":A==="issues"?"Issues only":A[0].toUpperCase()+A.slice(1)},A))}),r.jsx("div",{className:"agent-task-rows",children:k.length>0?k.map(A=>r.jsx(bR,{operation:e,state:A},A.deviceId)):r.jsx("small",{className:"agent-task-no-results",children:"No targets match this filter."})})]}),(c||v)&&r.jsxs("div",{className:"agent-task-actions",children:[c&&s&&r.jsxs("button",{onClick:s,disabled:i,type:"button",children:[r.jsx(rx,{size:14})," Cancel"]}),!c&&v&&a&&r.jsxs("button",{onClick:a,disabled:i,type:"button",children:[r.jsx(rp,{size:14})," Retry failed"]})]})]})}function wR(e){try{return JSON.stringify(e,null,2).slice(0,6e3)}catch{return"{}"}}function yR({approval:e,busy:t=!1,onApprove:n,onReject:s}){return r.jsxs("article",{className:"agent-approval-card","aria-label":"Agent approval required",children:[r.jsxs("div",{className:"agent-approval-head",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Approval required"}),r.jsx("strong",{children:e.toolName})]}),r.jsx("span",{className:`agent-approval-risk risk-${e.risk}`,children:e.risk})]}),r.jsx("p",{children:e.description}),r.jsx("pre",{children:wR(e.arguments)}),r.jsxs("small",{children:["Permission: ",e.permissionMode," · Scope: selected devices only · Expires in 5 minutes"]}),r.jsxs("div",{className:"agent-approval-actions",children:[r.jsxs("button",{className:"reject",disabled:t,onClick:s,type:"button",children:[r.jsx(xn,{size:14})," Reject"]}),r.jsxs("button",{disabled:t,onClick:()=>n("once"),type:"button",children:[r.jsx(Ns,{size:14})," Once"]}),r.jsx("button",{disabled:t,onClick:()=>n("same-action-this-run"),type:"button",children:"Allow same action"}),r.jsx("button",{disabled:t,onClick:()=>n("category-this-run"),type:"button",children:"Allow category"})]}),r.jsxs("div",{className:"agent-approval-scope",children:[r.jsx(vu,{size:13})," Approval is bound to this run, tool, arguments, selected devices, and policy hash."]})]})}function xR(e){return e==="queued"?"Request queued":e==="checking-codex"?"Checking Codex":e==="preparing-tools"?"Preparing tools":e==="thinking"?"Preparing answer":e==="tool-running"?"Working on computers":e==="recovering"?"Retrying safely":e==="waiting-approval"?"Waiting for approval":"Working"}function SR({items:e,onCancel:t,onRetry:n,busyBatchId:s,approvals:a,onApprove:i,onReject:c,busyApprovalId:u,progress:d,emptyTitle:p="Ask LiveDesk to work across your machines.",emptyBody:h="Start with a read-only request such as “현재 대상에서 CPU와 메모리 상태를 확인해줘”."}){const m=o.useRef(null),g=o.useRef(!0),w=o.useRef(""),v=e[e.length-1];return o.useLayoutEffect(()=>{const y=m.current;y&&(v?.type==="user"&&v.id!==w.current&&(g.current=!0),w.current=v?.id||"",g.current&&(y.scrollTop=y.scrollHeight))},[a,e,v?.id,v?.type,d?.message,d?.stage]),r.jsxs("section",{className:"agents-conversation","aria-live":"polite",ref:m,onScroll:y=>{const k=y.currentTarget;g.current=k.scrollHeight-k.scrollTop-k.clientHeight<72},children:[a.filter(y=>y.status==="pending").map(y=>r.jsx(yR,{approval:y,busy:u===y.approvalId,onApprove:k=>i(y,k),onReject:()=>c(y)},y.approvalId)),e.length===0&&r.jsxs("div",{className:"agents-empty-conversation",children:[r.jsx("strong",{children:p}),r.jsx("span",{children:h})]}),e.map(y=>{if(y.type==="task"){const k=y;return r.jsx(vR,{operation:k.operation,states:k.states,status:k.status,onCancel:()=>t(k.batchId,k.agentRunId),onRetry:()=>n(k.batchId),busy:s===k.batchId},k.id)}return r.jsxs("article",{className:`agents-message ${y.type}`,children:[r.jsx("span",{children:y.type==="user"?"You":"LiveDesk Agent"}),r.jsx("p",{children:y.text})]},y.id)}),d&&r.jsxs("article",{className:"agents-message agent agents-progress-message",role:"status",children:[r.jsxs("span",{children:[r.jsx(Zn,{"aria-hidden":"true",size:15}),xR(d.stage)]}),r.jsx("p",{children:d.message})]})]})}const vg=["Recommended","Health & capacity","Processes & services","Files & configuration","Software & automation","Network & connectivity","Power & maintenance","Troubleshooting & recovery"],Lt=["windows","macos","linux"],Qs={"system.health":{label:"system health",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:Lt},"gpu.status":{label:"GPU status",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:Lt},"disk.status":{label:"disk status",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:Lt},"process.list":{label:"process inspection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:Lt},"service.status":{label:"service inspection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:Lt},"diagnostics.collect":{label:"diagnostics collection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:Lt},"process.control":{label:"process control",permissionCategory:"processControl",readOnly:!1,risk:"high",supportedPlatforms:Lt},"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:Lt},"application.close":{label:"application close",permissionCategory:"applicationControl",readOnly:!1,risk:"medium",supportedPlatforms:Lt},"file.read":{label:"file reading",permissionCategory:"fileRead",readOnly:!0,risk:"low",supportedPlatforms:Lt},"file.write":{label:"file writing",permissionCategory:"fileWrite",readOnly:!1,risk:"high",supportedPlatforms:Lt},"file.delete":{label:"file deletion",permissionCategory:"fileDelete",readOnly:!1,risk:"critical",supportedPlatforms:Lt},"file.list":{label:"directory listing",permissionCategory:"fileRead",readOnly:!0,risk:"low",supportedPlatforms:Lt},"file.search":{label:"file name search",permissionCategory:"fileRead",readOnly:!0,risk:"low",supportedPlatforms:Lt},"directory.create":{label:"directory creation",permissionCategory:"fileWrite",readOnly:!1,risk:"medium",supportedPlatforms:Lt},"command.run":{label:"command execution",permissionCategory:"shell",readOnly:!1,risk:"critical",supportedPlatforms:Lt},"script.run":{label:"script execution",permissionCategory:"script",readOnly:!1,risk:"high",supportedPlatforms:Lt},"software.install":{label:"software installation",permissionCategory:"softwareInstall",readOnly:!1,risk:"high",supportedPlatforms:Lt},"network.status":{label:"network inspection",permissionCategory:"network",readOnly:!0,risk:"low",supportedPlatforms:Lt},"system.power":{label:"power control",permissionCategory:"systemPower",readOnly:!1,risk:"critical",supportedPlatforms:Lt},"system.configure":{label:"system configuration",permissionCategory:"systemConfiguration",readOnly:!1,risk:"critical",supportedPlatforms:Lt},"logs.collect":{label:"log collection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:Lt}};new Set(Object.keys(Qs));const CR={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","문제해결","복구","장애"]},wg=["low","medium","high","critical"];function kR(e){return e.reduce((t,n)=>{const s=Qs[n].risk;return wg.indexOf(s)>wg.indexOf(t)?s:t},"low")}function MR(e){return Lt.filter(t=>e.every(n=>Qs[n].supportedPlatforms.includes(t)))}function ze(e,t,n,s,a,i,c={}){const u=c.description||s,d=a.flatMap(h=>h.split(".")),p=[...new Set([...CR[t],...i,...d])];return{id:e,category:t,title:n,prompt:s,description:u,requiredOperations:a,risk:c.risk||kR(a),targetSupport:c.targetSupport||"single-or-multiple",supportedPlatforms:c.supportedPlatforms||MR(a),keywords:p,recommended:c.recommended??!1,enabled:!0}}const tw=[ze("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}),ze("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}),ze("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}),ze("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}),ze("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}),ze("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}),ze("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}),ze("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}),ze("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","높은 사용량"]),ze("health-uptime","Health & capacity","Review Client uptime","Show uptime, boot time, and current system health for the target Clients.",["system.health"],["uptime","boot","가동시간"]),ze("health-gpu-temperature","Health & capacity","Check GPU temperature","Check GPU temperature and thermal warnings on the current targets.",["gpu.status"],["thermal","temperature","발열"]),ze("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"]),ze("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","디스크"]),ze("health-gpu-compare","Health & capacity","Compare GPU capacity","Compare GPU model, memory, temperature, and utilization across the current targets.",["gpu.status"],["compare","graphics","capacity"]),ze("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","경고"]),ze("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"]),ze("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","실행 중"]),ze("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"]),ze("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"}),ze("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"}),ze("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"}),ze("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"}),ze("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","서비스 상태"]),ze("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"}),ze("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"}),ze("files-search-name","Files & configuration","Search files by name","Search for files or folders containing [name] under [path] on the target Client.",["file.search"],["search","find","filename","파일 찾기"],{targetSupport:"single"}),ze("files-create-directory","Files & configuration","Create a directory","Create directory [path] on the target Client and report the final path.",["directory.create"],["create","directory","folder","폴더 만들기"],{targetSupport:"single"}),ze("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","구성"]),ze("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"]),ze("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"}),ze("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"}),ze("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"]),ze("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"}),ze("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"}),ze("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"]}),ze("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"]}),ze("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"]}),ze("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"}),ze("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"}),ze("software-run-command","Software & automation","Run a shell command on one target","Run [command] with [PowerShell, cmd, bash, zsh, sh, or pwsh] on the target Client and return its exit status, duration, and output.",["command.run"],["command","powershell","shell","terminal"],{targetSupport:"single"}),ze("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"]),ze("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"}),ze("network-adapter-status","Network & connectivity","Check network adapters","Show adapter state, address, and link information for the current targets.",["network.status"],["adapter","ethernet","wifi","네트워크 상태"]),ze("network-disconnected","Network & connectivity","Find disconnected targets","Find current targets with disconnected or degraded network adapters.",["network.status"],["disconnected","offline","연결 끊김"]),ze("network-link-speed","Network & connectivity","Check link speed","Report network link speed and duplex information for the current targets.",["network.status"],["speed","bandwidth","duplex"]),ze("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"]),ze("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"]),ze("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"]),ze("network-compare","Network & connectivity","Compare target connectivity","Compare adapter state, addresses, and link speed across the current targets.",["network.status"],["compare","inventory","connectivity"]),ze("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"]),ze("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"}),ze("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"}),ze("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"}),ze("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"}),ze("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"}),ze("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"}),ze("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"}),ze("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"}),ze("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"}),ze("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"}),ze("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"}),ze("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"}),ze("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"}),ze("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"}),ze("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"}),ze("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","장애 보고서"])],Hd={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 AR(e,t){return e==="safe-auto"?Hd:e==="full-access"?{...Hd,processControl:"allow",serviceControl:"allow",applicationControl:"allow",fileDelete:"allow",shell:"allow",script:"allow",softwareInstall:"allow",systemPower:"allow",systemConfiguration:"allow"}:e==="custom"&&t?t:{...Hd,processControl:"ask",serviceControl:"ask",applicationControl:"ask",fileWrite:"ask",network:"ask"}}function NR(e,t,n){const s=AR(t,n),a=e.requiredOperations.map(i=>s[Qs[i].permissionCategory]);if(a.includes("deny")){const i=e.requiredOperations.find(c=>s[Qs[c].permissionCategory]==="deny");return{state:"blocked",label:"Blocked",reason:`This task requires ${Qs[i].label}, which is blocked by the current permission policy.`}}return a.includes("ask")?{state:"approval",label:"Approval required",reason:"This task requires approval before the requested changes can reach a Client."}:e.requiredOperations.every(i=>Qs[i].readOnly)?{state:"read-only",label:"Read only"}:t==="full-access"?{state:"full-access",label:"Full Access"}:{state:"auto",label:"Auto allowed"}}function RR(e){const t=String(e||"").trim().toLowerCase();return t==="windows"||t==="win32"||t==="win32nt"?"windows":t==="macos"||t==="macosx"||t==="darwin"||t==="osx"?"macos":t==="linux"?"linux":null}function TR(e,t,n){const s=new Set(n);return e.filter(a=>a.connected&&(t==="all"||t==="auto"||s.has(a.deviceId)))}function PR(e,t){const n=RR(e.platform);if(!n||!t.supportedPlatforms.includes(n))return!1;const s=e.capabilities?.agentTools;return!Array.isArray(s)||s.length===0?t.requiredOperations.every(a=>Qs[a].readOnly):t.requiredOperations.every(a=>s.includes(a))}function nw(e,t,n,s,a,i){const c=NR(e,a,i),u=TR(t,n,s),d=u.map(w=>w.deviceId),p={...c,available:!1,availableDeviceIds:[],unsupportedDeviceIds:d,risk:e.risk,supportedPlatforms:e.supportedPlatforms};if(u.length===0)return{...p,reason:"Select at least one connected Client."};if(e.targetSupport==="single"&&u.length!==1)return{...p,reason:"This task supports one Client at a time."};if(c.state==="blocked")return p;const h=u.filter(w=>PR(w,e)),m=h.map(w=>w.deviceId),g=d.filter(w=>!m.includes(w));return h.length===0?{...p,unsupportedDeviceIds:g,reason:"No current target supports the required platform and client capabilities."}:{...p,available:!0,availableDeviceIds:m,unsupportedDeviceIds:g}}function IR(e,t,n,s,a,i){return e.filter(c=>c.enabled&&nw(c,t,n,s,a,i).available).length}const Wd="livedesk.agentPromptRecent",zd="livedesk.agentPromptFavorites",jR={Recommended:Xs,"Health & capacity":Ji,"Processes & services":ox,"Files & configuration":ix,"Software & automation":fb,"Network & connectivity":Dp,"Power & maintenance":Zt,"Troubleshooting & recovery":ax};function yg(e){if(typeof window>"u")return[];try{const t=JSON.parse(window.localStorage.getItem(e)||"[]");return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}catch{return[]}}function $l(e,t){try{window.localStorage.setItem(e,JSON.stringify(t))}catch{}}function qd(e){return e==="all"?"All tasks":e==="recent"?"Recent":e==="favorites"?"Favorites":e==="read-only"?"Read only":e==="auto"?"Auto allowed":e==="approval"?"Approval required":e==="full-access"?"Full Access":e==="available"?"Available":e==="unavailable"?"Unavailable":e}function ER(e){return e==="all"?"All":e==="recent"?"Recent":e==="favorites"?"Favorites":e==="read-only"?"Read only":e==="auto"?"Auto":e==="approval"?"Approval":e==="full-access"?"Full access":e==="available"?"Available":e==="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"}[e]}function FR(e,t,n){if(!n.trim())return!0;const s=n.trim().toLowerCase();return[e.title,e.prompt,e.description,e.category,e.risk,t.label,...e.keywords,...e.requiredOperations,...e.supportedPlatforms].join(" ").toLowerCase().includes(s)}function DR(e){return`permission-${e}`}function LR(e){return e==="low"?"Low risk":e==="medium"?"Medium risk":e==="high"?"High risk":"Critical risk"}function _R(e){return e==="windows"?"Windows":e==="macos"?"macOS":"Linux"}function $R({devices:e,targetMode:t,selectedIds:n,permissionMode:s,customCategories:a,onSelectPrompt:i,onClose:c}){const[u,d]=o.useState(""),[p,h]=o.useState("all"),[m,g]=o.useState(()=>yg(Wd)),[w,v]=o.useState(()=>yg(zd)),[y,k]=o.useState(0),[N,C]=o.useState(""),A=o.useRef(null),E=o.useRef(null),I=o.useMemo(()=>tw.filter(U=>U.enabled),[]),F=o.useMemo(()=>new Map(I.map(U=>[U.id,nw(U,e,t,n,s,a)])),[a,e,s,n,t,I]),M=o.useMemo(()=>[...F.values()].filter(U=>U.available).length,[F]),H=o.useMemo(()=>e.filter(U=>U.connected&&(t==="all"||t==="auto"||n.includes(U.deviceId))).length,[e,n,t]),V=o.useMemo(()=>{const U=I.filter(ie=>FR(ie,F.get(ie.id),u));return p==="recent"?m.map(ie=>U.find(j=>j.id===ie)).filter(ie=>!!ie):p==="favorites"?w.map(ie=>U.find(j=>j.id===ie)).filter(ie=>!!ie):p==="all"?U:U.filter(ie=>{const j=F.get(ie.id);return p==="read-only"?j.state==="read-only":p==="auto"?j.state==="auto":p==="approval"?j.state==="approval":p==="full-access"?j.state==="full-access":p==="available"?j.available:p==="unavailable"?!j.available:ie.category===p})},[F,w,p,m,u,I]),P=o.useMemo(()=>p!=="all"?[{category:qd(p),templates:V}]:vg.map(U=>({category:U,templates:V.filter(ie=>ie.category===U)})).filter(U=>U.templates.length>0),[p,V]);o.useEffect(()=>{k(U=>Math.min(U,Math.max(0,V.length-1)))},[V.length]),o.useEffect(()=>{$l(Wd,m)},[m]),o.useEffect(()=>{$l(zd,w)},[w]),o.useEffect(()=>{E.current?.focus();const U=j=>{j.target instanceof Node&&!A.current?.contains(j.target)&&c()},ie=j=>{j.key==="Escape"&&(j.preventDefault(),c())};return document.addEventListener("pointerdown",U),document.addEventListener("keydown",ie),()=>{document.removeEventListener("pointerdown",U),document.removeEventListener("keydown",ie)}},[c]);const D=U=>{const ie=F.get(U.id);if(!ie.available){C(ie.reason||"This task is not available for the current targets and permission policy.");return}const j=[U.id,...m.filter(re=>re!==U.id)].slice(0,10);g(j),$l(Wd,j),i(U.prompt),c()},O=U=>{v(ie=>{const j=ie.includes(U)?ie.filter(re=>re!==U):[U,...ie];return $l(zd,j),j})},X=U=>{U.key==="ArrowDown"?(U.preventDefault(),k(ie=>Math.min(ie+1,Math.max(0,V.length-1)))):U.key==="ArrowUp"?(U.preventDefault(),k(ie=>Math.max(ie-1,0))):U.key==="Enter"&&V[y]&&(U.preventDefault(),D(V[y]))};let G=-1;return r.jsxs("section",{className:"agents-suggested-tasks",ref:A,"aria-label":"Suggested tasks",children:[r.jsxs("header",{className:"agents-suggested-header",children:[r.jsxs("div",{children:[r.jsxs("span",{className:"agents-suggested-title",children:[r.jsx(Xs,{size:15})," Suggested tasks"]}),r.jsxs("small",{children:[M," available · ",I.length," total. Choose a task, edit it, then run it."]})]}),r.jsx("button",{className:"agents-suggested-close",type:"button","aria-label":"Close suggested tasks",onClick:c,children:r.jsx(xn,{size:16})})]}),r.jsxs("label",{className:"agents-suggested-search",children:[r.jsx(sx,{size:15,"aria-hidden":"true"}),r.jsx("input",{ref:E,value:u,onChange:U=>d(U.target.value),onKeyDown:X,placeholder:"Search tasks...","aria-label":"Search suggested tasks"})]}),r.jsx("div",{className:"agents-suggested-filters","aria-label":"Task categories and availability filters",children:["all","recent","favorites","read-only","auto","approval","full-access","available","unavailable",...vg].map(U=>{const ie=U==="recent"?hb:U==="favorites"?sp:U==="all"?Xs:U==="available"?En:U==="unavailable"?xb:U==="read-only"||U==="auto"||U==="approval"||U==="full-access"?Zt:jR[U];return r.jsxs("button",{className:p===U?"active":"",type:"button",title:qd(U),"aria-label":qd(U),"aria-pressed":p===U,onClick:()=>{h(U),k(0),C("")},children:[r.jsx(ie,{size:12})," ",ER(U)]},U)})}),N&&r.jsx("div",{className:"agents-suggested-notice",role:"status",children:N}),r.jsxs("div",{className:"agents-suggested-list",role:"listbox","aria-label":"Suggested tasks",children:[P.map(U=>r.jsxs("div",{className:"agents-suggested-group",children:[r.jsx("strong",{children:U.category}),U.templates.map(ie=>{G+=1;const j=G===y,re=w.includes(ie.id),de=F.get(ie.id),Q=de.availableDeviceIds.length+de.unsupportedDeviceIds.length||H,ge=de.available?`Available on ${de.availableDeviceIds.length} of ${Q} target${Q===1?"":"s"}`:`Unavailable: ${de.reason||"not supported by the current targets"}`;return r.jsxs("div",{className:`agents-suggested-item ${j?"active":""} ${de.available?"":"unavailable"}`,children:[r.jsxs("button",{className:"agents-suggested-prompt",type:"button",role:"option","aria-selected":j,"aria-disabled":!de.available,onClick:()=>D(ie),children:[r.jsx("span",{children:ie.title}),r.jsx("small",{className:"agents-suggested-description",children:ie.description}),r.jsxs("span",{className:"agents-suggested-meta",children:[r.jsx("em",{children:ie.category}),r.jsx("em",{className:DR(de.state),children:de.label}),r.jsx("em",{className:`risk-${ie.risk}`,children:LR(ie.risk)}),r.jsx("em",{children:ie.supportedPlatforms.map(_R).join(" · ")}),r.jsx("em",{className:de.available?"availability-ok":"availability-unavailable",children:ge}),de.available&&de.unsupportedDeviceIds.length>0&&r.jsxs("em",{className:"availability-warning",children:["Unsupported on ",de.unsupportedDeviceIds.length]})]})]}),r.jsx("button",{className:`agents-suggested-favorite ${re?"favorite":""}`,type:"button","aria-label":re?`Remove ${ie.title} from favorites`:`Add ${ie.title} to favorites`,"aria-pressed":re,onClick:()=>O(ie.id),children:r.jsx(sp,{size:14,fill:re?"currentColor":"none"})})]},ie.id)})]},U.category)),V.length===0&&r.jsx("p",{className:"agents-suggested-empty",children:"No tasks match this search or current filter."})]})]})}function OR({devices:e,mode:t,selectedIds:n,onModeChange:s,onToggle:a,permissionMode:i,onPermissionModeChange:c}){const u=e.filter(mu),d=n.filter(p=>u.some(h=>h.deviceId===p)).length;return r.jsxs("section",{className:"agents-target-picker","aria-label":"Agent targets",children:[r.jsxs("div",{className:"agents-target-toolbar",children:[r.jsx("span",{className:"agents-section-label",children:"Targets"}),r.jsxs("div",{className:"agents-target-modes",children:[r.jsxs("button",{className:t==="all"?"active":"",onClick:()=>s("all"),type:"button",children:[r.jsx(sc,{size:14})," All connected ",r.jsx("small",{children:u.length})]}),r.jsxs("button",{className:t==="selected"?"active":"",onClick:()=>s("selected"),type:"button",children:[r.jsx(Ns,{size:14})," Selected ",d]}),r.jsxs("button",{className:t==="auto"?"active":"",onClick:()=>s("auto"),type:"button",children:[r.jsx(Xs,{size:14})," Auto"]}),r.jsxs("button",{type:"button",disabled:!0,title:"Saved Client groups are coming next.",children:[r.jsx(sc,{size:14})," Group ",r.jsx("small",{children:"Soon"})]})]}),r.jsxs("label",{className:`agents-permission-picker permission-${i}`,children:[r.jsx(vu,{size:14}),r.jsx("span",{children:"Permission"}),r.jsxs("select",{value:i,onChange:p=>c(p.target.value),"aria-label":"Agent permission mode",children:[r.jsx("option",{value:"ask",children:"Ask"}),r.jsx("option",{value:"safe-auto",children:"Safe Auto"}),r.jsx("option",{value:"full-access",children:"Full Access"}),r.jsx("option",{value:"custom",children:"Custom"})]}),r.jsx(yb,{size:13,"aria-hidden":"true"})]})]}),r.jsx("div",{className:"agents-target-list",children:e.length===0?r.jsx("span",{className:"agents-target-empty",children:"No Clients discovered."}):e.map(p=>{const h=mu(p),m=t==="all"||t==="auto"?h:n.includes(p.deviceId);return r.jsxs("label",{className:`agents-target-option ${m?"selected":""} ${h?"":"offline"}`,children:[r.jsx("input",{type:"checkbox",checked:m,disabled:!h||t!=="selected",onChange:()=>a(p.deviceId)}),r.jsx("span",{className:"agents-target-icon",children:r.jsx(pn,{size:15})}),r.jsxs("span",{children:[r.jsx("strong",{children:pu(p)}),r.jsx("small",{children:h?"Ready":p.connected?"Agent reconnecting":"Offline"})]}),m&&r.jsx(Ns,{className:"agents-target-check",size:15,"aria-hidden":"true"})]},p.deviceId)})})]})}const BR=800,xg=5e3;function HR(){return typeof document>"u"||document.visibilityState==="visible"}function WR(e){return typeof document>"u"?()=>{}:(document.addEventListener("visibilitychange",e),()=>document.removeEventListener("visibilitychange",e))}function Sg({poll:e,onResult:t,onError:n,intervalMs:s=BR,isVisible:a=HR,subscribeVisibility:i=WR,setTimeoutImpl:c=globalThis.setTimeout.bind(globalThis),clearTimeoutImpl:u=globalThis.clearTimeout.bind(globalThis),createAbortController:d=()=>new AbortController}){if(typeof e!="function")throw new TypeError("Agent polling requires a poll function.");const p={current:null};let h=!0,m=0,g=null,w=null;const v=()=>{g!==null&&(u(g),g=null)},y=()=>{!h||!a()||g!==null||p.current||(g=c(()=>{g=null,k()},s))},k=()=>{if(!h||!a()||p.current)return p.current;const E=++m,I=d();w=I;const F=Qa(p,()=>e(I.signal));return F.then(M=>{h&&E===m&&!I.signal.aborted&&t?.(M)},M=>{h&&E===m&&!I.signal.aborted&&n?.(M)}).finally(()=>{w===I&&(w=null),h&&a()&&y()}).catch(()=>{}),F},N=async()=>{if(!h)throw new Error("LiveDesk Agent polling owner is closed.");v(),m+=1;const E=p.current;if(w&&!w.signal.aborted&&w.abort(new Error("LiveDesk Agent polling was superseded by an explicit refresh.")),E)try{await E}catch{}if(!(!h||!a()))return v(),k()},A=i(()=>{if(v(),!a()){m+=1,w&&!w.signal.aborted&&w.abort(new Error("LiveDesk Agent polling paused while hidden."));return}k()});return k(),{refresh:N,stop(){h&&(h=!1,m+=1,v(),A?.(),w&&!w.signal.aborted&&w.abort(new Error("LiveDesk Agent polling owner closed.")))}}}async function zR(e,t){return Oe("/api/settings/agent/run",{method:"POST",body:JSON.stringify(t)},e)}async function qR(e,t,n={}){return Oe(`/api/settings/agent/runs/${encodeURIComponent(t)}`,n,e)}async function UR(e,t){return Oe(`/api/settings/agent/runs/${encodeURIComponent(t)}/cancel`,{method:"POST",body:JSON.stringify({})},e)}async function VR(e){return Oe("/api/settings/agent/runs/cancel-all",{method:"POST",body:JSON.stringify({})},e)}async function GR(e,t,n,s){return Oe(`/api/settings/agent/runs/${encodeURIComponent(t)}/approvals/${encodeURIComponent(n)}/approve`,{method:"POST",body:JSON.stringify({scope:s})},e)}async function KR(e,t,n,s="User rejected this action."){return Oe(`/api/settings/agent/runs/${encodeURIComponent(t)}/approvals/${encodeURIComponent(n)}/reject`,{method:"POST",body:JSON.stringify({reason:s})},e)}async function QR(e,t,n){return Oe(`/api/settings/agent/policies/${encodeURIComponent(t)}`,{method:"PUT",body:JSON.stringify({categories:n})},e)}async function YR(e,t,n={}){return Oe(`/api/remote/tasks/${encodeURIComponent(t)}`,n,e)}async function XR(e,t){return Oe(`/api/remote/tasks/${encodeURIComponent(t)}/cancel`,{method:"POST",body:JSON.stringify({})},e)}async function JR(e,t){return Oe(`/api/remote/tasks/${encodeURIComponent(t)}/retry`,{method:"POST",body:JSON.stringify({failedOnly:!0})},e)}function zo(e){return`${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function Ud(e,t){const n=new Map(t.map(s=>[s.deviceId,pu(s)]));return e.results.map(s=>({deviceId:s.deviceId,deviceName:s.deviceName||n.get(s.deviceId)||s.deviceId,status:mR(s.status),stage:s.stage||(s.status==="running"?"Checking processes":void 0),result:s.result,data:s.data,error:s.error,sequence:Number.isSafeInteger(s.sequence)?s.sequence:0}))}function ZR(e,t){const n=new Map(t.map(s=>[s.deviceId,s]));return e.map(s=>{const a=n.get(s.deviceId);return!a||a.sequence<=s.sequence?s:a})}const eT={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 tT(e){return e==="safe-auto"?"Safe Auto":e==="full-access"?"Full Access":e==="custom"?"Custom":"Ask"}function nT(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase())}function rT(e){const t=e instanceof Error?e.message:String(e);return/agent-disabled/i.test(t)?"Enable Codex Agent in Settings before running commands.":/agent-no-target-devices|agent-target-not-connected|device-not-connected/i.test(t)?"The selected Client is reconnecting. Wait until its Agent status is Ready and try again.":/codex-auth-required/i.test(t)?"Codex sign-in is required on the Hub. Open Settings > Agent and test the Codex connection.":t}function Cg({hubUrl:e,devices:t,launchRequest:n,variant:s="page",selectedDeviceIds:a=[]}){const i=s==="dock",[c,u]=o.useState(i?a.length>0?"selected":"auto":"all"),[d,p]=o.useState(a),[h,m]=o.useState("auto"),[g,w]=o.useState(""),[v,y]=o.useState([]),[k,N]=o.useState(""),[C,A]=o.useState(""),[E,I]=o.useState(""),[F,M]=o.useState("safe-auto"),[H]=o.useState("custom-default"),[V,P]=o.useState(eT),[D,O]=o.useState([]),[X,G]=o.useState(""),[U,ie]=o.useState(!1),[j,re]=o.useState(null),[de,Q]=o.useState(!1),[ge,oe]=o.useState(""),[me,Ae]=o.useState(!1),[Te,Pe]=o.useState(null),Se=o.useRef(null),te=o.useRef(null),Ce=o.useRef(null),Fe=o.useRef(new Set),Le=o.useRef(new Set),Ue=o.useMemo(()=>t.filter(mu).map(Y=>Y.deviceId),[t]),ne=o.useMemo(()=>IR(tw,t,c,d,F,V),[V,t,F,d,c]);o.useEffect(()=>{i&&p(a)},[i,a]),o.useEffect(()=>{n?.deviceId&&(u("selected"),p([n.deviceId]),w(n.instruction),Ae(!1),window.requestAnimationFrame(()=>{Se.current?.focus(),Se.current?.setSelectionRange(n.instruction.length,n.instruction.length)}))},[n]);const ae=o.useCallback(Y=>{const K=Ud(Y,t);y(ee=>ee.map(R=>R.type==="task"&&R.batchId===Y.batchId?{...R,states:ZR(R.states,K),status:Y.status}:R)),["running","queued"].includes(Y.status)||N(ee=>ee===Y.batchId?"":ee)},[t]),le=o.useCallback((Y,K)=>{Le.current.has(Y.batchId)||(Le.current.add(Y.batchId),y(ee=>[...ee,{type:"task",id:zo("task"),batchId:Y.batchId,agentRunId:K,operation:Y.operation||"diagnostics.collect",instruction:Y.instructionPreview,states:Ud(Y,t),status:Y.status}])),ae(Y)},[t,ae]),ce=o.useCallback((Y,K)=>{for(const R of K.taskBatches||[])le(R,Y);O(K.approvals||[]);const ee=["running","queued","waiting-approval"].includes(K.status);if(Pe(ee?{runId:Y,stage:K.stage||K.status,message:K.progressMessage||(K.status==="waiting-approval"?"Review the requested action to continue.":"Codex is preparing the answer.")}:R=>R?.runId===Y?null:R),!ee&&!Fe.current.has(Y)){Fe.current.add(Y);const R=[K.error,K.errorMessage].filter(Boolean).join(" — "),se=K.finalResponse?.trim()||(K.status==="cancelled"?"Codex 작업을 취소했습니다.":R?`Codex 작업이 완료되지 않았습니다: ${R}`:"Codex 작업이 완료되었습니다.");y(Ie=>[...Ie,{type:K.status==="failed"?"error":"agent",id:zo("agent-run-result"),text:se}])}},[le]),J=o.useCallback(async Y=>{const K=te.current;if(!(!K||K.id!==Y))try{return await K.owner.refresh()}catch(ee){if(te.current!==K)return;throw ee}},[]);o.useEffect(()=>{if(!C){te.current=null;return}const Y=C,K=Sg({poll:R=>qR(e,Y,{signal:R,timeoutMs:xg}),onResult:R=>{ce(Y,R),["running","queued","waiting-approval"].includes(R.status)||(A(se=>se===Y?"":se),Q(!1))},onError:R=>{oe(R instanceof Error?R.message:String(R))}}),ee={id:Y,owner:K};return te.current=ee,()=>{K.stop(),te.current===ee&&(te.current=null)}},[C,e,ce]),o.useEffect(()=>{if(!k){Ce.current=null;return}const Y=k,K=Sg({poll:R=>YR(e,Y,{signal:R,timeoutMs:xg}),onResult:R=>{ae(R),["running","queued"].includes(R.status)||N(se=>se===Y?"":se)},onError:R=>{oe(R instanceof Error?R.message:String(R))}}),ee={id:Y,owner:K};return Ce.current=ee,()=>{K.stop(),Ce.current===ee&&(Ce.current=null)}},[k,e,ae]);const ye=async(Y="",K,ee=!1)=>{const R=(Y||g).trim();if(!R||k||C)return;const se=K||(c==="all"||c==="auto"?Ue:d.filter(xe=>Ue.includes(xe)));if(se.length===0){oe("Select at least one connected Client.");return}if(F==="full-access"&&!de&&!ee){re({instruction:R,targetIds:se});return}if(y(xe=>[...xe,{type:"user",id:zo("user"),text:R}]),w(""),Ae(!1),oe(""),se.length===0){y(xe=>[...xe,{type:"error",id:zo("no-targets"),text:"연결된 대상 장비를 하나 이상 선택해 주세요."}]);return}const He=h==="ask"?`Read-only request. Inspect and answer without changing Client state.
164
+ `;function t0({eligibleCandidates:e,fallbackHubBaseUrl:t,publicConsole:n,authenticated:s}){const a=[...new Set((Array.isArray(e)?e:[]).map(c=>String(c||"").trim()).filter(Boolean))];if(a.length>0)return Object.freeze({candidates:Object.freeze(a),transport:"auto",reason:"direct-candidate"});const i=String(t||"").trim();return Object.freeze(n&&s&&i?{candidates:Object.freeze([i]),transport:"relay",reason:"authenticated-public-console-fallback"}:{candidates:Object.freeze([]),transport:"auto",reason:"unavailable"})}const n0=new Set(["not-connected","device-not-connected"]);function df(e,t=!1){const n=String(e||"").trim().toLowerCase();return n==="capture_transition_in_progress".toLowerCase()?t===!0:n0.has(n)}const pf="livedesk_remote_host_targets",r0="livedesk_entitlements",mf=4e3,s0=2500,Up=new TextDecoder,wp=new Set;function a0(){const e=[...wp].map(n=>n()),t=n=>e.reduce((s,a)=>s+Number(a[n]||0),0);return{ownerCount:e.length,activeOwnerCount:e.filter(n=>n.active).length,socketCount:t("socketCount"),openSocketCount:t("openSocketCount"),connectingSocketCount:t("connectingSocketCount"),closingSocketCount:t("closingSocketCount"),closingSocketTimerCount:t("closingSocketTimerCount"),closingSocketTimeoutCount:t("closingSocketTimeoutCount"),expectedBindingCount:t("expectedBindingCount"),reconnectTimerCount:t("reconnectTimerCount"),statsTimerCount:t("statsTimerCount"),configurationRefreshTimerCount:t("configurationRefreshTimerCount"),restartTokenCount:t("restartTokenCount"),retainedFrameCount:t("retainedFrameCount"),retainedPayloadBytes:t("retainedPayloadBytes"),owners:e}}function i0(){return Xt.snapshot()}function o0(e){const n=(Array.isArray(e)?e:[e||an]).map(s=>ub(s||an));return[...new Set(n.filter(Boolean))]}function c0(){const[e,t]=o.useState(null),[n,s]=o.useState(!0),a=o.useRef(null);return o.useEffect(()=>{let i=!0,c=0;const u=async(g=!1)=>{try{const w=await(window.liveDesk?.auth?.getSession?.()||pt.auth.getSession());if(!i)return;const v=Tb(w);(g||v)&&t(v)}finally{i&&s(!1)}},d=()=>{if(document.visibilityState==="hidden")return;const g=Date.now();g-c<1e3||(c=g,Ya(a,()=>u(!1)).catch(()=>{}))},p=window.liveDesk?.auth?.onComplete?.(g=>{g.ok&&g.session?pt.auth.setSession(g.session):g.ok&&g.signedOut&&(t(null),s(!1),pt.auth.signOut({scope:"local"}).catch(()=>{}))});u(!0).catch(()=>{});const{data:{subscription:h}}=pt.auth.onAuthStateChange((g,w)=>{if(!w&&window.liveDesk?.auth){s(!1);return}t(w),s(!1),w&&window.liveDesk?.auth?.persistSession?.(w)}),m=()=>d();return window.addEventListener("pageshow",d),window.addEventListener("online",d),window.addEventListener("focus",d),document.addEventListener("visibilitychange",m),()=>{i=!1,p?.(),h.unsubscribe(),window.removeEventListener("pageshow",d),window.removeEventListener("online",d),window.removeEventListener("focus",d),document.removeEventListener("visibilitychange",m)}},[]),{session:e,loading:n}}function l0(e,t=!0,n=""){const[s,a]=o.useState(null),[i,c]=o.useState([]),[u,d]=o.useState(""),[p,h]=o.useState(""),m=o.useRef(new Map),g=o.useRef(null),w=Array.isArray(e)?e.join(`
165
+ `):String(e||""),v=o.useMemo(()=>o0(e),[w]),y=o.useMemo(()=>v.find(C=>Ul(C)==="loopback")||v[0]||an,[v]),k=o.useCallback(async C=>{if(!t){a(null),c([]),h(""),d("");return}let A=null;const E=Date.now(),I=v.filter(M=>(m.current.get(M)||0)<=E),F=t0({eligibleCandidates:I,fallbackHubBaseUrl:y,publicConsole:eu(),authenticated:!!n});if(F.candidates.length===0)throw new Error("No LiveDesk Hub endpoint is reachable. Retrying shortly.");for(const M of F.candidates)try{const[H,V]=await Promise.all([Oe("/api/remote/status",{signal:C,timeoutMs:mf,transport:F.transport},M),Oe("/api/remote/devices",{signal:C,timeoutMs:mf,transport:F.transport},M)]);if(C?.aborted)throw C.reason||new Error("LiveDesk Hub snapshot cancelled.");if(!Array.isArray(V.devices))throw new Error("Invalid Hub devices response.");m.current.delete(M),a(H),c(V.devices),h(M),d("");return}catch(H){if(C?.aborted)throw H;A=H,F.transport==="auto"&&m.current.set(M,Date.now()+1e4)}throw h(""),A||new Error("No LiveDesk Hub endpoint is reachable.")},[n,t,y,v]),N=o.useCallback(()=>{m.current.clear(),Ya(g,()=>k()).catch(C=>{d(C instanceof Error?C.message:String(C))})},[k]);return o.useEffect(()=>{if(m.current.clear(),!t){a(null),c([]),h(""),d("");return}let C=!0,A=null;const E=new AbortController,I=()=>{Ya(g,()=>k(E.signal)).catch(M=>{C&&!E.signal.aborted&&d(M instanceof Error?M.message:String(M))}).finally(()=>{C&&!E.signal.aborted&&(A=window.setTimeout(I,s0))})};return I(),()=>{C=!1,E.abort(new Error("LiveDesk Hub snapshot polling stopped.")),A!==null&&window.clearTimeout(A)}},[t,k]),o.useEffect(()=>{if(!t)return;let C=0;const A=()=>{if(document.visibilityState==="hidden")return;const I=Date.now();I-C<1e3||(C=I,m.current.clear(),eu()&&$y(),N())},E=()=>A();return window.addEventListener("pageshow",A),window.addEventListener("online",A),window.addEventListener("focus",A),document.addEventListener("visibilitychange",E),()=>{window.removeEventListener("pageshow",A),window.removeEventListener("online",A),window.removeEventListener("focus",A),document.removeEventListener("visibilitychange",E)}},[t,N]),{status:s,devices:i,error:u,refresh:N,hubBaseUrl:p||y,hubCandidates:v}}function u0(e){const[t,n]=o.useState(null),[s,a]=o.useState(""),i=e?.user?.id||"",c=o.useRef(null),u=o.useCallback(async()=>{if(!i){n(null);return}const{data:d,error:p}=await pt.from(pf).select("*").eq("user_id",i).maybeSingle();if(p){a(p.message);return}n(d),a("")},[i]);return o.useEffect(()=>{Ya(c,u).catch(()=>{})},[u]),o.useEffect(()=>{if(!i)return;let d=0;const p=()=>{if(document.visibilityState==="hidden")return;const m=Date.now();m-d<1e3||(d=m,Ya(c,u).catch(()=>{}))},h=()=>p();return window.addEventListener("pageshow",p),window.addEventListener("online",p),window.addEventListener("focus",p),document.addEventListener("visibilitychange",h),()=>{window.removeEventListener("pageshow",p),window.removeEventListener("online",p),window.removeEventListener("focus",p),document.removeEventListener("visibilitychange",h)}},[u,i]),o.useEffect(()=>{if(!i)return;const d=pt.channel(`livedesk-remote-host-targets-${i.replace(/[^a-zA-Z0-9]/g,"")}`).on("postgres_changes",{event:"*",schema:"public",table:pf,filter:`user_id=eq.${i}`},p=>n(p.new)).subscribe();return()=>{pt.removeChannel(d)}},[i]),{target:t,error:s,refresh:u}}function d0(e){const[t,n]=o.useState(null),[s,a]=o.useState(!1),[i,c]=o.useState(""),u=e?.user?.id||"",d=o.useCallback(async()=>{if(!u){n(null),c(""),a(!1);return}a(!0);const{data:h,error:m}=await pt.from(r0).select("*").eq("user_id",u).eq("product_key","livedesk").maybeSingle();if(m){c(m.message),a(!1);return}n(h),c(""),a(!1)},[u]);o.useEffect(()=>{d()},[d]);const p=o.useMemo(()=>!t||t.status!=="active"?!1:t.expires_at?new Date(t.expires_at).getTime()>Date.now():!0,[t]);return{entitlement:t,licensed:p,loading:s,error:i,refresh:d}}const nc={totalFrames:0,totalBytes:0,framesPerSecond:0,bytesPerSecond:0,sampleMs:0,lastUpdatedAt:0},p0=2500,m0=3e4,h0=64*1024,f0=64*1024,g0=6,b0=g0,pv=new Map;function v0(e){return pv.get(e)}const hf={totalSent:0,totalDropped:0,sentPerSecond:0,droppedPerSecond:0,bufferedAmount:0,lastInputType:"",lastInputSeq:0,lastRoundTripMs:0,lastAgentApplyMs:0,lastUpdatedAt:0};function w0(e,t,n){const s=Number(t);if(!Number.isFinite(s)||s<=0)return 0;const a=n-s,i=e.minimumHubClockOffsetMs;if(!Number.isFinite(i)||a<Number(i))return e.minimumHubClockOffsetMs=a,0;const c=Math.max(0,a-Number(i));return c>m0?(e.minimumHubClockOffsetMs=a,0):c}function Ve(e){if(e==null||e==="")return;const t=Number(e);return Number.isFinite(t)?t:void 0}const y0=["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 x0(e){return Number(e.nativeCaptureTelemetryVersion)>=5&&y0.every(t=>Ve(e[t])!==void 0)&&typeof e.nativeOutputQueueAwaitingKeyFrame=="boolean"&&e.nativeCopyTelemetryAvailable===!0}function S0(e,t,n){if(!e||typeof e!="object")return null;const s=e,a=String(s.deviceId||t||"").trim(),i=String(s.sessionId||"").trim(),c=String(s.streamId||"").trim(),u=s.streamPurpose==="control"?"control":s.streamPurpose==="wall"?"wall":null,d=String(s.commandId||"").trim(),p=Number(s.captureGeneration||0),h=Number(s.monitorIndex??-1);return!a||a!==t||!u||u!==n||!i||!c||!d||!Number.isSafeInteger(p)||p<=0||!Number.isSafeInteger(h)||h<0?null:{deviceId:a,sessionId:i,streamId:c,streamPurpose:u,commandId:d,captureGeneration:p,monitorIndex:h}}function ff(e,t,n=an,s={}){const[a,i]=o.useState(new Map),[c,u]=o.useState("idle"),[d,p]=o.useState(""),[h,m]=o.useState(nc),g=o.useRef(new Map),w=o.useRef(new Map),v=o.useRef(new Map),y=o.useRef(null);y.current===null&&(y.current=NC());const k=o.useRef(0),N=o.useRef(new Map),C=o.useRef({enabled:!1,token:"",reason:""}),A=o.useRef(new Map),E=o.useRef(null),I=o.useRef(new Map),[F,M]=o.useState(0),H=o.useRef(s.onFrame),V=o.useRef(s.onStreamReady),P=o.useRef({totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0}),D=o.useMemo(()=>[...e].sort().join(","),[e]),O=t&&D.length>0,X=o.useRef(!1);o.useLayoutEffect(()=>(X.current=O,()=>{X.current=!1}),[O]);const G=Number.isFinite(s.fps)?Number(s.fps):2,U=Number.isFinite(s.maxWidth)?Number(s.maxWidth):640,ie=Number.isFinite(s.maxHeight)?Number(s.maxHeight):360,j=Number.isFinite(s.quality)?Number(s.quality):45,re=Number.isFinite(s.configurationRefreshMs)?Math.max(0,Math.round(Number(s.configurationRefreshMs))):0,de=String(s.frameMode||s.mode||"mode3-h264-hw").trim()||"mode3-h264-hw",Q=s.streamPurpose==="control"?"control":"wall",ge=s.forceRestart===!0,oe=String(s.forceRestartToken||"").trim(),me=String(s.restartReason||"").trim();C.current={enabled:ge,token:oe,reason:me};const Ae=o.useMemo(()=>{const ce=Object.entries(s.monitorSelections||{}).filter(([J])=>!!J).sort(([J],[ye])=>J.localeCompare(ye));return JSON.stringify(Object.fromEntries(ce))},[s.monitorSelections]),Te=o.useMemo(()=>{const ce=Object.entries(s.connectionSessionIds||{}).filter(([J])=>!!J).map(([J,ye])=>[J,String(ye||"").trim()]).sort(([J],[ye])=>J.localeCompare(ye));return JSON.stringify(Object.fromEntries(ce))},[s.connectionSessionIds]);o.useEffect(()=>{H.current=s.onFrame},[s.onFrame]),o.useEffect(()=>{V.current=s.onStreamReady},[s.onStreamReady]);const Pe=o.useCallback((ce,J="livedesk-frame-socket-release")=>{RC(ce,J,y.current)},[]),Se=o.useCallback(ce=>{const J=A.current.get(ce);J!==void 0&&(window.clearTimeout(J),A.current.delete(ce))},[]),te=o.useCallback(ce=>{const J=I.current.get(ce);J!==void 0&&(window.clearTimeout(J),I.current.delete(ce))},[]),Ce=o.useCallback((ce,J=!0)=>{for(const ye of A.current.values())window.clearTimeout(ye);A.current.clear();for(const ye of I.current.values())window.clearTimeout(ye);I.current.clear();for(const ye of v.current.values())ye.expectedBinding=void 0,Pe(ye,ce);v.current.clear(),N.current.clear(),g.current=new Map,w.current.clear(),P.current={totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0},J&&(i(new Map),p(""),m(nc),u("idle"))},[Pe]),Fe=o.useCallback(()=>{const ce=[...v.current.values()].map(J=>J.socket);if(ce.length===0){u("idle");return}if(ce.some(J=>J.readyState===WebSocket.OPEN)){u("open");return}if(ce.some(J=>J.readyState===WebSocket.CONNECTING)){u("connecting");return}u("closed")},[]),Le=o.useCallback((ce,J,ye,ue)=>{if(J.disposed||J.socket.readyState!==WebSocket.OPEN)return!1;try{return J.socket.send(JSON.stringify({...J.payload,type:"restart-live",deviceIds:[ce],forceRestart:!0,restartReason:ye,restartToken:ue})),J.expectedBinding=void 0,cf(J.sparseTelemetry),!0}catch{return!1}},[]),Ue=o.useCallback((ce,J)=>{if(J.disposed||v.current.get(ce)!==J||J.socket.readyState!==WebSocket.OPEN)return!1;try{return J.socket.send(JSON.stringify({...J.payload,type:"refresh-live",deviceIds:[ce],forceRestart:!1,reuseExisting:!0,reason:"initial-configuration-settle"})),!0}catch{try{J.socket.close(4003,"configuration-refresh-failed")}catch{}return!1}},[]),ne=o.useCallback((ce,J)=>{if(!X.current||J.disposed||!ce||ce.byteLength<5)return;const ye=Date.now(),Ee=new DataView(ce).getUint32(0,!1);if(Ee<=0||Ee+4>ce.byteLength)return;const nt=new Uint8Array(ce,4,Ee),T=JSON.parse(Up.decode(nt));EC(T,J.sparseTelemetry,J.expectedBinding);const ve=Ve(T.hubPacketEpochMs),De=ve!==void 0&&ve>0?ve:void 0,qe=w0(J,De,ye);if(qe>p0)return;const _e=new Uint8Array(ce,4+Ee),$e=Ve(T.nativeCaptureTelemetryVersion),mt=Ve(T.nativeCaptureTelemetryAgeMs),ct=Ve(T.hubClientDropped),z=Ve(T.hubClientQueueDepth),pe=Ve(T.hubClientQueueLimit),Y=Ve(T.hubClientBufferedBytes),K=ct!==void 0&&z!==void 0&&pe!==void 0&&Y!==void 0,ee={deviceId:String(T.deviceId||""),kind:T.kind==="thumbnail"?"thumbnail":"live",frameSeq:Number(T.frameSeq||0),streamFrameSeq:Number(T.streamFrameSeq||0)||void 0,streamId:String(T.streamId||""),commandId:T.commandId?String(T.commandId):void 0,sessionId:T.sessionId?String(T.sessionId):void 0,captureGeneration:Number(T.captureGeneration||0)||void 0,currentGenerationVerified:!1,streamPurpose:T.streamPurpose?String(T.streamPurpose):void 0,width:Number(T.width||0),height:Number(T.height||0),sourceWidth:Number(T.sourceWidth||0)||void 0,sourceHeight:Number(T.sourceHeight||0)||void 0,mimeType:String(T.mimeType||"image/jpeg"),mode:T.mode?String(T.mode):void 0,frameMode:T.frameMode?String(T.frameMode):void 0,frameProfile:T.frameProfile?String(T.frameProfile):void 0,encoding:T.encoding?String(T.encoding):void 0,codec:T.codec?String(T.codec):void 0,compression:T.compression?String(T.compression):void 0,pixelFormat:T.pixelFormat?String(T.pixelFormat):void 0,bytesPerPixel:Number(T.bytesPerPixel||0)||0,uncompressedByteLength:Number(T.uncompressedByteLength||0)||0,h264Format:T.h264Format?String(T.h264Format):void 0,isKeyFrame:T.isKeyFrame===!0,chunkType:T.chunkType?String(T.chunkType):void 0,timestampUs:Number(T.timestampUs||0)||0,durationUs:Number(T.durationUs||0)||0,sourceGapMs:Number(T.sourceGapMs||0)||0,agentSendGapMs:Number(T.agentSendGapMs||0)||0,agentSendDurationMs:Number(T.agentSendDurationMs||0)||0,agentSendDurationFrameSeq:Number(T.agentSendDurationFrameSeq||0)||0,agentPaceMs:Number(T.agentPaceMs||0)||0,agentQueueBeforePaceMs:Number(T.agentQueueBeforePaceMs||0)||0,agentFrameAgeMs:Number(T.agentFrameAgeMs||0)||0,inputFeedbackEventId:T.inputFeedbackEventId?String(T.inputFeedbackEventId):void 0,inputFeedbackInputSeq:Ve(T.inputFeedbackInputSeq),inputFeedbackInputType:T.inputFeedbackInputType?String(T.inputFeedbackInputType):void 0,inputFeedbackIssuedAtEpochMs:Ve(T.inputFeedbackIssuedAtEpochMs),inputFeedbackHubReceivedAtEpochMs:Ve(T.inputFeedbackHubReceivedAtEpochMs),inputFeedbackHubForwardedAtEpochMs:Ve(T.inputFeedbackHubForwardedAtEpochMs),inputFeedbackAgentReceivedAtEpochMs:Ve(T.inputFeedbackAgentReceivedAtEpochMs),inputFeedbackAppliedAtEpochMs:Ve(T.inputFeedbackAppliedAtEpochMs),inputFeedbackAgentApplyMs:Ve(T.inputFeedbackAgentApplyMs),inputFeedbackApplyToCaptureMs:Ve(T.inputFeedbackApplyToCaptureMs),inputFeedbackCaptureTimestampAvailable:typeof T.inputFeedbackCaptureTimestampAvailable=="boolean"?T.inputFeedbackCaptureTimestampAvailable:void 0,nativeCaptureTelemetryAvailable:typeof T.nativeCaptureTelemetryAvailable=="boolean"?T.nativeCaptureTelemetryAvailable:void 0,nativeCaptureTelemetryVersion:$e===void 0?void 0:Math.max(0,$e),nativeCaptureTelemetryAgeMs:mt===void 0?void 0:Math.max(0,mt),nativeEncoderHardwareAccelerationKnown:typeof T.nativeEncoderHardwareAccelerationKnown=="boolean"?T.nativeEncoderHardwareAccelerationKnown:void 0,nativeEncoderHardwareAccelerated:typeof T.nativeEncoderHardwareAccelerated=="boolean"?T.nativeEncoderHardwareAccelerated:void 0,nativeEncoderHardwareQueryStatus:T.nativeEncoderHardwareQueryStatus?String(T.nativeEncoderHardwareQueryStatus):void 0,nativeCaptureDisplayId:Ve(T.nativeCaptureDisplayId),nativeCaptureFps:Ve(T.nativeCaptureFps),nativeCompressionFps:Ve(T.nativeCompressionFps),nativeEncodedFps:Ve(T.nativeEncodedFps),nativeCaptureSampleCount:Ve(T.nativeCaptureSampleCount),nativeEncodableFrameCount:Ve(T.nativeEncodableFrameCount),nativeSkippedFrameCount:Ve(T.nativeSkippedFrameCount),nativeCompressionOutputCount:Ve(T.nativeCompressionOutputCount),nativeEncodedFrameCount:Ve(T.nativeEncodedFrameCount),nativeEncodeFramesInFlight:Ve(T.nativeEncodeFramesInFlight),nativeEncodePendingFrameCount:Ve(T.nativeEncodePendingFrameCount),nativeEncodeTimestampOwnerCount:Ve(T.nativeEncodeTimestampOwnerCount),nativeEncodeTimestampOwnerHighWatermark:Ve(T.nativeEncodeTimestampOwnerHighWatermark),nativeBackpressureCoalescedFrameCount:Ve(T.nativeBackpressureCoalescedFrameCount),nativeBackpressureSkippedFrameCount:Ve(T.nativeBackpressureSkippedFrameCount),nativeEncodePendingReplacedFrameCount:Ve(T.nativeEncodePendingReplacedFrameCount),nativeIdleSkippedFrameCount:Ve(T.nativeIdleSkippedFrameCount),nativeVideoToolboxActiveSessionCount:Ve(T.nativeVideoToolboxActiveSessionCount),nativeVideoToolboxSessionHighWatermark:Ve(T.nativeVideoToolboxSessionHighWatermark),nativeOutputQueueDepth:Ve(T.nativeOutputQueueDepth),nativeOutputQueueBytes:Ve(T.nativeOutputQueueBytes),nativeOutputQueueOldestAgeMs:Ve(T.nativeOutputQueueOldestAgeMs),nativeOutputQueueHighWatermark:Ve(T.nativeOutputQueueHighWatermark),nativeOutputQueueDroppedCount:Ve(T.nativeOutputQueueDroppedCount),nativeOutputQueueAwaitingKeyFrame:typeof T.nativeOutputQueueAwaitingKeyFrame=="boolean"?T.nativeOutputQueueAwaitingKeyFrame:void 0,nativeCopyTelemetryAvailable:typeof T.nativeCopyTelemetryAvailable=="boolean"?T.nativeCopyTelemetryAvailable:void 0,nativeAnnexBAccessUnitAllocationCount:Ve(T.nativeAnnexBAccessUnitAllocationCount),nativeAnnexBPayloadCopyCount:Ve(T.nativeAnnexBPayloadCopyCount),nativeAnnexBPayloadCopiedBytes:Ve(T.nativeAnnexBPayloadCopiedBytes),nativeAndPipeResidenceAgeMs:Ve(T.nativeAndPipeResidenceAgeMs),pipePayloadAllocationCount:Ve(T.pipePayloadAllocationCount),pipePayloadCopyCount:Ve(T.pipePayloadCopyCount),pipePayloadCopiedBytes:Ve(T.pipePayloadCopiedBytes),handoffDroppedFrameCount:Ve(T.handoffDroppedFrameCount),handoffRecoveryKeyFrameRequestCount:Ve(T.handoffRecoveryKeyFrameRequestCount),handoffOldestFrameAgeMs:Ve(T.handoffOldestFrameAgeMs),nativeCaptureResourceTelemetryAvailable:T.nativeCaptureResourceTelemetryAvailable===!0?x0(T):T.nativeCaptureResourceTelemetryAvailable===!1?!1:void 0,nativeCaptureTelemetryAt:T.nativeCaptureTelemetryAt?String(T.nativeCaptureTelemetryAt):void 0,droppedByAgent:Number(T.droppedByAgent||0)||0,hubIngressDropped:Number(T.hubIngressDropped||0)||0,hubClientDropped:ct,transport:T.transport?String(T.transport):void 0,videoTransport:T.videoTransport?String(T.videoTransport):void 0,frameTransportActive:T.frameTransportActive?String(T.frameTransportActive):void 0,frameTransportProtocol:T.frameTransportProtocol?String(T.frameTransportProtocol):void 0,frameTransportState:T.frameTransportState?String(T.frameTransportState):void 0,frameTransportReason:T.frameTransportReason?String(T.frameTransportReason):void 0,frameTransportChangedAt:T.frameTransportChangedAt?String(T.frameTransportChangedAt):void 0,frameTransportSwitchCount:Number(T.frameTransportSwitchCount||0)||0,frameTransportTcpFailureCount:Number(T.frameTransportTcpFailureCount||0)||0,frameTransportP2pReady:T.frameTransportP2pReady===!0,hubClientQueueTelemetryAvailable:K,hubClientQueueDepth:z,hubClientQueueLimit:pe,hubClientBufferedBytes:Y,udpIncompleteFrames:Number(T.udpIncompleteFrames||0)||0,hardwareEncoder:T.hardwareEncoder?String(T.hardwareEncoder):void 0,platformProfile:T.platformProfile?String(T.platformProfile):void 0,monitorIndex:Number.isFinite(Number(T.monitorIndex))?Number(T.monitorIndex):void 0,monitorCount:Number.isFinite(Number(T.monitorCount))?Number(T.monitorCount):void 0,requestedFps:Number(T.requestedFps||0)||0,effectiveFps:Number(T.effectiveFps||0)||0,captureTimingAvailable:T.captureTimingAvailable===!0,captureAverageMs:Ve(T.captureAverageMs),captureP95Ms:Ve(T.captureP95Ms),slowFrameCount:Number(T.slowFrameCount||0)||0,captureHelperRestarts:Number(T.captureHelperRestarts||0)||0,capturedAt:String(T.capturedAt||""),receivedAt:String(T.receivedAt||""),hubPacketAt:T.hubPacketAt?String(T.hubPacketAt):void 0,hubPacketEpochMs:De,browserReceivedEpochMs:ye,hubPacketTransitAgeMs:De!==void 0?qe:void 0,byteLength:Number(T.byteLength||_e.byteLength),contentHash:T.contentHash?String(T.contentHash):void 0,captureMs:Ve(T.captureMs),captureStageMs:Ve(T.captureStageMs),convertMs:Number(T.convertMs||0)||0,compressMs:Number(T.compressMs||0)||0,captureSourceSerial:Number(T.captureSourceSerial||0)||0,captureSourceSkipped:Number(T.captureSourceSkipped||0)||0,deltaTileSize:Number(T.deltaTileSize||0)||0,deltaTileCount:Number(T.deltaTileCount||0)||0,deltaVisualTileCount:Number(T.deltaVisualTileCount||0)||0,deltaRefreshTileCount:Number(T.deltaRefreshTileCount||0)||0,deltaTotalTiles:Number(T.deltaTotalTiles||0)||0,payload:_e};if(!ee.deviceId)return;const R=J.expectedBinding;if(!R)return;const se=ee.deviceId===R.deviceId&&String(ee.sessionId||"")===R.sessionId&&ee.streamId===R.streamId&&String(ee.commandId||"")===R.commandId&&Number(ee.captureGeneration||0)===R.captureGeneration&&Number(ee.monitorIndex??-1)===R.monitorIndex&&String(ee.streamPurpose||"")===R.streamPurpose;if(!se)return;ee.currentGenerationVerified=se;const Ie=Number(J.payload.monitorSelections?.[ee.deviceId]);if(Number.isFinite(Ie)&&Number.isFinite(Number(ee.monitorIndex))&&Number(ee.monitorIndex)!==Ie)return;const He={streamId:J.lastFrameStreamId,commandId:J.lastFrameCommandId,order:J.lastFrameOrder},Be=Number(ee.streamFrameSeq||ee.frameSeq||0),xe=!!He.commandId&&!!ee.commandId,Ge=He.streamId===ee.streamId&&(!xe||He.commandId===ee.commandId),rt=He.order;if(Ge&&rt>=Be&&(rt===Be||xe))return;J.lastFrameStreamId=ee.streamId,J.lastFrameCommandId=ee.commandId||"",J.lastFrameOrder=Be;const Ke=P.current;Ke.totalFrames+=1,Ke.totalBytes+=_e.byteLength,Ke.sampleFrames+=1,Ke.sampleBytes+=_e.byteLength;const gt=!g.current.has(ee.deviceId)&&!w.current.has(ee.deviceId),_=kC(w.current,ee);gt&&(g.current.set(ee.deviceId,_),w.current.delete(ee.deviceId),i(new Map(g.current))),H.current?.(ee)},[]);o.useEffect(()=>{if(!t||!D)return;P.current.sampleStartedAt=performance.now();const ce=window.setInterval(()=>{if(!X.current)return;const J=performance.now(),ye=P.current,ue=Math.max(1,J-ye.sampleStartedAt);m({totalFrames:ye.totalFrames,totalBytes:ye.totalBytes,framesPerSecond:ye.sampleFrames*1e3/ue,bytesPerSecond:ye.sampleBytes*1e3/ue,sampleMs:ue,lastUpdatedAt:Date.now()}),i(MC(g.current,w.current)),ye.sampleFrames=0,ye.sampleBytes=0,ye.sampleStartedAt=J},2e3);return E.current=ce,()=>{window.clearInterval(ce),E.current===ce&&(E.current=null)}},[t,D]),o.useEffect(()=>{const ce=()=>{const J=new Set,ye=[...v.current.values()];for(;ye.length>0;){const T=ye.pop();!T||J.has(T)||(J.add(T),T.handoffFrom&&ye.push(T.handoffFrom))}const ue=[...g.current.values(),...w.current.values()],Ee=[...J],nt=y.current?.snapshot()||{closingSocketCount:0,closingSocketTimerCount:0,closingSocketTimeoutCount:0};return{deviceKey:D,active:X.current,socketCount:Ee.length+nt.closingSocketCount,openSocketCount:Ee.filter(T=>T.socket.readyState===WebSocket.OPEN).length,connectingSocketCount:Ee.filter(T=>T.socket.readyState===WebSocket.CONNECTING).length,closingSocketCount:nt.closingSocketCount,closingSocketTimerCount:nt.closingSocketTimerCount,closingSocketTimeoutCount:nt.closingSocketTimeoutCount,expectedBindingCount:Ee.filter(T=>!!T.expectedBinding).length,reconnectTimerCount:A.current.size,statsTimerCount:E.current===null?0:1,configurationRefreshTimerCount:I.current.size,restartTokenCount:N.current.size,retainedFrameCount:ue.length,retainedPayloadBytes:ue.reduce((T,ve)=>T+Math.max(0,Number(ve.payload?.byteLength||0)),0)}};return wp.add(ce),()=>{wp.delete(ce)}},[D]),o.useEffect(()=>{const ce=D?D.split(",").filter(Boolean):[];if(!O){Ce(t?"livedesk-no-devices":"livedesk-stream-inactive");return}const J=new Set(ce),ye=performance.now();for(const ue of A.current.keys())J.has(ue)||Se(ue);for(const ue of I.current.keys())J.has(ue)||te(ue);for(const[ue,Ee]of v.current.entries())J.has(ue)||(Se(ue),Pe(Ee,"livedesk-device-unsubscribed"),v.current.delete(ue),N.current.delete(ue),g.current.delete(ue),w.current.delete(ue));P.current.sampleStartedAt<=0&&(P.current.sampleStartedAt=ye,m({...nc,lastUpdatedAt:Date.now()}));for(const ue of ce){Se(ue),te(ue);const Ee=Number(s.monitorSelections?.[ue]),nt=Number.isInteger(Ee)&&Ee>=0?Ee:0,T={[ue]:nt},ve={type:"subscribe",deviceIds:[ue],autoStartLive:t,fps:G,maxWidth:U,maxHeight:ie,quality:j,mode:de,frameMode:de,streamPurpose:Q,monitorSelections:T},De=String(s.connectionSessionIds?.[ue]||"").trim(),qe=JSON.stringify({subscribePayload:ve,connectionSessionId:De}),_e=v.current.get(ue),$e=Number(_e?.payload.monitorSelections?.[ue]),mt=Number(T[ue]),ct=!!_e&&Number.isFinite($e)&&Number.isFinite(mt)&&$e!==mt,z=!!_e&&_e?.connectionSessionId!==De;if(_e){const Ge=_e.socket.readyState===WebSocket.CONNECTING||_e.socket.readyState===WebSocket.OPEN;if(_e.payloadKey===qe&&Ge&&!_e.disposed)continue}const pe=_e&&(_e.socket.readyState===WebSocket.CONNECTING||_e.socket.readyState===WebSocket.OPEN)&&!_e.disposed?_e.handoffFrom&&!_e.handoffCompleted?_e.handoffFrom:_e:void 0,Y=_e&&_e!==pe?_e:void 0,K=`/api/remote/frames/ws?devices=${encodeURIComponent(ue)}`,ee=fu(gu(K,n),K);ee.binaryType="arraybuffer";const R=jC(),se={socket:ee,payload:ve,payloadKey:qe,connectionSessionId:De,generation:k.current+1,monitorRestartToken:ct?`monitor-${ue}-${mt}-${k.current+1}`:"",disposed:!1,handoffFrom:pe,handoffCompleted:!1,lastFrameStreamId:"",lastFrameCommandId:"",lastFrameOrder:-1,sparseTelemetry:R,releaseOwnedState:()=>cf(R)};k.current=se.generation,(ct||z)&&(g.current.delete(ue),w.current.delete(ue),i(new Map(g.current))),v.current.set(ue,se),Y&&(Y.handoffFrom=void 0,Pe(Y,"livedesk-subscription-superseded"));const Ie=()=>{if(!X.current||se.disposed||v.current.get(ue)!==se){Pe(se,"livedesk-stale-frame-socket");return}Se(ue),p("");const Ge=C.current,rt=Ge.enabled&&(!Ge.token||N.current.get(ue)!==Ge.token),Ke=rt||se.monitorRestartToken!=="",gt=rt?Ge.token:se.monitorRestartToken,_=rt?Ge.reason:se.monitorRestartToken?"monitor-selection-change":"";if(ee.send(JSON.stringify({...se.payload,forceRestart:Ke,restartReason:Ke?_:"",restartToken:Ke?gt:""})),re>0){const Qe=window.setTimeout(()=>{I.current.get(ue)===Qe&&I.current.delete(ue),X.current&&Ue(ue,se)},Math.max(1e3,re));I.current.set(ue,Qe)}rt&&Ge.token&&N.current.set(ue,Ge.token);const je=se.handoffFrom;se.handoffFrom=void 0,se.handoffCompleted=!0,je&&!je.disposed&&Pe(je,"livedesk-subscription-replaced"),Fe()},He=Ge=>{if(!X.current||se.disposed||v.current.get(ue)!==se)return;if(typeof Ge.data=="string"){try{const Ke=JSON.parse(Ge.data),gt=(_,je=!0)=>{const Qe=S0(_,ue,Q);return Qe?(se.expectedBinding=Qe,je&&V.current?.(Qe),!0):!1};if(Ke?.type==="RemoteFrameSubscriptionError"){const _=String(Ke.error||"control-stream-start-failed");df(_,Ke.retryScheduled===!0)?(p(""),u("connecting")):p(_)}else if(Ke?.type==="RemoteFrameLiveAutoStart"){const je=(Array.isArray(Ke.skipped)?Ke.skipped:[]).find(Qe=>Qe?.deviceId===ue);if(je)df(je.reason,je.retryScheduled===!0)?(p(""),u("connecting")):p(String(je.reason||"control-stream-start-failed"));else if(Array.isArray(Ke.started)){const Qe=Ke.started.find(Ye=>Ye?.deviceId===ue);Qe&&(p(""),gt(Qe,Qe.ready===!0))}}else Ke?.type==="RemoteFrameStreamReady"&&Ke.deviceId===ue&&gt(Ke)&&p("")}catch{}return}const rt=Ge.data instanceof ArrayBuffer?Ge.data:null;rt&&(p(""),ne(rt,se))},Be=()=>{!X.current||se.disposed||v.current.get(ue)!==se||u("connecting")},xe=()=>{const Ge=!se.disposed;se.disposed=!0,se.handoffCompleted=!0;const rt=se.detachListeners;se.detachListeners=void 0,rt?.();const Ke=v.current.get(ue);Ke===se&&te(ue);let gt=!1;if(Ke===se){const _=se.handoffFrom;se.handoffFrom=void 0,_&&!_.disposed&&(_.socket.readyState===WebSocket.CONNECTING||_.socket.readyState===WebSocket.OPEN)?(v.current.set(ue,_),gt=!0):v.current.delete(ue)}if(Fe(),Ge&&X.current&&Ke===se&&!gt){const _=window.setTimeout(()=>{A.current.get(ue)===_&&A.current.delete(ue),X.current&&M(je=>je+1)},750);Se(ue),A.current.set(ue,_)}};se.detachListeners=()=>{ee.removeEventListener("open",Ie),ee.removeEventListener("message",He),ee.removeEventListener("error",Be),ee.removeEventListener("close",xe)},ee.addEventListener("open",Ie),ee.addEventListener("message",He),ee.addEventListener("error",Be),ee.addEventListener("close",xe)}Fe()},[t,te,Se,Pe,re,Te,D,G,de,ne,n,ie,U,Ae,s.monitorSelections,j,F,Ce,Ue,Q,O,Fe]),o.useEffect(()=>{if(!O||!ge||!oe)return;const ce=D?D.split(",").filter(Boolean):[];for(const J of ce){if(N.current.get(J)===oe)continue;const ye=v.current.get(J);!ye||!Le(J,ye,me,oe)||N.current.set(J,oe)}},[D,ge,oe,me,Le,O]),o.useEffect(()=>()=>{Ce("livedesk-hook-unmount",!1)},[Ce]);const ae=o.useCallback((ce,J="browser-stale")=>{if(!O)return!1;const ye=Array.isArray(ce)&&ce.length>0?ce:D.split(",").filter(Boolean);if(ye.length===0)return!1;let ue=!1;for(const Ee of ye){const nt=v.current.get(Ee);!nt||nt.socket.readyState!==WebSocket.OPEN||(ue=Le(Ee,nt,J,`${Date.now()}-${Math.random().toString(36).slice(2)}`)||ue)}return ue},[D,Le,O]),le=o.useCallback((ce,J="browser-reconnect")=>{if(!O)return!1;const ye=Array.isArray(ce)&&ce.length>0?ce:D.split(",").filter(Boolean);if(ye.length===0)return!1;let ue=!1;for(const Ee of ye){const nt=v.current.get(Ee);nt&&(Se(Ee),Pe(nt,`livedesk-${J}`),v.current.delete(Ee),N.current.delete(Ee),g.current.delete(Ee),w.current.delete(Ee),ue=!0)}return ue&&i(new Map(g.current)),M(Ee=>Ee+1),Fe(),!0},[Se,Pe,D,O,Fe]);return{frames:a,state:c,error:d,stats:h,restartLive:ae,reconnectLive:le}}function C0(e,t,n=an,s={}){const[a,i]=o.useState(null),[c,u]=o.useState(null),[d,p]=o.useState("idle"),[h,m]=o.useState(nc),g=o.useRef(null),w=o.useRef(s.onFrame),v=o.useRef(null),y=o.useRef(0),k=o.useRef({totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0}),N=o.useMemo(()=>[...new Set(e.filter(Boolean))].join(","),[e]),C=o.useMemo(()=>[...new Set((s.captureDeviceIds||e).filter(Boolean))].join(","),[e,s.captureDeviceIds]),A=o.useMemo(()=>JSON.stringify(s.monitorSelections||{}),[s.monitorSelections]),E=o.useMemo(()=>{const D=Object.entries(s.connectionSessionIds||{}).filter(([O])=>!!O).map(([O,X])=>[O,String(X||"").trim()]).sort(([O],[X])=>O.localeCompare(X));return JSON.stringify(Object.fromEntries(D))},[s.connectionSessionIds]),I=o.useMemo(()=>({deviceIds:N.split(",").filter(Boolean),captureDeviceIds:C.split(",").filter(Boolean),fps:Number(s.fps||20),inputFps:Number(s.inputFps||8),width:Number(s.width||1920),height:Number(s.height||1080),tileWidth:Number(s.tileWidth||320),tileHeight:Number(s.tileHeight||180),monitorSelections:s.monitorSelections||{}}),[C,N,A,s.fps,s.height,s.inputFps,s.monitorSelections,s.tileHeight,s.tileWidth,s.width]),F=o.useMemo(()=>JSON.stringify({atlasConfiguration:I,connectionSessionKey:E}),[I,E]),M=o.useRef(I);M.current=I;const H=t&&I.deviceIds.length>0,V=o.useCallback(D=>D.readyState!==WebSocket.OPEN?!1:(D.send(JSON.stringify({type:"configure",...M.current})),!0),[]);o.useEffect(()=>{w.current=s.onFrame},[s.onFrame]),o.useEffect(()=>{if(!H)return;k.current.sampleStartedAt=performance.now();const D=window.setInterval(()=>{const O=k.current,X=performance.now(),G=Math.max(1,X-O.sampleStartedAt);m({totalFrames:O.totalFrames,totalBytes:O.totalBytes,framesPerSecond:O.sampleFrames*1e3/G,bytesPerSecond:O.sampleBytes*1e3/G,sampleMs:G,lastUpdatedAt:Date.now()});const U=v.current;U&&U.frameSeq!==y.current&&(y.current=U.frameSeq,i(U)),O.sampleFrames=0,O.sampleBytes=0,O.sampleStartedAt=X},1e3);return()=>window.clearInterval(D)},[H]),o.useEffect(()=>{if(!H){g.current?.close(),g.current=null,i(null),v.current=null,y.current=0,u(null),p("idle"),m(nc);return}let D=!1,O=0;const X=()=>{if(D)return;const G=fu(gu("/api/remote/atlas/ws",n),"/api/remote/atlas/ws");G.binaryType="arraybuffer",g.current=G,p("connecting"),G.addEventListener("open",()=>{k.current.sampleStartedAt=performance.now(),p("open"),V(G)}),G.addEventListener("message",U=>{if(typeof U.data=="string"){try{const j=JSON.parse(U.data);j?.type==="Mode4AtlasLayout"&&u({layoutVersion:Number(j.layoutVersion||0),width:Number(j.width||1920),height:Number(j.height||1080),columns:Number(j.columns||1),rows:Number(j.rows||1),tiles:Array.isArray(j.tiles)?j.tiles:[]})}catch{}return}const ie=U.data instanceof ArrayBuffer?U.data:null;if(!(!ie||ie.byteLength<5))try{const j=Date.now(),de=new DataView(ie).getUint32(0,!1);if(de<=0||de+4>ie.byteLength)return;const Q=JSON.parse(Up.decode(new Uint8Array(ie,4,de))),ge=new Uint8Array(ie,4+de),oe=Ve(Q.hubClientDropped),me=Ve(Q.hubClientQueueDepth),Ae=Ve(Q.hubClientQueueLimit),Te=Ve(Q.hubClientBufferedBytes),Pe={deviceId:String(Q.deviceId||"__livedesk_mode4_atlas__"),kind:"live",frameSeq:Number(Q.frameSeq||0),streamFrameSeq:Number(Q.streamFrameSeq||0)||void 0,streamId:String(Q.streamId||"mode4-atlas"),commandId:Q.commandId?String(Q.commandId):void 0,width:Number(Q.width||1920),height:Number(Q.height||1080),sourceWidth:Number(Q.sourceWidth||Q.width||1920),sourceHeight:Number(Q.sourceHeight||Q.height||1080),mimeType:String(Q.mimeType||"video/h264"),mode:String(Q.mode||"mode4-h264-atlas"),frameMode:String(Q.frameMode||"mode4-h264-atlas"),frameProfile:String(Q.frameProfile||"mode4-h264-atlas-v1"),encoding:String(Q.encoding||"video-atlas"),codec:String(Q.codec||"h264"),compression:String(Q.compression||"video/h264"),h264Format:String(Q.h264Format||"annexb"),isKeyFrame:Q.isKeyFrame===!0,chunkType:String(Q.chunkType||""),timestampUs:Number(Q.timestampUs||0),durationUs:Number(Q.durationUs||0),transport:Q.transport?String(Q.transport):void 0,videoTransport:Q.videoTransport?String(Q.videoTransport):void 0,frameTransportActive:Q.frameTransportActive?String(Q.frameTransportActive):void 0,frameTransportProtocol:Q.frameTransportProtocol?String(Q.frameTransportProtocol):void 0,frameTransportState:Q.frameTransportState?String(Q.frameTransportState):void 0,frameTransportReason:Q.frameTransportReason?String(Q.frameTransportReason):void 0,frameTransportChangedAt:Q.frameTransportChangedAt?String(Q.frameTransportChangedAt):void 0,frameTransportSwitchCount:Number(Q.frameTransportSwitchCount||0)||0,frameTransportTcpFailureCount:Number(Q.frameTransportTcpFailureCount||0)||0,frameTransportP2pReady:Q.frameTransportP2pReady===!0,hubClientQueueTelemetryAvailable:oe!==void 0&&me!==void 0&&Ae!==void 0&&Te!==void 0,hubClientDropped:oe,hubClientQueueDepth:me,hubClientQueueLimit:Ae,hubClientBufferedBytes:Te,udpIncompleteFrames:Number(Q.udpIncompleteFrames||0)||0,hardwareEncoder:Q.hardwareEncoder?String(Q.hardwareEncoder):void 0,platformProfile:Q.platformProfile?String(Q.platformProfile):void 0,capturedAt:String(Q.capturedAt||""),receivedAt:String(Q.receivedAt||""),hubPacketAt:Q.hubPacketAt?String(Q.hubPacketAt):void 0,hubPacketEpochMs:Number(Q.hubPacketEpochMs||0)||void 0,browserReceivedEpochMs:j,byteLength:ge.byteLength,layoutVersion:Number(Q.layoutVersion||0),atlasComposeMs:Number(Q.atlasComposeMs||0),atlasPoolStarved:Number(Q.atlasPoolStarved||0),atlasReadyTiles:Number(Q.atlasReadyTiles||0),atlasTileCount:Number(Q.atlasTileCount||0),atlasInputRevision:Number(Q.atlasInputRevision||0),atlasSourceNewestAtEpochMs:Number(Q.atlasSourceNewestAtEpochMs||0),atlasSourceOldestAtEpochMs:Number(Q.atlasSourceOldestAtEpochMs||0),atlasSourceMaxAgeMs:Number(Q.atlasSourceMaxAgeMs||0),payload:ge},Se=k.current;Se.totalFrames+=1,Se.totalBytes+=ge.byteLength,Se.sampleFrames+=1,Se.sampleBytes+=ge.byteLength,v.current=Pe,y.current===0&&(y.current=Pe.frameSeq,i(Pe)),w.current?.(Pe)}catch{}}),G.addEventListener("error",()=>p("error")),G.addEventListener("close",()=>{g.current===G&&(g.current=null),!D&&(p("closed"),O=window.setTimeout(X,1200))})};return X(),()=>{D=!0,window.clearTimeout(O),g.current?.close(),g.current=null}},[H,n,V]),o.useEffect(()=>{if(!H)return;const D=g.current;D&&V(D)},[F,H,V]);const P=o.useCallback(()=>{const D=g.current;return D?V(D):!1},[V]);return{frame:a,layout:c,state:d,stats:h,refreshInputs:P}}function k0(e,t=an){const n=o.useRef(null),s=o.useRef(0),a=o.useRef(0),i=o.useRef(new Map),c=o.useRef(""),[u,d]=o.useState("idle"),[p,h]=o.useState(""),[m,g]=o.useState(""),[w,v]=o.useState(hf),y=o.useRef({totalSent:0,totalDropped:0,sampleSent:0,sampleDropped:0,sampleStartedAt:0,lastInputType:"",lastInputSeq:0,lastRoundTripMs:0,lastAgentApplyMs:0});o.useEffect(()=>{if(!e){n.current?.close(),n.current=null,a.current=0,c.current="",i.current.clear(),d("idle"),h(""),g(""),v(hf);return}let N=!1,C=0;const A=()=>{if(N)return;const E=fu(gu("/api/remote/input/ws",t),"/api/remote/input/ws");n.current=E,g(""),y.current.sampleStartedAt=performance.now(),d("connecting"),h(""),E.addEventListener("open",()=>{N||n.current!==E||(h(""),d("open"))}),E.addEventListener("message",I=>{if(!(N||n.current!==E||typeof I.data!="string"))try{const F=JSON.parse(I.data);if(F?.type==="RemoteInputSocketReady"){g(String(F.clientId||""));return}const M=Number(F.inputSeq||F.result?.inputSeq||0),H=String(F.deviceId||F.result?.deviceId||""),V=String(F.inputEventId||F.result?.inputEventId||""),P=i.current.get(M);if(H&&(P&&P.deviceId!==H||!P&&c.current&&c.current!==H)||P?.inputEventId&&V&&P.inputEventId!==V)return;if(F?.type==="RemoteInputError"){M>0&&i.current.delete(M),h(String(F.error||F.result?.error||"Remote input failed.")),E.readyState===WebSocket.OPEN&&d("open");return}if(F?.type!=="RemoteInputApplied")return;P&&(y.current.lastRoundTripMs=Math.max(0,performance.now()-P.sentAt),i.current.delete(M)),y.current.lastInputSeq=M,y.current.lastAgentApplyMs=Math.max(0,Number(F.agentApplyMs||0)),h(""),d("open")}catch{}}),E.addEventListener("close",()=>{N||n.current!==E||(n.current=null,g(""),d("closed"),C=window.setTimeout(A,1200))}),E.addEventListener("error",()=>{!N&&n.current===E&&d("error")})};return A(),()=>{N=!0,window.clearTimeout(C);const E=n.current;n.current=null,g(""),E?.close(),i.current.clear()}},[e,t]),o.useEffect(()=>{if(!e)return;const N=window.setInterval(()=>{const C=performance.now(),A=y.current,E=Math.max(1,C-A.sampleStartedAt);v({totalSent:A.totalSent,totalDropped:A.totalDropped,sentPerSecond:A.sampleSent*1e3/E,droppedPerSecond:A.sampleDropped*1e3/E,bufferedAmount:n.current?.bufferedAmount||0,lastInputType:A.lastInputType,lastInputSeq:A.lastInputSeq,lastRoundTripMs:A.lastRoundTripMs,lastAgentApplyMs:A.lastAgentApplyMs,lastUpdatedAt:Date.now()}),A.sampleSent=0,A.sampleDropped=0,A.sampleStartedAt=C},1e3);return()=>window.clearInterval(N)},[e]);const k=o.useCallback((N,C)=>{const A=n.current;if(!A||A.readyState!==WebSocket.OPEN||!N)return!1;const E=String(C.type||"").toLowerCase(),M=E==="pointermove"||E==="wheel",H=y.current;if(M&&A.bufferedAmount>h0)return H.totalDropped+=1,H.sampleDropped+=1,H.lastInputType=`${E}-coalescible-drop`,!1;if(!M&&A.bufferedAmount>f0){H.lastInputType=`${E||"input"}-fail-closed`,h("Remote input channel was reset because ordered input could not drain.");try{A.close(4001,"ordered-input-backpressure")}catch{}return!1}const V=s.current+1;s.current=V;const P=`${V}-${crypto.randomUUID()}`,D=Date.now(),O=!M||V-a.current>=b0;for(O&&(i.current.set(V,{sentAt:performance.now(),deviceId:N,inputEventId:P}),M&&(a.current=V)),c.current=N,pv.set(N,{inputSeq:V,inputType:E||"input",sentAt:performance.now()});i.current.size>256;){const X=i.current.keys().next().value;if(X===void 0)break;i.current.delete(X)}try{A.send(JSON.stringify({type:"input",requestId:M?"":crypto.randomUUID(),fireAndForget:M,deviceId:N,input:{...C,inputEventId:P,inputSeq:V,requestAck:O,issuedAtEpochMs:D,issuedAt:new Date(D).toISOString()}}))}catch{i.current.delete(V),h("Remote input channel closed before the ordered input was queued.");try{A.close(4002,"input-send-failed")}catch{}return!1}return H.totalSent+=1,H.sampleSent+=1,H.lastInputType=E||"input",!0},[]);return{state:u,connectionId:m,sendInput:k,stats:w,error:p}}const Ui={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},M0=.25,gf=300,bf=2,Al=1500,Pd=5e3,A0=2e3,vf=1e4,Wo=[0,1e3,3e3];function wf(e){const t=Date.parse(String(e||""));return Number.isFinite(t)?Math.max(0,Date.now()-t):0}function N0(e,t,n=an,s=0,a=!1,i="",c,u){const d=o.useRef(null),[p,h]=o.useState("idle"),[m,g]=o.useState(null),[w,v]=o.useState(Ui),[y,k]=o.useState(""),N=o.useRef(a);return N.current=a,o.useEffect(()=>{a||(g(C=>C===null?C:null),v(C=>C===Ui?C:Ui))},[a]),o.useEffect(()=>{if(!t||!e){h("idle"),g(null),v(Ui),k("");return}h("connecting"),g(null),v(Ui),k("");const C=window.AudioContext||window.webkitAudioContext;if(!C){h("unsupported"),v(Ui),k("Audio playback is not supported in this browser.");return}let A=!1,E=null;const I=HC.acquire(({release:F})=>{if(A){F();return}const M=new C({latencyHint:"interactive"});d.current=M;let H=String(i||"").trim();const V="/api/remote/audio/ws?devices="+encodeURIComponent(e)+(H?"&streamId="+encodeURIComponent(H):""),P=fu(gu(V,n),V);P.binaryType="arraybuffer";const D=Xt.createOwner({deviceId:e,socket:P,audioContext:M,statsTimer:null});let O=!1;const X=()=>{const K=Xt.releaseIfDrained(D);return(K||!Xt.hasOwner(D))&&!O&&(O=!0,F()),K},G=qp({sampleRate:192e3,channels:8}).capacityBytes,U=QC({maxPendingPackets:bp,maxPendingBytes:G}),ie=LC(),j={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(M.state),stalledCount:0,automaticRestarts:0,maximumAcceptedGapMs:0,activeStreamId:H,lastCaptureStatusAt:0,lastPcmAtEpochMs:0,workletRingCapacityBytes:0,workletRingBufferedBytes:0,workletRingBufferedMs:0,workletRingDroppedFrames:0,workletRingUnderflowCount:0};let re=!1,de=!1,Q=null,ge=0,oe=0,me="",Ae=!1,Te=()=>{},Pe="connecting",Se="";const te=K=>{re||K===Pe||(Pe=K,h(K))},Ce=K=>{re||K===Se||(Se=K,k(K))};let Fe=0,Le=!1,Ue=0,ne=0,ae=0,le=!1;const ce=()=>{Xt.setPendingWorkletPackets(D,U.getPendingPacketCount(),U.getPendingPacketBytes(),U.getPendingPacketHighWater(),U.getPendingByteHighWater())},J=K=>{j.workletRingCapacityBytes=Math.max(0,Math.min(G,Number(K.ringCapacityBytes||0)||0)),j.workletRingBufferedBytes=Math.max(0,Math.min(j.workletRingCapacityBytes,Number(K.ringBufferedBytes||0)||0)),j.workletRingBufferedMs=Math.max(0,Math.min(M0*1e3,Number(K.ringBufferedMs||0)||0)),j.workletRingDroppedFrames=Math.max(j.workletRingDroppedFrames,Number(K.ringDroppedFrames||0)||0),j.workletRingUnderflowCount=Math.max(j.workletRingUnderflowCount,Number(K.ringUnderflowCount||0)||0),Xt.setPcmRing(D,j.workletRingCapacityBytes,j.workletRingBufferedBytes)},ye=()=>{const K=Q;if(Q=null,Ae=!1,K){K.onprocessorerror=null,K.port.onmessage=null;try{K.disconnect()}catch{}try{K.port.close()}catch{}}U.terminate(),ce(),j.workletRingCapacityBytes=0,j.workletRingBufferedBytes=0,j.workletRingBufferedMs=0,Xt.setPcmRing(D,0,0),Xt.setWorkletNode(D,0,0,ge),X()},ue=K=>{const ee=K.data||{},R=String(ee.type||"");if((R==="packet-terminal"||R==="processor-error")&&(U.acknowledge(typeof ee.packetId=="number"?ee.packetId:String(ee.packetId||"")),ce()),R==="packet-terminal"){const se=Math.max(0,Number(ee.droppedFrames||0)||0);se>0&&(j.workletRingDroppedFrames+=se,j.resyncs+=1)}if(R==="ring-configured"||R==="ring-state"||R==="disposed"){const se=j.workletRingDroppedFrames;J(ee),j.workletRingDroppedFrames>se&&(j.resyncs+=1)}R==="disposed"?ye():R==="processor-error"&&Te(String(ee.error||"Remote audio worklet processing failed."))},Ee=()=>{if(!(!Q||!Ae))try{Q.port.postMessage({type:"flush"})}catch{Te("Remote audio worklet could not be flushed.")}},nt=()=>{P.readyState===WebSocket.OPEN&&P.send(JSON.stringify({type:"subscribe",deviceIds:[e],streamIdsByDeviceId:H?{[e]:H}:{}}))},T=()=>{j.audioContextState=String(M.state),!re&&(j.audioContextState==="suspended"||j.audioContextState==="interrupted"?te("suspended"):j.audioContextState==="closed"&&(te("error"),Ce("The browser audio context is closed. Toggle Remote Audio off and on to recover.")))},ve=async()=>{if(re||String(M.state)==="closed")return!1;try{if(String(M.state)!=="running"&&await M.resume(),j.audioContextState=String(M.state),!re&&!Le&&j.audioContextState==="running"){const K=j.lastAcceptedAt>0&&performance.now()-j.lastAcceptedAt<=Al,ee=j.lastCaptureStatusAt>0&&performance.now()-j.lastCaptureStatusAt<=Pd&&j.captureHealthy;te(K?"playing":ee?"silent":"open")}return j.audioContextState==="running"}catch(K){return re||(te("suspended"),Ce(K instanceof Error?"Audio playback is suspended: "+K.message:"Audio playback is suspended.")),!1}},De=async()=>{if(!M.audioWorklet||typeof AudioWorkletNode>"u")throw new Error("AudioWorklet is unavailable in this browser.");const K=new Blob([e0],{type:"text/javascript"});me=URL.createObjectURL(K);try{await M.audioWorklet.addModule(me)}finally{URL.revokeObjectURL(me),me=""}if(re||String(M.state)==="closed")return;const ee=new AudioWorkletNode(M,dv,{numberOfInputs:0,numberOfOutputs:1,outputChannelCount:[bf],channelCount:bf,channelCountMode:"explicit"});ge+=1,Q=ee,ee.port.onmessage=ue,ee.onprocessorerror=()=>{Te("Remote audio worklet stopped unexpectedly.")},ee.connect(M.destination),Ae=!0,Xt.setWorkletNode(D,1,1,ge)},qe=(K,ee,R,se)=>{const Ie=Q;if(re||!Ae||!Ie||ee.byteLength<=0)return!1;const He=zp({sampleRate:K.sampleRate,channels:K.channels,mimeType:K.mimeType}),Be=++oe;if(!U.claim(Be,ee.byteLength))return ce(),!1;ce();try{return Ie.port.postMessage({type:"pcm",packetId:Be,buffer:ee,byteOffset:R,byteLength:se,sampleRate:He.sampleRate,channels:He.channels,mimeType:K.mimeType,sampleFormat:He.sampleFormat},[ee]),!0}catch{return U.acknowledge(Be),ce(),!1}},_e=async()=>{if(re||Le||P.readyState!==WebSocket.OPEN)return;if(Ue>=Wo.length){te("error"),Ce("Remote audio stopped sending frames. Toggle Audio off and on to retry.");return}const K=Ue;Ue+=1,Le=!0,j.stalledCount+=1,j.automaticRestarts+=1,te("reconnecting");try{if(!c)throw new Error("Remote audio restart owner is unavailable.");const ee=await c(e);if(re||!ee)return;H=ee,nt();const R=performance.now();Fe=R,j.lastPacketAt=R,j.lastAcceptedAt=0,j.lastCaptureStatusAt=0,j.lastPcmAtEpochMs=0,j.captureAlive=null,j.helperAlive=null,j.helperReady=!1,j.captureHealthy=!1,j.captureStatusFailed=!1,j.captureAwaitingCurrentPcm=!1,j.captureAwaitingSinceAt=0,j.capturePhase="",j.backendKind="",j.helperRequired=!1,j.helperPid=0,j.nativeCallbackDiagnosticsAvailable=!1,j.nativeRejectedCallbackCount=0,j.nativeCurrentnessDropCount=0,j.nativeLastDropReason="",j.silentForMs=0,j.activeStreamId=H,j.lastFrameSeq=0,j.maximumAcceptedGapMs=0,Ee(),ne=R+(Wo[K+1]??3e3),Ce(""),re||te("open")}catch(ee){re||(ne=performance.now()+(Wo[K+1]??3e3),te("error"),Ce(ee instanceof Error?"Remote audio restart failed: "+ee.message:"Remote audio restart failed."))}finally{Le=!1}},$e=()=>{j.drops+=1},mt=window.setInterval(()=>{if(re)return;const K=performance.now(),ee=j.lastPacketAt>0?Math.max(0,K-j.lastPacketAt):Fe>0?Math.max(0,K-Fe):0,R=j.lastAcceptedAt>0?Math.max(0,K-j.lastAcceptedAt):0,se=j.lastCaptureStatusAt>0?Math.max(0,K-j.lastCaptureStatusAt):0,Ie=P.readyState===WebSocket.OPEN,He=j.lastCaptureStatusAt>0,Be=He&&se<=Pd&&j.captureHealthy,xe=He&&j.captureStatusFailed&&se>A0,Ge=He&&se>Pd,rt=!He&&Fe>0&&K-Fe>vf,Ke=j.captureAwaitingCurrentPcm&&j.captureAwaitingSinceAt>0&&K-j.captureAwaitingSinceAt>vf,gt=Fe>0&&(j.lastAcceptedAt<=0?K-Fe>Al:R>Al);if(Ie&&Fe>0&&(xe||Ge||rt||Ke)?Ue>=Wo.length&&!Le?(te("error"),Ce("Remote audio capture heartbeat stopped. Toggle Audio off and on to retry.")):!Le&&K>=ne?_e():Le||te("stalled"):Ie&&gt&&!Le&&j.audioContextState!=="suspended"&&j.audioContextState!=="interrupted"&&te(Be?"silent":"open"),WC({enabled:N.current,now:K,lastPublishedAt:ae})){ae=K,v({queuedMs:j.workletRingBufferedMs,browserAgeMs:j.browserAgeMs,captureAgeMs:j.captureAgeMs,captureStatusAgeMs:se,silentForMs:j.silentForMs,captureAlive:j.captureAlive,helperAlive:j.helperAlive,helperReady:j.helperReady,captureHealthy:j.captureHealthy,captureAwaitingCurrentPcm:j.captureAwaitingCurrentPcm,capturePhase:j.capturePhase,backendKind:j.backendKind,helperRequired:j.helperRequired,helperPid:j.helperPid,captureRestartCount:j.captureRestartCount,nativeCallbackDiagnosticsAvailable:j.nativeCallbackDiagnosticsAvailable,nativeRejectedCallbackCount:j.nativeRejectedCallbackCount,nativeCurrentnessDropCount:j.nativeCurrentnessDropCount,nativeLastDropReason:j.nativeLastDropReason,localProcessingAgeMs:j.localProcessingAgeMs,lastPacketAgeMs:ee,lastAcceptedAgeMs:R,framesReceived:j.framesReceived,drops:j.drops,resyncs:j.resyncs,pendingDecodes:j.pendingDecodes,lastFrameSeq:j.lastFrameSeq,audioContextState:j.audioContextState,stalledCount:j.stalledCount,automaticRestarts:j.automaticRestarts,maximumAcceptedGapMs:j.maximumAcceptedGapMs,workletRingCapacityBytes:j.workletRingCapacityBytes,workletRingBufferedBytes:j.workletRingBufferedBytes,workletRingDroppedFrames:j.workletRingDroppedFrames,workletRingUnderflowCount:j.workletRingUnderflowCount,lastUpdatedAt:Date.now()});const _=ie.publish();_&&(le=!0,Xt.setRetainedFrame(D,1,_.payload.byteLength),g(_))}else!N.current&&le&&(le=!1,ie.clear(),Xt.setRetainedFrame(D,0,0))},250);Xt.setStatsTimer(D,mt);const ct=()=>{T(),(String(M.state)==="suspended"||String(M.state)==="interrupted")&&ve()},z=()=>{document.visibilityState==="visible"&&ve()},pe=()=>{ve()};M.addEventListener("statechange",ct),document.addEventListener("visibilitychange",z),window.addEventListener("pageshow",pe),window.addEventListener("pointerdown",pe),window.addEventListener("keydown",pe),te("connecting"),Ce(""),T();const Y=(K,ee,R,se,Ie)=>{if(j.localProcessingAgeMs=Math.max(0,performance.now()-Ie),re||j.localProcessingAgeMs>gf||!vp(K,{deviceId:e,streamId:H}))return $e(),!1;j.activeStreamId!==H&&(j.activeStreamId=H,j.lastFrameSeq=0,j.maximumAcceptedGapMs=0,Ee());const He=VC(K,{deviceId:e,streamId:H,lastFrameSeq:j.lastFrameSeq});if(!He.accepted||!qe(K,ee,R,se))return $e(),!1;j.browserAgeMs=wf(K.receivedAt),j.captureAgeMs=wf(K.capturedAt);const Be=performance.now();j.lastAcceptedAt>0&&(j.maximumAcceptedGapMs=Math.max(j.maximumAcceptedGapMs,Be-j.lastAcceptedAt)),j.lastAcceptedAt=Be,j.framesReceived+=1,j.lastFrameSeq=He.nextFrameSeq,Ue=0,ne=0,N.current&&(ie.accept(K),le=!0,Xt.setRetainedFrame(D,1,0)),String(M.state)!=="running"&&ve();const xe=String(M.state)==="running";return xe&&Ce(""),te(xe?"playing":"suspended"),!0};Te=(K="")=>{if(!de){if(de=!0,K&&(Xt.recordTerminalFailure(D,K,K.includes("setup failed")?"setup":"processor"),te(K.includes("AudioWorklet is unavailable")?"unsupported":"error"),Ce(K),u?.(e,H,"browser-audio-playback-failed").catch(()=>{})),re=!0,Xt.deactivate(D),window.clearInterval(mt),Xt.setStatsTimer(D,null),M.removeEventListener("statechange",ct),document.removeEventListener("visibilitychange",z),window.removeEventListener("pageshow",pe),window.removeEventListener("pointerdown",pe),window.removeEventListener("keydown",pe),ie.clear(),Xt.setRetainedFrame(D,0,0),Q)try{Q.port.postMessage({type:"dispose"})}catch{}try{P.close()}catch{}P.readyState===WebSocket.CLOSED&&Xt.setSocket(D,null),M.close().catch(()=>{}).finally(()=>{ye(),String(M.state)==="closed"&&Xt.setAudioContext(D,null),X()}),d.current===M&&(d.current=null),X()}},De().catch(K=>{Te(K instanceof Error?`Remote audio worklet setup failed: ${K.message}`:"Remote audio worklet setup failed.")}),P.addEventListener("open",()=>{re||(Fe=performance.now(),j.lastPacketAt=Fe,j.lastAcceptedAt=0,j.lastCaptureStatusAt=0,j.lastPcmAtEpochMs=0,j.captureAlive=null,j.helperAlive=null,j.helperReady=!1,j.captureHealthy=!1,j.captureStatusFailed=!1,j.captureAwaitingCurrentPcm=!1,j.captureAwaitingSinceAt=0,j.capturePhase="",j.backendKind="",j.helperRequired=!1,j.helperPid=0,j.maximumAcceptedGapMs=0,j.silentForMs=0,te("open"),nt(),ve())}),P.addEventListener("message",K=>{if(typeof K.data=="string")return;const ee=K.data instanceof ArrayBuffer?K.data:null;if(!ee||ee.byteLength<5)return;const R=performance.now();j.lastPacketAt=R;try{const Ie=new DataView(ee).getUint32(0,!1);if(Ie<=0||Ie+4>ee.byteLength){$e();return}const He=new Uint8Array(ee,4,Ie),Be=JSON.parse(Up.decode(He)),xe=new Uint8Array(ee,4+Ie),Ge=String(Be.deviceId||""),rt=String(Be.streamId||"");if(!vp({deviceId:Ge,streamId:rt},{deviceId:e,streamId:H})){$e();return}const Ke=String(Be.frameKind||Be.kind||"").toLowerCase();if(Be.type==="remote.audio.status"||Ke==="audio-status"){j.lastCaptureStatusAt=R;const _=GC(Be);if(j.captureAlive=_.captureAlive,j.helperAlive=_.helperAlive,j.helperReady=_.helperReady,j.captureHealthy=_.healthy,j.captureStatusFailed=_.failed,j.captureAwaitingCurrentPcm=_.awaitingCurrentPcm,_.awaitingCurrentPcm?j.captureAwaitingSinceAt||=R:j.captureAwaitingSinceAt=0,j.capturePhase=_.capturePhase,j.backendKind=_.backendKind,j.helperRequired=_.helperRequired===!0,j.helperPid=_.helperPid,j.captureRestartCount=Math.max(0,Number(Be.restartCount||0)||0),j.nativeCallbackDiagnosticsAvailable=Be.callbackDiagnosticsAvailable===!0,j.nativeRejectedCallbackCount=j.nativeCallbackDiagnosticsAvailable?Math.max(0,Number(Be.rejectedCallbackCount||0)||0):0,j.nativeCurrentnessDropCount=j.nativeCallbackDiagnosticsAvailable?Math.max(0,Number(Be.currentnessDropCount||0)||0):0,j.nativeLastDropReason=j.nativeCallbackDiagnosticsAvailable?String(Be.lastDropReason||""):"",j.lastPcmAtEpochMs=Math.max(0,Number(Be.lastPcmAtEpochMs||0)||0),j.silentForMs=Math.max(0,Number(Be.silentForMs||0)||0),j.captureAgeMs=j.lastPcmAtEpochMs>0?Math.max(0,Date.now()-j.lastPcmAtEpochMs):j.silentForMs,j.captureHealthy){if(Ue=0,ne=0,!Le){Ce("");const je=String(M.state)==="running",Qe=j.lastAcceptedAt>0&&performance.now()-j.lastAcceptedAt<=Al;te(je?Qe?"playing":"silent":"suspended")}}else j.captureAwaitingCurrentPcm&&!Le?te("open"):j.captureStatusFailed&&!Le&&te("stalled");return}const gt={deviceId:Ge,frameSeq:Number(Be.frameSeq||0),streamId:rt,mimeType:String(Be.mimeType||"audio/webm;codecs=opus"),sampleRate:Number(Be.sampleRate||48e3),channels:Number(Be.channels||2),capturedAt:String(Be.capturedAt||""),receivedAt:String(Be.receivedAt||""),byteLength:Number(Be.byteLength||xe.byteLength),payload:uv};if(!gt.deviceId||re)return;if(performance.now()-R>gf){$e();return}if(UC(gt.mimeType)){Y(gt,ee,xe.byteOffset,xe.byteLength,R);return}$e(),te("error"),Ce(`Unsupported remote audio format "${gt.mimeType}". Requesting a bounded PCM restart.`),!Le&&Ue<Wo.length&&(ne=0,_e());return}catch(se){re||(te("error"),Ce(se instanceof Error?se.message:String(se)))}}),P.addEventListener("error",()=>{re||(te("error"),Ce("Remote audio WebSocket error."))}),P.addEventListener("close",()=>{Xt.setSocket(D,null),X(),re||te("closed")}),E=()=>{Te()}});return I.ready.catch(F=>{A||(h("error"),k(F instanceof Error?`Remote audio owner setup failed: ${F.message}`:"Remote audio owner setup failed."))}),()=>{A=!0,E?E():I.cancel()}},[e,t,n,s,c,u]),{state:p,lastFrame:m,stats:w,error:y}}const Ql=384e3,R0=1024*1024,T0=24*1024*1024,P0=256*1024*1024,I0=24;function j0(e,t){if(!e||e.repeat||e.altKey||e.shiftKey)return"";const n=String(e.key||"").toLowerCase();return n!=="c"&&n!=="v"||!(t?e.metaKey===!0&&e.ctrlKey!==!0:e.ctrlKey===!0&&e.metaKey!==!0)?"":n==="c"?"copy":"paste"}function E0(e){return`clipboard-${e==="copy"?"copy":"paste"}-${Date.now()}-${crypto.randomUUID()}`}function yp(e,t=""){const n=e&&typeof e=="object"?e:{},s=String(n.operationId||""),a=String(n.contentKind||"").toLowerCase(),i=Array.isArray(n.items)?n.items:[];if(!s||t&&s!==t||!["text","image","files"].includes(a)||i.length<1||i.length>I0)throw new Error("clipboard-manifest-invalid");let c=0;const u=i.map((d,p)=>{const h=Number(d?.itemIndex),m=Number(d?.size),g=String(d?.kind||"").toLowerCase();if(h!==p||!Number.isSafeInteger(m)||m<0||g!=="file"&&m===0||!["text","image","file"].includes(g)||g!==(a==="files"?"file":a))throw new Error("clipboard-item-invalid");c+=m;const w=String(d?.sha256||"").toLowerCase(),v=String(d?.storageName||`item-${p}.bin`);if(!/^[a-f0-9]{64}$/.test(w)||v!==`item-${p}.bin`||String(d?.name||"").includes("\0"))throw new Error("clipboard-item-metadata-invalid");return{itemIndex:h,kind:g,name:String(d?.name||"").slice(0,240),mimeType:String(d?.mimeType||"").slice(0,160),size:m,lastModified:Math.max(0,Number(d?.lastModified||0)||0),sha256:w,storageName:v}});if(c!==Number(n.totalBytes)||c>P0||a==="text"&&c>R0||a==="image"&&c>T0)throw new Error("clipboard-size-limit");return{operationId:s,contentKind:a,totalBytes:c,items:u}}function Id(e,t=Ql){if(!Number.isSafeInteger(e)||e<0||!Number.isSafeInteger(t)||t<1)throw new Error("clipboard-chunk-plan-invalid");if(e===0)return[{offset:0,byteLength:0,final:!0}];const n=[];for(let s=0;s<e;s+=t){const a=Math.min(t,e-s);n.push({offset:s,byteLength:a,final:s+a===e})}return n}const F0=3;function yf(e,t,n){const s=Math.max(1,Number(n)||1),a=Math.max(0,Math.min(s,Number(e)-Number(t))),i=Math.min(s/2,F0);return a<=i?0:a>=s-i?1:a/s}function D0(e,t,n){return{normalizedX:yf(e,n.left,n.width),normalizedY:yf(t,n.top,n.height)}}const xf=8,xp=320,Sf=28,lc=1,mv=4;function L0(){let e=!1;return{claimNativeTouchEvents(){e=!0},shouldHandlePointerEvent(){return!e}}}function xt(e,t=0){const n=Number(e);return Number.isFinite(n)?n:t}function Vp(e,t){const n=xt(e?.clientX)-xt(t?.clientX),s=xt(e?.clientY)-xt(t?.clientY);return n*n+s*s}function Yl(e,t,n){return Math.min(n,Math.max(t,e))}function hv(e,t){return{clientX:(xt(e?.clientX)+xt(t?.clientX))/2,clientY:(xt(e?.clientY)+xt(t?.clientY))/2}}function fv(e,t){return Math.sqrt(Vp(e,t))}function ou(){return{scale:lc,translateX:0,translateY:0}}function _0(e,t,n,s){const a=n||ou(),i=Yl(xt(a.scale,lc),lc,mv),c={left:xt(s?.left),top:xt(s?.top),width:Math.max(1,xt(s?.width,1)),height:Math.max(1,xt(s?.height,1))},u=hv(e,t);return{startDistance:Math.max(1,fv(e,t)),startScale:i,anchorX:(u.clientX-c.left-xt(a.translateX))/i,anchorY:(u.clientY-c.top-xt(a.translateY))/i,bounds:c}}function $0(e,t,n){if(!e)return ou();const s=hv(t,n),a=Yl(xt(e.startScale,lc)*fv(t,n)/Math.max(1,xt(e.startDistance,1)),lc,mv),i=Math.max(1,xt(e.bounds?.width,1)),c=Math.max(1,xt(e.bounds?.height,1)),u=Yl(s.clientX-xt(e.bounds?.left)-xt(e.anchorX)*a,i*(1-a),0),d=Yl(s.clientY-xt(e.bounds?.top)-xt(e.anchorY)*a,c*(1-a),0);return{scale:a,translateX:u,translateY:d}}function O0(e,t,n){return{pointerId:xt(e,-1),startClientX:xt(t),startClientY:xt(n),clientX:xt(t),clientY:xt(n),dragged:!1}}function gv(e,t,n,s){if(!e||e.pointerId!==xt(t,-1))return e;const a={...e,clientX:xt(n,e.clientX),clientY:xt(s,e.clientY)},i=xf*xf;return{...a,dragged:e.dragged||Vp({clientX:e.startClientX,clientY:e.startClientY},a)>=i}}function B0(e,t,n,s,a){if(!e||e.pointerId!==xt(t,-1))return{kind:"ignore",gesture:e,tap:null};const i=gv(e,t,n,s);return{kind:i.dragged?"drag":"tap",gesture:i,tap:i.dragged?null:{clientX:i.clientX,clientY:i.clientY,at:xt(a)}}}function Cf(e,t){if(!e||!t)return!1;const n=xt(t.at)-xt(e.at);if(n<0||n>xp)return!1;const s=Sf*Sf;return Vp(e,t)<=s}const cu=Object.freeze({shiftKey:Object.freeze(["ShiftLeft","ShiftRight"]),ctrlKey:Object.freeze(["ControlLeft","ControlRight"]),altKey:Object.freeze(["AltLeft","AltRight"]),metaKey:Object.freeze(["MetaLeft","MetaRight"])}),H0=Object.freeze({shiftKey:"ShiftLeft",ctrlKey:"ControlLeft",altKey:"AltLeft",metaKey:"MetaLeft"}),kf=Object.freeze({OSLeft:"MetaLeft",OSRight:"MetaRight"}),Sp=64,W0=256,Mf=Object.freeze({Backspace:Object.freeze({key:"Backspace",code:"Backspace",keyCode:8,location:0}),Tab:Object.freeze({key:"Tab",code:"Tab",keyCode:9,location:0}),Enter:Object.freeze({key:"Enter",code:"Enter",keyCode:13,location:0}),Escape:Object.freeze({key:"Escape",code:"Escape",keyCode:27,location:0}),PageUp:Object.freeze({key:"PageUp",code:"PageUp",keyCode:33,location:0}),PageDown:Object.freeze({key:"PageDown",code:"PageDown",keyCode:34,location:0}),End:Object.freeze({key:"End",code:"End",keyCode:35,location:0}),Home:Object.freeze({key:"Home",code:"Home",keyCode:36,location:0}),ArrowLeft:Object.freeze({key:"ArrowLeft",code:"ArrowLeft",keyCode:37,location:0}),ArrowUp:Object.freeze({key:"ArrowUp",code:"ArrowUp",keyCode:38,location:0}),ArrowRight:Object.freeze({key:"ArrowRight",code:"ArrowRight",keyCode:39,location:0}),ArrowDown:Object.freeze({key:"ArrowDown",code:"ArrowDown",keyCode:40,location:0}),Delete:Object.freeze({key:"Delete",code:"Delete",keyCode:46,location:0})}),Af=Object.freeze({deleteContentBackward:"Backspace",deleteWordBackward:"Backspace",deleteSoftLineBackward:"Backspace",deleteHardLineBackward:"Backspace",deleteContentForward:"Delete",deleteWordForward:"Delete",deleteSoftLineForward:"Delete",deleteHardLineForward:"Delete",insertLineBreak:"Enter",insertParagraph:"Enter"});function Gp(e,t=80){return String(e||"").replace(/[\u0000-\u001f\u007f]/g,"").trim().slice(0,t)}function bv(e){const t=String(e??"");return t===" "?" ":Gp(t)}function Cp(e){const t=Gp(e);return Object.prototype.hasOwnProperty.call(kf,t)?kf[t]:t}function jd(e={}){const t=bv(e.key),n=Number(e.keyCode??e.which);if(t===" "||t==="Spacebar"||n===32)return"Space";const s=Number.isFinite(Number(e.location))?Math.max(0,Math.min(3,Math.trunc(Number(e.location)))):0,a=s===2?"Right":"Left";return t==="Shift"?`Shift${a}`:t==="Control"?`Control${a}`:t==="Alt"||t==="AltGraph"?`Alt${a}`:t==="Meta"||t==="OS"?`Meta${a}`:t?`Key:${s}:${t}`.slice(0,80):""}function kp(e={}){const t=Cp(e.code);return["Shift","Control","Alt","AltGraph","Meta","OS"].includes(t)?jd({...e,key:t}):t==="Unidentified"?jd(e):t||jd(e)}function Xl(e){for(const[t,n]of Object.entries(cu))if(n.includes(e))return t;return""}function Ys(e,t){return cu[t].some(n=>e.has(n))}function Nl(e,t,n={},s="",a=""){for(const i of Object.keys(cu)){const c=n[i]===!0,u=cu[i];if(i===s){if(a==="keyup"&&!c)for(const d of u)t.has(d)||e.delete(d);continue}if(c){!Ys(e,i)&&e.size<Sp&&e.add(H0[i]);continue}for(const d of u)t.has(d)||e.delete(d)}}function z0(e,t){if(e.length!==t.size)return!1;let n=0;for(const s of t){if(e[n]!==s)return!1;n+=1}return!0}function Nf(e){for(const t of[...e])Xl(t)||e.delete(t)}function Mp(e){return{shiftKey:Ys(e,"shiftKey"),ctrlKey:Ys(e,"ctrlKey"),altKey:Ys(e,"altKey"),metaKey:Ys(e,"metaKey")}}function q0(e={},t={}){return{shiftKey:e.shiftKey===!0||t.shiftKey===!0,ctrlKey:e.ctrlKey===!0||t.ctrlKey===!0,altKey:e.altKey===!0||t.altKey===!0,metaKey:e.metaKey===!0||t.metaKey===!0}}function Rl(e){const t=String(e||""),n=Object.prototype.hasOwnProperty.call(Af,t)?Af[t]:t;return Object.prototype.hasOwnProperty.call(Mf,n)?{...Mf[n],repeat:!1}:null}function U0(e){const t=String(e??"").replace(/\0/g,"");if(!t)return[];const n=[];let s=t;for(;s.length>0;){let a=Math.min(W0,s.length);a<s.length&&/[\uD800-\uDBFF]/.test(s[a-1])&&/[\uDC00-\uDFFF]/.test(s[a])&&(a-=1),n.push(s.slice(0,a)),s=s.slice(a)}return n}function V0(e,t,n){const s=kp(e),a=bv(e.key),i=Number(e.keyCode??e.which),c=Number(e.location);return{type:t,key:a,code:s,keyCode:Number.isFinite(i)?Math.max(0,Math.min(65535,Math.trunc(i))):0,location:Number.isFinite(c)?Math.max(0,Math.min(255,Math.trunc(c))):0,text:a.length===1?a:"",repeat:t==="keydown"&&e.repeat===!0,pressedCodes:[...n],...Mp(n)}}function G0(){const e=new Set,t=new Set,n=()=>({pressedCodes:[...e]});return{event(s={},a=""){if(a!=="keydown"&&a!=="keyup")return null;const i=kp(s);if(!i)return null;const c=Xl(i),u=e.has(i),d=[...e];return c?a==="keydown"?(Nl(e,t,s,c,a),e.size<Sp&&e.add(i)):(t.has(i)||e.delete(i),Nl(e,t,s,c,a)):(Nl(e,t,s),a==="keydown"?e.size<Sp&&e.add(i):e.delete(i)),a==="keyup"&&c==="metaKey"&&!Ys(e,"metaKey")&&Nf(e),a==="keydown"&&u&&s.repeat!==!0&&z0(d,e)?null:V0(s,a,e)},modifier(s,a){const i=Cp(s),c=Xl(i);if(!c)return null;const u=t.has(i);return a===u?null:(a?(t.add(i),e.add(i)):(t.delete(i),e.delete(i),c==="metaKey"&&!Ys(e,"metaKey")&&Nf(e)),{type:a?"keydown":"keyup",key:c==="metaKey"?"Meta":c==="ctrlKey"?"Control":c==="altKey"?"Alt":"Shift",code:i,keyCode:0,location:i.endsWith("Right")?2:1,text:"",repeat:!1,...n(),...Mp(e)})},reset(s="keyboard-owner-reset",a=!1){const i=e.size>0;return e.clear(),t.clear(),!i&&!a?null:{type:"keyboard.reset",reason:Gp(s,120)||"keyboard-owner-reset",pressedCodes:[],shiftKey:!1,ctrlKey:!1,altKey:!1,metaKey:!1,repeat:!1}},isPressed(s={}){const a=typeof s=="string"?Cp(s):kp(s);if(e.has(a))return!0;const i=Xl(a);return!!i&&Ys(e,i)},snapshot(){return{...n(),latchedCodes:[...t],...Mp(e)}}}}const vv=64,K0=2;function wv(e){const t=Math.floor(Number(e));return Number.isFinite(t)?Math.max(1,Math.min(vv,t)):1}function Kp(e){const t=Math.floor(Number(e));return Number.isFinite(t)?Math.max(0,Math.min(vv-1,t)):0}function yv(e){const t=String(e||"").trim().toLowerCase();return t==="macos"||t==="darwin"||t==="mac"||t==="macosx"||t==="linux"||t.startsWith("linux ")}function Q0(e,t,n){const s=String(t||"").trim();if(!s)return e||null;const a=String(n||"").trim();return e&&e.fingerprint===s&&(a?e.sampleId===a:e.sampleId==="")?e:{fingerprint:s,sampleId:a,consecutiveSamples:e?.fingerprint===s?e.consecutiveSamples+1:1}}function xv({platform:e,topologyFingerprint:t,consecutiveTopologySamples:n}){return yv(e)?!!String(t||"").trim()&&Number(n)>=K0:!0}function Y0({requestedIndex:e,monitorCount:t,platform:n,topologyFingerprint:s,consecutiveTopologySamples:a}){const i=Kp(e),c=wv(t);return i<c||!xv({platform:n,topologyFingerprint:s,consecutiveTopologySamples:a})?i:c-1}function X0(e,t,n){const s=Kp(e),a=wv(t);return s<a||yv(n)?s:a-1}function sa(e){const t=Number(e);return Number.isSafeInteger(t)&&t>0?t:0}function Jt(e){return String(e||"").trim()}function Ed(e,t,n={}){return{deviceId:Jt(e),transitionGeneration:sa(t),sessionId:Jt(n.sessionId),streamId:Jt(n.streamId),commandId:Jt(n.commandId),captureGeneration:sa(n.captureGeneration),monitorIndex:Math.max(0,Math.floor(Number(n.monitorIndex)||0))}}function Dt(e,t){return!!e&&!!t&&Jt(e.deviceId)===Jt(t.deviceId)&&sa(e.transitionGeneration)===sa(t.transitionGeneration)}function Rf({deviceId:e,requestTransitionGeneration:t,currentTransitionGeneration:n,actualControlOwner:s}){const a=Jt(e),i=sa(t),c=sa(n);return!!a&&i>0&&i===c&&(!s||Jt(s.deviceId)===a)}function Tf(e,t){const n=Promise.resolve(e).catch(()=>{}).then(t);return{result:n,tail:n.then(()=>{},()=>{})}}function Tl(e,t,n){const s=Jt(e);return!s||!t||Jt(t.deviceId)!==s?!1:!n||Jt(n.deviceId)!==s}function Fd(e,t){if(!e||!t)return!1;const n=sa(t.captureGeneration),s=Jt(t.commandId),a=Jt(t.sessionId),i=Jt(t.streamId),c=Number(e.monitorIndex);return!n||!s||!a||!i||!Number.isInteger(c)||c<0?!1:Jt(e.deviceId)===Jt(t.deviceId)&&Jt(e.sessionId)===a&&Jt(e.streamId)===i&&Jt(e.commandId)===s&&sa(e.captureGeneration)===n&&Jt(e.streamPurpose).toLowerCase()==="control"&&c===t.monitorIndex}const J0=820,Z0=500,Pf=`(max-width: ${J0}px), (orientation: landscape) and (max-height: ${Z0}px) and (pointer: coarse)`,ek="1200px 0px 1800px 0px",tk=960,nk=540,rk=68,If=24,sk=16;function ak(e,t,n,s){return/iPad|iPhone|iPod/i.test(String(e||""))||t==="MacIntel"&&Number(n)>1||typeof s=="boolean"}function ik(e,t){const n=e&&typeof e=="object"?e:{},s={fps:Math.max(1,Math.floor(Number(n.fps)||1)),maxWidth:Math.max(1,Math.floor(Number(n.maxWidth)||1)),maxHeight:Math.max(1,Math.floor(Number(n.maxHeight)||1)),quality:Math.max(1,Math.min(100,Math.floor(Number(n.quality)||1)))};return t?{...s,maxWidth:Math.min(s.maxWidth,tk),maxHeight:Math.min(s.maxHeight,nk),quality:Math.min(s.quality,rk)}:s}function ok(e,t){return!t||!e||typeof e.closest!="function"?null:e.closest(".desk-stage")}function jf(e,t,n){return!!(e||t&&n)}function ck({isIos:e,standalone:t,safeAreaTop:n,screenHeight:s,layoutViewportHeight:a}){if(!e||!t)return 0;const i=Number(s),c=Number(a);if((Number.isFinite(i)&&i>0&&Number.isFinite(c)&&c>0?Math.max(0,i-c):0)>=sk)return 0;const d=Number(n);return Number.isFinite(d)&&d>0?Math.max(If,Math.round(d)-20):If}function lk(e,t,n,s=!1,a=s){const i=Number(e?.height),c=Number(t),u=Number(e?.offsetTop),d=s&&Number.isFinite(c)&&c>0,p=d?0:Number.isFinite(u)?Math.max(0,Math.round(u)):0,h=d?c:Number.isFinite(i)&&i>0?i:Number.isFinite(c)&&c>0?c:1,m=Number(e?.width),g=Number(n),w=a&&Number.isFinite(g)&&g>0,v=w?g:Number.isFinite(m)&&m>0?m:Number.isFinite(g)&&g>0?g:1,y=Number(e?.offsetLeft);return{height:Math.max(1,Math.round(h)),width:Math.max(1,Math.round(v)),offsetTop:p,offsetLeft:w?0:Number.isFinite(y)?Math.max(0,Math.round(y)):0}}function uk(e,t){const n=Promise.resolve(e).catch(()=>{}).then(t);return{result:n,tail:n.then(()=>{},()=>{})}}function dk(){let e=Promise.resolve(),t=Promise.resolve();const n=s=>{const a=uk(e,s);return e=a.tail,a.result};return{enqueue:n,enqueueStop(s){const a=n(s);return t=a.then(()=>{}),t.catch(()=>{}),a},enqueueStart(s){const a=t;return n(async()=>(await a,s()))}}}function pk(e={}){return Number(e.generation)===Number(e.currentGeneration)&&e.enabled===!0&&String(e.deviceId||"")!==""&&String(e.deviceId||"")===String(e.currentDeviceId||"")&&e.documentVisible===!0&&e.presentationVisible===!0&&String(e.streamId||"")!==""&&String(e.streamId||"")===String(e.currentStreamId||"")}function mk(e={}){const t=e.ok!==!1,n=t&&e.staleOwner===!0;return{confirmed:t&&(n||e.captureStopConfirmed===!0||e.alreadyStopped===!0),staleOwner:n,preserveNewerOwner:n&&(e.retainedNewerOwner===!0||String(e.activeStreamId||"")!=="")}}const $t=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,controlWallReuseStarvationFactor:1.5,scalableAtlasMinInputFps:8,scalableAtlasMaxInputFps:20,scalableAtlasAggregateInputFps:120,atlasOutputFps:20,directDecodeAcceleration:"prefer-hardware",directLatencyMode:"interactive"});function Ap(e){return e==="slow"?$t.slowWallFps:$t.fastWallFps}function Ef(e,t){const n=e&&typeof e=="object"?e:{};return Object.entries(t&&typeof t=="object"?t:{}).some(([a,i])=>{const c=String(i||"").trim();return c.length>0&&String(n[a]||"").trim()!==c})}function Ff({paintStale:e,lastRecoveryAt:t,now:n,recoveryCooldownMs:s,transportRecoveryAfterMs:a}){if(e!==!0)return"none";const i=Math.max(0,Number(n)||0),c=Math.max(0,Number(t)||0),u=c>0?i-c:Number.POSITIVE_INFINITY;return c>0&&u>=Math.max(1,Number(a)||1)?"recover-transport":c<=0||u>=Math.max(1,Number(s)||1)?"reset-decoder":"wait"}function Df({lastReceivedAt:e,lastPaintedAt:t,now:n,staleAfterMs:s}){const a=Math.max(0,Number(e)||0);if(a<=0)return!1;const i=Math.max(0,Number(t)||0),c=i>0?i:a;return Math.max(0,Number(n)||0)-c>Math.max(1,Number(s)||1)}function hk(e){return e==="share-files"||e==="agents"}function fk({captureOwnershipActive:e,localFeatureAccess:t,controlSessionDeviceId:n,planAllowed:s,sessionState:a,controlFocusVisible:i,presentationCanvasMounted:c,wallPresentationVisible:u,wallPresentationCanvasMounted:d,decoderOwnerExists:p}){const h=a==="connecting"||a==="active"||a==="warm";return e!==!0||t!==!0||!String(n||"").trim()||s!==!0||!h?!1:p===!0||i===!0&&c===!0||u===!0&&d===!0}function gk({decodeWidth:e,decodeHeight:t,presentationCssWidth:n,presentationCssHeight:s,devicePixelRatio:a,sourceWidth:i,sourceHeight:c}){const u=Math.max(0,Number(e)||0),d=Math.max(0,Number(t)||0),p=Math.max(0,Number(n)||0),h=Math.max(0,Number(s)||0),m=Math.max(1,Math.min(2,Number(a)||1)),g=Math.max(0,Number(i)||0),w=Math.max(0,Number(c)||0);if(u<=0||d<=0||p<=0||h<=0||g<=0||w<=0)return!1;const v=p*m,y=h*m,k=Math.min(1,v/g,y/w),N=Math.max(1,Math.round(g*k)),C=Math.max(1,Math.round(w*k));return u<N*.9||d<C*.9}function bk({cadenceCredit:e,targetFps:t,sourceFps:n,elapsedSincePaintMs:s=0,nowMs:a=0,scheduledPaintAtMs:i=0,force:c=!1}){const u=Math.max(1,Number(t)||1),d=Math.max(1,Number(n)||1);if(u>=d)return{shouldPaint:!0,nextCadenceCredit:0,sourceCadencePassthrough:!0,nextScheduledPaintAtMs:0};const p=Math.max(0,Number(a)||0),h=Math.max(0,Number(i)||0),m=p>0&&h>0,g=1e3/u,w=Math.min(g/3,1e3/d*.5),v=Number.isFinite(Number(e))?Math.max(0,Math.min(d-Number.EPSILON,Number(e))):0;if(c)return{shouldPaint:!0,nextCadenceCredit:v,sourceCadencePassthrough:!1,nextScheduledPaintAtMs:m?h:p>0?p+g:0};const y=v+u,k=y>=d,N=1e3/u*$t.controlWallReuseStarvationFactor,C=!k&&Number(s)>=N,A=m&&p+w>=h,E=m?A||C:k||C;let I=h;return E&&p>0&&(!m||C?I=p+g:(I=h+g,I<=p-g&&(I=p+g))),{shouldPaint:E,nextCadenceCredit:C?0:k&&E?y-d:Math.min(d-Number.EPSILON,y),sourceCadencePassthrough:!1,deadlineForced:C,scheduleSelected:A,nextScheduledPaintAtMs:I}}function vk(e,t){const n=Number.isFinite(Number(t))?Math.max(0,Math.floor(Number(t))):Number.POSITIVE_INFINITY;if(n<=0)return[];const s=(Array.isArray(e)?e:[]).filter(c=>c&&String(c.deviceId||"").trim()).slice().sort((c,u)=>{const d=Number.isFinite(Number(c.slotNumber))?Number(c.slotNumber):Number.MAX_SAFE_INTEGER,p=Number.isFinite(Number(u.slotNumber))?Number(u.slotNumber):Number.MAX_SAFE_INTEGER;return d!==p?d-p:String(c.deviceId).localeCompare(String(u.deviceId))}),a=[],i=new Set;for(const c of s){const u=String(c.deviceId).trim();if(!i.has(u)&&(i.add(u),a.push(u),a.length>=n))break}return a}function wk(e,t){const n=Math.max(0,Math.floor(Number(t)||0));return e===!0&&n>0}function zo({mode4Enabled:e,directMode4WallEnabled:t,isMac:n}){return"direct"}function yk({mode4Enabled:e,directMode4WallEnabled:t,adaptiveFps:n,directDeviceCount:s,adaptive:a=!0}){return Math.max(1,Math.floor(Number(n)||1))}function xk({directDeviceCount:e,requestedFps:t,measuredFramesPerSecond:n,measuredPaintFramesPerSecond:s,measuredBytesPerSecond:a,maxBytesPerSecond:i,worstReceiveGapMs:c,worstPaintP95Ms:u,maxFrameGapMs:d}){const p=Math.max(1,Math.floor(Number(e)||1)),h=Math.max(1,Number(t)||1),m=Math.max(0,Number(n)||0),g=Math.max(0,Number(s)||0),w=Math.max(0,Number(a)||0),v=Math.max(1,Number(i)||1),y=Math.max(0,Number(c)||0),k=Math.max(0,Number(u)||0),N=Math.max(1,Number(d)||1),C=p*h,A=C>8&&m<C*$t.missingDeliveryRatio,E=C>8&&g<C*$t.missingDeliveryRatio,I=w>v||y>N||A||E,F=m>=C*$t.recoveryDeliveryRatio&&g>=C*$t.recoveryDeliveryRatio&&w<v*$t.recoveryByteRatio&&y<N*$t.recoveryGapRatio&&k<N*$t.recoveryGapRatio;return{expectedFramesPerSecond:C,estimatedMissingFrames:A,estimatedMissingPaints:E,overloaded:I,healthyForRecovery:F}}function Sk({receiveSampleMs:e,paintSampleMs:t,currentGenerationVerified:n,frameRequestedFps:s,adaptiveFps:a}){const i=Number(e),c=Number(t),u=Number(s),d=Number(a);return n===!0&&Number.isFinite(i)&&i>=$t.adaptiveMinimumCurrentSampleMs&&Number.isFinite(c)&&c>=$t.adaptiveMinimumCurrentSampleMs&&Number.isFinite(u)&&u>0&&u===d}function Ck({deviceCount:e,targetFps:t,adaptive:n=!0}){const s=Math.max(1,Math.floor(Number(e)||1)),a=Math.max(1,Math.min($t.scalableAtlasMaxInputFps,Math.floor(Number(t)||$t.scalableAtlasMaxInputFps)));if(!n)return a;const i=Math.max($t.scalableAtlasMinInputFps,Math.min($t.scalableAtlasMaxInputFps,Math.floor($t.scalableAtlasAggregateInputFps/s)));return Math.min(a,i)}function kk(e,t){return{acceleration:$t.directDecodeAcceleration,latencyMode:$t.directLatencyMode}}const lu=0,Za=100,Mk=25,Ak=50,Lf=300,Nk=560;function hc(e){return Number.isFinite(e)?Math.min(Za,Math.max(lu,Math.round(e))):Za}function Rk(e){const t=hc(e);return t===lu?"list":t<Ak?"medium":"large"}function Tk(e){const n=(Math.max(1,hc(e))-1)/(Za-1);return Math.round(Lf+n*(Nk-Lf))}const za={revision:0,settings:{connection:{showThisComputer:!1},security:{accessMode:"trusted-only"},control:{allowKeyboardMouse:!0,allowRemoteRestart:!1},filesAudio:{allowFileTransfer:!0,allowRemoteAudio:!0,rollingBufferEnabled:!1,recordingQuality:"standard",timelapseIntervalSeconds:10,includeRemoteCursor:!0}}},_f=[{id:"connection",label:"Connection",icon:bu},{id:"remote-access",label:"Remote Access",icon:Zt},{id:"capture-audio",label:"Capture & Audio",icon:rp},{id:"agent",label:"Agent",icon:Zs}];function Yo(e,t){return e?.settings?.[t]||za.settings[t]||{}}function $f(e,t){return{...e,settings:{...e.settings,[t.section]:{...Yo(e,t.section),[t.key]:t.value}}}}function Dd(e){return{revision:Number(e.revision||0),updatedAt:e.updatedAt,settings:e.settings}}function Us({icon:e,title:t,description:n,children:s,recommended:a=!1}){return r.jsxs("div",{className:"product-setting-row",children:[r.jsx("div",{className:"product-setting-control",children:s}),e&&r.jsx("span",{className:"product-setting-icon",children:r.jsx(e,{size:17})}),r.jsxs("div",{className:"product-setting-copy",children:[r.jsx("strong",{children:t}),a&&r.jsx("em",{children:"Recommended"}),r.jsx("small",{children:n})]})]})}function Vi({checked:e,onChange:t,label:n}){return r.jsxs("label",{className:"product-switch",children:[r.jsx("input",{"aria-label":n,type:"checkbox",checked:e,onChange:s=>t(s.target.checked)}),r.jsx("span",{})]})}function Of({value:e,onChange:t,options:n,label:s}){return r.jsx("select",{"aria-label":s,value:String(e),onChange:a=>t(a.target.value),children:n.map(([a,i])=>r.jsx("option",{value:a,children:i},a))})}function Pk({hubUrl:e="",mobileLayout:t=!1,runtimeRole:n="hub",runtimeDeviceId:s="",sessionAccessToken:a="",showThisComputerSetting:i=!0,onShowThisComputerChange:c,initialTab:u="connection",pin:d,agent:p,captureGallery:h,desktopUpdate:m}){const[g,w]=o.useState(()=>t&&u==="connection"?"remote-access":u),[v,y]=o.useState(null),[k,N]=o.useState("loading"),[C,A]=o.useState(""),[E,I]=o.useState("idle"),[F,M]=o.useState(""),H=o.useRef(null),V=o.useRef(null),P=o.useRef([]),D=o.useRef(Promise.resolve()),O=o.useRef(0),X=o.useRef(0);o.useEffect(()=>{const Se=++X.current;let te=!0;return P.current=[],V.current=null,H.current=null,D.current=Promise.resolve(),N("loading"),Oe("/api/settings",void 0,e).then(Ce=>{if(!te||Se!==X.current)return;const Fe=Dd(Ce);V.current=Fe,H.current=Fe,y(Fe),N("saved")}).catch(Ce=>{!te||Se!==X.current||(A(Ce instanceof Error?Ce.message:String(Ce)),V.current=za,H.current=za,y(za),N("failed"))}),()=>{te=!1}},[e]);const G=async(Se,te,Ce)=>{const Fe={id:++O.current,section:Se,key:te,value:Ce},Le=X.current;P.current.push(Fe);const Ue=$f(H.current||V.current||za,Fe);H.current=Ue,y(Ue),N("saving"),A(""),D.current=D.current.then(async()=>{if(Le!==X.current)return;let ne=null,ae=null;for(let J=0;J<2&&!ne;J+=1){const ye=V.current||za;try{const ue=await Oe("/api/settings",{method:"PATCH",body:JSON.stringify({revision:ye.revision,[Fe.section]:{[Fe.key]:Fe.value}})},e);ne=Dd(ue)}catch(ue){if(ae=ue,J!==0||!String(ue instanceof Error?ue.message:ue).startsWith("409 "))break;try{const Ee=await Oe("/api/settings",void 0,e);if(Le!==X.current)return;V.current=Dd(Ee)}catch(Ee){ae=Ee;break}}}if(Le!==X.current)return;P.current=P.current.filter(J=>J.id!==Fe.id),ne&&(V.current=ne);const le=V.current||za,ce=P.current.reduce($f,le);H.current=ce,y(ce),ne?(A(""),N(P.current.length>0?"saving":"saved")):(N(P.current.length>0?"saving":"failed"),A(ae instanceof Error?ae.message:String(ae||"Settings could not be saved.")))}),await D.current},U=(Se,te)=>Ce=>{G(Se,te,Ce)},ie=async()=>{if(n!=="hub"||!s||!a){I("failed"),M("Sign in to this Hub before changing its runtime role.");return}I("changing"),M("");try{const Se=await Oe("/api/runtime/status",void 0,e);await Oe("/api/runtime/role",{method:"POST",headers:{Authorization:`Bearer ${a}`},body:JSON.stringify({role:"client"})},e),I("accepted"),await lb({baseUrl:e,targetRole:"client",previousRuntimePid:Number(Se.runtimePid||0),allowedStates:["running","waiting-auth"]}),Oy(5179)}catch(Se){I("failed"),M(Se instanceof Error?Se.message:String(Se))}},j=Yo(v,"security"),re=Yo(v,"control"),de=Yo(v,"filesAudio"),Q=Yo(v,"connection"),ge=`settings-panel-${g}`,oe=t?_f.filter(Se=>Se.id!=="connection"):_f;o.useEffect(()=>{t&&g==="connection"&&w("remote-access")},[g,t]),o.useEffect(()=>{v&&c?.(!!Q.showThisComputer)},[Q.showThisComputer,c,v]);const me=r.jsxs("div",{className:"settings-tab-content product-settings-content",children:[d,m,i&&r.jsxs("section",{className:"settings-section-card",children:[r.jsxs("div",{className:"settings-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Hub computer list"}),r.jsx("h3",{children:"This computer"})]}),r.jsx(pn,{size:20})]}),r.jsx(Us,{icon:pn,title:"Show this computer",description:"Show this Hub computer in its own Wall and computer lists. It stays available from other computers and the mobile app when hidden.",children:r.jsx(Vi,{checked:!!Q.showThisComputer,onChange:U("connection","showThisComputer"),label:"Show this computer"})})]}),r.jsxs("section",{className:"settings-section-card runtime-role-settings",children:[r.jsxs("div",{className:"settings-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Runtime role"}),r.jsx("h3",{children:"Use this computer as a Client"})]}),r.jsx(bb,{size:20})]}),r.jsx("p",{className:"settings-help",children:"Stop hosting from this computer and reconnect it to the selected Hub."}),E==="accepted"?r.jsx("p",{className:"settings-help runtime-role-success",children:"LiveDesk is restarting as Client."}):F?r.jsx("p",{className:"settings-help runtime-role-error",role:"alert",children:F}):null,r.jsx("button",{className:"settings-reset",onClick:()=>{ie()},disabled:E==="changing"||n!=="hub",type:"button",children:E==="changing"?"Switching role...":"Switch this computer to Client"})]})]}),Ae=r.jsxs("div",{className:"settings-tab-content product-settings-content",children:[r.jsxs("section",{className:"settings-section-card",children:[r.jsxs("div",{className:"settings-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Remote access"}),r.jsx("h3",{children:"Who may connect?"})]}),r.jsx(Ns,{size:20})]}),r.jsx(Us,{icon:Zt,title:"Access mode",description:"Choose the default permission boundary for remote sessions.",recommended:!0,children:r.jsx(Of,{value:String(j.accessMode),onChange:U("security","accessMode"),label:"Access mode",options:[["trusted-only","Trusted devices only"],["block-remote-access","Block remote access"]]})})]}),r.jsxs("section",{className:"settings-section-card",children:[r.jsxs("div",{className:"settings-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Session permissions"}),r.jsx("h3",{children:"What may remote users do?"})]}),r.jsx(pn,{size:20})]}),r.jsx(Us,{icon:pn,title:"Keyboard and mouse control",description:"Allow Control to send keyboard and pointer input.",recommended:!0,children:r.jsx(Vi,{checked:!!re.allowKeyboardMouse,onChange:U("control","allowKeyboardMouse"),label:"Keyboard and mouse control"})}),r.jsx(Us,{icon:vb,title:"Power actions",description:"Allow confirmed sleep, restart, and shut down commands from the Hub.",children:r.jsx(Vi,{checked:!!re.allowRemoteRestart,onChange:U("control","allowRemoteRestart"),label:"Power actions"})}),r.jsx(Us,{icon:rp,title:"File transfer",description:"Allow files to be delivered to connected computers.",children:r.jsx(Vi,{checked:!!de.allowFileTransfer,onChange:U("filesAudio","allowFileTransfer"),label:"File transfer"})}),r.jsx(Us,{icon:Zi,title:"Remote audio",description:"Allow sound capture from connected computers.",children:r.jsx(Vi,{checked:!!de.allowRemoteAudio,onChange:U("filesAudio","allowRemoteAudio"),label:"Remote audio"})})]})]}),Te=r.jsxs("div",{className:"settings-tab-content product-settings-content",children:[r.jsxs("section",{className:"settings-section-card",children:[r.jsxs("div",{className:"settings-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Capture"}),r.jsx("h3",{children:"Recording defaults"})]}),r.jsx(rp,{size:20})]}),r.jsx(Us,{icon:Zi,title:"Keep a Last 30s buffer",description:"Keep recent video in memory until you explicitly save it.",children:r.jsx(Vi,{checked:!!de.rollingBufferEnabled,onChange:U("filesAudio","rollingBufferEnabled"),label:"Keep a Last 30s buffer"})}),r.jsx(Us,{icon:Zi,title:"Timelapse interval",description:"Choose how often a timelapse frame is captured.",children:r.jsx(Of,{value:Number(de.timelapseIntervalSeconds),onChange:Se=>U("filesAudio","timelapseIntervalSeconds")(Number(Se)),label:"Timelapse interval",options:[["5","5 seconds"],["10","10 seconds"],["30","30 seconds"],["60","60 seconds"]]})})]}),h]}),Pe=g==="connection"?me:g==="remote-access"?Ae:g==="capture-audio"?Te:p;return r.jsxs("section",{className:"settings-page",children:[r.jsx("div",{className:"settings-page-tabs",role:"tablist","aria-label":"LiveDesk settings",children:oe.map(({id:Se,label:te,icon:Ce})=>r.jsxs("button",{className:g===Se?"active":"",id:`settings-tab-${Se}`,role:"tab","aria-selected":g===Se,"aria-controls":`settings-panel-${Se}`,tabIndex:g===Se?0:-1,onClick:()=>w(Se),type:"button",children:[r.jsx(Ce,{size:16}),te]},Se))}),k==="saving"&&r.jsx("div",{className:"product-save-state",role:"status",children:"Saving settings..."}),C&&r.jsx("div",{className:"agent-settings-alert error",role:"alert",children:C}),r.jsx("section",{className:"settings-page-panel",id:ge,role:"tabpanel","aria-labelledby":`settings-tab-${g}`,tabIndex:0,children:Pe})]})}function Ik({children:e}){return r.jsx("div",{className:"settings-tab-content",children:e})}const Bf={enabled:!1};function Hf(e){return{enabled:e?.enabled===!0}}async function jk(e,t,n){let s=null;for(let a=0;a<2;a+=1){const i=await Oe("/api/settings",{signal:n},t);if(i.settings.agent?.enabled===e)return;try{await Oe("/api/settings",{method:"PATCH",signal:n,body:JSON.stringify({revision:i.revision,agent:{enabled:e}})},t);return}catch(c){if(s=c,a!==0||!String(c instanceof Error?c.message:c).startsWith("409 "))throw c}}throw s}function Ek({hubUrl:e,showToast:t}){const[n,s]=o.useState(Bf),[a,i]=o.useState(null),[c,u]=o.useState(""),[d,p]=o.useState(""),[h,m]=o.useState(""),g=o.useRef(0),w=o.useRef(null);o.useEffect(()=>{let F=!0;w.current?.abort();const M=new AbortController;w.current=M;const H=++g.current;return i(null),s(Bf),u(""),m(""),p(""),Oe("/api/settings/agent",{signal:M.signal},e).then(V=>{!F||M.signal.aborted||H!==g.current||(i(V.settings),s(Hf(V.settings)))}).catch(V=>{F&&!M.signal.aborted&&H===g.current&&m(V instanceof Error?V.message:String(V))}),()=>{F=!1,M.abort(),w.current===M&&(w.current=null)}},[e]);const v=(F,M)=>s(H=>({...H,[F]:M})),y=F=>{i(F),s(Hf(F))},k=()=>({generation:g.current,controller:w.current}),N=F=>F.generation===g.current&&F.controller!==null&&F.controller===w.current&&!F.controller.signal.aborted,C=async()=>{if(!a){m("Agent settings are not available yet.");return}const F=k();if(N(F)){u("save"),m(""),p("");try{if(await jk(n.enabled,e,F.controller.signal),!N(F))return;const M=await Oe("/api/settings/agent",{signal:F.controller.signal},e);if(!N(F))return;y(M.settings),p("Codex Agent settings saved.")}catch(M){N(F)&&m(M instanceof Error?M.message:String(M))}finally{N(F)&&u("")}}},A=async()=>{const F=k();if(N(F)){u("test"),m(""),p("");try{const M=await Oe("/api/settings/agent/test",{method:"POST",signal:F.controller.signal,body:JSON.stringify({})},e);if(!N(F))return;const H=await Oe("/api/settings/agent",{signal:F.controller.signal},e);if(!N(F))return;y(H.settings);const V=Number.isFinite(M.connection?.latencyMs)?Math.max(0,Math.round(M.connection.latencyMs)):null;t(`Codex Agent connection verified${V!==null?` in ${V} ms.`:"."}`,"success")}catch(M){N(F)&&m(M instanceof Error?M.message:String(M))}finally{N(F)&&u("")}}},E=a?.codexInstallation==="installed"&&a.codexAuth==="signed-in",I=a!==null;return r.jsxs("div",{className:"settings-tab-content agent-settings-content",children:[r.jsx("section",{className:"settings-section-card agent-enable-card",children:r.jsxs("label",{className:"settings-toggle agent-enable-toggle",children:[r.jsx("input",{type:"checkbox",checked:n.enabled,onChange:F=>v("enabled",F.target.checked),disabled:!I||c!==""}),r.jsx("span",{children:"Enable Codex Agent"})]})}),h&&r.jsx("div",{className:"agent-settings-alert error",role:"alert",children:h}),d&&r.jsx("div",{className:"agent-settings-alert success",role:"status",children:d}),r.jsxs("section",{className:"settings-section-card",children:[r.jsxs("div",{className:"settings-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Connection"}),r.jsx("h3",{children:"Codex SDK / CLI"})]}),r.jsx(Zt,{size:20})]}),r.jsxs("div",{className:"agent-connection-row",children:[r.jsx("span",{className:`agent-connection-dot ${E?"connected":a?.codexAuth==="not-signed-in"?"unavailable":""}`}),r.jsx("span",{children:a?.codexInstallation==="not-installed"?"Codex SDK not installed":a?.codexAuth==="signed-in"?"Codex CLI signed in":a?.codexAuth==="not-signed-in"?"Codex CLI sign-in required":"Codex status not tested"}),r.jsxs("button",{className:"settings-reset",onClick:()=>{A()},disabled:c!=="",type:"button",children:[r.jsx(Zy,{size:15})," ",c==="test"?"Testing":"Test connection"]})]}),r.jsxs("p",{className:"settings-help",children:[r.jsx(ex,{size:12})," The Hub uses the installed Codex SDK / CLI to plan approved commands and run them through LiveDesk Agent tools on selected computers."]})]}),r.jsx("div",{className:"settings-action-row agent-settings-actions",children:r.jsxs("button",{className:"text-button primary",onClick:()=>{C()},disabled:!I||c!=="",type:"button",children:[r.jsx(tx,{size:15})," ",c==="save"?"Saving":"Save Agent settings"]})})]})}new Date().valueOf();function us(e){const[t,n]=o.useState(e),s=o.useRef(e);return o.useEffect(()=>{if(s.current!==e){if(Array.isArray(s.current)&&Array.isArray(e)&&s.current.length===0&&e.length===0)return;s.current=e,n(e)}},[e]),[t,n]}function Qp(e,t){return typeof e=="function"?typeof t=="object"?e(t):e():e}function so(e,t="data-id"){let n=e;for(!n.tagName&&e.target&&(n=e.target);n;){if(n.getAttribute&&n.getAttribute(t))return n;n=n.parentNode}return null}function Fk(e,t="data-id"){const n=so(e,t);return n?n.getAttribute(t):null}function uc(e,t="data-id"){const n=so(e,t);return n?Mu(n,t):null}function Mu(e,t="data-id"){const n=e.getAttribute(t);return n?Dk(n):null}function mn(e){return typeof e=="string"?":"+e:e}function Dk(e){if(e.startsWith(":"))return e.substring(1);const t=e*1;return isNaN(t)?e:t}function Lk(){return{detect:()=>!0,addEvent:function(e,t,n){return e.addEventListener(t,n),()=>e.removeEventListener(t,n)},addGlobalEvent:function(e,t){return document.addEventListener(e,t),()=>document.removeEventListener(e,t)},getTopNode:function(){return window.document.body}}}var nr=Lk();function Yp(e){Object.assign(nr,e)}function Wf(e,t,n){function s(a){const i=so(a);if(!i)return;const c=Mu(i);if(typeof t=="function")return t(c,a);let u,d=a.target;for(;d!=i;){if(u=d.dataset?d.dataset.action:null,u&&t[u]){t[u](c,a);return}d=d.parentNode}t[n]&&t[n](c,a)}nr.addEvent(e,n,s)}function ao(e,t){Wf(e,t,"click"),t.dblclick&&Wf(e,t.dblclick,"dblclick")}function _k(e,t){for(let n=e.length-1;n>=0;n--)if(e[n]===t){e.splice(n,1);break}}function $k(e,t,n){for(let s=0;s<Ts.length;s++){if(s===n)continue;const a=Ts[s],i=a.props.parent?.();if(i&&e.contains(i)&&a.node.contains(t))return!0}return!1}var Sv=new Date,uu=!1,Pl=[],Ts=[],zf=e=>{const t=e.target;if(uu||!t.isConnected){uu=!1;return}for(let n=Ts.length-1;n>=0;n--){const{node:s,date:a,props:i}=Ts[n];if(!(a>Sv)&&!s.contains(t)&&s!==t&&($k(s,t,n)||(i.callback&&i.callback(e),i.modal||e.defaultPrevented)))break}},Ok=e=>{Sv=new Date,uu=!0;for(let t=Ts.length-1;t>=0;t--){const{node:n}=Ts[t];if(!n.contains(e.target)&&n!==e.target){uu=!1;break}}};function ds(e,t){Pl.length||(Pl=[nr.addGlobalEvent("click",zf,e),nr.addGlobalEvent("contextmenu",zf,e),nr.addGlobalEvent("mousedown",Ok,e)]),typeof t!="object"&&(t={callback:t});const n={node:e,date:new Date,props:t};return Ts.push(n),{destroy(){_k(Ts,n),Ts.length||(Pl.forEach(s=>s()),Pl=[])}}}var Il=e=>e.indexOf("bottom")!==-1,jl=e=>e.indexOf("left")!==-1,El=e=>e.indexOf("right")!==-1,Ld=e=>e.indexOf("top")!==-1,qf=e=>e.indexOf("fit")!==-1,qo=e=>e.indexOf("overlap")!==-1,Bk=e=>e.split("-").every(t=>["center","fit"].indexOf(t)>-1),Hk=e=>{const t=e.match(/(start|center|end)/);return t?t[0]:null};function Wk(e,t){let n=0;const s=nr.getTopNode(e);for(;e&&e!==s;){const a=getComputedStyle(e).position;if((a==="absolute"||a==="relative"||a==="fixed")&&(n=parseInt(getComputedStyle(e).zIndex)||0),e=e.parentNode,e===t)break}return n}var Yt,Pn,Uo,yn;function Cv(e,t,n="bottom",s=0,a=0){if(!e)return null;Yt=s,Pn=a,Uo="auto";let i=0,c=0,u=n;const d=kv(e),p=qo(n)?nr.getTopNode(e):d;if(!d)return null;const h=d.getBoundingClientRect(),m=e.getBoundingClientRect(),g=p.getBoundingClientRect(),w=window.getComputedStyle(p),v={left:0,top:0,bottom:0,right:0};for(const E in v){const I=`border-${E}-width`;v[E]=parseFloat(w.getPropertyValue(I))}if(t){const E=Wk(t,d);i=Math.max(E+1,20)}if(t){if(yn=t.getBoundingClientRect(),qf(n)&&(Uo=yn.width+"px"),n!=="point")if(Bk(n))qf(n)?Yt=0:(Yt=g.width/2,c=1),Pn=(g.height-m.height)/2;else{const E=qo(n)?0:1;Yt=El(n)?yn.right+E:yn.left-E,Pn=Il(n)?yn.bottom+1:yn.top;const I=Hk(n);I&&(El(n)||jl(n)?I==="center"?Pn-=(m.height-yn.height)/2:I==="end"&&(Pn-=m.height-yn.height):(Il(n)||Ld(n))&&(I==="center"?Yt-=(m.width-yn.width)/2:I==="end"&&(Yt-=m.width-yn.width),qo(n)||(Yt+=1)))}}else yn={left:s,right:s,top:a,bottom:a};const y=(jl(n)||El(n))&&(Il(n)||Ld(n));jl(n)&&(c=2);const k=Yt-m.width-g.left;t&&jl(n)&&!y&&k<0&&(Yt=yn.right,c=0,u=u.replace("left","right"));const N=Yt+m.width*(1-c/2)-g.right;if(N>0)if(!El(n))Yt=g.right-v.right-m.width;else{const E=yn.left-g.x-m.width;t&&!y&&E>=0?(Yt=yn.left-m.width,u=u.replace("right","left")):Yt-=N+v.right}c&&(Yt=Math.round(Yt-m.width*c/2));const C=k<0||N>0||!y;Ld(n)&&(Pn=yn.top-m.height,t&&Pn<g.y&&C&&(Pn=yn.bottom,u=u.replace("top","bottom")));const A=Pn+m.height-g.bottom;return A>0&&(t&&Il(n)&&C?(Pn-=m.height+yn.height+1,u=u.replace("bottom","top")):Pn-=A+v.bottom),Yt-=h.left+v.left,Pn-=h.top+v.top,Yt=(qo(n)?Yt:Math.max(Yt,0))+p.scrollLeft,Pn=(qo(n)?Pn:Math.max(Pn,0))+p.scrollTop,Uo=Uo||"auto",{at:u,x:Yt,y:Pn,z:i,width:Uo}}function kv(e){const t=nr.getTopNode(e);for(e&&(e=e.parentElement);e;){const n=getComputedStyle(e).position;if(e===t||n==="relative"||n==="absolute"||n==="fixed")return e;e=e.parentNode}return null}function zk(e){const t=[];let n=e;const s=nr.getTopNode(e);for(;n&&n!==s&&!n.getAttribute("data-wx-portal-root");)getComputedStyle(n).position==="absolute"&&t.push(n),n=n.parentNode;return t}var Uf=new Date().valueOf();function Xp(){return Uf+=1,Uf}function jn(e){return e<10?"0"+e:e.toString()}function qk(e){const t=jn(e);return t.length==2?"0"+t:t}function Mv(e){const t=Math.floor(e/11)*11;return{start:t,end:t+11}}function _d(e){const t=(e.getDay()+6)%7,n=new Date(e.valueOf());n.setDate(e.getDate()+(3-t)),n.setHours(0,0,0,0);const s=new Date(n.getFullYear(),0,1),a=Math.round((n.getTime()-s.getTime())/864e5);return 1+Math.floor(a/7)}var Vf=["",""];function Uk(e,t,n){switch(e){case"%d":return jn(t.getDate());case"%m":return jn(t.getMonth()+1);case"%j":return t.getDate();case"%n":return t.getMonth()+1;case"%y":return jn(t.getFullYear()%100);case"%Y":return t.getFullYear();case"%D":return n.dayShort[t.getDay()];case"%l":return n.dayFull[t.getDay()];case"%M":return n.monthShort[t.getMonth()];case"%F":return n.monthFull[t.getMonth()];case"%h":return jn((t.getHours()+11)%12+1);case"%g":return(t.getHours()+11)%12+1;case"%G":return t.getHours();case"%H":return jn(t.getHours());case"%i":return jn(t.getMinutes());case"%a":return((t.getHours()>11?n.pm:n.am)||Vf)[0];case"%A":return((t.getHours()>11?n.pm:n.am)||Vf)[1];case"%s":return jn(t.getSeconds());case"%S":return qk(t.getMilliseconds());case"%W":return jn(_d(t));case"%w":{const s=n.weekStart??1;if(s===1)return jn(_d(t));const a=(t.getDay()-s+7)%7,i=(1-s+7)%7,c=new Date(t.valueOf());return c.setDate(t.getDate()+(i-a)),jn(_d(c))}case"%c":{let s=t.getFullYear()+"";return s+="-"+jn(t.getMonth()+1),s+="-"+jn(t.getDate()),s+="T",s+=jn(t.getHours()),s+=":"+jn(t.getMinutes()),s+=":"+jn(t.getSeconds()),s}case"%Q":return Math.floor(t.getMonth()/3)+1;default:return e}}var Vk=/%[a-zA-Z]/g;function eo(e,t){return typeof e=="function"?e:function(n){return n?(n.getMonth||(n=new Date(n)),e.replace(Vk,s=>Uk(s,n,t))):""}}function Gf(e){return e&&typeof e=="object"&&!Array.isArray(e)}function Np(e,t){for(const n in t){const s=t[n];Gf(e[n])&&Gf(s)?e[n]=Np({...e[n]},t[n]):e[n]=t[n]}return e}function fc(e){return{getGroup(t){const n=e[t];return s=>n&&n[s]||s},getRaw(){return e},extend(t,n){if(!t)return this;let s;return n?s=Np({...t},e):s=Np({...e},t),fc(s)}}}var Gk=Cx();const Kk="en-US",Qk={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},Yk={ok:"OK",cancel:"Cancel",select:"Select","No data":"No data","Rows per page":"Rows per page","Total pages":"Total pages"},Xk={timeFormat:"%H:%i",dateFormat:"%m/%d/%Y",monthYearFormat:"%F %Y",yearFormat:"%Y"},Av={core:Yk,calendar:Qk,formats:Xk,lang:Kk},Jp=o.createContext(""),Nv=o.createContext({}),_r=o.createContext(null),Rv=o.createContext(null),fn=Object.freeze(Object.defineProperty({__proto__:null,fieldId:Rv,helpers:Nv,i18n:_r,theme:Jp},Symbol.toStringTag,{value:"Module"}));function Tv(e){const t=o.useContext(Rv),[n]=o.useState(()=>e||t||Xp());return n}function rc({type:e="",css:t="",icon:n="",disabled:s=!1,title:a="",tooltip:i,text:c="",children:u,onClick:d}){const p=o.useMemo(()=>{let m=e?e.split(" ").filter(g=>g!=="").map(g=>"wx-"+g).join(" "):"";return t+(t?" ":"")+m},[e,t]),h=m=>{d&&d(m)};return r.jsxs("button",{title:a,className:`wx-2ZWgb4 wx-button ${p} ${n&&!u?"wx-icon":""}`,disabled:s,onClick:h,"data-tooltip-text":i,children:[n&&r.jsx("i",{className:"wx-2ZWgb4 "+n}),u||c||" "]})}function Jk({id:e,label:t="",inputValue:n="",value:s=!1,onChange:a,disabled:i=!1,css:c=""}){const u=Tv(e),[d,p]=us(s),h=({target:m})=>{const g=m.checked;p(g),a&&a({value:g,inputValue:n})};return r.jsxs("div",{className:`wx-2IvefP wx-checkbox ${c}`,children:[r.jsx("input",{type:"checkbox",id:u,disabled:i,className:"wx-2IvefP wx-check",checked:d,value:n,onChange:h}),r.jsxs("label",{htmlFor:u,className:"wx-2IvefP wx-label",children:[r.jsx("span",{className:"wx-2IvefP wx-before"}),t&&r.jsx("span",{className:"wx-2IvefP wx-after",children:t})]})]})}function Zp({theme:e="",target:t,children:n}){const s=o.useRef(null),a=o.useRef(null),[i,c]=o.useState(null);s.current||(s.current=document.createElement("div"));const u=o.useContext(Jp);return o.useEffect(()=>{c(t||Zk(a.current)||nr.getTopNode(a.current))},[a.current]),r.jsxs(r.Fragment,{children:[r.jsx("span",{ref:a,style:{display:"none"}}),a.current&&i?Gk.createPortal(r.jsx("div",{className:`wx-3ZWsT0 wx-${e||u}-theme`,children:n}),i):null]})}function Zk(e){const t=nr.getTopNode(e);for(;e&&e!==t&&!e.getAttribute("data-wx-portal-root");)e=e.parentNode;return e}function eM({left:e=0,top:t=0,at:n="bottom",parent:s=null,width:a="auto",css:i="",onCancel:c,children:u,trackScroll:d=!1}){const[p,h]=o.useState(0),[m,g]=o.useState(0),[w,v]=o.useState("auto"),[y,k]=o.useState(!1),N=o.useRef(null),C=o.useRef(null),A=o.useRef(c);o.useEffect(()=>{A.current=c},[c]);function E(F){return s&&(a+"").indexOf("%")>-1?a.replace(/(\d+)%/,(M,H)=>(H=H*s.offsetWidth/100+"px",a.replace(M,H))):a&&a!=="auto"?a:F}const I=o.useCallback(()=>{if(!N.current)return;const F=Cv(N.current,s,n,e,t);F&&(h(F.x),g(F.y),v(E(F.width)))},[N,s,n,e,t,a]);return o.useLayoutEffect(()=>{const F=H=>{A.current&&H.target!==C.current&&N.current&&!N.current.contains(H.target)&&A.current(H)};let M;return requestAnimationFrame(()=>{I(),k(!0),d&&N.current&&(C.current=kv(N.current),C.current&&C.current.addEventListener("scroll",F,!0)),s&&(M=new ResizeObserver(I),M.observe(s))}),()=>{d&&C.current&&C.current.removeEventListener("scroll",F,!0),M?.disconnect()}},[]),o.useLayoutEffect(()=>{I()},[s,n,e,t]),o.useEffect(()=>{const F=M=>{A.current&&A.current(M)};if(N.current)return ds(N.current,{callback:F,parent:()=>s}).destroy},[s]),r.jsx("div",{ref:N,className:["wx-37M6Fj","wx-popup",i].filter(Boolean).join(" "),style:{position:"absolute",visibility:y?"visible":"hidden",top:m+"px",left:p+"px",width:w},children:u})}function tM({position:e="bottom",align:t="start",autoFit:n=!0,onCancel:s=null,width:a="100%",css:i="",children:c}){const u=o.useRef(null),[d,p]=o.useState(e),[h,m]=o.useState(t),g=o.useRef(s);return o.useEffect(()=>{g.current=s},[s]),o.useEffect(()=>{if(n){const w=u.current;if(w){const v=w.getBoundingClientRect(),y=document.body.getBoundingClientRect();v.right>=y.right&&m("end"),v.bottom>=y.bottom&&p("top")}}},[]),o.useEffect(()=>{if(u.current){const w=v=>{g.current&&g.current(v)};return ds(u.current,w).destroy}},[]),r.jsx("div",{ref:u,className:["wx-dropdown",`wx-${d}-${h}`,i||"","wx-aaaVytZW"].filter(Boolean).join(" "),style:{width:a},children:c})}function em({position:e="bottom",align:t="start",autoFit:n=!0,inline:s=!1,onCancel:a,width:i="100%",children:c,...u}){const[d,p]=o.useState(void 0),h=o.useRef(null),m=o.useMemo(()=>`${e}-${t}`,[e,t]);return o.useLayoutEffect(()=>{h.current&&p(h.current.parentNode)},[]),r.jsxs(r.Fragment,{children:[d&&(s?r.jsx(tM,{onCancel:a,position:e,align:t,autoFit:n,width:i,...u,children:c}):r.jsx(Zp,{children:r.jsx(eM,{parent:d,at:m,onCancel:a,width:i,...u,children:c})})),r.jsx("span",{ref:h,className:"wx-portal-node wx-32GZ52"})]})}function Au(){return fc(Av)}function nM(){let e=null,t=!1,n=!1,s,a,i,c;const u=(m,g,w,v,y)=>{s=m,a=g,i=w,c=v,n=y},d=m=>{e=m,t=e!==null,i(e)},p=(m,g)=>{if(!n&&m!==null&&s){const w=s.querySelectorAll(".wx-list > .wx-item")[m];w&&(w.scrollIntoView({block:"nearest"}),g&&g.preventDefault())}},h=(m,g)=>{const w=m===null?null:Math.max(0,Math.min(e+m,a.length-1));w!==e&&(d(w),s?p(w,g):requestAnimationFrame(()=>p(w,g)))};return{move:m=>{const g=uc(m),w=a.findIndex(v=>v.id===g);w!==e&&d(w)},keydown:(m,g)=>{switch(m.code){case"Enter":t?c():d(0);break;case"Space":t||d(0);break;case"Escape":i(e=null);break;case"Tab":i(e=null);break;case"ArrowDown":h(t?1:g||0,m);break;case"ArrowUp":h(t?-1:g||0,m);break}},init:u,navigate:h}}const Kf=10,rM=o.memo(function({data:e,checkboxes:t,itemTemplate:n,value:s}){return r.jsxs(r.Fragment,{children:[t&&r.jsx(Jk,{id:e.id,css:"wx-list-checkbox",value:s&&s.includes(e.id)}),n?Qp(n,{option:e}):e.label]})});function Qf({visibleItems:e,visibleRange:t,navIndex:n,checkboxes:s,itemTemplate:a,value:i,measureRefCallback:c}){return e.map((u,d)=>{const p=t.start+d;return r.jsx("div",{ref:d===0?c:void 0,className:`wx-233fr7 wx-item ${p===n?"wx-focus":""}`,"data-id":u.id,children:r.jsx(rM,{data:u,checkboxes:s,itemTemplate:a,value:i})},u.id)})}function Nu({items:e=[],children:t,onSelect:n,onReady:s,virtualized:a=!1,checkboxes:i,multiselect:c,value:u,...d}){const p=o.useRef(),h=o.useRef(!1),m=o.useRef(nM()),[g,w]=o.useState(null),v=o.useRef(g),[y,k]=o.useState(0),[N,C]=o.useState(24),A=o.useRef(!1),E=(o.useContext(_r)||Au()).getGroup("core"),I=o.useRef(e);o.useEffect(()=>{I.current=e},[e]);const F=o.useRef(u);o.useEffect(()=>{F.current=u},[u]);const M=o.useRef(0);o.useEffect(()=>{M.current=N},[N]);const H=o.useCallback(oe=>{oe&&oe.stopPropagation();const me=I.current,Ae=F.current,Te=v.current;let Pe;const Se=me[Te]?.id;c?Ae&&Ae.includes(Se)?Pe=Ae.filter(te=>te!==Se):Pe=[...Ae||[],Se]:Pe=Se,n&&n({id:Pe})},[c,n]),V=o.useRef(H);o.useEffect(()=>{V.current=H},[H]);const P=o.useCallback(oe=>{if(p.current){let me=oe*M.current-p.current.clientHeight+M.current;k(me),p.current.scrollTop=me}},[M.current]),D=o.useCallback(oe=>{p.current=oe,a&&(oe&&!h.current&&v.current!==null&&requestAnimationFrame(()=>{p.current&&(P(v.current),h.current=!0)}),oe||(h.current=!1))},[P]),O=o.useCallback(oe=>{if(!oe||A.current)return;const me=oe.getBoundingClientRect().height;me&&(C(me),M.current=me,A.current=!0)},[]);o.useEffect(()=>{m.current.init(p.current,e,oe=>{w(oe),v.current=oe},oe=>V.current(oe),a)},[e,p.current,a]),o.useEffect(()=>{const oe=(Ae,Te)=>{m.current.navigate(Ae,Te),P(v.current)},me=(Ae,Te)=>{const Pe=v.current,Se=I.current;if(Pe!==0&&Pe!==Se.length-1&&(Ae.key==="ArrowDown"||Ae.key==="ArrowUp")&&Ae.preventDefault(),m.current.keydown(Ae,Te),p.current){const te=p.current.scrollTop<=v.current*M.current,Ce=p.current.scrollTop+p.current.clientHeight>=v.current*M.current+M.current;te?Ce||P(v.current):(p.current.scrollTop=v.current*M.current,k(p.current.scrollTop))}};s&&s({navigate:a?oe:m.current.navigate,keydown:a?me:m.current.keydown,move:m.current.move})},[]);const X=o.useRef(0),G=o.useRef(e);G.current!==e&&(G.current=e,X.current+=1);const U=o.useCallback(()=>{m.current.navigate(null)},[m]),ie=o.useCallback(oe=>{a&&k(oe.target.scrollTop)},[a]),j=o.useMemo(()=>Math.ceil((p.current?.clientHeight||0)/N),[N,y]),re=o.useMemo(()=>{if(!a)return{start:0,end:e.length};if(!e.length)return{start:0,end:0};const oe=Math.floor(y/N),me=oe+j;return{start:Math.max(0,oe-Kf),end:Math.min(e.length,me+Kf)}},[a,e,y,N,j]),de=o.useMemo(()=>{if(!a)return e;const{start:oe,end:me}=re;return e.slice(oe,me).map(Ae=>({...Ae}))},[a,e,re]),Q=re.start*N,ge=e.length*N;return o.useEffect(()=>{a&&k(0)},[e,a]),o.useEffect(()=>{g===null&&(h.current=!1)},[g]),g===null?null:r.jsx(em,{onCancel:U,...d,children:r.jsx("div",{className:"wx-233fr7 wx-list",ref:D,onClick:H,onMouseMove:m.current.move,onScroll:ie,children:e.length?a?r.jsx("div",{className:"wx-233fr7 wx-list-wrapper",style:{height:`${ge}px`},children:r.jsx("div",{className:"wx-233fr7 wx-list-content",style:{transform:`translateY(${Q}px)`},children:r.jsx(Qf,{visibleRange:re,visibleItems:de,navIndex:g,measureRefCallback:O,checkboxes:i,itemTemplate:t,value:u})})}):r.jsx(Qf,{visibleRange:re,visibleItems:de,navIndex:g,measureRefCallback:O,checkboxes:i,itemTemplate:t,value:u}):r.jsx("div",{className:"wx-233fr7 wx-no-data",children:E("No data")})})},X.current)}function tm({value:e="",id:t,readonly:n=!1,focus:s=!1,select:a=!1,type:i="text",placeholder:c="",disabled:u=!1,error:d=!1,title:p="",tooltip:h,css:m="",icon:g="",clear:w=!1,onChange:v}){const y=Tv(t),[k,N]=us(e),C=o.useRef(null),A=o.useMemo(()=>g&&m.indexOf("wx-icon-left")===-1?"wx-icon-right "+m:m,[g,m]),E=o.useMemo(()=>g&&m.indexOf("wx-icon-left")!==-1,[g,m]);o.useEffect(()=>{const V=setTimeout(()=>{s&&C.current&&C.current.focus(),a&&C.current&&C.current.select()},1);return()=>clearTimeout(V)},[s,a]);const I=o.useCallback(V=>{const P=V.target.value;N(P),v&&v({value:P,input:!0})},[v]),F=o.useCallback(V=>v&&v({value:V.target.value}),[v]);function M(V){V.stopPropagation(),N(""),v&&v({value:""})}let H=i;return i!=="password"&&i!=="number"&&(H="text"),o.useEffect(()=>{const V=F,P=C.current;return P.addEventListener("change",V),()=>{P&&P.removeEventListener("change",V)}},[F]),r.jsxs("div",{className:`wx-hQ64J4 wx-text ${A} ${d?"wx-error":""} ${u?"wx-disabled":""} ${w?"wx-clear":""}`,"data-tooltip-text":h,children:[r.jsx("input",{className:"wx-hQ64J4 wx-input",ref:C,id:y,readOnly:n,disabled:u,placeholder:c,type:H,title:p,value:k,onInput:I}),w&&!u&&k?r.jsxs(r.Fragment,{children:[r.jsx("i",{className:"wx-hQ64J4 wx-icon wxi-close",onClick:M}),E&&r.jsx("i",{className:`wx-hQ64J4 wx-icon ${g}`})]}):g?r.jsx("i",{className:`wx-hQ64J4 wx-icon ${g}`}):null]})}function sM({date:e,type:t,part:n,onShift:s}){const{calendar:a,formats:i}=o.useContext(_r).getRaw(),c=e.getFullYear(),u=o.useMemo(()=>{switch(t){case"month":return eo(i.monthYearFormat,a)(e);case"year":return eo(i.yearFormat,a)(e);case"duodecade":{const{start:p,end:h}=Mv(c),m=eo(i.yearFormat,a);return`${m(new Date(p,0,1))} - ${m(new Date(h,11,31))}`}default:return""}},[e,t,c,a,i]);function d(){s&&s({diff:0,type:t})}return r.jsxs("div",{className:"wx-8HQVQV wx-header",children:[n!=="right"?r.jsx("i",{className:"wx-8HQVQV wx-pager wxi-angle-left",onClick:()=>s&&s({diff:-1,type:t})}):r.jsx("span",{className:"wx-8HQVQV wx-spacer"}),r.jsx("span",{className:"wx-8HQVQV wx-label",onClick:d,children:u}),n!=="left"?r.jsx("i",{className:"wx-8HQVQV wx-pager wxi-angle-right",onClick:()=>s&&s({diff:1,type:t})}):r.jsx("span",{className:"wx-8HQVQV wx-spacer"})]})}function nm({onClick:e,children:t}){return r.jsx("button",{className:"wx-3s8W4d wx-button",onClick:e,children:t})}function aM({value:e,current:t,part:n="",markers:s=null,css:a="",onCancel:i,onChange:c}){const u=(o.useContext(_r)||Au()).getRaw().calendar,d=(u.weekStart||7)%7,p=u.dayShort.slice(d).concat(u.dayShort.slice(0,d)),h=(I,F,M)=>new Date(I.getFullYear(),I.getMonth()+(F||0),I.getDate()+(M||0));let m=n!=="normal";function g(I){const F=I.getDay();return F===0||F===6}function w(){const I=h(t,0,1-t.getDate());return I.setDate(I.getDate()-(I.getDay()-(d-7))%7),I}function v(){const I=h(t,1,-t.getDate());return I.setDate(I.getDate()+(6-I.getDay()+d)%7),I}const y=o.useRef(0);function k(I,F){F.timeStamp!==y.current&&(y.current=F.timeStamp,F.stopPropagation(),c&&c(new Date(I)),i&&i())}const N=o.useMemo(()=>n=="normal"?[e?h(e).valueOf():0]:e?[e.start?h(e.start).valueOf():0,e.end?h(e.end).valueOf():0]:[0,0],[n,e]),C=o.useMemo(()=>{const I=w(),F=v(),M=t.getMonth();let H=[];for(let V=I;V<=F;V.setDate(V.getDate()+1)){const P={day:V.getDate(),in:V.getMonth()===M,date:V.valueOf()};let D="";if(D+=P.in?"":" wx-inactive",D+=N.indexOf(P.date)>-1?" wx-selected":"",m){const O=P.date==N[0],X=P.date==N[1];O&&!X?D+=" wx-left":X&&!O&&(D+=" wx-right"),P.date>N[0]&&P.date<N[1]&&(D+=" wx-inrange")}if(D+=g(V)?" wx-weekend":"",s){const O=s(V);O&&(D+=" "+O)}H.push({...P,css:D})}return H},[t,N,m,s]),A=o.useRef(null);let E=o.useRef({});return E.current.click=k,o.useEffect(()=>{ao(A.current,E.current)},[]),r.jsxs("div",{className:`wx-398RBS wx-month ${a}`,children:[r.jsx("div",{className:"wx-398RBS wx-weekdays",children:p.map(I=>r.jsx("div",{className:"wx-398RBS wx-weekday",children:I},I))}),r.jsx("div",{className:"wx-398RBS wx-days",ref:A,children:C.map(I=>r.jsx("div",{className:`wx-398RBS wx-day ${I.css} ${I.in?"":"wx-out"}`,"data-id":I.date,children:I.day},I.date))})]})}function iM({value:e,current:t,part:n,onCancel:s,onChange:a,onShift:i}){const c=o.useRef(new Date),[u,d]=us(e||c.current),[p,h]=us(t||c.current),m=o.useContext(_r).getRaw().calendar,g=m.monthShort||[],w=o.useMemo(()=>p.getMonth(),[p]),v=o.useCallback((N,C)=>{if(N!=null){C.stopPropagation();const A=new Date(p);A.setMonth(N),h(A),i&&i({current:A})}n==="normal"&&d(new Date(p)),s&&s()},[p,n,i,s]),y=o.useCallback(()=>{const N=new Date(Pv(u,n)||p);N.setMonth(p.getMonth()),N.setFullYear(p.getFullYear()),a&&a(N)},[u,p,n,a]),k=o.useCallback(N=>{const C=N.target.closest("[data-id]");if(C){const A=parseInt(C.getAttribute("data-id"),10);v(A,N)}},[v]);return r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"wx-34U8T8 wx-months",onClick:k,children:g.map((N,C)=>r.jsx("div",{className:"wx-34U8T8 wx-month"+(w===C?" wx-current":""),"data-id":C,children:N},C))}),r.jsx("div",{className:"wx-34U8T8 wx-buttons",children:r.jsx(nm,{onClick:y,children:m.done})})]})}const $d="wx-1XEF33",oM=({value:e,current:t,onCancel:n,onChange:s,onShift:a,part:i})=>{const c=o.useContext(_r).getRaw().calendar,[u,d]=us(t),[p,h]=us(e),m=o.useMemo(()=>u.getFullYear(),[u]),g=o.useMemo(()=>{const{start:N,end:C}=Mv(m),A=[];for(let E=N;E<=C;++E)A.push(E);return A},[m]),w={click:v};function v(N,C){if(N){C.stopPropagation();const A=new Date(u);A.setFullYear(N),d(A),a&&a({current:A})}i==="normal"&&h(new Date(u)),n&&n()}function y(){const N=new Date(Pv(p,i)||u);N.setFullYear(u.getFullYear()),s&&s(N)}const k=o.useRef(null);return o.useEffect(()=>{k.current&&ao(k.current,w)},[]),r.jsxs(r.Fragment,{children:[r.jsx("div",{className:$d+" wx-years",ref:k,children:g.map((N,C)=>r.jsx("div",{className:$d+` wx-year ${m==N?"wx-current":""} ${C===0?"wx-prev-decade":""} ${C===11?"wx-next-decade":""}`,"data-id":N,children:N},C))}),r.jsx("div",{className:$d+" wx-buttons",children:r.jsx(nm,{onClick:y,children:c.done})})]})},Yf={month:{component:aM,next:lM,prev:cM},year:{component:iM,next:dM,prev:uM},duodecade:{component:oM,next:mM,prev:pM}};function cM(e){return e=new Date(e),e.setMonth(e.getMonth()-1),e}function lM(e){return e=new Date(e),e.setMonth(e.getMonth()+1),e}function uM(e){return e=new Date(e),e.setFullYear(e.getFullYear()-1),e}function dM(e){return e=new Date(e),e.setFullYear(e.getFullYear()+1),e}function pM(e){return e=new Date(e),e.setFullYear(e.getFullYear()-10),e}function mM(e){return e=new Date(e),e.setFullYear(e.getFullYear()+10),e}function Pv(e,t){let n;if(t==="normal")n=e;else{const{start:s,end:a}=e;t==="left"?n=s:t=="right"?n=a:n=s&&a}return n}const hM=["clear","today"];function fM(e){if(e==="done")return-1;if(e==="clear")return null;if(e==="today")return new Date}function gM({value:e,current:t,onCurrentChange:n,part:s="normal",markers:a=null,buttons:i,css:c="",onShift:u,onChange:d}){const p=o.useContext(_r).getGroup("calendar"),[h,m]=o.useState("month"),g=Array.isArray(i)?i:i?hM:[],w=(C,A)=>{C.preventDefault(),d&&d({value:A})},v=()=>{h==="duodecade"?m("year"):h==="year"&&m("month")},y=C=>{const{diff:A,current:E}=C;if(A===0){h==="month"?m("year"):h==="year"&&m("duodecade");return}if(A){const I=Yf[h];n(A>0?I.next(t):I.prev(t))}else E&&n(E);u&&u()},k=C=>{m("month"),d&&d({select:!0,value:C})},N=o.useMemo(()=>Yf[h].component,[h]);return r.jsx("div",{className:`wx-2Gr4AS wx-calendar ${s!=="normal"&&s!=="both"?"wx-part":""} ${c}`,children:r.jsxs("div",{className:"wx-2Gr4AS wx-wrap",children:[r.jsx(sM,{date:t,part:s,type:h,onShift:y}),r.jsxs("div",{children:[r.jsx(N,{value:e,current:t,onCurrentChange:n,part:s,markers:a,onCancel:v,onChange:k,onShift:y}),h==="month"&&g.length>0&&r.jsx("div",{className:"wx-2Gr4AS wx-buttons",children:g.map(C=>r.jsx("div",{className:"wx-2Gr4AS wx-button-item",children:r.jsx(nm,{onClick:A=>w(A,fM(C)),children:p(C)})},C))})]})]})})}function rm(e){let{words:t=null,optional:n=!1,children:s}=e,a=o.useContext(_r);const i=o.useMemo(()=>{let c=a;return(!c||!c.extend)&&(c=fc(Av)),t!==null&&(c=c.extend(t,n)),c},[t,n,a]);return r.jsx(_r.Provider,{value:i,children:s})}function Xf(e,t,n,s){if(!e||s){const a=t?new Date(t):new Date;a.setDate(1),n(a)}else if(e.getDate()!==1){const a=new Date(e);a.setDate(1),n(a)}}const bM=["clear","today"];function Iv({value:e,current:t,markers:n=null,buttons:s=bM,css:a="",onChange:i}){const[c,u]=us(e),[d,p]=us(t);o.useEffect(()=>{Xf(d,c,p,!1)},[c,d]);const h=o.useCallback(g=>{const w=g.value;w?(u(new Date(w)),Xf(d,new Date(w),p,!0)):u(null),i&&i({value:w?new Date(w):null})},[i,d]),m=o.useCallback(g=>{p(g)},[p]);return d?r.jsx(rm,{children:r.jsx(gM,{value:c,current:d,markers:n,buttons:s,css:a,onChange:h,onCurrentChange:m})}):null}function vM(e){return e||(e={}),e.width||(e.width="unset"),e}const wM=["clear","today"];function yM({value:e,id:t,disabled:n=!1,error:s=!1,placeholder:a="",format:i="",buttons:c=wM,css:u="",title:d="",tooltip:p,editable:h=!1,clear:m=!1,onChange:g,dropdown:w={}}){const{calendar:v,formats:y}=(o.useContext(_r)||Au()).getRaw(),k=i||y?.dateFormat;let N=typeof k=="function"?k:eo(k,v);const[C,A]=o.useState(e),[E,I]=o.useState(!1);o.useEffect(()=>{A(e)},[e]);function F(){I(!1)}function M(P){const D=P===C||P&&C&&P.valueOf()===C.valueOf()||!P&&!C;A(P),D||g&&g({value:P}),setTimeout(F,1)}const H=o.useMemo(()=>C?N(C):"",[C,N]);function V({value:P,input:D}){if(!h&&!m||D)return;let O=typeof h=="function"?h(P):P?new Date(P):null;O=isNaN(O)?C||null:O||null,M(O)}return o.useEffect(()=>{const P=F;return window.addEventListener("scroll",P),()=>window.removeEventListener("scroll",P)},[]),r.jsxs("div",{className:"wx-1lKOFG wx-datepicker",onClick:()=>I(!0),children:[r.jsx(tm,{css:`wx-date-input ${u}`,title:d,tooltip:p,value:H,id:t,readonly:!h,disabled:n,error:s,placeholder:a,onInput:F,onChange:V,icon:"wxi-calendar",clear:m}),E&&!n&&r.jsx(em,{onCancel:F,...vM(w),children:r.jsx(Iv,{buttons:c,value:C,onChange:P=>M(P.value)})})]})}function xM({value:e="",options:t=[],textOptions:n=null,placeholder:s="",disabled:a=!1,error:i=!1,title:c="",tooltip:u,textField:d="label",clear:p=!1,css:h="",children:m,onChange:g,dropdown:w={}}){const v=o.useRef(null),y=o.useRef(null);let[k,N]=us(e);function C(M){v.current=M.navigate,y.current=M.keydown}const A=o.useMemo(()=>k||k===0?(n||t).find(M=>M.id===k):null,[k,n,t]),E=o.useCallback(({id:M})=>{(M||M===0)&&(N(M),v.current(null),g&&g({value:M}))},[N,g]),I=o.useCallback(M=>{M.stopPropagation(),N(""),g&&g({value:""})},[N,g]),F=o.useCallback(()=>t.findIndex(M=>M.id===k),[t,k]);return r.jsxs("div",{className:`wx-2YgblL wx-richselect ${h} ${i?"wx-2YgblL wx-error":""} ${a?"wx-2YgblL wx-disabled":""} ${m?"":"wx-2YgblL wx-nowrap"}`,title:c,onClick:()=>v.current(F()),onKeyDown:M=>y.current(M,F()),tabIndex:0,"data-tooltip-text":u,children:[r.jsx("div",{className:"wx-2YgblL wx-label",children:A?m?m(A):A[d]:s?r.jsx("span",{className:"wx-2YgblL wx-placeholder",children:s}):" "}),p&&!a&&k?r.jsx("i",{className:"wx-2YgblL wx-icon wxi-close",onClick:I}):r.jsx("i",{className:"wx-2YgblL wx-icon wxi-angle-down"}),!a&&r.jsx(Nu,{items:t,onReady:C,onSelect:E,...w,children:({option:M})=>m?m(M):M[d]})]})}const SM=({options:e=[],value:t="",css:n="",children:s,onChange:a})=>{const[i,c]=o.useState(t),u=d=>{c(d),a&&a({value:d})};return o.useEffect(()=>{c(t)},[t]),r.jsx("div",{className:`wx-0hMO7P wx-segmented ${n}`,children:e.map(d=>r.jsx("button",{className:`wx-0hMO7P wx-segment ${d.css} ${d.id===i?"wx-selected":""}`,title:d.title,onClick:()=>u(d.id),"data-tooltip-text":d.tooltip,children:s?Qp(s,{option:d}):r.jsxs(r.Fragment,{children:[d.icon&&r.jsx("i",{className:`wx-0hMO7P wx-icon ${d.icon} ${d.label?"":"wx-only"}`}),d.label&&r.jsx("span",{className:"wx-0hMO7P wx-label",children:d.label})]})},d.id))})};function CM({notice:e={}}){function t(){e.remove&&e.remove()}return r.jsxs("div",{className:`wx-11sNg5 wx-notice wx-${e.type?e.type:""}`,role:"status","aria-live":"polite",children:[r.jsx("div",{className:"wx-11sNg5 wx-text",children:e.text}),r.jsx("div",{className:"wx-11sNg5 wx-button",children:r.jsx("i",{className:"wx-11sNg5 wxi-close",onClick:t})})]})}function kM({data:e=[]}){return r.jsx("div",{className:"wx-3nwoO9 wx-notices",children:e.map(t=>r.jsx(CM,{notice:t},t.id))})}function Rp({title:e="",buttons:t=["cancel","ok"],header:n,children:s,footer:a,css:i="",onConfirm:c,onCancel:u}){const d=(o.useContext(_r)||Au()).getGroup("core"),p=o.useRef(null);o.useEffect(()=>{p.current?.focus()},[]);function h(g){switch(g.code){case"Enter":{const w=g.target.tagName;if(w==="TEXTAREA"||w==="BUTTON")return;c&&c({event:g});break}case"Escape":u&&u({event:g});break}}function m(g,w){const v={event:g,button:w};w==="cancel"?u&&u(v):c&&c(v)}return r.jsx("div",{className:`wx-1FxkZa wx-modal ${i}`,ref:p,tabIndex:0,onKeyDown:h,children:r.jsxs("div",{className:"wx-1FxkZa wx-window",children:[n||(e?r.jsx("div",{className:"wx-1FxkZa wx-header",children:e}):null),r.jsx("div",{children:s}),a||t&&r.jsx("div",{className:"wx-1FxkZa wx-buttons",children:t.map(g=>r.jsx("div",{className:"wx-1FxkZa wx-button",children:r.jsx(rc,{type:`block ${g==="ok"?"primary":"secondary"}`,onClick:w=>m(w,g),children:d(g)})},g))})]})})}function MM({children:e},t){const[n,s]=o.useState(null),[a,i]=o.useState([]);return o.useImperativeHandle(t,()=>({showModal:c=>{const u={...c};return s(u),new Promise((d,p)=>{u.resolve=h=>{s(null),d(h)},u.reject=h=>{s(null),p(h)}})},showNotice:c=>{c={...c},c.id=c.id||Xp(),c.remove=()=>i(u=>u.filter(d=>d.id!==c.id)),c.expire!=-1&&setTimeout(c.remove,c.expire||5100),i(u=>[...u,c])}}),[]),r.jsxs(r.Fragment,{children:[e,n&&r.jsx(Rp,{title:n.title,buttons:n.buttons,onConfirm:n.resolve,onCancel:n.reject,children:n.message}),r.jsx(kM,{data:a})]})}const AM=o.forwardRef(MM);function NM(e){let{children:t}=e,n=o.useRef();const s=o.useMemo(()=>({showNotice:a=>n.current.showNotice(a),showModal:a=>n.current.showModal(a)}),[]);return r.jsx(Nv.Provider,{value:s,children:r.jsx(AM,{ref:n,children:t})})}const RM=({value:e=!1,type:t="",icon:n="",disabled:s=!1,iconActive:a="",onClick:i,title:c="",tooltip:u,css:d="",text:p="",textActive:h="",children:m,active:g,onChange:w})=>{const[v,y]=us(e),k=o.useMemo(()=>(v?"pressed":"")+(t?" "+t:""),[v,t]),N=o.useCallback(C=>{let A=!v;i&&i(C),C.defaultPrevented||(y(A),w&&w({value:A}))},[v,i,w]);return v&&g?r.jsx(rc,{title:c,tooltip:u,text:v&&h||p,css:d,type:k,icon:v&&a||n,onClick:N,disabled:s,children:Qp(g,{value:v})}):m?r.jsx(rc,{title:c,tooltip:u,text:v&&h||p,css:d,type:k,icon:v&&a||n,onClick:N,disabled:s,children:m}):r.jsx(rc,{title:c,tooltip:u,text:v&&h||p,css:d,type:k,icon:v&&a||n,onClick:N,disabled:s})};function TM(){return r.jsx(r.Fragment,{})}function Jf(e){const{fonts:t=!0,children:n}=e;return r.jsx(Jp.Provider,{value:"willow",children:r.jsxs(r.Fragment,{children:[n&&n&&r.jsx("div",{className:"wx-theme wx-willow-theme",children:n}),t&&r.jsxs(r.Fragment,{children:[r.jsx("link",{rel:"preconnect",href:"https://cdn.svar.dev",crossOrigin:"true"}),r.jsx(TM,{}),r.jsx("link",{rel:"stylesheet",href:"https://cdn.svar.dev/fonts/wxi/wx-icons.css"})]})]})})}Yp(nr);const sm={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 jv=class{constructor(e){this._nextHandler=null,this._dispatch=e,this.exec=this.exec.bind(this)}async exec(e,t){return this._dispatch(e,t),this._nextHandler&&await this._nextHandler.exec(e,t),t}setNext(e){return this._nextHandler=e}};new Date().valueOf();var PM=class{constructor(e){const t={id:0,$level:0,data:[],parent:null},n=new Map;n.set(0,t),this._pool=n,e&&e.length&&this.parse(e,0)}parse(e,t){const n=this._pool;for(let a=0;a<e.length;a++){const i=e[a];i.parent=i.parent||t,i.data=null,n.set(i.id,i)}for(let a=0;a<e.length;a++){const i=e[a],c=n.get(i.parent);c&&(c.data||(c.data=[]),c.data.push(i))}const s=n.get(t);this.setLevel(s,s.$level+1,!1)}add(e,t){const n=this._pool.get(e.parent||0);e.$level=n.$level+1,this._pool.set(e.id,e),n.data?t===-1?n.data=[...n.data,e]:Zf(n,t,e):n.data=[e]}addAfter(e,t){if(!t)return this.add(e,-1);const n=this.byId(t),s=this.byId(n.parent),a=Fl(s,n.id)+1;e.parent=s.id,e.$level=s.$level+1,this.add(e,a)}remove(e){const t=this._pool.get(e);this._remove(t);const n=this._pool.get(t.parent);n.data=n.data.filter(s=>s.id!=e),this._clearBranch(n)}_remove(e){e.data&&e.data.forEach(t=>this._remove(t)),this._pool.delete(e.id)}update(e,t){let n=this._pool.get(e);const s=this._pool.get(n.parent),a=Fl(s,n.id);n={...n,...t},s&&a>=0&&(s.data[a]=n,s.data=[...s.data]),this._pool.set(n.id,n)}move(e,t,n){const s=this._pool.get(e),a=t==="child",i=this._pool.get(n),c=i.$level+(a?1:0);if(!s||!i)return;const u=this._pool.get(s.parent),d=a?i:this._pool.get(i.parent);d.data||(d.data=[]);const p=Fl(u,s.id);IM(u,p);const h=a?d.data.length:Fl(d,i.id)+(t==="after"?1:0);if(Zf(d,h,s),u.id===d.id&&p===h)return null;s.parent=d.id,s.$level!==c&&(s.$level=c,this.setLevel(s,c+1,!0)),this.update(s.id,s),this._clearBranch(u)}_clearBranch(e){e.data&&!e.data.length&&(e.open&&delete e.open,this.update(e.id,{data:null}))}toArray(){const e=[],t=this._pool.get(0).data;return t&&Ev(t,e),e}byId(e){return this._pool.get(e)}getBranch(e){return this._pool.get(e).data}forEach(e){this._pool.forEach((t,n)=>{n!==0&&e(t)})}eachChild(e,t){const n=this.byId(t);!n||!n.data||n.data.forEach((s,a)=>{e(this.byId(s.id),a),this.eachChild(e,s.id)})}setLevel(e,t,n){e.data&&(e.data=e.data.map(s=>(n&&(s={...s},this._pool.set(s.id,s)),s.$level=t,s.data&&this.setLevel(s,t+1,n),s)))}};function Ev(e,t){e.forEach(n=>{t.push(n),n.open===!0&&Ev(n.data,t)})}function IM(e,t){const n=[...e.data];n.splice(t,1),e.data=n}function Zf(e,t,n){const s=[...e.data];s.splice(t,0,n),e.data=s}function Fl(e,t){return e?.data.findIndex(n=>n.id===t)}var Fv=2,jM=class{constructor(t){t&&(this._writable=t.writable,this._async=t.async),this._values={},this._state={}}setState(t,n=0){const s={};return this._wrapProperties(t,this._state,this._values,"",s,n),s}getState(){return this._values}getReactive(){return this._state}_wrapProperties(t,n,s,a,i,c){for(const u in t){const d=n[u],p=s[u],h=t[u];if(d&&(p===h&&typeof h!="object"||h instanceof Date&&p instanceof Date&&p.getTime()===h.getTime()))continue;const m=a+(a?".":"")+u;d?(d.__parse(h,m,i,c)&&(s[u]=h),c&Fv?i[m]=d.__trigger:d.__trigger()):(h&&h.__reactive?n[u]=this._wrapNested(h,h,m,i):n[u]=this._wrapWritable(h),s[u]=h),i[m]=i[m]||null}}_wrapNested(t,n,s,a){const i=this._wrapWritable(t);return this._wrapProperties(t,i,n,s,a,0),i.__parse=(c,u,d,p)=>(this._wrapProperties(c,i,n,u,d,p),!1),i}_wrapWritable(t){const n=[],s=function(){for(let a=0;a<n.length;a++)n[a](t)};return{subscribe:a=>(n.push(a),this._async?setTimeout(a,1,t):a(t),()=>{const i=n.indexOf(a);i>=0&&n.splice(i,1)}),__trigger:()=>{n.length&&(this._async?setTimeout(s,1):s())},__parse:function(a){return t=a,!0}}}};function eg(e,t){return Object.defineProperty(e,"__reactive",{value:!0,enumerable:!1,writable:!1}),e}var EM=class{constructor(t,n,s,a){typeof t=="function"?this._setter=t:this._setter=t.setState.bind(t),this._routes=n,this._parsers=s,this._prev={},this._triggers=new Map,this._sources=new Map,this._routes.forEach(i=>{i.in.forEach(c=>{const u=this._triggers.get(c)||[];u.push(i),this._triggers.set(c,u)}),i.out.forEach(c=>{const u=this._sources.get(c)||{};i.in.forEach(d=>u[d]=!0),this._sources.set(c,u)})}),this._routes.forEach(i=>{i.length=Math.max(...i.in.map(c=>Dv(c,this._sources,1)))}),this._bus=a}init(t){const n={};for(const s in t)if(this._prev[s]!==t[s]){const a=this._parsers[s];n[s]=a?a(t[s]):t[s]}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,Fv);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 s=t.signals[n];s&&s()}}}setState(t,n=[]){const s=this._setter(t);return this._triggerUpdates(s,n),s}_triggerUpdates(t,n){const s=Object.keys(t),a=!n.length;n=n||[];for(let i=0;i<s.length;i++){const c=s[i],u=this._triggers.get(c);u&&u.forEach(d=>{n.indexOf(d)==-1&&n.push(d)})}a&&this._execNext(n)}_execNext(t){for(;t.length;){t.sort((s,a)=>s.length<a.length?1:-1);const n=t[t.length-1];t.splice(t.length-1),n.exec(t)}}};function Dv(e,t,n){const s=t.get(e);if(!s)return n;const a=Object.keys(s).map(i=>Dv(i,t,n+1));return Math.max(...a)}var FM=class{constructor(){this._nextHandler=null,this._handlers={},this._tag=new WeakMap,this.exec=this.exec.bind(this)}on(t,n,s){let a=this._handlers[t];a?s&&s.intercept?a.unshift(n):a.push(n):a=this._handlers[t]=[n],s&&s.tag&&this._tag.set(n,s.tag)}intercept(t,n,s){this.on(t,n,{...s,intercept:!0})}detach(t){for(const n in this._handlers){const s=this._handlers[n];for(let a=s.length-1;a>=0;a--)this._tag.get(s[a])===t&&s.splice(a,1)}}async exec(t,n){const s=this._handlers[t];if(s)for(let a=0;a<s.length;a++){const i=s[a](n);if(i===!1||i&&i.then&&await i===!1)return}return this._nextHandler&&await this._nextHandler.exec(t,n),n}setNext(t){return this._nextHandler=t}};const Gi=1024;function dc(e){return e<Gi?`${e} B`:e<Gi**2?`${(e/Gi).toFixed(1)} KB`:e<Gi**3?`${(e/Gi**2).toFixed(1)} MB`:`${(e/Gi**3).toFixed(1)} GB`}function tg(e,t){t||(t={key:"name",order:"asc"});const n=e.filter(c=>c.type==="folder"),s=e.filter(c=>c.type!=="folder"),a=n.sort(ng(t)),i=s.sort(ng(t));return[...a,...i]}function DM(e,t){return typeof e=="string"?e.localeCompare(t,void 0,{numeric:!0}):typeof e=="object"?e.getTime()-t.getTime():(e??0)-(t??0)}function LM(e,t){return typeof e=="string"?-e.localeCompare(t,void 0,{numeric:!0}):typeof t=="object"?t.getTime()-e.getTime():(t??0)-(e??0)}function ng({key:e,order:t}){const n=t==="asc"?DM:LM;return(s,a)=>n(s[e],a[e])}function am(e,t){const n=e==="/"?1:e.split("/").length;return n>=t.length?null:t[n].id}function _M(e){return e.length>1?e[e.length-2].id:null}let $M=class extends PM{constructor(t){const n={id:"/",name:"My files",open:!0,$level:1,parent:0,ext:"",type:"folder"};super([n]),this.parse(t,"/")}parse(t,n,s){!t||!t.length||(t.forEach(a=>this.parseId(a,s?n:void 0)),super.parse(t,n))}parseId(t,n){if(t.parent===0)return;const s=t.id,a=s.lastIndexOf("/");if(t.parent=n??(a===0?"/":s.slice(0,a)),t.name=s.slice(a+1),t.type=t.type||"file",t.type!=="folder"){const i=t.name.lastIndexOf("."),c=i!==-1?t.name.slice(i+1):"";t.ext=c!=="new"?c?.toLocaleLowerCase():""}}getParents(t){const n=[];let s=this.byId(t);if(!s)return n;for(;s.id!==0;)n.push(s),s=this.byId(s.parent);return n.reverse()}findFiles(t,n="/"){const s=[],a=t.toLocaleLowerCase();return this.eachChild(i=>{i.name.toLowerCase().indexOf(a)!==-1&&s.push(i)},n),s}add(t,n){const s=this.byId(t.parent||"/"),a=t.data?[...t.data]:null;t.data=null,super.add(t,n??s.data?s.data.length:0),a&&a.forEach(i=>this.add(i))}renameFiles(t,n,s){const a=this.byId(t),i=this.normalizeFile(a,n),c=[];return i.data?.forEach(u=>c.push(this.renameFiles(u.id,i.id,s))),c.length&&(i.data=c),s[t]=i.id,i}copyFiles(t,n,s){const a={};return t.forEach(i=>{const c=this.renameFiles(i,n,a);this.add(c),s&&this.remove(i),a[i]=c.id}),a}moveFiles(t,n){if(this.byId(t[0]).parent!==n)return this.copyFiles(t,n,!0)}serialize(t="/"){const n=[],s=this.byId(t);return s?(s.data?.forEach(a=>{const{id:i,date:c,type:u,size:d,lazy:p}=a,h={id:i,date:c,type:u??"file"};p&&(h.lazy=p),d&&(h.size=d),n.push(h);const m=this.serialize(i);m.length&&n.push(...m)}),n):null}normalizeFile(t,n){const s=t.name,a=s.lastIndexOf("."),i=a!==-1?s.slice(a+1):"",c=i?`.${i}`:"";let u=a!==-1?s.slice(0,a):s,d=n+(n==="/"?"":"/")+u;for(;this.byId(d+c);){const p=".new";d+=p,u+=p}return{...t,id:d+c,name:u+c,parent:n,ext:i.toLocaleLowerCase()}}},OM=class extends jM{in;_router;constructor(t){super({writable:t,async:!1});const n=[];for(let i=0;i<2;i++)n.push({in:["data",`panels.${i}.path`],out:[`panels.${i}._crumbs`],exec:c=>{const{data:u,panels:d}=this.getState(),p=[];p[i]={_crumbs:u.getParents(d[i].path)},this.setState({panels:p},c)}}),n.push({in:["data",`panels.${i}.path`,`panels.${i}._sorts`,"search"],out:[`panels.${i}._files`],exec:c=>{const{data:u,panels:d,search:p}=this.getState();let h;p?h=u.findFiles(p,d[i].path):h=u.byId(d[i].path)?.data||[];const{path:m,_sorts:g}=d[i];h=tg(h,g[m]);const w=[];w[i]={_files:h},this.setState({panels:w},c)}}),n.push({in:["data",`panels.${i}.selected`,`panels.${i}._sorts`],out:[`panels.${i}._selected`],exec:c=>{const{data:u,panels:d}=this.getState(),p=[];d[i].selected.forEach(v=>{const y=u.byId(v);y&&p.push(y)});const{path:h,_sorts:m}=d[i],g=tg(p,m[h]),w=[];w[i]={_selected:g},this.setState({panels:w},c)}});this._router=new EM(super.setState.bind(this),n,{data:i=>new $M(i)});const s=this.in=new FM;s.on("select-file",({id:i,toggle:c,range:u,panel:d,type:p})=>{const{panels:h,activePanel:m}=this.getState();typeof d>"u"&&(d=m),i||(c=u=!1);let g=[...h[d].selected];if(c){const v=g.indexOf(i);v===-1?g.push(i):g.splice(v,1)}else if(u&&h[d]._lastSelected){const v=h[d]._files;let y=v.findIndex(C=>C.id==h[d]._lastSelected),k=v.findIndex(C=>C.id==i);k<y&&([y,k]=[k,y]);const N=v.slice(y,k+1).map(C=>C.id);g=[...new Set([...g,...N])]}else g=i?[i]:[];const w=[];w[d]={selected:g,_lastSelected:i,_selectNavigation:p==="navigation"},this.setState({panels:w})}),s.on("set-path",({id:i,panel:c,selected:u})=>{const{data:d,activePanel:p}=this.getState(),h=d.byId(i);if(h){const m=[];typeof c>"u"&&(c=p),m[c]={path:i},this.setState({panels:m}),s.exec("select-file",{panel:c}),u&&u.forEach(g=>s.exec("select-file",{id:g,panel:c,toggle:!0})),h.lazy&&s.exec("request-data",{id:i})}}),s.on("provide-data",({id:i,data:c})=>{const{mode:u,data:d}=this.getState(),p=d.byId(i);p&&(p.lazy||(p.data=[]),p.lazy=!1,d.parse(c,i,u==="search"),this.setState({data:d}))}),s.on("open-tree-folder",({id:i,mode:c})=>{const{data:u}=this.getState();u.update(i,{open:c}),this.setState({data:u})}),s.on("show-preview",({mode:i})=>{this.setState({preview:i})}),s.on("rename-file",i=>{const{id:c,name:u}=i,{data:d,panels:p}=this.getState(),h=d.byId(c);if(h.name!==u){h.name=u;const m=d.normalizeFile(h,h.parent);i.newId=m.id,m.data=null,d.add(m);let g={[c]:m.id};h.data?.forEach(v=>g={...d.moveFiles([v.id],m.id),...g});const w=p.map(v=>({selected:v.selected,_crumbs:v._crumbs,_lastSelected:v._lastSelected,_sorts:v._sorts}));d.remove(c),this._updatePanels(w,g),this.setState({data:d,panels:w})}}),s.on("create-file",i=>{const{file:c,parent:u}=i,{data:d}=this.getState(),p=d.normalizeFile(c,u);p.type=c.type||"file",i.newId=p.id,d.add(p),this.setState({data:d}),s.exec("select-file",{id:p.id})}),s.on("delete-files",({ids:i})=>{const{data:c,panels:u}=this.getState(),d=u.map(p=>({selected:p.selected,_crumbs:p._crumbs,_lastSelected:p._lastSelected,_sorts:p._sorts}));i.forEach(p=>c.remove(p)),this._updatePanels(d,{}),this.setState({data:c,panels:d})}),s.on("copy-files",i=>{const{ids:c,target:u}=i;if(this._isPlacedIntoSelf(c,u)){console.error("You cannot copy a folder into itself"),i.skipProvider=!0;return}const{data:d,panels:p,activePanel:h}=this.getState(),m=d.copyFiles(c,u);i.newIds=c.map(g=>m[g]),this.setState({data:d}),p[h].path==u&&(s.exec("select-file",{}),c.forEach(g=>{s.exec("select-file",{id:m[g],toggle:!0})}))}),s.on("move-files",i=>{const{ids:c,target:u}=i;if(this._isPlacedIntoSelf(c,u)){console.error("You cannot move a folder into itself"),i.skipProvider=!0;return}const{data:d,panels:p,activePanel:h}=this.getState(),m=d.moveFiles(c,u);if(m){i.newIds=c.map(w=>m[w]);const g=p.map(w=>({selected:w.selected,_crumbs:w._crumbs,_lastSelected:w._lastSelected,_sorts:w._sorts}));this._updatePanels(g,m,!0),this.setState({data:d,panels:g}),p[h].path==u&&(s.exec("select-file",{}),c.forEach(w=>{s.exec("select-file",{id:m[w],toggle:!0})}))}});let a=null;s.on("filter-files",({text:i})=>{if(!i){a&&this.setState({...a});return}s.exec("select-file",{});const{panels:c,mode:u}=this.getState();a||(a={panels:c,mode:u,search:""}),this.setState({mode:"search",search:i})}),s.on("set-mode",({mode:i})=>{const{activePanel:c}=this.getState(),u=[];u[c]={_selectNavigation:!1};const d={mode:i,search:"",panels:u};a=null,this.setState(d)}),s.on("set-active-panel",({panel:i})=>{this.setState({activePanel:i})}),s.on("sort-files",({key:i,order:c,panel:u,path:d})=>{const{activePanel:p,panels:h}=this.getState();u=u??p,d=d??h[u].path;const m=[];m[u]={_sorts:{...h[u]._sorts,[d]:{key:i,order:c}}},this.setState({panels:m})}),this.initOnce()}initOnce(){const t=[];for(let s=0;s<2;s++)t[s]=eg({_crumbs:[],_files:[],_selected:[],_sorts:{},path:"/",selected:[],...t[s]});const n={panels:eg(t),data:[],search:""};this._router.init(n)}init(t){const n={...t};this._router.init(n)}setState(t,n){return this._router.setState(t,n)}getFile(t){const{data:n}=this.getState();return n.byId(t)||null}serialize(t){const{data:n}=this.getState();return n.serialize(t)}_updatePanels(t,n,s){const{data:a}=this.getState();t.forEach(i=>{const c=[];i.selected.forEach(p=>{a.byId(p)?c.push(p):!s&&n[p]&&c.push(n[p])}),i.selected=c,a.byId(i._lastSelected)||(i._lastSelected=s?null:n[i._lastSelected]||null);const u={};Object.keys(i._sorts).forEach(p=>{a.byId(p)?u[p]=i._sorts[p]:n[p]&&!s&&(u[n[p]]=i._sorts[p])}),i._sorts=u;const d=i._crumbs[i._crumbs.length-1];d?.id!=="/"&&(n[d.id]?i.path=n[d.id]:a.byId(d.id)||(i.path="/"))})}_isPlacedIntoSelf(t,n){return t.some(s=>s===n||this.getState().data.getParents(n).some(a=>a.id===s))}};function BM(e){switch(e){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[e==="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(t=>t!==null)}}function HM(e,t="data-id"){let n=e;for(!n.tagName&&e.target&&(n=e.target);n;){if(n.getAttribute&&n.getAttribute(t))return n;n=n.parentNode}return null}function WM(e,t="data-id"){const n=HM(e,t);return n?n.getAttribute(t):null}new Date().valueOf();function zM(e,t){const{api:n}=t;function s(i,c){const u=t.getPanel(),d=u.selected,p=c.ctrlKey||c.metaKey,h=c.shiftKey;let m;const g=d?.[0]?n.getFile(d[0]):null;d?.length?d.length>1?m=t.menuOptions("multiselect"):m=t.menuOptions(g.type,g):m=t.menuOptions("body");const w=`${p?"ctrl+":""}${h?"shift+":""}${i}`,v=m?m.find(k=>k.hotkey?.toLowerCase()===w):!1,y=t.performAction;if(v)switch(w){case"ctrl+c":y("copy");break;case"ctrl+x":y("move");break;case"ctrl+v":y("paste",g);break;case"delete":y("delete");break;case"ctrl+r":c.preventDefault(),y("rename",g);break;case"ctrl+d":c.preventDefault(),y("download",g);break;default:v.handler?.({context:g})}switch(i){case"enter":{if(p||h)break;const{_crumbs:k,_selectNavigation:N}=u;if(N){const C=_M(k);if(C){const A=am(C,k);n.exec("set-path",{id:C,selected:[A]})}}else if(d.length===1){const C=n.getFile(d[0]);C&&n.exec(C.type==="folder"?"set-path":"open-file",{id:C.id})}break}case"arrowup":case"arrowleft":{const{_files:k,_selected:N,path:C,_selectNavigation:A}=u;let E;if(N.length){const I=N.at(0).id,F=k.findIndex(M=>M.id===I);if(F!==-1){const M=F-1;k[M]?E=k[M].id:C!=="/"&&!(p||h)&&n.exec("select-file",{type:"navigation"})}}else{if(A)break;if(C!=="/"){n.exec("select-file",{type:"navigation"});break}E=k.at(0)?.id}E&&n.exec("select-file",{id:E,toggle:p,range:h});break}case"arrowdown":case"arrowright":{const{_files:k,_selected:N,path:C,_selectNavigation:A}=u;let E;if(N.length){const I=N.at(-1).id,F=k.findIndex(M=>M.id===I);if(F!==-1){const M=F+1;k[M]&&(E=k[M].id)}}else{if(C!=="/"&&!A){n.exec("select-file",{type:"navigation"});break}E=k.at(0)?.id}E&&n.exec("select-file",{id:E,toggle:p,range:h});break}}}function a(i){const c=i.code.replace("Key","").toLowerCase();s(c,i),c=="tab"&&setTimeout(()=>{const u=document.activeElement;u.className.indexOf("table")!=-1&&n.exec("set-active-panel",{panel:+WM(u,"data-panel")})})}return e.addEventListener("keydown",a),{destroy:()=>{e.removeEventListener("keydown",a)}}}function qM(e,t="data-id"){let n=e;for(!n.tagName&&e.target&&(n=e.target);n;){if(n.getAttribute&&n.getAttribute(t))return n;n=n.parentNode}return null}function UM(e,t="data-id"){const n=e.getAttribute(t);return n?VM(n):null}function VM(e){if(e.startsWith(":"))return e.substring(1);const t=e*1;return isNaN(t)?e:t}function GM(){return{detect:()=>!0,addEvent:function(e,t,n){return e.addEventListener(t,n),()=>e.removeEventListener(t,n)},addGlobalEvent:function(e,t){return document.addEventListener(e,t),()=>document.removeEventListener(e,t)},getTopNode:function(){return window.document.body}}}var KM=GM();new Date().valueOf();function Lv(e){const[t,n]=o.useState(e),s=o.useRef(e);return o.useEffect(()=>{if(s.current!==e){if(Array.isArray(s.current)&&Array.isArray(e)&&s.current.length===0&&e.length===0)return;s.current=e,n(e)}},[e]),[t,n]}function QM(e,t,n){const[s,a]=o.useState(()=>t);return e||console.warn(`Writable ${n} is not defined`),o.useEffect(()=>e?e.subscribe(c=>{a(()=>c)}):void 0,[e]),s}function dt(e,t){const n=e.getState(),s=e.getReactiveState();return QM(s[t],n[t],t)}function YM(e,t){const n=o.useRef(t);n.current=t;const[s,a]=o.useState(1);return o.useEffect(()=>e.subscribe(c=>{n.current=c,a(u=>u+1)}),[e]),[n.current,s]}function xr(e,t){const n=e.getState(),s=e.getReactiveState();return YM(s[t],n[t])}function _v(e){const t={};return e.split(";").forEach(n=>{const[s,a]=n.split(":");if(a){let i=s.trim();i.indexOf("-")&&(i=i.replace(/-([a-z])/g,(c,u)=>u.toUpperCase())),t[i]=a.trim()}}),t}function $v(e){let t=e,n=[];return{subscribe:u=>{n.push(u),u(t)},unsubscribe:u=>{n=n.filter(d=>d!==u)},set:u=>{t=u,n.forEach(d=>d(t))},update:u=>{t=u(t),n.forEach(d=>d(t))}}}function rg(e,t,n){function s(a){const i=qM(a);if(!i)return;const c=UM(i);if(typeof t=="function")return t(c,a);let u,d=a.target;for(;d!=i;){if(u=d.dataset?d.dataset.action:null,u&&t[u]){t[u](c,a);return}d=d.parentNode}t[n]&&t[n](c,a)}return KM.addEvent(e,n,s)}function XM(e,t){const n=[rg(e,t,"click")];return t.dblclick&&n.push(rg(e,t.dblclick,"dblclick")),()=>{n.forEach(s=>s())}}function Ov(e,t){return e.map((n,s)=>{const a=t(n,s);return n.data&&n.data.length&&(a.data=Ov(n.data,t)),a}).filter(Boolean)}function Bv(e,t){const n=[];return e.forEach(s=>{if(s.data){const a=Bv(s.data,t);a.length&&n.push({...s,data:a})}else t(s)&&n.push(s)}),n}function JM(e){return Ov(e,(t,n)=>{const s={...t,id:t.id||Xp()};return s.type&&(s.comp=s.type),s.comp==="separator"&&e[n-1]?.comp==="separator"?null:s})}const Hv={};function ZM(e){return Hv[e]||e}function eA(e,t){Hv[e]=t}function tA({onClick:e,onShow:t,option:n}){const s=o.useRef(null),a=o.useCallback(()=>{t(n.data?n.id:!1,s.current)},[t,n]),i=o.useCallback(u=>{if(n.data){u.stopPropagation(),t(n.id,s.current);return}e(u)},[e,t,n]),c=o.useMemo(()=>n&&n.comp?ZM(n.comp):null,[n]);return r.jsxs("div",{ref:s,className:`wx-cDCz9rZQ wx-option ${n.css||""} ${n.disabled?"wx-disabled":""}`,"data-id":mn(n.id),onMouseEnter:a,onClick:i,children:[n.icon?r.jsx("i",{className:`wx-cDCz9rZQ wx-icon ${n.icon}`}):null,n.comp?c?r.jsx(c,{item:n,option:n}):null:r.jsxs("span",{className:"wx-cDCz9rZQ wx-value",children:[" ",n.text," "]}),n.subtext?r.jsx("span",{className:"wx-cDCz9rZQ wx-subtext",children:n.subtext}):null,n.data?r.jsx("i",{className:"wx-cDCz9rZQ wx-sub-icon wxi-angle-right"}):null]})}function im({options:e,left:t=0,top:n=0,at:s="bottom",parent:a=null,mount:i=null,context:c=null,css:u="",onClick:d,onCancel:p}){const[h,m]=o.useState(-1e4),[g,w]=o.useState(-1e4),[v,y]=o.useState(20),[k,N]=o.useState(),C=o.useRef(null),[A,E]=o.useState(!1),[I,F]=o.useState(null),M=o.useCallback(()=>{const G=Cv(C.current,a,s,t,n);G&&(m(G.x),w(G.y),N(G.width));let U=G?.z??20;const ie=a?zk(a):[];let j=0;for(const re of ie){const de=parseInt(getComputedStyle(re).zIndex,10);de>j&&(j=de)}j>=U&&(U=j+1),y(U)},[a,s,t,n]);o.useEffect(()=>{i&&i(M)},[]);const H=o.useCallback(()=>{E(!1)},[]),V=o.useCallback((G,U)=>{E(G),F(U)},[]),P=o.useMemo(()=>JM(e),[e]);o.useEffect(()=>{M()},[a,M]);const D=o.useRef(d),O=o.useRef(p),X=o.useRef(a);return o.useEffect(()=>{D.current=d},[d]),o.useEffect(()=>{O.current=p},[p]),o.useEffect(()=>{X.current=a},[a]),o.useEffect(()=>{if(!C.current)return;function G(U){O.current?O.current(U):D.current&&D.current({action:null,option:null})}return ds(C.current,{callback:G,modal:!0,parent:()=>X.current}).destroy},[]),r.jsx("div",{ref:C,"data-wx-menu":"true",className:`wx-XMmAGqVx wx-menu ${u}`,style:{position:"absolute",top:g+"px",left:h+"px",width:k,zIndex:v},onMouseLeave:H,children:P.map(G=>r.jsxs(o.Fragment,{children:[G.comp==="separator"?r.jsx("div",{className:"wx-XMmAGqVx wx-separator"}):r.jsx(tA,{option:G,onShow:V,onClick:U=>{if(!G.data&&!U.defaultPrevented){const ie={context:c,action:G,option:G,event:U};G.handler&&G.handler(ie),d&&d(ie),U.stopPropagation()}}}),G.data&&A===G.id?r.jsx(im,{css:u,options:G.data,at:"right-overlap",parent:I,context:c,onClick:d,onCancel:p}):null]},G.id))})}const Wv=o.forwardRef(function(e,t){const{options:n,at:s="bottom",resolver:a=null,dataKey:i="contextId",filter:c=null,css:u="",children:d,onClick:p}=e,[h,m]=o.useState(null),[g,w]=o.useState(null),[v,y]=o.useState(0),[k,N]=o.useState(0),C=o.useRef(null),A=o.useMemo(()=>`data-${i.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}`,[i]),E=o.useMemo(()=>h!==null&&c?Bv(n,H=>c(H,h)):n,[h,c,n]);function I(H){w(null),p&&p(H)}function F(H){if(C.current===H){C.current=null;return}w(null),p&&p({action:null,option:null})}const M=o.useCallback((H,V)=>{if(!H){w(null);return}if(H.defaultPrevented)return;const P=H.target;if(P&&P.dataset&&P.dataset.menuIgnore)return;if(g&&g===P){w(null),H.preventDefault();return}y(H.clientX+1),N(H.clientY+1);let D=typeof V<"u"?V:uc(P,A);a&&(D=a(D,H),!D)||(m(D),w(P),C.current=H.nativeEvent||H,H.preventDefault())},[g,A,a]);return o.useImperativeHandle(t,()=>({show:M}),[M]),r.jsxs(r.Fragment,{children:[d?r.jsx("span",{onClick:M,"data-menu-ignore":"true",children:typeof d=="function"?d():d}):null,g?r.jsx(Zp,{children:r.jsx(im,{css:u,at:s,top:k,left:v,parent:g,context:h,onClick:I,onCancel:F,options:E},g)}):null]})}),nA=o.forwardRef(function(e,t){const{options:n,at:s="bottom",css:a="",children:i,onClick:c}=e,[u,d]=o.useState(null),p=o.useRef(null);function h(v){d(null),c&&c(v)}function m(v){if(p.current===v){p.current=null;return}d(null),c&&c({action:null,option:null})}const g=o.useCallback(v=>{d(v.target),p.current=v.nativeEvent||v,v.preventDefault()},[]);o.useImperativeHandle(t,()=>({show:g}),[g]);function w(v){let y=v.target;for(;!y.dataset.menuIgnore;)d(y),y=y.parentNode}return r.jsxs(r.Fragment,{children:[r.jsx("span",{onClick:w,"data-menu-ignore":"true",children:i}),u?r.jsx(Zp,{children:r.jsx(im,{css:a,at:s,parent:u,options:n,onClick:h,onCancel:m})}):null]})}),rA=o.forwardRef(function(e,t){const{options:n,at:s="bottom",resolver:a=null,dataKey:i="contextId",filter:c=null,css:u="",children:d,onClick:p}=e,h=o.useRef(null),m=o.useCallback((g,w)=>{h.current.show(g,w)},[]);return o.useImperativeHandle(t,()=>({show:m}),[m]),r.jsxs(r.Fragment,{children:[d?r.jsx("span",{onContextMenu:m,"data-menu-ignore":"true",children:d}):null,r.jsx(Wv,{css:u,at:s,options:n,resolver:a,dataKey:i,filter:c,ref:h,onClick:p})]})}),sA={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 aA=class{constructor(t,n,s,a,i){this.setFiles=t,this.setReady=n,this.setSignal=s,this.setDrag=a,i&&i.length&&this.setFiles(i)}open(t){this.setSignal(["click",t||{}])}getState(){let t="server";const n=this.files;for(let s=0;s<n.length;s++){if(n[s].status==="client")return"client";n[s].status==="error"&&(t="error")}return t}droparea(t,n){n=n||{};const s=()=>{n.dragEnter&&n.dragEnter(),this.setDrag(!0)},a=()=>{n.dragLeave&&n.dragLeave(),this.setDrag(!1)},i=u=>{u.preventDefault()},c=u=>{u.preventDefault(),this.setDrag(!1),this.setSignal(["drop",n,u]),n.dragLeave&&n.dragLeave(),n.drop&&n.drop()};return t.addEventListener("dragenter",s),t.addEventListener("dragleave",a),t.addEventListener("dragover",i,!0),t.addEventListener("drop",c,!0),()=>{t.removeEventListener("dragenter",s),t.removeEventListener("dragleave",a),t.removeEventListener("dragover",i,!0),t.removeEventListener("drop",c,!0)}}updateFile(t,n){const s=this.files.findIndex(i=>i.id===t);if(s===-1)return;const a=[...this.files];return a[s]={...a[s],...n},this.files=a,this.setFiles(this.files),this.files[s]}deleteFile(t){this.files=this.files.filter(n=>n.id!==t),this.setFiles(this.files)}addFile(t,n){n?this.files=[...this.files,t]:this.files=[t],this.setFiles(this.files)}deleteAll(){this.files=[],this.setFiles(this.files)}};function zv(e){const[t,n]=o.useState([]),[s,a]=o.useState(Promise.resolve(null)),[i,c]=o.useState(null),[u,d]=o.useState(!1),p=o.useRef();return p.current||(p.current=new aA(n,a,c,d,e)),p.current.files=t,p.current.ready=s,p.current.signal=i,p.current.drag=u,p.current}function iA(e,t){{if(e){const n=e.getGroup(t);if(n)return n}return fc(sA).getGroup(t)}}const oA=()=>Math.random().toString(36).substr(2,9),cA=({data:e,accept:t="",multiple:n=!0,folder:s=!1,uploadURL:a="",apiOnly:i=!1,disabled:c=!1,children:u,onChange:d,onUpload:p})=>{const h=o.useRef(null),m=o.useRef(null),[g,w]=o.useState({}),v=zv(),y=e||v,k=o.useContext(fn.i18n),N=iA(k,"uploader");o.useEffect(()=>{h.current&&s&&(h.current.webkitdirectory=!0)},[s]),o.useEffect(()=>{if(!i&&m.current&&!c)return y.droparea(m.current)},[i,c,m]);const C=P=>{const D=new FormData;return D.append("upload",P.file),fetch(a,{method:"POST",body:D}).then(O=>O.json()).then(O=>({id:P.id,...O}),()=>({id:P.id,status:"error"})).catch(O=>(console.log(O),{id:P.id,status:"error"}))},A=(P,D)=>{const O=y.updateFile(P,D),X={...O,status:y.getState()};O&&O.uploaded&&O.uploaded(X),p&&p(X),O.temp&&y.deleteFile(O.id)},E=P=>{if(!P)return;const D=typeof a=="function"?a(P):C(P);y.setReady(D.then(O=>{O.status=O.status||"server",A(P.id,O)}).catch(O=>{A(P.id,{status:"error",error:O})}))},I=(P,D)=>{const O={...D||g,id:oA(),status:"client",name:P.name,file:P};O.selected&&O.selected(O),d&&d(O),y.addFile(O,n),E(O),h.current&&(h.current.value="")},F=(P,D,O)=>{P.isFile?P.file(X=>{I(X,O)}):P.isDirectory&&P.createReader().readEntries(X=>{X.forEach(G=>{F(G,D+G.name+"/",O)})})},M=P=>{Array.from(P.target.files).forEach(D=>I(D))},H=(P,D)=>{Array.from(P.dataTransfer.items).forEach(O=>{const X=O.webkitGetAsEntry();X&&F(X,"",D)})},V=()=>{h.current&&h.current.click()};return o.useEffect(()=>{if(y.signal){const[P,D,O]=y.signal;w(D),P==="click"?V():P==="drop"&&H(O,D),y.setSignal(null)}},[y.signal]),i?r.jsxs(r.Fragment,{children:[r.jsx("input",{type:"file",className:"wx-at1A8tb8 wx-input",ref:h,onChange:M,accept:t,multiple:n,disabled:c}),u]}):r.jsxs("div",{className:`wx-at1A8tb8 wx-label ${y.drag?"wx-active":""} ${c?"wx-disabled":""}`,ref:m,children:[r.jsx("input",{type:"file",className:"wx-at1A8tb8 wx-input",ref:h,onChange:M,accept:t,multiple:n,disabled:c}),u||r.jsx("div",{className:"wx-at1A8tb8 wx-dropzone",children:r.jsxs("span",{children:[N("Drop files here or")," ",r.jsx("span",{className:"wx-at1A8tb8 wx-action",onClick:V,children:N("select files")})]})})]})};new Date().valueOf();function lA(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(const n in t){const s=e[n],a=t[n];if(!Ru(s,a))return!1}return!0}function Ru(e,t){if(typeof e=="number"||typeof e=="string"||typeof e=="boolean"||e===null)return e===t;if(typeof e!=typeof t||(e===null||t===null)&&e!==t||e instanceof Date&&t instanceof Date&&e.getTime()!==t.getTime())return!1;if(typeof e=="object")if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let n=e.length-1;n>=0;n--)if(!Ru(e[n],t[n]))return!1;return!0}else return lA(e,t);return e===t}function Tp(e){if(typeof e!="object"||e===null)return e;if(e instanceof Date)return new Date(e);if(e instanceof Array)return e.map(Tp);const t={};for(const n in e)t[n]=Tp(e[n]);return t}var qv=2,uA=class{constructor(e){e&&(this._writable=e.writable,this._async=e.async),this._values={},this._state={}}setState(e,t=0){const n={};return this._wrapProperties(e,this._state,this._values,"",n,t),n}getState(){return this._values}getReactive(){return this._state}_wrapProperties(e,t,n,s,a,i){for(const c in e){const u=t[c],d=n[c],p=e[c];if(u&&(d===p&&typeof p!="object"||p instanceof Date&&d instanceof Date&&d.getTime()===p.getTime()))continue;const h=s+(s?".":"")+c;u?(u.__parse(p,h,a,i)&&(n[c]=p),i&qv?a[h]=u.__trigger:u.__trigger()):(p&&p.__reactive?t[c]=this._wrapNested(p,p,h,a):t[c]=this._wrapWritable(p),n[c]=p),a[h]=a[h]||null}}_wrapNested(e,t,n,s){const a=this._wrapWritable(e);return this._wrapProperties(e,a,t,n,s,0),a.__parse=(i,c,u,d)=>(this._wrapProperties(i,a,t,c,u,d),!1),a}_wrapWritable(e){const t=[],n=function(){for(let s=0;s<t.length;s++)t[s](e)};return{subscribe:s=>(t.push(s),this._async?setTimeout(s,1,e):s(e),()=>{const a=t.indexOf(s);a>=0&&t.splice(a,1)}),__trigger:()=>{t.length&&(this._async?setTimeout(n,1):n())},__parse:function(s){return e=s,!0}}}},dA=class{constructor(e,t,n,s){typeof e=="function"?this._setter=e:this._setter=e.setState.bind(e),this._routes=t,this._parsers=n,this._prev={},this._triggers=new Map,this._sources=new Map,this._routes.forEach(a=>{a.in.forEach(i=>{const c=this._triggers.get(i)||[];c.push(a),this._triggers.set(i,c)}),a.out.forEach(i=>{const c=this._sources.get(i)||{};a.in.forEach(u=>c[u]=!0),this._sources.set(i,c)})}),this._routes.forEach(a=>{a.length=Math.max(...a.in.map(i=>Uv(i,this._sources,1)))}),this._bus=s}init(e){const t={};for(const n in e)if(this._prev[n]!==e[n]){const s=this._parsers[n];t[n]=s?s(e[n]):e[n]}this._prev=this._prev?{...this._prev,...e}:{...e},this.setState(t),this._bus&&this._bus.exec("init-state",t)}setStateAsync(e){const t=this._setter(e,qv);return this._async?Object.assign(this._async.signals,t):this._async={signals:t,timer:setTimeout(this._applyState.bind(this),1)},t}_applyState(){const e=this._async;if(e){this._async=null,this._triggerUpdates(e.signals,[]);for(const t in e.signals){const n=e.signals[t];n&&n()}}}setState(e,t=[]){const n=this._setter(e);return this._triggerUpdates(n,t),n}_triggerUpdates(e,t){const n=Object.keys(e),s=!t.length;t=t||[];for(let a=0;a<n.length;a++){const i=n[a],c=this._triggers.get(i);c&&c.forEach(u=>{t.indexOf(u)==-1&&t.push(u)})}s&&this._execNext(t)}_execNext(e){for(;e.length;){e.sort((n,s)=>n.length<s.length?1:-1);const t=e[e.length-1];e.splice(e.length-1),t.exec(e)}}};function Uv(e,t,n){const s=t.get(e);if(!s)return n;const a=Object.keys(s).map(i=>Uv(i,t,n+1));return Math.max(...a)}var pA=class{constructor(){this._nextHandler=null,this._handlers={},this._tag=new WeakMap,this.exec=this.exec.bind(this)}on(e,t,n){let s=this._handlers[e];s?n&&n.intercept?s.unshift(t):s.push(t):s=this._handlers[e]=[t],n&&n.tag&&this._tag.set(t,n.tag)}intercept(e,t,n){this.on(e,t,{...n,intercept:!0})}detach(e){for(const t in this._handlers){const n=this._handlers[t];for(let s=n.length-1;s>=0;s--)this._tag.get(n[s])===e&&n.splice(s,1)}}async exec(e,t){const n=this._handlers[e];if(n)for(let s=0;s<n.length;s++){const a=n[s](t);if(a===!1||a&&a.then&&await a===!1)return}return this._nextHandler&&await this._nextHandler.exec(e,t),t}setNext(e){return this._nextHandler=e}};function mA(e){return t=>t[e]}function hA(e){return(t,n)=>t[e]=n}function aa(e,t){return(t.getter||mA(t.id))(e)}function Od(e,t,n){return(t.setter||hA(t.id))(e,n)}function fA(e,t){const n=document.createElement("a");n.href=URL.createObjectURL(e),n.download=t,document.body.appendChild(n),n.click(),document.body.removeChild(n)}function ea(e,t){let n=aa(e,t)??"";return t.template?n=t.template(n,e,t):t.optionsMap&&(Array.isArray(n)?n=n.map(s=>t.optionsMap.get(s)).join(", "):n=t.optionsMap.get(n)),typeof n>"u"?"":n+""}function gA(e,t){const n=/\n|"|;|,/;let s="";const a=t.rows||`
166
+ `,i=t.cols||" ",c=e._columns,u=e.flatData;t.header!==!1&&c[0].header&&(s=sg("header",c,s,i,a));for(let d=0;d<u.length;d++){const p=[];for(let h=0;h<c.length;h++){let m=ea(u[d],c[h]);n.test(m)&&(m='"'+m.replace(/"/g,'""')+'"'),p.push(m)}s+=(s?a:"")+p.join(i)}return t.footer!==!1&&c[0].footer&&(s=sg("footer",c,s,i,a)),s}function sg(e,t,n,s,a){const i=/\n|"|;|,/;for(let c=0;c<t[0][e].length;c++){const u=[];for(let d=0;d<t.length;d++){let p=(t[d][e][c].text||"")+"";i.test(p)&&(p='"'+p.replace(/"/g,'""')+'"'),u.push(p)}n+=(n?a:"")+u.join(s)}return n}const bA="portrait",vA=100,wA="a4",yA={a3:{width:11.7,height:16.5},a4:{width:8.27,height:11.7},letter:{width:8.5,height:11}};function xA(e,t){const n=[];let s=[],a=0;const i=e.filter(u=>!u.hidden),c=SA(t);return i.forEach((u,d)=>{a+u.width<=c?(a+=u.width,s.push(u)):(s.length&&n.push(s),s=[u],a=u.width),d===i.length-1&&s.length&&n.push(s)}),n}function ag(e,t,n){const s=[];return e.forEach((a,i)=>{const c=a[t];for(let u=0;u<n.length;u++){s[u]||(s[u]=[]);const d={...c[u]};if(s[u][i]!==null){if(!i&&!d.rowspan&&!d.colspan){let p=1,h=e[i+p][t][u],m=d.width;for(;!h.rowspan&&!h.colspan;)p++,h=e[i+p][t][u],m+=h.width;d.colspan=p,d.width=m,d.height=n[u]}if(s[u].push(d),!d.collapsed&&d.colspan>1){let p=d.colspan-1;if(d.colspan+i>e.length){const h=d.colspan-(d.colspan+i-e.length);d.colspan=h,d.width=e.slice(i,i+p+1).reduce((m,g)=>m+g.width,0),h>1&&(p=h-1)}for(let h=0;h<p;h++)s[u].push(null)}if(d.rowspan>1){const p=d.rowspan;for(let h=1;h<p;h++)s[u+h]||(s[u+h]=[]),s[u+h].push(null)}}}if(a.collapsed)for(let u=0;u<s.length;u++){const d=s[u],p=d[i];if(p&&p.collapsed){if(d[i]=null,!u)break}else{const h=p||d.findLast(m=>m?.colspan>=1);h&&(h.colspan=h.colspan-1,h.width=h.width-a.width)}}}),s.map(a=>a.filter(i=>i&&i.colspan!==0))}function SA(e){const{mode:t,ppi:n,paper:s}=e,{width:a,height:i}=yA[s];return CA(t==="portrait"?a:i,n)}function CA(e,t){return e*t}function kA(e={}){const{mode:t,ppi:n,paper:s}=e;return{mode:t||bA,ppi:n||vA,paper:s||wA}}function Vv(e,t){return e.flexgrow?`min-width:${t}px;width:auto`:`width:${e.width}px; max-width:${e.width}px; height:${e.height}px`}function MA(e,t,n){let s=e[n.id];if(n.filter.type==="richselect"&&s){const a=n.filter.config?.options||t.find(({id:i})=>i==n.id).options;a&&(s=a.find(({id:i})=>i==s).label)}return s??""}const ig=["resize-column","hide-column","update-cell"],AA=["delete-row","update-row","update-cell"],NA=["move-item"],RA=["resize-column","move-item"];class TA{undo=[];redo=[];progress={};in;getState;setState;_previousValues={};constructor(t,n,s){this.in=t,this.getState=n,this.setState=s,this.setHandlers(),this.resetStateHistory()}getHandlers(){return{"add-row":{handler:t=>({action:"delete-row",data:{id:t.id},source:{action:"add-row",data:t}})},"delete-row":{handler:t=>{const{id:n}=t,{data:s}=this.getPrev(),a=s.findIndex(i=>i.id===n);return{action:"add-row",data:{id:n,row:s[a],before:a<s.length-1?s[a+1].id:void 0},source:{action:"delete-row",data:t}}}},"update-cell":{handler:t=>{const{id:n,column:s}=t,a=this.getRow(n),i=this.getColumn(s),c=aa(a,i);return Ru(c,t.value)?null:{action:"update-cell",data:{id:n,column:s,value:c},source:{action:"update-cell",data:t}}}},"update-row":{handler:t=>{const{id:n,row:s}=t,a=this.getRow(n);for(const i in s)Object.keys(a).includes(i)||(a[i]=void 0);return{action:"update-row",data:{id:n,row:a},source:{action:"update-row",data:t}}}},"copy-row":{handler:t=>{const{id:n}=t,{data:s}=this.getState(),a=s.findIndex(c=>c.id===n),i=s[a];return{action:"delete-row",data:{id:n},source:{action:"add-row",data:{id:n,row:i,before:a<s.length-1?s[a+1].id:void 0}}}}},"resize-column":{handler:t=>{const{id:n,width:s}=t,a=this.getColumn(n),{_sizes:i}=this.getState();return{action:"resize-column",data:{id:n,width:a.width??i.columnWidth},source:{action:"resize-column",data:{id:n,width:s}}}}},"hide-column":{handler:t=>{const{id:n}=t,s=this.getColumn(n);return{action:"hide-column",data:{id:n,mode:s.hidden},source:{action:"hide-column",data:t}}}},"collapse-column":{handler:t=>{const{id:n,row:s,mode:a}=t;return{action:"collapse-column",data:{id:n,row:s,mode:typeof a=="boolean"?!a:a},source:{action:"collapse-column",data:t}}}},"move-item":{handler:t=>{const{id:n,target:s,mode:a}=t,{flatData:i}=this.getPrev(),c=i.findIndex(u=>u.id===n);return{action:"move-item",data:{id:n,target:i[c+(c?-1:1)].id,mode:c?"after":"before"},source:{action:"move-item",data:{id:n,target:s,mode:a}}}}},"open-row":{handler:t=>{const{id:n,nested:s}=t;return{action:"close-row",data:{id:n,nested:s},source:{action:"open-row",data:t}}}},"close-row":{handler:t=>{const{id:n,nested:s}=t;return{action:"open-row",data:{id:n,nested:s},source:{action:"close-row",data:t}}}}}}resetHistory(){this.undo=[],this.redo=[],this.progress={},this.resetStateHistory()}getPrev(){return this._previousValues}setHandlers(){const t=this.getHandlers();for(const n in t)this.in.intercept(n,s=>{if(!(s.eventSource==="undo"||s.eventSource==="redo"||s.skipUndo)){if(RA.includes(n)){(s.inProgress&&!this.progress[n]||typeof s.inProgress!="boolean")&&(NA.includes(n)&&this.setPrev("flatData"),ig.includes(n)&&this.setPrev("columns")),this.progress[n]=s.inProgress;return}AA.includes(n)&&this.setPrev("data"),ig.includes(n)&&this.setPrev("columns")}}),this.in.on(n,s=>{if(s.eventSource==="undo"||s.eventSource==="redo"||s.skipUndo||s.inProgress)return;const a=t[n].handler(s);a&&this.addToHistory(a)})}setPrev(t){this._previousValues[t]=Tp(this.getState()[t])}addToHistory(t){this.undo.push(t),this.redo=[],this.setStateHistory()}handleUndo(){if(!this.undo.length)return;const t=this.undo.pop();this.redo.push({...t.source,source:t}),this.in.exec(t.action,{...t.data,eventSource:"undo"}),this.setStateHistory()}handleRedo(){if(!this.redo.length)return;const t=this.redo.pop();this.undo.push({...t.source,source:t}),this.in.exec(t.action,{...t.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(t){const{data:n}=this.getPrev();return this.getState().tree?this.getTreeRow(n,t):n.find(s=>s.id===t)}getTreeRow(t,n){for(let s=0;s<t.length;s++){if(t[s].id===n)return t[s];if(t[s].data){const a=this.getTreeRow(t[s].data,n);if(a)return a}}return null}getColumn(t){const{columns:n}=this.getPrev();return n.find(s=>s.id===t)}}function Gv(e,t){return typeof e>"u"||e===null?-1:typeof t>"u"||t===null?1:e===t?0:e>t?1:-1}function PA(e,t){return-Gv(e,t)}function IA(e,t){if(typeof t.sort=="function")return function(s,a){const i=t.sort(s,a);return e==="asc"?i:-i};const n=e==="asc"?Gv:PA;return function(s,a){return n(aa(s,t),aa(a,t))}}function jA(e,t){if(!e||!e.length)return;const n=e.map(s=>{const a=t.find(i=>i.id==s.key);return IA(s.order,a)});return e.length===1?n[0]:function(s,a){for(let i=0;i<n.length;i++){const c=n[i](s,a);if(c!==0)return c}return 0}}const Dl=28,EA=20;function FA(){if(typeof document>"u")return"willow";const e=document.querySelector('[class^="wx"][class$="theme"]');return e?e.className.substring(3,e.className.length-6):"willow"}function du(e,t,n,s,a){const i=document.createElement("div"),c=document.createElement("div"),u=document.body;a=a?`${a}px`:"auto";let d,p;c.className=t,i.classList.add(`wx-${n}-theme`),i.style.cssText=`height:auto;position:absolute;top:0px;left:100px;overflow:hidden;width=${a};white-space:nowrap;`,i.appendChild(c),u.appendChild(i),typeof e!="object"&&(e=[e]);for(let h=0;h<e.length;h++){c.innerText=e[h]+"";const m=i.getBoundingClientRect(),g=Math.ceil(m.width)+(s&&s.length?s[h]:0),w=Math.ceil(m.height);d=Math.max(d||0,g),p=Math.max(p||0,w)}return i.remove(),{width:d,height:p}}function og(e,t,n,s,a){const i=[];for(let c=0;c<e.length;c++){const u=e[c][t],d=u.length;for(let p=0;p<d;p++){const{text:h,vertical:m,collapsed:g,rowspan:w,css:v}=u[p];if(!h){i[p]=Math.max(i[p]||0,s);continue}let y=0;if(m&&!g){let k=`wx-measure-cell-${t}`;if(k+=v?` ${v}`:"",y=du(h,k,a).width,(w>1||!u[p+1])&&n>p+1){const N=w||n-p,C=i.slice(p,p+N).reduce((A,E)=>A+E,0);if(C<y){const A=Math.ceil((y-C)/N);for(let E=p;E<p+N;E++)i[E]=(i[E]||s)+A}continue}}i[p]=Math.max(i[p]||s,y)}}return i}function DA(e,t,n){const s=[],a=[];let i="wx-measure-cell-body";i+=e.css?` ${e.css}`:"";for(let c=0;c<t.length;c++){const u=t[c],d=ea(u,e);d&&(s.push(d),e.treetoggle?a.push(t[c].$level*Dl+(t[c].$count?Dl:0)+(e.draggable?Dl:0)):e.draggable&&a.push(Dl))}return du(s,i,n,a).width}function LA(e,t){const n="wx-measure-cell-header",s=e.sort?EA:0;let a=e.header;if(typeof a=="string")return du(a,n,t).width+s;let i;Array.isArray(a)||(a=[a]);for(let c=0;c<a.length;c++){const u=a[c],d=typeof u=="string"?u:u.text,p=n+(typeof u=="string"?"":` ${u.css}`);let h=du(d,p,t).width;c===a.length-1&&(h+=s),i=Math.max(i||0,h)}return i}const _A={text:(e,t)=>e?e.toString().toLowerCase().indexOf(t.toLowerCase())!==-1:!t,richselect:(e,t)=>typeof t!="number"&&!t?!0:e==t,datepicker:(e,t)=>t?e&&OA(e,t):!0,multiselect:(e,t)=>!t||t?.length===0?!0:Array.isArray(e)?e?.some(n=>t.includes(n)):e&&t.includes(e)};function Kv(e){return _A[e]}function $A(e,t){const n=[];for(const s in e){const a=t.find(d=>d.id==s),{config:i,type:c}=a.header.find(d=>d.filter).filter,u=e[s];n.push(d=>{const p=aa(d,a);return i?.handler?i.handler(p,u):Kv(c)(p,u)})}return s=>{for(let a=0;a<n.length;a++)if(!n[a](s))return!1;return!0}}function OA(e,t){return e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate()}let BA=class extends uA{in;_router;_branches;_xlsxWorker;_historyManager;constructor(t){super({writable:t,async:!1});const n={rowHeight:37,columnWidth:160,headerHeight:36,footerHeight:36};this._router=new dA(super.setState.bind(this),[{in:["columns","sizes","_skin"],out:["_columns","_sizes"],exec:a=>{const{columns:i,sizes:c,_skin:u}=this.getState(),d=this.copyColumns(i),p=d.reduce((g,w)=>Math.max(w.header.length,g),0),h=d.reduce((g,w)=>Math.max(w.footer.length,g),0);d.forEach(this.setCollapsibleColumns);const m=this.normalizeSizes(d,c,p,h,u);for(let g=0;g<d.length;g++)this.normalizeColumns(d,g,"header",p,m),this.normalizeColumns(d,g,"footer",h,m);this.setState({_columns:d,_sizes:m},a)}},{in:["data","tree","_filterIds"],out:["flatData","_rowHeightFromData"],exec:a=>{const{data:i,tree:c,dynamic:u,_filterIds:d}=this.getState(),p=d&&new Set(d),h=c?this.flattenRows(i,[],d):p?i.filter(g=>p.has(g.id)):i,m=!u&&h.some(g=>g.rowHeight);this.setState({flatData:h,_rowHeightFromData:m},a)}}],{sizes:a=>({...n,...a})});const s=this.in=new pA;s.on("close-editor",({ignore:a})=>{const{editor:i}=this.getState();i&&(a||s.exec("update-cell",i),this.setState({editor:null}))}),s.on("open-editor",({id:a,column:i})=>{let c=this.getState().editor;c&&s.exec("close-editor",{});const u=this.getRow(a),d=i?this.getColumn(i):this.getNextEditor(u);if(d?.editor){let p=d.editor;if(typeof p=="function"&&(p=p(u,d)),!p)return;c={column:d.id,id:a,value:aa(u,d)??"",renderedValue:ea(u,d),type:p.type||p},typeof p=="object"&&p.config&&(c.config=p.config,p.config.options&&(c.options=p.config.options)),d.options&&!c.options&&(c.options=d.options),this.setState({editor:c})}}),s.on("editor",({value:a})=>{let i=this.getState().editor;if(i){i={...i},i.value=a;const c=this.getColumn(i.column),u={...this.getRow(i.id)};Od(u,c,a),i.renderedValue=ea(u,c),this.setState({editor:i})}}),s.on("add-row",a=>{const i=this.getState();let{data:c}=i;const{select:u,_filterIds:d}=i,{row:p,before:h,after:m,select:g}=a;if(a.id=p.id=a.id||p.id||Ll(),h||m){const v=h||m,y=c.findIndex(k=>k.id===v);c=[...c],c.splice(y+(m?1:0),0,a.row)}else c=[...c,a.row];const w={data:c};d&&(w._filterIds=[...d,a.id]),this.setState(w),!(typeof g=="boolean"&&!g)&&(g||u)&&s.exec("select-row",{id:p.id,show:!0})}),s.on("delete-row",a=>{const{data:i,selectedRows:c,focusCell:u,editor:d}=this.getState(),{id:p}=a,h={data:i.filter(m=>m.id!==p)};this.isSelected(p)&&(h.selectedRows=c.filter(m=>m!==p)),d?.id===p&&(h.editor=null),this.setState(h),u?.row===p&&this.in.exec("focus-cell",{eventSource:"delete-row"})}),s.on("update-cell",a=>{const i=this.getState();let{data:c}=i;c=[...c];const{tree:u}=i,{id:d,column:p,value:h}=a,m=this.getColumn(p);if(u){const g={...this._branches[d]};Od(g,m,h);const w=this.updateTreeRow(g);g.$parent===0&&(c=w)}else{const g=c.findIndex(v=>v.id===d),w={...c[g]};Od(w,m,h),c[g]=w}this.setState({data:c})}),s.on("update-row",a=>{let{data:i}=this.getState();const{id:c,row:u}=a,d=i.findIndex(p=>p.id===c);i=[...i],i[d]={...i[d],...u},this.setState({data:i})}),s.on("select-row",({id:a,toggle:i,range:c,mode:u,show:d,column:p})=>{const h=this.getState(),{focusCell:m}=h;let{selectedRows:g}=h;if(g.length||(c=i=!1),c){const{data:w}=this.getState();let v=w.findIndex(k=>k.id===g[g.length-1]),y=w.findIndex(k=>k.id===a);v>y&&([v,y]=[y,v]),w.slice(v,y+1).forEach(k=>{this.isSelected(k.id)||g.push(k.id)})}else if(i&&this.isSelected(a)){if(u===!0)return;g=g.filter(w=>w!==a)}else if(i){if(u===!1)return;g.push(a)}else g=[a];this.setState({selectedRows:[...g]}),m?.row!==a&&this.in.exec("focus-cell",{eventSource:"select-row"}),d&&this.in.exec("scroll",{row:a,column:p})}),this.in.on("focus-cell",a=>{const{row:i,column:c,eventSource:u}=a,{_columns:d,split:p}=this.getState();i&&c?(this.setState({focusCell:{row:i,column:c}}),u!=="click"&&((!p.left||d.findIndex(h=>h.id===a.column)>=p.left)&&(!p.right||d.findIndex(h=>h.id===a.column)<d.length-p.right)?this.in.exec("scroll",{row:i,column:c}):this.in.exec("scroll",{row:i}))):this.setState({focusCell:null})}),s.on("resize-column",a=>{const{id:i,auto:c,maxRows:u,inProgress:d}=a;if(d===!1)return;let p=a.width||0;const h=[...this.getState().columns],m=this.getColumn(i);if(c){if(c==="data"||c===!0){const{flatData:g,_skin:w}=this.getState();let v=g.length;u&&(v=Math.min(u,v));const y=g.slice(0,v);p=DA(m,y,w)}if(c==="header"||c===!0){const{_skin:g}=this.getState();p=Math.max(LA(m,g),p)}}m.width=Math.max(17,p),delete m.flexgrow,this.setState({columns:h})}),s.on("hide-column",a=>{const{id:i,mode:c}=a,u=[...this.getState().columns],d=this.getColumn(i),p=u.reduce((h,m)=>h+(m.hidden?0:1),0);!c||p>1?(d.hidden=!d.hidden,this.setState({columns:u})):a.skipUndo=!0}),s.on("sort-rows",a=>{const{key:i,add:c,sort:u}=a,d=this.getState(),{columns:p,data:h,tree:m}=d;if(u){const C=[...h];C.sort(u),this.setState({data:C});return}const{order:g="asc"}=a;let w=d.sortMarks;const v=Object.keys(w),y=v.length;!c||!y||y===1&&w[i]?w={[i]:{order:g}}:(y===1&&(w[v[0]]={...w[v[0]],index:0}),w={...w,[i]:{order:g,index:typeof c=="number"?c:w[i]?.index??y}});const k=Object.keys(w).sort((C,A)=>w[C].index-w[A].index).map(C=>({key:C,order:w[C].order}));this.setState({sortMarks:w});const N=jA(k,p);if(N){const C=[...h];m?this.sortTree(C,N):C.sort(N),this.setState({data:C})}}),s.on("filter-rows",a=>{const{value:i,key:c,filter:u}=a;if(!Object.keys(a).length){this.setState({filterValues:{},_filterIds:null});return}const d=this.getState(),{data:p,tree:h,_columns:m}=d;let g=d.filterValues;const w={};c&&(g={...g,[c]:i},w.filterValues=g);const v=u??$A(g,m);let y=[];h?y=this.filterTree(p,v,y):p.forEach(k=>{v(k)&&y.push(k.id)}),w._filterIds=y,this.setState(w)}),s.on("collapse-column",a=>{const{id:i,row:c,mode:u}=a,d=[...this.getState().columns],p=this.getColumn(i).header,h=Array.isArray(p)?p[c]:p;typeof h=="object"&&(h.collapsed=u??!h.collapsed,this.setState({columns:d}))}),s.on("move-item",a=>{const{id:i,inProgress:c}=a;let{target:u,mode:d="after"}=a;const{data:p,flatData:h,tree:m}=this.getState(),g=h.findIndex(y=>y.id===i);let w;if(d==="up"||d==="down"){if(d==="up"){if(g===0)return;w=g-1,d="before"}else if(d==="down"){if(g===h.length-1)return;w=g+1,d="after"}u=h[w]&&h[w].id}else w=h.findIndex(y=>y.id===u);if(g===-1||w===-1||c===!1)return;let v;m||(v=this.moveItem(i,u,p,d)),this.setState({data:m?this.normalizeTreeRows(v):v})}),s.on("copy-row",a=>{const{id:i,target:c,mode:u="after"}=a,d=this.getState(),{flatData:p,_filterIds:h}=d;let{data:m}=d;const g=this.getRow(i);if(!g)return;const w={...g,id:Ll()};a.id=w.id;const v=p.findIndex(k=>k.id===c);if(v===-1)return;m.splice(v+(u==="after"?1:0),0,w),m=[...m];const y={data:m};h&&(y._filterIds=[...h,w.id]),this.setState(y)}),s.on("open-row",a=>{const{id:i,nested:c}=a;this.toggleBranch(i,!0,c)}),s.on("close-row",a=>{const{id:i,nested:c}=a;this.toggleBranch(i,!1,c)}),s.on("export-data",a=>new Promise((i,c)=>{const u=a.format||"csv",d=`${a.fileName||"data"}.${u}`;if(u==="csv"){const p=gA(this.getState(),a.csv||{});a.download!==!1?fA(new Blob(["\uFEFF"+p],{type:"text/csv"}),d):a.result=p,i(!0)}else c()})),s.on("hotkey",({key:a,event:i,isInput:c})=>{switch(a){case"arrowup":{const{flatData:u,focusCell:d,select:p}=this.getState();if(i.preventDefault(),c)return;const h=d?d.column:this._getFirstVisibleColumn()?.id,m=d?this.getPrevRow(d.row)?.id:u[u.length-1]?.id;h&&m&&(this.in.exec("focus-cell",{row:m,column:h,eventSource:"key"}),p&&this.in.exec("select-row",{id:m}));break}case"arrowdown":{const{flatData:u,focusCell:d,select:p}=this.getState();if(i.preventDefault(),c)return;const h=d?d.column:this._getFirstVisibleColumn()?.id,m=d?this.getNextRow(d.row)?.id:u[0]?.id;h&&m&&(this.in.exec("focus-cell",{row:m,column:h,eventSource:"key"}),p&&this.in.exec("select-row",{id:m}));break}case"arrowright":{const{focusCell:u}=this.getState();if(c)return;if(i.preventDefault(),u){const d=this.getNextColumn(u.column,!0)?.id;d&&this.in.exec("focus-cell",{row:u.row,column:d,eventSource:"key"})}break}case"arrowleft":{const{focusCell:u}=this.getState();if(c)return;if(i.preventDefault(),u){const d=this.getPrevColumn(u.column,!0)?.id;d&&this.in.exec("focus-cell",{row:u.row,column:d,eventSource:"key"})}break}case"tab":{const{editor:u,focusCell:d,select:p}=this.getState();if(u){i.preventDefault();const h=u.column;let m=u.id,g=this.getNextEditor(this.getRow(m),this.getColumn(h));if(!g){const w=this.getNextRow(m);w&&(m=w.id,g=this.getNextEditor(w))}g&&(this.in.exec("open-editor",{id:m,column:g.id}),this.in.exec("focus-cell",{row:m,column:g.id,eventSource:"key"}),p&&!this.isSelected(m)&&this.in.exec("select-row",{id:m}))}else d&&this.in.exec("focus-cell",{eventSource:"key"});break}case"shift+tab":{const{editor:u,focusCell:d,select:p}=this.getState();if(u){i.preventDefault();const h=u.column;let m=u.id,g=this.getPrevEditor(this.getRow(m),this.getColumn(h));if(!g){const w=this.getPrevRow(m);w&&(m=w.id,g=this.getPrevEditor(w))}g&&(this.in.exec("open-editor",{id:m,column:g.id}),this.in.exec("focus-cell",{row:m,column:g.id,eventSource:"key"}),p&&!this.isSelected(m)&&this.in.exec("select-row",{id:m}))}else d&&this.in.exec("focus-cell",{eventSource:"key"});break}case"escape":{const{editor:u}=this.getState();u&&(this.in.exec("close-editor",{ignore:u.type!="multiselect"}),this.in.exec("focus-cell",{row:u.id,column:u.column,eventSource:"key"}));break}case"f2":{const{editor:u,focusCell:d}=this.getState();!u&&d&&this.in.exec("open-editor",{id:d.row,column:d.column});break}case"enter":{const{focusCell:u,tree:d}=this.getState();if(!c&&d&&u&&this.getColumn(u.column).treetoggle){const p=this.getRow(u.row);if(!p.data)return;this.in.exec(p.open?"close-row":"open-row",{id:u.row,nested:!0})}break}case"home":{const{editor:u,focusCell:d}=this.getState();if(!u&&d){i.preventDefault();const p=this._getFirstVisibleColumn()?.id;this.in.exec("focus-cell",{row:d.row,column:p,eventSource:"key"})}break}case"ctrl+home":{const{editor:u,focusCell:d,flatData:p,select:h}=this.getState();if(!u&&d){i.preventDefault();const m=p[0]?.id,g=this._getFirstVisibleColumn()?.id;m&&g&&(this.in.exec("focus-cell",{row:m,column:g,eventSource:"key"}),h&&!this.isSelected(m)&&this.in.exec("select-row",{id:m}))}break}case"end":{const{editor:u,focusCell:d}=this.getState();if(!u&&d){i.preventDefault();const p=this._getLastVisibleColumn()?.id,h=d.row;this.in.exec("focus-cell",{row:h,column:p,eventSource:"key"})}break}case"ctrl+end":{const{editor:u,focusCell:d,flatData:p,select:h}=this.getState();if(!u&&d){i.preventDefault();const m=p.at(-1).id,g=this._getLastVisibleColumn()?.id;m&&g&&(this.in.exec("focus-cell",{row:m,column:g,eventSource:"key"}),h&&!this.isSelected(m)&&this.in.exec("select-row",{id:m}))}break}case"ctrl+z":{this.in.exec("undo",{});break}case"ctrl+y":{this.in.exec("redo",{});break}}}),s.on("scroll",a=>{const{_columns:i,split:c,_sizes:u,flatData:d,dynamic:p,_rowHeightFromData:h}=this.getState();let m=-1,g=-1,w=0,v=0;if(a.column){m=0;const y=i.findIndex(k=>k.id===a.column);w=i[y].width;for(let k=c.left??0;k<y;k++){const N=i[k];N.hidden||(m+=N.width)}}if(a.row&&!p){const y=d.findIndex(k=>k.id===a.row);y>=0&&(h?(g=d.slice(0,y).reduce((k,N)=>k+(N.rowHeight||u.rowHeight),0),v=d[y].rowHeight):g=u.rowHeight*y)}this.setState({scroll:{top:g,left:m,width:w,height:v||u.rowHeight}})}),s.on("scroll-to",a=>{const i={};a.top!==void 0&&(i.scrollTop=a.top),a.left!==void 0&&(i.scrollLeft=a.left),Object.keys(i).length&&this.setState(i)}),s.on("print",a=>{const i=kA(a);this.setState({_print:i}),this.setStateAsync({_print:null})}),s.on("undo",()=>{this._historyManager?.handleUndo()}),s.on("redo",()=>{this._historyManager?.handleRedo()}),this.initOnce()}getXlsxWorker(t){if(!this._xlsxWorker){const n=window.URL.createObjectURL(new Blob([`importScripts('${t}');`],{type:"text/javascript"}));this._xlsxWorker=new Promise(s=>{const a=new Worker(n);a.addEventListener("message",i=>{i.data.type==="init"&&s(a)})})}return this._xlsxWorker}initOnce(){const t={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(t)}init(t){t.hasOwnProperty("_skin")&&!t._skin&&(t._skin=FA()),t.columns&&t.columns.forEach(n=>{n.options&&(n.optionsMap=new Map(n.options.map(s=>[s.id,s.label])))}),Ru(this.getState().data,t.data)||(t.tree?t.data=this.normalizeTreeRows(t.data):t.data=this.normalizeRows(t.data),this.setState({_filterIds:null,filterValues:{},sortMarks:{},search:null}),this._historyManager&&this._historyManager.resetHistory()),t.tree&&(t.undo=!1,t.reorder=!1),t.split?.right&&(t.split.right=0),t.undo&&!this._historyManager&&(this._historyManager=new TA(this.in,this.getState.bind(this),this.setState.bind(this))),this._router.init({...t})}setState(t,n){return this._router.setState(t,n)}setStateAsync(t){this._router.setStateAsync(t)}getRow(t){const{tree:n}=this.getState();return n?this._branches[t]:this.getState().data.find(s=>s.id===t)}getRowIndex(t,n){return n||(n=this.getState().flatData),n.findIndex(s=>s.id===t)}getNextRow(t){const n=this.getState().flatData,s=this.getRowIndex(t,n);return n[s+1]}getPrevRow(t){const n=this.getState().flatData,s=this.getRowIndex(t,n);return n[s-1]}getColumn(t){return this.getState().columns.find(n=>n.id===t)}getNextColumn(t,n){const s=this.getState()._columns,a=s.findIndex(i=>i.id===t);return n?this._getFirstVisibleColumn(a+1):s[a+1]}getPrevColumn(t,n){const s=this.getState()._columns,a=s.findIndex(i=>i.id===t);return n?this._getLastVisibleColumn(a-1):s[a-1]}_getFirstVisibleColumn(t){const n=this.getState()._columns;let s=t??0;for(;s<n.length&&(n[s]?.hidden||n[s]?.collapsed);)s++;return n[s]}_getLastVisibleColumn(t){const n=this.getState()._columns;let s=t??n.length-1;for(;s<n.length&&(n[s]?.hidden||n[s]?.collapsed);)s--;return n[s]}isCellEditable(t,n){const{editor:s,hidden:a}=n;return!s||a?!1:typeof s=="function"?s(t,n):!0}getNextEditor(t,n){let s=this.getState().columns;if(n){const a=s.findIndex(i=>i.id===n.id);s=s.slice(a+1)}return s.find(a=>this.isCellEditable(t,a))}getPrevEditor(t,n){let s=this.getState().columns;if(n){const a=s.findLastIndex(i=>i.id===n.id);s=s.slice(0,a)}return s.findLast(a=>this.isCellEditable(t,a))}toggleBranch(t,n,s){let a=this._branches[t],{data:i}=this.getState();if(i=[...i],t!==0){a={...a,open:n};const c=this.updateTreeRow(a);a.$parent===0&&(i=c)}s&&a.data?.length&&a.data.forEach(c=>{const u=this.toggleKids(c,n,s);t===0&&(i=u)}),this.setState({data:i})}toggleKids(t,n,s){t={...t,open:n};const a=this.updateTreeRow(t);return s&&t.data?.length&&t.data.forEach(i=>{this.toggleKids(i,n,s)}),a}updateTreeRow(t){const n=t.id;this._branches[n]=t;const s=this._branches[t.$parent],a=s.data.findIndex(i=>i.id===n);return s.data=[...s.data],s.data[a]=t,s.data}isSelected(t){return this.getState().selectedRows.indexOf(t)!==-1}findAndRemove(t,n){for(let s=0;s<t.length;s++){if(t[s].id===n)return t.splice(s,1)[0];if(t[s].data){const a=[...t[s].data],i=this.findAndRemove(a,n);if(i)return t[s]={...t[s],data:a},i}}return null}insertItem(t,n,s,a){for(let i=0;i<t.length;i++){if(t[i].id===n){const c=t[i],u=a==="before"?i:i+1;if(c.data){if(a==="before"){const d=i>0?t[i-1]:null;return d?.data&&d.open?t[i-1]={...d,data:[...d.data,s]}:t.splice(u,0,s),!0}else if(c.open)return t[i]={...c,data:[s,...c.data]},!0}return t.splice(u,0,s),!0}if(t[i].data&&(t[i]={...t[i],data:[...t[i].data]},this.insertItem(t[i].data,n,s,a)))return!0}return!1}moveItem(t,n,s,a){const i=[...s],c=this.findAndRemove(i,t);return this.insertItem(i,n,c,a),i}copyColumns(t){const n=[];for(let s=0;s<t.length;s++){const a={...t[s]};this.copyHeaderFooter(a,"header"),this.copyHeaderFooter(a,"footer"),n[s]=a}return n}copyHeaderFooter(t,n){let s=t[n];s=Array.isArray(s)?[...s]:[s],s.forEach((a,i)=>{s[i]=typeof a=="string"?{text:a}:{...a}}),t[n]=s}setCollapsibleColumns(t,n,s){let a=t.header;for(let i=0;i<a.length;i++){const c=a[i];if(c.collapsible&&c.collapsed){if(c.collapsible!=="first"){t.collapsed=!0,t.width=36,c.vertical=!0;const d=a.length-i;a=a.slice(0,i+1),a[i].rowspan=d}const u=c.colspan;if(u){const d=a[i+1];let p=1;d&&d.colspan&&!d.collapsed&&(p=d.colspan);for(let h=p;h<u;h++){const m=s[n+h];m&&(m.hidden=!0)}}}}}normalizeColumns(t,n,s,a,i){const c=t[n];c.width||(c.width=c.flexgrow?17:i.columnWidth),c._colindex=n+1;const u=c[s],d=i[`${s}RowHeights`];for(let p=0;p<a;p++){const h=u[p];h.id=c.id,p===u.length-1&&(h.rowspan=h.rowspan?Math.min(h.rowspan,a-p):a-p);for(let m=1;m<h.rowspan;m++){u.splice(p+m,0,{_hidden:!0});for(let g=1;g<h.colspan;g++)t[n+g][s].splice(p+m,0,{})}if(h.rowspan){const m=(h.rowspan===a?d:d.slice(p,h.rowspan+p)).reduce((g,w)=>g+w,0);h.height=m,p+h.rowspan!=a&&h.height--}if(h.colspan){let m=c.width,g=c.flexgrow||0;const w=h.colspan;for(let v=1;v<w;v++){const y=t[n+v];y&&(y.hidden?h.colspan-=1:y.flexgrow?g+=y.flexgrow:m+=y.width||i.columnWidth),g?h.flexgrow=g:h.width=m}}else h.width=c.width,h.flexgrow=c.flexgrow;s==="header"&&h.filter&&typeof h.filter=="string"&&(h.filter={type:h.filter})}u.length>a&&(u.length=a),c[s]=u}normalizeRows(t){for(let n=0;n<t.length;n++)t[n].id||(t[n].id=Ll());return t}normalizeTreeRows(t,n,s){return!n&&!s&&(this._branches={0:{data:t}}),t.forEach(a=>{a.id||(a.id=Ll()),a.$level=n||0,a.$parent=s||0,this._branches[a.id]=a,a.data&&(a.data.length?(a.$count=a.data.length,this.normalizeTreeRows(a.data,a.$level+1,a.id)):(delete a.data,delete a.$count,delete a.open))}),t}sortTree(t,n){t.sort(n),t.forEach(s=>{s.data&&this.sortTree(s.data,n)})}filterTree(t,n,s){return t.forEach(a=>{n(a)&&s.push(a.id),a.data&&this.filterTree(a.data,n,s)}),s}flattenRows(t,n,s){const a=n;return t.forEach(i=>{(!s||s.includes(i.id))&&a.push(i),i.data?.length&&i.open!==!1&&this.flattenRows(i.data,a,s)}),a}createFilter(t){const{_columns:n}=this.getState(),s=[];for(const a in t){const i=n.find(p=>p.id==a),{config:c,type:u}=i.header.find(p=>p.filter).filter,d=t[a];s.push(p=>{const h=aa(p,i);return c?.handler?c.handler(h,d):Kv(u)(h,d)})}return a=>{for(let i=0;i<s.length;i++)if(!s[i](a))return!1;return!0}}searchRows(t,n){t=t.trim().toLowerCase();const s={};if(!t)return s;const{flatData:a,columns:i}=this.getState(),c=n?i.filter(u=>n[u.id]):i;return a.forEach(u=>{const d={};c.forEach(p=>{const h=ea(u,p);String(h).toLowerCase().includes(t)&&(d[p.id]=!0)}),Object.keys(d).length&&(s[u.id]=d)}),s}normalizeSizes(t,n,s,a,i){const c=og(t,"header",s,n.headerHeight,i),u=og(t,"footer",a,n.footerHeight,i),d=c.reduce((h,m)=>h+m,0),p=u.reduce((h,m)=>h+m,0);return{...n,headerRowHeights:c,footerRowHeights:u,headerHeight:d,footerHeight:p}}},HA=new Date().valueOf();function Ll(){return"temp://"+HA++}function WA(e,t="data-id"){let n=e;for(!n.tagName&&e.target&&(n=e.target);n;){if(n.getAttribute&&n.getAttribute(t))return n;n=n.parentNode}return null}new Date().valueOf();var zA=class{constructor(){this.store=new Map}configure(e,t){this.node=t;for(const n in e)if(e[n]){const s=n.toLowerCase().replace(/[ ]/g,""),a=e[n];this.store.set(s,a)}}},to=[],qA={subscribe:e=>{UA();const t=new zA;return to.push(t),e(t),()=>{const n=to.findIndex(s=>s===t);n>=0&&to.splice(n,1)}}},cg=!1;function UA(){cg||(cg=!0,document.addEventListener("keydown",e=>{if(to.length&&(e.ctrlKey||e.altKey||e.metaKey||e.shiftKey||e.key.length>1||e.key===" ")){const t=[];e.ctrlKey&&t.push("ctrl"),e.altKey&&t.push("alt"),e.metaKey&&t.push("meta"),e.shiftKey&&t.push("shift");let n=e.code.replace("Key","").toLocaleLowerCase();e.key===" "&&(n="space"),t.push(n);const s=t.join("+");for(let a=to.length-1;a>=0;a--){const i=to[a],c=i.store.get(s)||i.store.get(n);c&&i.node.contains(e.target)&&c(e,{key:s,evKey:n})}}}))}const VA={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 GA(e,{keys:t,exec:n}){if(!t)return;function s(c){const u=c.target;return u.tagName==="INPUT"||u.tagName==="TEXTAREA"||WA(u,"data-header-id")?.classList.contains("wx-filter")||!!u.closest(".wx-cell.wx-editor")}const a={};for(const c in t){const u=t[c];typeof u<"u"&&(typeof u=="function"?a[c]=u:u&&(a[c]=d=>{const p=s(d);n({key:c,event:d,isInput:p})}))}const i=qA.subscribe(c=>{c.configure(a,e)});return{destroy:()=>{i()}}}function KA(e,t){let n=null;t.scroll.subscribe(s=>{if(!s||s===n)return;n=s;const{left:a,top:i,height:c,width:u}=s,d=t.getHeight(),p=t.getWidth(),h=t.getScrollMargin();if(i>=0){const m=e.scrollTop;i<m?e.scrollTop=i:i+c>m+d&&(e.scrollTop=i-d+c)}if(a>=0){const m=e.scrollLeft;a<m?e.scrollLeft=a:a+u>m+p-h&&(e.scrollLeft=a-p+u+h)}}),t.scrollLeft?.subscribe?.(s=>{requestAnimationFrame(()=>{Math.abs(e.scrollLeft-s)>1&&(e.scrollLeft=s)})}),t.scrollTop?.subscribe?.(s=>{requestAnimationFrame(()=>{Math.abs(e.scrollTop-s)>1&&(e.scrollTop=s)})})}const ur=o.createContext(null);function QA(e,t){const n=new ResizeObserver(s=>{requestAnimationFrame(()=>t(s[0].contentRect))});return n.observe(e.parentNode),{destroy(){n.disconnect()}}}const lg=5,YA=700;function Jl(e){const t=e.getBoundingClientRect(),n=document.body,s=t.top+n.scrollTop-n.clientTop||0,a=t.left+n.scrollLeft-n.clientLeft||0;return{y:Math.round(s),x:Math.round(a),width:e.offsetWidth,height:e.offsetHeight}}function Pp(e,t){const n=Jl(t);return{x:e.clientX-n.x,y:e.clientY-n.y}}function XA(e,t){const n=t.current;let s=null,a,i,c=!1,u=!1;const d=document.createElement("DIV");d.className="wx-drag-zone",d.setAttribute("tabindex",-1);function p(){clearTimeout(a),a=null}function h(M){const H=so(M);H&&(s={container:d,sourceNode:M.target,from:Mu(H),pos:Pp(M,e)},i=s.pos,m(M))}function m(M){if(!s)return;const H=s.pos=Pp(M,e);if(!c){if(!u&&!M?.target?.getAttribute("draggable-data")&&Math.abs(i.x-H.x)<lg&&Math.abs(i.y-H.y)<lg)return;if(I(M)===!1)return F()}if(u){const V=window.scrollX||document.documentElement.scrollLeft||document.body.scrollLeft,P=window.scrollY||document.documentElement.scrollTop||document.body.scrollTop;s.targetNode=document.elementFromPoint(M.pageX-V,M.pageY-P)}else s.targetNode=M.target;n.move&&n.move(M,s),d.style.left=-(s.offset?s.offset.x:0)+"px",d.style.top=s.pos.y+(s.offset?s.offset.y:0)+"px"}function g(M){d.parentNode&&d.parentNode.removeChild(d),d.innerHTML="",c&&n.end&&n.end(M,s),s=i=null,F()}function w(M){n.getReorder&&!n.getReorder()||M.button===0&&(E(M),window.addEventListener("mousemove",v),window.addEventListener("mouseup",y),h(M))}function v(M){m(M)}function y(M){g(M)}function k(M){if(n.getReorder&&!n.getReorder())return;a=setTimeout(()=>{u=!0,h(M.touches[0])},YA),E(M);function H(){a&&p(),M.target.removeEventListener("touchmove",N),M.target.removeEventListener("touchend",H),g(M)}M.target.addEventListener("touchmove",N),M.target.addEventListener("touchend",H),e.addEventListener("contextmenu",C)}function N(M){c?(M.preventDefault(),m(M.touches[0])):a&&p()}function C(M){if(c||a)return M.preventDefault(),!1}function A(M){M.preventDefault()}function E(M){if(!n.getDraggableInfo)return;const{hasDraggable:H}=n.getDraggableInfo();(!H||M.target.getAttribute("draggable-data"))&&(document.body.style.userSelect="none",document.body.style.webkitUserSelect="none")}function I(M){if(c=!0,n.start){if(n.start(M,s)===!1)return!1;e.appendChild(d),document.body.style.cursor="move"}}function F(M){c=u=!1,document.body.style.cursor="",document.body.style.userSelect="",document.body.style.webkitUserSelect="",window.removeEventListener("mousemove",v),window.removeEventListener("mouseup",y),M&&(e.removeEventListener("mousedown",w),e.removeEventListener("touchstart",k),e.removeEventListener("dragstart",A))}return e.addEventListener("mousedown",w),e.addEventListener("touchstart",k),e.addEventListener("dragstart",A),{destroy(){F(!0)}}}const JA=.004;function ZA(){return{dirX:0,dirY:0,scrollSpeedFactor:1}}function eN(e,t,n,s){const{node:a,left:i,top:c,bottom:u,sense:d,xScroll:p,yScroll:h}=s,m=Pp(e,a);n.scrollState||(n.scrollState=ZA());let g=0,w=0;m.x<i+d?g=-1:m.x>t.width-d&&(g=1),m.y<c+Math.round(d/2)?w=-1:m.y>t.height-u-Math.round(d/2)&&(w=1),(n.scrollState.dirX!==g||n.scrollState.dirY!==w)&&(Qv(n),n.scrollState.dirX=g,n.scrollState.dirY=w),(p&&n.scrollState.dirX!==0||h&&n.scrollState.dirY!==0)&&tN(n,s,{x:n.scrollState.dirX,y:n.scrollState.dirY})}function tN(e,t,n){e.autoScrollTimer||(e.autoScrollTimer=setTimeout(()=>{e.activeAutoScroll=setInterval(nN,15,e,t,n)},250))}function Qv(e){e.scrollSpeedFactor=1,e.autoScrollTimer&&(e.autoScrollTimer=clearTimeout(e.autoScrollTimer),e.activeAutoScroll=clearInterval(e.activeAutoScroll))}function nN(e,t,n){const{x:s,y:a}=n;e.scrollSpeedFactor+=JA,s!==0&&sN(e,t,s),a!==0&&rN(e,t,a)}function rN(e,t,n){const s=t.node.scrollTop;Yv(s+Math.round(t.sense/3)*e.scrollSpeedFactor*n,"scrollTop",t)}function sN(e,t,n){const s=t.node.scrollLeft;Yv(s+Math.round(t.sense/3)*e.scrollSpeedFactor*n,"scrollLeft",t)}function Yv(e,t,n){n.node[t]=e}function Tu(e,t,n,s,a,i){const c={};return e&&(c.width=`${e}px`,c.minWidth=`${e}px`),t&&(c.flexGrow=t),i&&(c.height=`${i}px`),n&&(c.position="sticky",n.left&&(c.left=`${s}px`),n.right&&(c.right=`${a}px`)),c}function Xv(e,t,n){let s="";if(e.fixed)for(const a in e.fixed){let i=e.fixed[a]===-1;!i&&e.fixed.leftSize&&t.colspan&&(i=t.colspan+e._colindex-1===e.fixed.leftSize),s+=i?"wx-shadow ":"wx-fixed "}return s+=t.rowspan>1?"wx-rowspan ":"",s+=t.colspan>1?"wx-colspan ":"",s+=t.vertical?"wx-vertical ":"",s+=n?n(e)+" ":"",s}function aN(e){const{row:t,column:n,cellStyle:s=null,columnStyle:a=null,children:i,focusable:c}=e,u=o.useContext(ur),d=dt(u,"focusCell"),p=dt(u,"search"),h=dt(u,"reorder"),m=o.useMemo(()=>p?.rows[t.id]&&p.rows[t.id][n.id],[p,t.id,n.id]),g=o.useMemo(()=>Tu(n.width,n.flexgrow,n.fixed,n.left,n.right),[n.width,n.flexgrow,n.fixed,n.left,n.right]);function w(I,F){let M="wx-cell";return M+=n.fixed?" "+(n.fixed===-1?"wx-shadow":"wx-fixed"):"",M+=I?" "+I(n):"",M+=F?" "+F(t,n):"",M+=n.treetoggle?" wx-tree-cell":"",M}const v=o.useMemo(()=>w(a,s),[a,s,n,t]),y=o.useMemo(()=>typeof n.draggable=="function"?n.draggable(t,n)!==!1:n.draggable,[n,t]),k=o.useRef(null);o.useEffect(()=>{k.current&&c&&d?.row===t.id&&d?.column===n.id&&k.current.focus()},[d,c,t.id,n.id]);const N=o.useCallback(()=>{c&&!d&&u.exec("focus-cell",{row:t.id,column:n.id,eventSource:"focus"})},[u,c,d,t.id,n.id]);function C(I){const F=new RegExp(`(${p.value.trim()})`,"gi");return String(I).split(F).map(M=>({text:M,highlight:F.test(M)}))}const A=o.useMemo(()=>{const I=n.fixed&&n.fixed.left===-1||n.fixed.right===-1,F=n.fixed&&n.fixed.right;return[v,I?"wx-shadow":"",F?"wx-fixed-right":""].filter(Boolean).join(" ")},[v,n]),E=n.cell;return r.jsxs("div",{className:"wx-TSCaXsGV "+A,ref:k,onFocus:N,style:g,"data-row-id":mn(t.id),"data-col-id":mn(n.id),tabIndex:c?"0":"-1",role:"gridcell","aria-colindex":n._colindex,"aria-readonly":n.editor?void 0:!0,children:[h&&n.draggable?y?r.jsx("i",{"draggable-data":"true",className:"wx-TSCaXsGV wx-draggable wxi-drag"}):r.jsx("i",{className:"wx-TSCaXsGV wx-draggable-stub"}):null,n.treetoggle?r.jsxs(r.Fragment,{children:[r.jsx("span",{style:{marginLeft:`${t.$level*28}px`}}),t.$count?r.jsx("i",{"data-action":"toggle-row",className:`wx-TSCaXsGV wx-table-tree-toggle wxi-menu-${t.open!==!1?"down":"right"}`}):null]}):null,E?r.jsx(E,{api:u,row:t,column:n,onAction:({action:I,data:F})=>u.exec(I,F)}):i?i():m?r.jsx("span",{children:C(ea(t,n)).map(({highlight:I,text:F},M)=>I?r.jsx("mark",{className:"wx-TSCaXsGV wx-search",children:F},M):r.jsx("span",{children:F},M))}):ea(t,n)]})}function ug(e,t){let n,s;function a(u){n=u.clientX,e.style.opacity=1,document.body.style.cursor="ew-resize",document.body.style.userSelect="none",window.addEventListener("mousemove",i),window.addEventListener("mouseup",c),t&&t.down&&t.down(e)}function i(u){s=u.clientX-n,t&&t.move&&t.move(s)}function c(){e.style.opacity="",document.body.style.cursor="",document.body.style.userSelect="",t&&t.up&&t.up(s),window.removeEventListener("mousemove",i),window.removeEventListener("mouseup",c)}return e.addEventListener("mousedown",a),{destroy(){e.removeEventListener("mousedown",a)}}}function iN({filter:e,column:t,action:n,filterValue:s}){function a({value:i}){n({value:i,key:t.id})}return r.jsx(tm,{...e.config??{},value:s,onChange:a})}function oN({filter:e,column:t,action:n,filterValue:s}){const a=o.useContext(ur),i=dt(a,"flatData"),c=o.useMemo(()=>e?.config?.options||t?.options||d(),[e,t,i]),u=o.useMemo(()=>e?.config?.template,[e]);function d(){const m=[];return i.forEach(g=>{const w=aa(g,t);m.includes(w)||m.push(w)}),m.map(g=>({id:g,label:g}))}function p({value:m}){n({value:m,key:t.id})}function h(m){m.key!=="Tab"&&m.preventDefault()}return r.jsx("div",{style:{width:"100%"},onKeyDown:h,children:r.jsx(xM,{placeholder:"",clear:!0,...e?.config??{},options:c,value:s,onChange:p,children:m=>u?u(m):m.label})})}function cN({filter:e,column:t,action:n,filterValue:s}){function a({value:i}){n({value:i,key:t.id})}return r.jsx("div",{className:"wx-aaaK5VYO",style:{width:"100%"},children:r.jsx(yM,{placeholder:"",clear:!0,...e?.config??{},value:s,onChange:a})})}function Jv(e){const{value:t,options:n=[],placeholder:s="",clear:a=!1,text:i=null,template:c=null,cell:u=null,dropdown:d={},autoOpen:p=!1,onChange:h,onAction:m}=e,[g,w]=Lv(t||[]),v=o.useMemo(()=>(g||[]).map(P=>n.find(D=>D.id===P)).filter(Boolean),[g,n]),y=o.useRef(null),k=o.useRef(null),[N,C]=o.useState(null),A=()=>{const P=g||[];if(!P.length)return 0;const D=n.find(O=>P.includes(O.id));return D?n.indexOf(D):0};function E(P){k.current=P.navigate,C(()=>P.keydown),p&&P.navigate(A())}o.useEffect(()=>{p&&(y.current?.focus(),typeof window<"u"&&window.getSelection&&window.getSelection().removeAllRanges())},[]);function I({id:P}){w(P),h&&h({value:P})}function F(P){P.stopPropagation(),w([]),h&&h({value:[]})}function M(){k.current?.(A())}function H(){k.current?.(null)}function V(P){N?.(P,A())}return r.jsxs("div",{ref:y,className:"wx-multiselect wx-aadNNOwy",onClick:M,onKeyDown:V,tabIndex:0,children:[r.jsx("div",{className:"wx-label wx-aadNNOwy",children:c?c(v):u?r.jsx(u,{data:v,onAction:m}):i?r.jsx("span",{className:"wx-text wx-aadNNOwy",children:i}):v.length?r.jsx("span",{className:"wx-text wx-aadNNOwy",children:v.map(P=>P.label).join(", ")}):s?r.jsx("span",{className:"wx-placeholder wx-aadNNOwy",children:s}):" "}),a&&g?.length?r.jsx("i",{className:"wx-icon wxi-close wx-aadNNOwy",onClick:F}):r.jsx("i",{className:"wx-icon wxi-angle-down wx-aadNNOwy"}),r.jsx(Nu,{items:n,onReady:E,onSelect:I,multiselect:!0,checkboxes:!0,value:g||[],onCancel:H,...d,children:({option:P})=>r.jsx("div",{className:"wx-option wx-aadNNOwy",children:c?c(P):u?r.jsx(u,{data:P,onAction:m}):P.label})})]})}function lN({filter:e,column:t,action:n,filterValue:s}){const a=o.useContext(fn.i18n)?.getGroup("grid")||fc(sm).getGroup("grid"),i=o.useMemo(()=>({clear:!0,...e?.config||{}}),[e]),c=o.useMemo(()=>i.options||t.options,[i,t]),u=o.useMemo(()=>{const h=s?.length;return h?h<3?s.map(m=>t.optionsMap.get(m)).join(", "):h+" "+a("selected"):""},[s,t,a]);function d({value:h}){n({value:h,key:t.id})}function p(h){h.key!=="Tab"&&h.preventDefault()}return r.jsx("div",{style:{width:"100%"},onKeyDown:p,children:r.jsx(Jv,{placeholder:"",...i,options:c,value:s||[],text:u,onChange:d})})}const uN={text:iN,richselect:oN,datepicker:cN,multiselect:lN};function dN({filter:e,column:t}){const n=o.useContext(ur),s=dt(n,"filterValues");function a(c){n.exec("filter-rows",c)}const i=o.useMemo(()=>uN[e.type],[e.type]);return r.jsx(i,{filter:e,column:t,action:a,filterValue:s[t.id]})}function pN(e){const{cell:t,column:n,row:s,lastRow:a,sortRow:i,columnStyle:c,bodyHeight:u,hasSplit:d}=e,p=o.useContext(ur),h=dt(p,"sortMarks"),m=o.useMemo(()=>h?h[n.id]:void 0,[h,n.id]),g=o.useRef(),w=o.useCallback(G=>{g.current=t.flexgrow?G.parentNode.clientWidth:t.width},[t.flexgrow,t.width]),v=o.useCallback((G,U)=>{p.exec("resize-column",{id:t.id,width:Math.max(1,(g.current||0)+G),inProgress:U})},[p,t.id]),y=o.useCallback(G=>v(G,!0),[v]),k=o.useCallback(G=>v(G,!1),[v]),N=o.useCallback(G=>{if(!n.sort||t.filter)return;let U=m?.order;U&&(U=U==="asc"?"desc":"asc"),p.exec("sort-rows",{key:t.id,add:G.ctrlKey||G.metaKey,order:U})},[p,t.id,t.filter,n.sort,m?.order]),C=o.useCallback(G=>{G&&G.stopPropagation(),p.exec("collapse-column",{id:t.id,row:s})},[p,t.id,s]),A=o.useCallback(G=>{G.key==="Enter"&&C()},[C]),E=o.useCallback(G=>{G.key==="Enter"&&!t.filter&&N(G)},[N,t.filter]),I=o.useMemo(()=>t.collapsed&&n.collapsed,[t.collapsed,n.collapsed]),F=o.useMemo(()=>I&&!d&&t.collapsible!=="header",[I,d,t.collapsible]),M=o.useMemo(()=>F?{top:-u/2,position:"absolute"}:{},[F,u]),H=o.useMemo(()=>Tu(t.width,t.flexgrow,n.fixed,n.left,t.right??n.right,t.height+(I&&F?u:0)),[t.width,t.flexgrow,n.fixed,n.left,t.right,n.right,t.height,I,F,u]),V=o.useMemo(()=>Xv(n,t,c),[n,t,c]),P=o.useCallback(()=>Object.fromEntries(Object.entries(t).filter(([G])=>G!=="cell")),[t]),D=`wx-cell ${V} ${t.css||""} wx-collapsed`,O=["wx-cell",V,t.css||"",t.filter?"wx-filter":"",n.fixed&&n.fixed.right?"wx-fixed-right":""].filter(Boolean).join(" "),X=o.useRef(null);return o.useEffect(()=>{const G=X.current;if(!G)return;const U=ug(G,{down:w,move:y,up:k});return()=>{typeof U=="function"&&U()}},[w,y,k,ug]),I?r.jsx("div",{className:"wx-RsQD74qC "+D,style:H,role:"button","aria-label":`Expand column ${t.text||""}`,"aria-expanded":!t.collapsed,tabIndex:0,onKeyDown:A,onClick:C,"data-header-id":mn(n.id),children:r.jsx("div",{className:"wx-RsQD74qC wx-text",style:M,children:t.text||""})}):r.jsxs("div",{className:"wx-RsQD74qC "+O,style:H,onClick:N,"data-header-id":mn(n.id),tabIndex:!t._hidden&&n.sort&&!t.filter?0:void 0,role:"columnheader","aria-colindex":n._colindex,"aria-colspan":t.colspan>1?t.colspan:void 0,"aria-rowspan":t.rowspan>1?t.rowspan:void 0,"aria-sort":!m?.order||t.filter?"none":m?.order==="asc"?"ascending":"descending",onKeyDown:E,children:[t.collapsible?r.jsx("div",{className:"wx-RsQD74qC wx-collapse",role:"button","aria-label":t.collapsed?"Expand column":"Collapse column","aria-expanded":!t.collapsed,tabIndex:0,onKeyDown:A,onClick:C,children:r.jsx("i",{className:`wx-RsQD74qC wxi-angle-${t.collapsed?"down":"right"}`})}):null,t.cell?(()=>{const G=t.cell;return r.jsx(G,{api:p,cell:P(),column:n,row:s,onAction:({action:U,data:ie})=>p.exec(U,ie)})})():t.filter?r.jsx(dN,{filter:t.filter,column:n}):r.jsx("div",{className:"wx-RsQD74qC wx-text",children:t.text||""}),n.resize&&a&&!t._hidden?r.jsx("div",{className:"wx-RsQD74qC wx-grip",role:"presentation","aria-label":"Resize column",ref:X,onClick:G=>G.stopPropagation(),children:r.jsx("div",{})}):null,i?r.jsx("div",{className:"wx-RsQD74qC wx-sort",children:m?r.jsxs(r.Fragment,{children:[typeof m.index<"u"?r.jsx("div",{className:"wx-RsQD74qC wx-order",children:m.index+1}):null,r.jsx("i",{className:`wx-RsQD74qC wxi-arrow-${m.order==="asc"?"up":"down"}`})]}):null}):null]})}function mN({cell:e,column:t,row:n,columnStyle:s}){const a=o.useContext(ur),i=o.useMemo(()=>Tu(e?.width,e?.flexgrow,t?.fixed,t?.left,e?.right??t?.right,e?.height),[e?.width,e?.flexgrow,t?.fixed,t?.left,e?.right,t?.right,e?.height]),c=o.useMemo(()=>Xv(t,e,s),[t,e,s]),u=o.useCallback(()=>Object.fromEntries(Object.entries(e||{}).filter(([p])=>p!=="cell")),[e]),d=`wx-6Sdi3Dfd wx-cell ${c||""} ${e?.css||""}`+(t?.fixed&&t?.fixed.right?" wx-fixed-right":"");return r.jsx("div",{className:d,style:i,children:!t?.collapsed&&!e?.collapsed?e?.cell?Dp.createElement(e.cell,{api:a,cell:u(),column:t,row:n,onAction:({action:p,data:h})=>a.exec(p,h)}):r.jsx("div",{className:"wx-6Sdi3Dfd wx-text",children:e?.text||""}):null})}function dg({deltaLeft:e,contentWidth:t,columns:n,type:s="header",columnStyle:a,bodyHeight:i}){const c=o.useContext(ur),u=dt(c,"_sizes"),d=dt(c,"split"),p=o.useMemo(()=>u?.[`${s}RowHeights`],[u,s]),h=o.useMemo(()=>{let y=[];if(n&&n.length){const k=n[0][s].length;for(let N=0;N<k;N++){let C=0;y.push([]),n.forEach((A,E)=>{const I={...A[s][N]};C||y[N].push(I),I.colspan>1?C=I.colspan-1:C&&C--})}}return y},[n,s]),m=o.useMemo(()=>d?.left||d?.right,[d]);function g(y){return n.find(k=>k.id===y)}function w(y,k){let N=k;return y.rowspan&&(N+=y.rowspan-1),N===h.length-1}function v(y,k,N){if(!N.sort)return!1;for(let C=h.length-1;C>=0;C--){const A=N.header[C];if(!A.filter&&!A._hidden)return k===C}return w(y,k)}return r.jsx("div",{className:`wx-sAsPVaUK wx-${s}`,style:{paddingLeft:`${e}px`,width:`${t}px`},role:"rowgroup",children:h.map((y,k)=>r.jsx("div",{className:s==="header"?"wx-sAsPVaUK wx-h-row":"wx-sAsPVaUK wx-f-row",style:{height:`${p?.[k]}px`,display:"flex"},role:"row",children:y.map(N=>{const C=g(N.id);return s==="header"?r.jsx(pN,{cell:N,columnStyle:a,column:C,row:k,lastRow:w(N,k),bodyHeight:i,sortRow:v(N,k,C),hasSplit:m},N.id):r.jsx(mN,{cell:N,columnStyle:a,column:g(N.id),row:k},N.id)})},k))})}function hN({overlay:e}){const t=o.useContext(ur);function n(a){return typeof a=="function"}const s=e;return r.jsx("div",{className:"wx-1ty666CQ wx-overlay",children:n(e)?r.jsx(s,{onAction:({action:a,data:i})=>t.exec(a,i)}):e})}function fN(e){const{editor:t,onSave:n,onApply:s}=e,[a,i]=o.useState(t?.value||""),{type:c="text"}=o.useMemo(()=>t?.config||{},[t]),u=o.useRef(null);o.useEffect(()=>{u.current&&u.current.focus()},[]),o.useEffect(()=>{if(!u.current)return;const h=ds(u.current,()=>n(!0));return()=>h.destroy()},[n]);function d(){u.current&&(i(u.current.value),s(u.current.value))}function p({key:h}){h==="Enter"&&n()}return r.jsx("input",{className:"wx-e7Ao5ejY wx-text",onInput:d,onKeyDown:p,ref:u,type:c,value:a})}function gN({editor:e,onAction:t,onSave:n,onApply:s,onCancel:a}){const[i,c]=o.useState(e?.value),[u,d]=o.useState(e?.renderedValue),[p,h]=o.useState(e?.options||[]),m=o.useMemo(()=>e?.config?.template,[e]),g=o.useMemo(()=>e?.config?.cell,[e]),w=o.useMemo(()=>e?.config?.dropdown||{},[e]),v=o.useMemo(()=>({trackScroll:!0,...w}),[w]),y=o.useMemo(()=>(p||[]).findIndex(M=>M.id===i),[p,i]),k=o.useRef(null),N=o.useRef(null),C=o.useCallback(M=>{k.current=M.navigate,N.current=M.keydown,k.current(y)},[y,k]),A=o.useCallback(M=>{const H=M?.target?.value??"";d(H);const V=H?(e?.options||[]).filter(P=>(P.label||"").toLowerCase().includes(H.toLowerCase())):e?.options||[];h(V),V.length?k.current(-1/0):k.current(null)},[e]),E=o.useRef(null);o.useEffect(()=>{E.current&&E.current.focus()},[]);const I=o.useRef(n);o.useEffect(()=>{I.current=n},[n]),o.useEffect(()=>{if(!E.current)return;const M=ds(E.current,()=>I.current(!0));return()=>M.destroy()},[]),o.useEffect(()=>{c(e?.value),d(e?.renderedValue),h(e?.options||[])},[e]);const F=o.useCallback(({id:M})=>{s(M),n()},[s,n]);return r.jsxs(r.Fragment,{children:[r.jsx("input",{className:"wx-0UYfSd1x wx-input",ref:E,value:u??"",onChange:A,onKeyDown:M=>N.current?N.current(M,y):void 0}),r.jsx(Nu,{items:p,onReady:C,onSelect:F,...v,onCancel:a,children:({option:M})=>m?m(M):g?r.jsx(g,{data:M,onAction:t}):M.label})]})}function bN({editor:e,onAction:t,onSave:n,onApply:s,onCancel:a}){const[i]=o.useState(()=>e.value||new Date),{template:c,cell:u,dropdown:d={}}=e?.config||{},p=o.useMemo(()=>({trackScroll:!0,width:"auto",...d}),[d]);function h({value:v}){s(v),n()}const m=o.useRef(null),[g,w]=o.useState(null);return o.useEffect(()=>{m.current&&m.current.focus(),typeof window<"u"&&window.getSelection&&window.getSelection().removeAllRanges()},[]),o.useEffect(()=>{if(!g)return;const v=ds(g,()=>n(!0));return()=>v.destroy()},[g,n]),r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"wx-lNWNYUb6 wx-value",ref:m,tabIndex:0,onClick:a,onKeyDown:v=>v.preventDefault(),children:c?c(i):u?r.jsx(u,{data:e.value,onAction:t}):r.jsx("span",{className:"wx-lNWNYUb6 wx-text",children:e.renderedValue})}),r.jsx(em,{...p,onCancel:a,children:r.jsx("div",{ref:w,className:"wx-lNWNYUb6",children:r.jsx(Iv,{value:i,onChange:h,buttons:e.config?.buttons})})})]})}function vN(e){const{editor:t}=e,n=e.onAction??e.onaction,s=e.onSave??e.onsave,a=e.onApply??e.onapply,i=e.onCancel??e.oncancel,c=t.config||{},{dropdown:u={}}=c,d=o.useMemo(()=>({trackScroll:!0,...u}),[u]),[p]=o.useState(t.options.find(A=>A.id===t.value)),[h]=o.useState(t.value),[m]=o.useState(t.options),g=o.useMemo(()=>m.findIndex(A=>A.id===h),[m,h]);function w({id:A}){a(A),s()}let v;const[y,k]=o.useState();function N(A){v=A.navigate,k(()=>A.keydown),v(g)}const C=o.useRef(null);return o.useEffect(()=>{C.current&&C.current.focus(),typeof window<"u"&&window.getSelection&&window.getSelection().removeAllRanges()},[]),o.useEffect(()=>{if(!C.current)return;const A=ds(C.current,()=>s(!0));return()=>A.destroy()},[s]),r.jsxs(r.Fragment,{children:[r.jsx("div",{ref:C,className:"wx-ywGRk611 wx-value",tabIndex:0,onClick:i,onKeyDown:A=>{y(A,g),A.preventDefault()},children:c.template?c.template(p):c.cell?(()=>{const A=c.cell;return r.jsx(A,{data:p,onAction:n})})():r.jsx("span",{className:"wx-ywGRk611 wx-text",children:t.renderedValue})}),r.jsx(Nu,{items:m,onReady:N,onSelect:w,...d,onCancel:i,children:({option:A})=>c.template?c.template(A):c.cell?(()=>{const E=c.cell;return r.jsx(E,{data:A,onAction:n})})():A.label})]})}function wN(e){const{editor:t,onAction:n,onSave:s,onApply:a}=e,i=t?.config||{},c=t?.options??[],u=t?.value||[],d=t?.renderedValue,p=o.useMemo(()=>({trackScroll:!0,...i.dropdown||{}}),[i]);function h({value:g}){a(g)}const m=o.useRef(null);return o.useEffect(()=>{if(!m.current)return;const g=ds(m.current,()=>s(!0));return()=>g.destroy()},[s]),r.jsx("div",{ref:m,className:"wx-value wx-aacZ4gNU",onClick:()=>s(!0),children:r.jsx(Jv,{value:u,options:c,text:d,template:i.template,cell:i.cell,clear:i.clear,dropdown:p,autoOpen:!0,onChange:h,onAction:n})})}const yN={text:fN,combo:gN,datepicker:bN,richselect:vN,multiselect:wN};function xN({column:e,row:t}){const n=o.useContext(ur),s=dt(n,"editor"),a=o.useCallback((v,y)=>{n.exec("close-editor",{ignore:v}),y&&n.exec("focus-cell",{...y,eventSource:"click"})},[n]),i=o.useCallback(v=>{const y=v?null:{row:s?.id,column:s?.column};a(!1,y)},[s,a]),c=o.useCallback(()=>{a(!0,{row:s?.id,column:s?.column})},[s,a]),u=o.useCallback(v=>{n.exec("editor",{value:v})},[n]),d=o.useCallback(v=>{v.key==="Enter"&&s&&(e.editor.type==="multiselect"?u(s.value):c())},[s,e.editor,c,u]),p=o.useMemo(()=>Tu(e.width,e.flexgrow,e.fixed,e.left,e.right),[e.width,e.flexgrow,e.fixed,e.left,e.right]),h=o.useMemo(()=>{let v=e.editor;if(typeof v=="function"&&(v=v(t,e)),!v)return null;let y=typeof v=="string"?v:v.type;return yN[y]},[e,t]),m=o.useRef(null);o.useEffect(()=>{m.current&&typeof p=="string"&&m.current.setAttribute("style",p)},[p]);const g=typeof t.$parent<"u"?"gridcell":"cell",w=typeof t.$parent<"u"?!e.editor:void 0;return r.jsx("div",{className:"wx-8l724t2g wx-cell wx-editor",ref:m,style:typeof p=="object"&&p!==null?p:void 0,role:g,"aria-readonly":w,tabIndex:-1,onClick:v=>v.stopPropagation(),onDoubleClick:v=>v.stopPropagation(),onKeyDown:d,children:h?r.jsx(h,{editor:s,onSave:i,onApply:u,onCancel:c,onAction:({action:v,data:y})=>n.exec(v,y)}):null})}function pg(e){const{columns:t,type:n,columnStyle:s}=e,a=o.useContext(ur),{filterValues:i,_columns:c,_sizes:u}=a.getState();function d(p){return s?" "+s(p):""}return r.jsx(r.Fragment,{children:t.map((p,h)=>r.jsx("tr",{children:p.map(m=>{const g=c.find(y=>y.id===m.id),w=`wx-print-cell-${n}${d(g)}${m.filter?" wx-print-cell-filter":""}${m.vertical?" wx-vertical":""}`,v=m.cell;return r.jsx("th",{style:_v(Vv(m,u.columnWidth)),className:"wx-Gy81xq2u "+w,rowSpan:m.rowspan,colSpan:m.colspan,children:v?r.jsx(v,{api:a,cell:Object.fromEntries(Object.entries(m).filter(([y])=>y!=="cell")),column:g,row:h}):m.filter?r.jsx("div",{className:"wx-Gy81xq2u wx-print-filter",children:MA(i,c,m)}):r.jsx("div",{className:"wx-Gy81xq2u wx-text",children:m.text??""})},m.id)})},h))})}function SN(e){const{columns:t,rowStyle:n,columnStyle:s,cellStyle:a,header:i,footer:c,reorder:u}=e,d=o.useContext(ur),{flatData:p,_sizes:h}=d.getState(),m=i&&ag(t,"header",h.headerRowHeights),g=c&&ag(t,"footer",h.footerRowHeights);function w(y,k){let N="";return N+=s?" "+s(k):"",N+=a?" "+a(y,k):"",N}function v(y,k){return typeof k.draggable=="function"?k.draggable(y,k)!==!1:k.draggable}return r.jsxs("table",{className:`wx-8NTMLH0z wx-print-grid ${t.some(y=>y.flexgrow)?"wx-flex-columns":""}`,children:[i?r.jsx("thead",{children:r.jsx(pg,{columns:m,type:"header",columnStyle:s})}):null,r.jsx("tbody",{children:p.map((y,k)=>r.jsx("tr",{className:"wx-8NTMLH0z wx-row"+(n?" "+n(y):""),style:{height:`${y.rowHeight||h.rowHeight}px`},children:t.map(N=>N.collapsed?null:r.jsxs("td",{className:`wx-8NTMLH0z wx-print-cell wx-cell ${w(y,N)}`,style:_v(Vv(N,h.columnWidth)),children:[u&&N.draggable?r.jsx("span",{className:"wx-8NTMLH0z wx-print-draggable",children:v(y,N)?r.jsx("i",{className:"wx-8NTMLH0z wxi-drag"}):null}):null,N.treetoggle?r.jsxs(r.Fragment,{children:[r.jsx("span",{style:{marginLeft:y.$level*28+"px"}}),y.$count?r.jsx("i",{className:`wx-8NTMLH0z wx-print-grid-tree-toggle wxi-menu-${y.open!==!1?"down":"right"}`}):null]}):null,N.cell?(()=>{const C=N.cell;return r.jsx(C,{api:d,row:y,column:N})})():r.jsx("span",{children:ea(y,N)})]},N.id))},k))}),c?r.jsx("tfoot",{children:r.jsx(pg,{columns:g,type:"footer",columnStyle:s})}):null]})}function CN(e){const{config:t,...n}=e,s=o.useContext(ur),{_skin:a,_columns:i}=s.getState(),c=o.useMemo(()=>xA(i,t),[]),u=o.useRef(null);return o.useEffect(()=>{const d=document.body;d.classList.add("wx-print");const p=u.current;if(!p)return;const h=p.cloneNode(!0);d.appendChild(h);const m=`@media print { @page { size: ${t.paper} ${t.mode}; }`,g=document.createElement("style");g.setAttribute("type","text/css"),g.setAttribute("media","print"),document.getElementsByTagName("head")[0].appendChild(g),g.appendChild(document.createTextNode(m)),window.print(),g.remove(),d.classList.remove("wx-print"),h.remove()},[]),r.jsx("div",{className:`wx-4zwCKA7C wx-${a}-theme wx-print-container`,ref:u,children:c.map((d,p)=>r.jsx("div",{className:"wx-4zwCKA7C wx-print-grid-wrapper",children:r.jsx(SN,{columns:d,...n})},p))})}function kN(e){const{header:t,footer:n,overlay:s,multiselect:a,onreorder:i,rowStyle:c,columnStyle:u,cellStyle:d,autoRowHeight:p,resize:h,clientWidth:m,clientHeight:g,responsiveLevel:w,hotkeys:v}=e,y=o.useContext(ur),k=dt(y,"dynamic"),N=dt(y,"_columns"),C=dt(y,"flatData"),A=dt(y,"split"),E=dt(y,"_sizes"),[I,F]=xr(y,"selectedRows"),M=dt(y,"select"),H=dt(y,"editor"),V=dt(y,"scrollLeft"),P=dt(y,"scrollTop"),D=dt(y,"tree"),O=dt(y,"focusCell"),X=dt(y,"_print"),G=dt(y,"undo"),U=dt(y,"reorder"),ie=dt(y,"_rowHeightFromData"),[j,re]=o.useState(0);o.useEffect(()=>{re(Ye())},[]);const[de,Q]=o.useState(0),ge=o.useMemo(()=>(N||[]).some(Z=>!Z.hidden&&Z.flexgrow),[N]),oe=o.useMemo(()=>E?.rowHeight||0,[E]),me=o.useRef(null),[Ae,Te]=o.useState(null),[Pe,Se]=o.useState(null),te=o.useMemo(()=>{let Z=[],be=0;return A&&A.left&&(Z=(N||[]).slice(0,A.left).filter(We=>!We.hidden).map(We=>({...We})),Z.forEach(We=>{We.fixed={left:1,leftSize:A.left},We.left=be,be+=We.width}),Z.length&&(Z[Z.length-1].fixed.left=-1)),{columns:Z,width:be}},[A,N]),Ce=o.useMemo(()=>{let Z=[],be=0;if(A&&A.right){Z=(N||[]).slice(A.right*-1).filter(We=>!We.hidden).map(We=>({...We}));for(let We=Z.length-1;We>=0;We--){const lt=Z[We];lt.fixed={right:1},lt.right=be,be+=lt.width}Z.length&&(Z[0].fixed={right:-1})}return{columns:Z,width:be}},[A,N]),Fe=o.useMemo(()=>{const Z=(N||[]).slice(A?.left||0,(N||[]).length-(A?.right??0)).filter(be=>!be.hidden);return Z.forEach(be=>{be.fixed=0}),Z},[N,A]),Le=o.useMemo(()=>(N||[]).reduce((Z,be)=>(be.hidden||(Z+=be.width),Z),0),[N]),Ue=1;function ne(Z,be,We){let lt=be,It=Z;if(Fe.length){let At=Fe.length;for(let et=Z;et>=0;et--)Fe[et][We].forEach(Mt=>{Mt.colspan>1&&et>Z-Mt.colspan&&et<At&&(At=et)});if(At!==Fe.length&&At<Z){for(let et=At;et<Z;et++)lt-=Fe[et].width;It=At}}return{index:It,delta:lt}}const ae=o.useMemo(()=>{let Z,be,We;const lt=V||0,It=(V||0)+(m||0);let At=0,et=0,Mt=0,Cn=0;Fe.forEach((jt,tn)=>{lt>Mt&&(At=tn,Cn=Mt),Mt=Mt+jt.width,It>Mt&&(et=tn+Ue)});const zt={header:0,footer:0};for(let jt=et;jt>=At;jt--)["header","footer"].forEach(tn=>{Fe[jt]&&Fe[jt][tn].forEach(ps=>{const Is=ps.colspan;if(Is&&Is>1){const Bt=Is-(et-jt+1);Bt>0&&(zt[tn]=Math.max(zt[tn],Bt))}})});const kn=ne(At,Cn,"header"),Nt=ne(At,Cn,"footer"),cn=kn.delta,ht=kn.index,we=Nt.delta,Ot=Nt.index;return ge&&Le>(m||0)?Z=be=We=[...te.columns,...Fe,...Ce.columns]:(Z=[...te.columns,...Fe.slice(At,et+1),...Ce.columns],be=[...te.columns,...Fe.slice(ht,et+zt.header+1),...Ce.columns],We=[...te.columns,...Fe.slice(Ot,et+zt.footer+1),...Ce.columns]),{data:Z||[],header:be||[],footer:We||[],d:Cn,df:we,dh:cn}},[Fe,te,Ce,V,m,ge,Le]),le=o.useMemo(()=>t&&E?.headerHeight||0,[t,E]),ce=o.useMemo(()=>n&&E?.footerHeight||0,[n,E]),J=o.useMemo(()=>m&&g?Le>=m:!1,[m,g,Le]),[ye,ue]=o.useState(!1),Ee=o.useMemo(()=>(g||0)-le-ce-(J?j:0),[g,le,ce,J,j]),nt=o.useMemo(()=>Math.ceil((Ee||0)/(oe||1))+1,[Ee,oe]),T=o.useRef([]),[ve,De]=o.useState(0),[qe,_e]=o.useState(void 0),$e=o.useMemo(()=>{let Z=0,be=0;const We=2,lt=P||0;if(p){let et=lt;for(;et>0;)et-=T.current[Z]||oe,Z++;be=lt-et;for(let Mt=Math.max(0,Z-We-1);Mt<Z;Mt++)be-=T.current[Z-Mt]||oe;Z=Math.max(0,Z-We)}else{if(ie){let et=0,Mt=0;for(let Nt=0;Nt<(C||[]).length;Nt++){const cn=C[Nt].rowHeight||oe;if(Mt+cn>lt){et=Nt;break}Mt+=cn}Z=Math.max(0,et-We);for(let Nt=0;Nt<Z;Nt++)be+=C[Nt].rowHeight||oe;let Cn=0,zt=0;for(let Nt=et+1;Nt<(C||[]).length;Nt++){const cn=C[Nt].rowHeight||oe;if(Cn++,zt+cn>Ee)break;zt+=cn}const kn=Math.min(k?k.rowCount:(C||[]).length,et+Cn+We);return{d:be,start:Z,end:kn}}Z=Math.floor(lt/(oe||1)),Z=Math.max(0,Z-We),be=Z*(oe||0)}const It=k?k.rowCount:(C||[]).length,At=Math.min(It,Z+(nt||0)+We);return{d:be,start:Z,end:At}},[p,ie,P,oe,k,C,nt,Ee]),mt=o.useMemo(()=>{const Z=k?k.rowCount:(C||[]).length;if(p)return ve+$e.d+(Z-(qe||0))*(oe||0);if(!ie)return Z*(oe||0);let be=0;for(let We=0;We<Z;We++)be+=C[We]?.rowHeight||oe;return be},[k,C,oe,p,ie,ve,$e.d,qe]),ct=o.useRef({});ct.current={clientWidth:m,clientHeight:g,fullHeight:mt,headerHeight:le,footerHeight:ce,fullWidth:Le,SCROLLSIZE:j};const z=o.useCallback(()=>{const Z=ct.current;ue(Z.clientWidth&&Z.clientHeight?Z.fullHeight+Z.headerHeight+Z.footerHeight>=Z.clientHeight-(Z.fullWidth>=Z.clientWidth?Z.SCROLLSIZE:0):!1)},[]);o.useEffect(()=>{const Z=requestAnimationFrame(z);return()=>window.cancelAnimationFrame(Z)},[de,z]),o.useEffect(()=>{z()},[g,z]);const pe=o.useMemo(()=>ge&&Le<=(m||0)?(m||0)-0-(ye?j:0):Le,[ge,Le,m,ye,j,J]),Y=o.useMemo(()=>ge&&Le<=(m||0)?m||0:pe<(m||0)?Le+(ye?j:0):-1,[ge,Le,m,pe,ye,j]),K=o.useRef({});o.useEffect(()=>{if(k&&(K.current.start!==$e.start||K.current.end!==$e.end)){const{start:Z,end:be}=$e;K.current={start:Z,end:be},y&&y.exec&&y.exec("request-data",{row:{start:Z,end:be}})}},[k,$e,y]);const ee=o.useMemo(()=>k?C||[]:(C||[]).slice($e.start,$e.end),[k,C,$e]),R=o.useMemo(()=>(I||[]).filter(Z=>(ee||[]).some(be=>be.id===Z)),[F,ee]),se=o.useMemo(()=>$e.start,[$e.start]),Ie=o.useRef({top:P,left:V});Ie.current={top:P,left:V};const He=o.useCallback(Z=>{const be=Z.target.scrollTop,We=Z.target.scrollLeft,lt=Ie.current;(be!==lt.top||We!==lt.left)&&y.exec("scroll-to",{top:be,left:We})},[y]),Be=o.useCallback(Z=>{Z.shiftKey&&Z.preventDefault(),me.current&&me.current.focus&&me.current.focus()},[]),xe=o.useCallback(()=>!!(N||[]).find(Z=>!!Z.draggable),[N]),Ge=o.useRef(null),rt=o.useRef(null),Ke=o.useRef({dblclick:(Z,be)=>{const We={id:Z,column:uc(be,"data-col-id")};y.exec("open-editor",We)},click:(Z,be)=>{if(be.target.closest("input")||Ge.current)return;const We=uc(be,"data-col-id");if(O?.id!==Z&&y.exec("focus-cell",{row:Z,column:We,eventSource:"click"}),M===!1)return;const lt=a&&(be.ctrlKey||be.metaKey),It=a&&be.shiftKey;(lt||I.length>1||!I.includes(Z))&&y.exec("select-row",{id:Z,toggle:lt,range:It})},"toggle-row":Z=>{const be=y.getRow(Z);y.exec(be.open!==!1?"close-row":"open-row",{id:Z})},"ignore-click":()=>!1}),gt=o.useMemo(()=>({top:le,bottom:ce,left:te.width,xScroll:J,yScroll:ye,sense:p&&Pe?Pe.offsetHeight:Math.max(E?.rowHeight||0,40),node:me.current&&me.current.firstElementChild}),[le,ce,te.width,J,ye,p,Pe,E]);function _(Z,be){const{container:We,sourceNode:lt,from:It}=be;if(xe()&&!lt.getAttribute("draggable-data"))return!1;Te(It),D&&y.getRow(It).open&&y.exec("close-row",{id:It,nested:!0});const At=so(lt),et=At.cloneNode(!0);et.classList.remove("wx-selected"),et.querySelectorAll("[tabindex]").forEach(kn=>kn.setAttribute("tabindex","-1")),We.appendChild(et),Se(et);const Mt=(V||0)-ae.d,Cn=ye?j:0;We.style.width=Math.min((m||0)-Cn,ge&&Le<=(m||0)?pe:pe-Cn)+Mt+"px";const zt=Jl(At);be.offset={x:Mt,y:-Math.round(zt.height/2)},rt.current||(rt.current=Z.clientY)}function je(Z,be){const{from:We}=be,lt=be.pos,It=Jl(me.current);lt.x=It.x;const At=gt.top;if(lt.y<At)lt.y=At;else{const et=It.height-(J&&j>0?j:Math.round(gt.sense/2))-gt.bottom;lt.y>et&&(lt.y=et)}if(me.current.contains(be.targetNode)){const et=so(be.targetNode),Mt=et&&Mu(et);if(Mt&&Mt!==We){be.to=Mt;const Cn=p?Pe?.offsetHeight:E?.rowHeight;if(Pe&&((P||0)===0||lt.y>At+Cn-1)){const zt=et.getBoundingClientRect(),kn=Jl(Pe).y,Nt=zt.y,cn=kn>Nt?-1:1,ht=cn===1?"after":"before",we=y.getState().flatData,Ot=Math.abs(we.findIndex(tn=>tn.id===We)-we.findIndex(tn=>tn.id===Mt)),jt=Ot!==1?ht==="before"?"after":"before":ht;if(Ot===1&&(cn===-1&&Z.clientY>rt.current||cn===1&&Z.clientY<rt.current))return;rt.current=Z.clientY,y.exec("move-item",{id:We,target:Mt,mode:jt,inProgress:!0})}}i&&i({event:Z,context:be})}eN(Z,It,be,gt)}function Qe(Z,be){const{from:We,to:lt}=be;y.exec("move-item",{id:We,target:lt,inProgress:!1}),Ge.current=setTimeout(()=>{Ge.current=0},1),Te(null),Se(null),rt.current=null,Qv(be)}function Ye(){const Z=document.createElement("div");Z.style.cssText="position:absolute;left:-1000px;width:100px;padding:0px;margin:0px;min-height:100px;overflow-y:scroll;",document.body.appendChild(Z);const be=Z.offsetWidth-Z.clientWidth;return document.body.removeChild(Z),be}const Gt=o.useMemo(()=>Y>0?{width:`${Y}px`}:void 0,[Y]),en=o.useRef(null);function qn(){Promise.resolve().then(()=>{let Z=0,be=se;const We=en.current;We&&(Array.from(We.children).forEach((lt,It)=>{T.current[se+It]=lt.offsetHeight,Z+=lt.offsetHeight,be++}),De(Z),_e(be))})}o.useEffect(()=>{ee&&p&&qn()},[ee,p,se]);let[on,Sr]=o.useState();o.useEffect(()=>{if(O&&(!M||!R.length||R.includes(O.row)))Sr({...O});else if(ee.length&&ae.data.length){if(!on||R.length&&!R.includes(on.row)||ee.findIndex(Z=>Z.id===on.row)===-1||ae.data.findIndex(Z=>Z.id===on.column&&!Z.collapsed)===-1){const Z=R[0]||ee[0].id,be=ae.data.findIndex(We=>!We.collapsed);Sr(be!==-1?{row:Z,column:ae.data[be].id}:null)}}else Sr(null)},[O]);const Un=o.useRef(null);o.useEffect(()=>{const Z=me.current;if(!Z)return;const be=QA(Z,h);return()=>{typeof be=="function"&&be()}},[h]);const Fn=o.useRef({});Object.assign(Fn.current,{start:_,move:je,end:Qe,getReorder:()=>U,getDraggableInfo:()=>({hasDraggable:xe()})}),o.useEffect(()=>{const Z=me.current;return Z?XA(Z,Fn).destroy:void 0},[U,me.current]),o.useEffect(()=>{const Z=me.current;return Z?GA(Z,{keys:v!==!1&&{...VA,"ctrl+z":G,"ctrl+y":G,...v},exec:be=>y.exec("hotkey",be)}).destroy:void 0},[y,G,v]);const Sn=o.useRef({scroll:y.getReactiveState().scroll,scrollLeft:y.getReactiveState().scrollLeft,scrollTop:y.getReactiveState().scrollTop});Sn.current.getWidth=()=>(m||0)-(ye?j:0),Sn.current.getHeight=()=>Ee,Sn.current.getScrollMargin=()=>te.width+Ce.width,o.useEffect(()=>{KA(Un.current,Sn.current)},[]);const rr=o.useRef(null);o.useEffect(()=>{const Z=rr.current;if(!Z)return;const be=[];be.push(ds(Z,()=>O&&y.exec("focus-cell",{eventSource:"click"})).destroy),be.push(XM(Z,Ke.current)),Q(Z.clientHeight);const We=new ResizeObserver(()=>{Q(Z.clientHeight)});return We.observe(Z),be.push(()=>We.disconnect()),()=>be.forEach(lt=>lt())},[]);const bt=`wx-grid ${w?`wx-responsive-${w}`:""}`;return o.useEffect(()=>{O&&(ee.some(Z=>Z.id===O.row)&&ae.data.some(Z=>Z.id===O.column&&!Z.collapsed)||y.exec("focus-cell",{eventSource:"destroy"}))},[O,ee,ae.data,y]),r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"wx-4VuBwK2D "+bt,style:{"--header-height":`${le}px`,"--footer-height":`${ce}px`,"--split-left-width":`${te.width}px`,"--split-right-width":`${Ce.width}px`},children:r.jsx("div",{ref:me,className:"wx-4VuBwK2D wx-table-box",style:Gt,role:D?"treegrid":"grid","aria-colcount":ae.data.length,"aria-rowcount":ee.length,"aria-multiselectable":D&&a?!0:void 0,tabIndex:-1,children:r.jsxs("div",{ref:Un,className:"wx-4VuBwK2D wx-scroll",style:{overflowX:J?"scroll":"hidden",overflowY:ye?"scroll":"hidden"},onScroll:He,children:[t?r.jsx("div",{className:"wx-4VuBwK2D wx-header-wrapper",children:r.jsx(dg,{contentWidth:pe,deltaLeft:ae.dh,columns:ae.header,columnStyle:u,bodyHeight:Ee-+n})}):null,r.jsxs("div",{ref:rr,className:"wx-4VuBwK2D wx-body",style:{width:`${pe}px`,height:`${mt}px`},onMouseDown:Z=>Be(Z),children:[s?r.jsx(hN,{overlay:s}):null,r.jsx("div",{ref:en,className:"wx-4VuBwK2D wx-data",style:{paddingTop:`${$e.d}px`,paddingLeft:`${ae.d}px`},children:ee.map((Z,be)=>{const We=I.indexOf(Z.id)!==-1,lt=Ae===Z.id,It="wx-row"+(p?" wx-autoheight":"")+(c?" "+c(Z):"")+(We?" wx-selected":"")+(lt?" wx-inactive":""),At=p?{minHeight:`${Z.rowHeight||oe}px`}:{height:`${Z.rowHeight||oe}px`};return r.jsx("div",{className:"wx-4VuBwK2D "+It,"data-id":mn(Z.id),"data-context-id":mn(Z.id),style:At,role:"row","aria-rowindex":be,"aria-expanded":Z.open,"aria-level":D?Z.$level+1:void 0,"aria-selected":D?We:void 0,tabIndex:-1,children:ae.data.map(et=>et.collapsed?r.jsx("div",{className:"wx-4VuBwK2D wx-cell wx-collapsed"},et.id):H?.id===Z.id&&H.column===et.id?r.jsx(xN,{row:Z,column:et},et.id):r.jsx(aN,{row:Z,column:et,columnStyle:u,cellStyle:d,reorder:U,focusable:on?.row===Z.id&&on?.column===et.id},et.id))},Z.id)})})]}),n&&(C||[]).length?r.jsx(dg,{type:"footer",contentWidth:pe,deltaLeft:ae.df,columns:ae.footer,columnStyle:u}):null]})})}),X?r.jsx(CN,{config:X,rowStyle:c,columnStyle:u,cellStyle:d,header:t,footer:n,reorder:U}):null]})}const MN=e=>e.split("-").map(t=>t?t.charAt(0).toUpperCase()+t.slice(1):"").join(""),AN=o.forwardRef(function({data:e=[],columns:t=[],rowStyle:n=null,columnStyle:s=null,cellStyle:a=null,selectedRows:i,select:c=!0,multiselect:u=!1,header:d=!0,footer:p=!1,dynamic:h=null,overlay:m=null,reorder:g=!1,onReorder:w=null,autoRowHeight:v=!1,sizes:y,split:k,tree:N=!1,autoConfig:C=!1,init:A=null,responsive:E=null,sortMarks:I,undo:F=!1,hotkeys:M=null,filterValues:H,...V},P){const D=o.useRef();D.current=V;const O=o.useMemo(()=>new BA($v),[]),X=o.useMemo(()=>O.in,[O]),G=o.useRef(null);G.current===null&&(G.current=new jv((Ce,Fe)=>{const Le="on"+MN(Ce);D.current&&D.current[Le]&&D.current[Le](Fe)}),X.setNext(G.current));const U=o.useMemo(()=>({getState:O.getState.bind(O),getReactiveState:O.getReactive.bind(O),getStores:()=>({data:O}),exec:X.exec,setNext:Ce=>(G.current=G.current.setNext(Ce),G.current),intercept:X.intercept.bind(X),on:X.on.bind(X),detach:X.detach.bind(X),getRow:O.getRow.bind(O),getColumn:O.getColumn.bind(O)}),[O,X]),[ie,j]=o.useState(0),[re,de]=o.useState(0),[Q,ge]=o.useState(null),[oe,me]=o.useState(null),Ae=o.useMemo(()=>{if(C&&!t.length&&e.length){const Ce=e[0],Fe=[];for(let Le in Ce)if(Le!=="id"&&Le[0]!=="$"){let Ue={id:Le,header:Le[0].toUpperCase()+Le.slice(1)};typeof C=="object"&&(Ue={...Ue,...C}),Fe.push(Ue)}return Fe}return(oe&&oe.columns)??t},[C,t,e,oe]),Te=o.useMemo(()=>(oe&&oe.sizes)??y,[oe,y]),Pe=o.useCallback(Ce=>{if(j(Ce.width),de(Ce.height),E){const Fe=Object.keys(E).map(Number).sort((Le,Ue)=>Le-Ue).find(Le=>Ce.width<=Le)??null;Fe!==Q&&(me(E[Fe]),ge(Fe))}},[E,Q]),Se=o.useContext(fn.theme),te=o.useRef(0);return o.useEffect(()=>{if(!te.current)A&&A(U);else{const Ce=O.getState();O.init({data:e,columns:Ae,split:k||Ce.split,sizes:Te||Ce.sizes,selectedRows:i||Ce.selectedRows,dynamic:h,tree:N,sortMarks:I||Ce.sortMarks,filterValues:H||Ce.filterValues,undo:F,reorder:g,_skin:Se,_select:c})}te.current++},[O,e,Ae,k,Te,i,h,N,I,H,F,g,Se,c,A,U]),te.current===0&&O.init({data:e,columns:Ae,split:k||{left:0},sizes:Te||{},selectedRows:i||[],dynamic:h,tree:N,sortMarks:I||{},filterValues:H||{},undo:F,reorder:g,_skin:Se,select:c}),o.useImperativeHandle(P,()=>({...U}),[U]),r.jsx(ur.Provider,{value:U,children:r.jsx(rm,{words:sm,optional:!0,children:r.jsx(kN,{header:d,footer:p,overlay:m,rowStyle:n,columnStyle:s,cellStyle:a,onReorder:w,multiselect:u,autoRowHeight:v,clientWidth:ie,clientHeight:re,responsiveLevel:Q,resize:Pe,hotkeys:M})})})});Yp(nr);const hn=o.createContext(null),om=o.createContext(null),cm=o.createContext(null);function NN({children:e}){const t=o.useContext(fn.i18n),n=o.useMemo(()=>t.getGroup("filemanager"),[t]),s=o.useContext(hn),[a]=xr(s,"panels"),i=dt(s,"activePanel"),c=a[i].path,[u,d]=o.useState(null),[p,h]=o.useState(null),[m,g]=o.useState(""),[w,v]=o.useState(""),[y,k]=o.useState(!1);function N(){const I=m.trim();if(!I){k(!0);return}u.add?s.exec("create-file",{file:{...u.item,name:I},parent:c}):w!==I&&s.exec("rename-file",{id:u.item.id,name:I}),C()}function C(){d(null),k(null),v(""),g("")}function A(){s.exec("delete-files",{ids:p.selected}),h(null)}const E=o.useMemo(()=>({showPrompt(I){const F=I.item.name||(I.item.type==="folder"?n("New folder"):`${n("New file")}.txt`);v(F),g(F),d({...I})},showConfirm(I){h({...I})}}),[n]);return r.jsxs(om.Provider,{value:E,children:[r.jsx(NM,{children:e}),u?r.jsx(Rp,{title:n(`Enter ${u.item.type} name`),onConfirm:N,onCancel:C,children:r.jsx(tm,{error:y,select:!0,focus:!0,value:m,onChange:({value:I})=>g(I)})}):null,p?r.jsx(Rp,{title:n("Are you sure you want to delete these items:"),onConfirm:A,onCancel:()=>h(null),children:p.selected?r.jsx("ul",{className:"wx-gq7BMzEP wx-list",children:p.selected.map((I,F)=>r.jsx("li",{children:I},F))}):null}):null]})}let mg={"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 RN(e){const t=e.lastIndexOf("."),n=t>0&&t<e.length-1?Math.min(10,e.length-t):Math.min(5,e.length),s=e.slice(0,-n),a=e.slice(-n);return[s,a]}function TN({item:e}){const t=o.useContext(hn),n=o.useContext(fn.i18n).getGroup("filemanager"),s=o.useContext(hn).templates,[a]=xr(t,"panels"),i=dt(t,"activePanel"),c=dt(t,"mode"),u=a[i].selected,d=o.useMemo(()=>s.preview(e,214,163),[s,e]),p=o.useMemo(()=>s.icon(e,"big"),[s,e]),[h,m]=o.useMemo(()=>RN(e.name),[e.name]);return r.jsx(r.Fragment,{children:e.id==="/wx-filemanager-parent-link"?c!=="search"?r.jsx("div",{className:"wx-GAOa4kDV wx-back-item",children:r.jsxs("div",{className:`wx-GAOa4kDV wx-back ${e.navigation?"wx-selected":""}`,"data-id":mn("/wx-filemanager-parent-link"),children:[r.jsx("i",{className:"wx-GAOa4kDV wxi-arrow-left"}),r.jsx("span",{children:n("Back to parent folder")})]})}):null:r.jsxs("div",{className:`wx-GAOa4kDV wx-item ${u?.length&&u.indexOf(e.id)>=0?"wx-selected":""}`,"data-id":mn(e.id),children:[d?r.jsx("div",{className:"wx-GAOa4kDV wx-preview wx-file-preview",children:r.jsx("img",{className:"wx-GAOa4kDV wx-card-preview",alt:n("A miniature file preview"),src:d})}):p?r.jsx("div",{className:"wx-GAOa4kDV wx-preview wx-file-icon",children:r.jsx("img",{className:"wx-GAOa4kDV wx-card-preview",alt:"",src:p})}):r.jsx("div",{className:"wx-GAOa4kDV wx-preview",children:r.jsx("i",{className:`wx-GAOa4kDV wxi-${e.type}`})}),e.type==="folder"?r.jsxs("div",{className:"wx-GAOa4kDV wx-info",children:[r.jsxs("div",{className:"wx-GAOa4kDV wx-folder-name",children:[r.jsx("span",{className:"wx-GAOa4kDV wx-type",children:n("Folder")}),r.jsxs("span",{className:"wx-GAOa4kDV wx-name",children:[r.jsx("span",{children:h}),r.jsx("span",{children:m})]})]}),r.jsx("div",{"data-action-id":mn(e.id),className:"wx-GAOa4kDV wx-more",children:r.jsx("i",{className:"wx-GAOa4kDV wxi-dots-v"})})]}):r.jsxs("div",{className:"wx-GAOa4kDV wx-info",children:[r.jsx("div",{className:"wx-GAOa4kDV wx-file-name",children:r.jsxs("span",{className:"wx-GAOa4kDV wx-name",children:[r.jsx("span",{children:h}),r.jsx("span",{children:m})]})}),r.jsx("div",{"data-action-id":mn(e.id),className:"wx-GAOa4kDV wx-more",children:r.jsx("i",{className:"wx-GAOa4kDV wxi-dots-v"})})]})]})})}function Zv(){const e=o.useContext(hn),t=o.useContext(fn.i18n),n=o.useMemo(()=>t.getGroup("filemanager"),[t]),[s]=xr(e,"panels"),a=dt(e,"activePanel"),i=dt(e,"mode"),c=s[a]._files,u=s[a].selected,d=s[a].path,p=s[a]._crumbs,h=s[a]._selectNavigation,m=o.useCallback((C,A)=>{const E=A&&(A.ctrlKey||A.metaKey),I=A&&A.shiftKey;if(C==="/wx-filemanager-parent-link"){if(u.length&&(E||I))return;e.exec("select-file",{type:"navigation"});return}let F=C==="body"&&A?null:C;const M=A.target.className.indexOf("wx-more")!==-1||A.target.className.indexOf("wxi-dots-v")!==-1;setTimeout(()=>{e.exec("select-file",{id:F,toggle:E&&!M,range:I&&!M,panel:a})},1)},[e,u,a]),g=o.useCallback(()=>{p.length>1&&e.exec("set-path",{id:p[p.length-2].id,panel:a,selected:[p[p.length-1].id]})},[e,p,a]),w=o.useCallback(C=>{if(C==="/wx-filemanager-parent-link")return g();i==="search"&&e.exec("filter-files",{text:""});const A=c.find(E=>E.id===C);A&&(A.type=="folder"?e.exec("set-path",{id:A.id,panel:a}):e.exec("open-file",{id:A.id}))},[e,g,i,c,a]),v=o.useCallback((C,A)=>{(!u?.length||!u.filter(E=>E?.id===C).length>0)&&m(C,A)},[u,m]),y=o.useMemo(()=>d!=="/"?[{id:"/wx-filemanager-parent-link",name:n("Back to parent folder"),navigation:h},...c]:c,[d,n,h,c]),k=o.useRef(null),N=o.useRef();return o.useEffect(()=>{k.current&&(N.current?(N.current.click=m,N.current._dblclick=w,N.current.context=v):(N.current={click:m,dblclick:C=>N.current._dblclick(C),_dblclick:w,context:v},ao(k.current,N.current)))},[m,w,v]),i=="search"&&!y.length?r.jsx("div",{className:"wx-iyjASZCY wx-not-found",children:r.jsx("div",{className:"wx-iyjASZCY wx-not-found-text",children:n("Looks like nothing is here")})}):r.jsx("div",{tabIndex:0,className:"wx-iyjASZCY "+("wx-cards"+(d!=="/"&&i!=="search"?" wx-has-back-link":"")),"data-id":mn("body"),ref:k,children:y.map(C=>r.jsx(TN,{item:C},C.id))})}function Qa({name:e="",spin:t=!1,onClick:n}){return r.jsx("i",{"data-menu-ignore":"true",className:`wx-uwcvNSAG wx-icon wxi-${e} ${t?"wx-spin":""} ${n?"wx-clickable":""}`,onClick:()=>{n&&n()}})}function PN(){const e=o.useContext(fn.i18n).getGroup("filemanager"),t=o.useContext(hn),n=dt(t,"activePanel"),[s]=xr(t,"panels"),a=o.useMemo(()=>s[n]._crumbs,[s,n]);function i(){t.exec("filter-files",{text:""})}return r.jsxs("div",{className:"wx-GDJvtROw wx-search",children:[r.jsxs("div",{className:"wx-GDJvtROw wx-toolbar",children:[r.jsx("div",{className:"wx-GDJvtROw wx-back-icon",children:r.jsx(Qa,{name:"angle-left",onClick:i})}),r.jsxs("div",{className:"wx-GDJvtROw wx-text",children:[e("Search results in")," ",Array.isArray(a)&&a.map((c,u)=>r.jsxs(o.Fragment,{children:[u?"/":null,c.id=="/"?e(c.name):c.name]},u))]})]}),r.jsx(Zv,{})]})}function Bd({narrowMode:e,extraInfo:t}){const n=o.useContext(hn),{preview:s,icon:a}=n.templates,i=o.useContext(fn.i18n),c=o.useMemo(()=>i.getGroup("filemanager"),[i]),u=o.useMemo(()=>eo("%D, %d %F %Y, %H:%i",i.getRaw().calendar),[i]),[d,p]=xr(n,"panels"),h=dt(n,"activePanel"),m=dt(n,"preview"),g=dt(n,"search"),w=o.useMemo(()=>{const M=d&&h!=null&&d[h]?._selected?.length||0;return g&&!M},[g,p,h]),v=o.useMemo(()=>{const M=d&&h!=null?d[h]:null;return M?w?M._files:M._selected:[]},[w,p,h]),y=o.useCallback((M,H)=>(M?`${M} ${c(M>1?"folders":"folder")} `:"")+(H?`${H} ${c(H>1?"files":"file")}`:""),[c]),k=o.useCallback(()=>{n.exec("show-preview",{mode:!m})},[n,m]),N=o.useCallback(M=>M.type==="folder"?c("Folder"):M.ext||c("Unknown file"),[c]),C=o.useMemo(()=>{let M,H,V,P,D,O,X,G;if(v.length===1&&!w){H=v[0],M=H.name;const U=s(H,400,500);U?(V=U,P=""):(P=a(H,"big"),V=""),D=H.type!=="folder"}else{if(H=D=null,M="",v.length){let U=0,ie=0,j=0,re=[],de;v.forEach(ge=>{typeof ge.size>"u"&&(de=!0,U=void 0),de||(U+=ge.size),re.push(N(ge)),ge.type==="folder"?ie++:j++});const Q=new Set(re);O=Q.size>1?c("multiple"):[...Q][0],X=y(ie,j),G=U,w||(M=c("Multiple files"))}P=a({type:w?"search":v.length?"multiple":"none"},"big"),V=""}return{name:M,item:H,previewSrc:V,iconSrc:P,showDownloadIcon:D,type:O,totalCount:X,totalSize:G}},[v,w,s,a,c,N,y]),A=o.useCallback(()=>{n.exec("download-file",{id:v[0].id})},[n,v]),E=o.useCallback(async M=>{if(!t||!M)return null;try{return await t(M)}catch(H){return console.log(H),null}},[t]),[I,F]=o.useState(null);return o.useEffect(()=>{let M=!1;return F(null),Promise.resolve(E(C.item)).then(H=>{M||F(H)}).catch(()=>{M||F(null)}),()=>{M=!0}},[E,C.item]),r.jsx("div",{className:"wx-O0BTtRrH wx-wrapper",children:v&&v.length?r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"wx-O0BTtRrH wx-preview",children:[r.jsxs("div",{className:"wx-O0BTtRrH wx-toolbar",children:[r.jsx("div",{className:"wx-O0BTtRrH wx-name",children:C.name}),r.jsxs("div",{className:"wx-O0BTtRrH wx-icons",children:[C.showDownloadIcon?r.jsx(Qa,{name:"download",onClick:A}):null,e?r.jsx(Qa,{name:"close",onClick:k}):null]})]}),C.previewSrc?r.jsx("div",{className:"wx-O0BTtRrH wx-img-wrapper",children:r.jsx("img",{src:C.previewSrc,alt:c("A miniature file preview")})}):C.iconSrc?r.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:r.jsx("img",{src:C.iconSrc,alt:c("A miniature file preview")})}):r.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:C.item?r.jsx("i",{className:`wx-O0BTtRrH wx-icon wxi-${C.item.type}`}):r.jsx("i",{className:`wx-O0BTtRrH wx-icon wxi-${w?"search":"file-multiple-outline"}`})})]}),r.jsxs("div",{className:"wx-O0BTtRrH wx-info-panel",children:[r.jsx("div",{className:"wx-O0BTtRrH wx-title",children:c(w?"Found":"Information")}),r.jsxs("div",{className:"wx-O0BTtRrH wx-list",children:[C.item?r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"wx-O0BTtRrH wx-name",children:c("Type")}),r.jsx("span",{className:"wx-O0BTtRrH wx-value",children:N(C.item)}),typeof C.item.size<"u"?r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"wx-O0BTtRrH wx-name",children:c("Size")}),r.jsx("span",{className:"wx-O0BTtRrH wx-value",children:dc(C.item.size)})]}):null,r.jsx("span",{className:"wx-O0BTtRrH wx-name",children:c("Date")}),r.jsxs("span",{className:"wx-O0BTtRrH wx-value",children:[u(C.item.date)," "]})]}):r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"wx-O0BTtRrH wx-name",children:c("Count")}),r.jsx("span",{className:"wx-O0BTtRrH wx-value",children:C.totalCount}),r.jsx("span",{className:"wx-O0BTtRrH wx-name",children:c("Type")}),r.jsx("span",{className:"wx-O0BTtRrH wx-value",children:C.type}),typeof C.totalSize<"u"?r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"wx-O0BTtRrH wx-name",children:c("Size")}),r.jsx("span",{className:"wx-O0BTtRrH wx-value",children:dc(C.totalSize)})]}):null]}),I?Object.entries(I).map(([M,H])=>r.jsxs(Dp.Fragment,{children:[r.jsx("span",{className:"wx-O0BTtRrH wx-name",children:M}),r.jsx("span",{className:"wx-O0BTtRrH wx-value",children:H})]},M)):null]})]})]}):r.jsxs("div",{className:"wx-O0BTtRrH wx-no-info-panel",children:[r.jsxs("div",{className:"wx-O0BTtRrH wx-toolbar",children:[r.jsx("div",{className:"wx-O0BTtRrH wx-name",children:C.name}),r.jsx("div",{className:"wx-O0BTtRrH wx-icons",children:e?r.jsx(Qa,{name:"close",onClick:k}):null})]}),r.jsx("div",{className:"wx-O0BTtRrH wx-no-info-wrapper",children:r.jsxs("div",{className:"wx-O0BTtRrH wx-no-info",children:[C.previewSrc?r.jsx("div",{className:"wx-O0BTtRrH wx-img-wrapper",children:r.jsx("img",{src:C.previewSrc,alt:c("A miniature file preview")})}):C.iconSrc?r.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:r.jsx("img",{src:C.iconSrc,alt:c("A miniature file preview")})}):r.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:r.jsx("i",{className:`wx-O0BTtRrH wx-icon wxi-${w?"search":"message-question-outline"}`})}),r.jsx("span",{className:"wx-O0BTtRrH wx-text",children:w?"":c("Select file or folder to view details")})]})})]})})}function ew({panel:e}){const t=o.useContext(hn),n=o.useContext(fn.i18n),s=o.useMemo(()=>n.getGroup("filemanager"),[n]),[a,i]=xr(t,"panels"),c=o.useMemo(()=>a[e]._files,[i,e]),u=o.useMemo(()=>a[e]._crumbs||[],[i,e]);function d(v){const y=am(v,u);t.exec("set-path",{id:v,panel:e,...y&&{selected:[y]}})}const[p,h]=o.useState(null);o.useEffect(()=>{c&&h(null)},[c]);function m(){h(!0),t.exec("request-data",{id:u[u.length-1].id}),setTimeout(()=>{h(null)},5e3)}const g=o.useRef(null),w=o.useRef();return o.useEffect(()=>{w.current?w.current.click=d:(w.current={click:d},ao(g.current,w.current))},[d]),r.jsxs("div",{className:"wx-SNY5LTYx wx-breadcrumbs","data-menu-ignore":"true",ref:g,children:[r.jsx("div",{className:"wx-SNY5LTYx wx-refresh-icon",children:r.jsx(Qa,{name:"refresh",spin:!!p,onClick:m})}),u.map((v,y)=>r.jsxs(Dp.Fragment,{children:[y?r.jsx(Qa,{name:"angle-right"}):null,r.jsx("div",{className:"wx-SNY5LTYx wx-item","data-id":mn(v.id),"data-menu-ignore":"true",children:v.id=="/"?s(v.name):v.name})]},y))]})}function IN({row:e}){const t=o.useContext(fn.i18n),[n]=o.useState(()=>t.getGroup("filemanager")),s=o.useContext(hn).templates,[a]=o.useState(()=>s.icon(e,"small"));return r.jsx("div",{className:"wx-qgAqG6sL wx-name-cell",children:e.id==="/wx-filemanager-parent-link"?r.jsxs(r.Fragment,{children:[r.jsx("i",{className:"wx-qgAqG6sL wxi-arrow-left"}),r.jsxs("span",{className:"wx-qgAqG6sL wx-name",children:[" ",n("Back to parent folder")]})]}):r.jsxs(r.Fragment,{children:[a?r.jsx("img",{className:"wx-qgAqG6sL wx-icon",alt:"",src:a,height:"24px",width:"24px"}):r.jsx("i",{className:`wx-qgAqG6sL wxi-${e.type}`}),r.jsxs("span",{className:"wx-qgAqG6sL wx-name",children:[" ",e.name," "]})]})})}function tw({children:e}){const t=o.useContext(hn),n=dt(t,"activePanel"),s=o.useContext(cm),a=o.useRef(null);let i=o.useRef({});return i.current.drop=()=>{const c=a.current,u=Fk(c,"data-panel");u&&u!=n&&t.exec("set-active-panel",{panel:u*1})},i.current.dragEnter=()=>{const c=a.current;c&&c.classList.toggle("wx-active")},i.current.dragLeave=()=>{const c=a.current;c&&c.classList.toggle("wx-active")},o.useEffect(()=>{const c=a.current;return s.droparea(c,i.current)},[]),r.jsx("div",{className:"wx-LT9X7tb7 wx-upload-area",ref:a,children:e})}function Ip({panel:e,active:t=!1,onClick:n,onContextMenu:s}){const a=o.useContext(hn),i=o.useContext(fn.i18n),c=o.useMemo(()=>i.getGroup("filemanager"),[i]),u=o.useMemo(()=>eo("%d %M %Y",i.getRaw().calendar),[i]),[d]=xr(a,"panels"),p=d[e].selected,h=d[e].path,m=d[e]._crumbs,g=d[e]._sorts,w=d[e]._selectNavigation,v=d[e]._files,y=o.useMemo(()=>[{id:"name",header:c("Name"),flexgrow:3,sort:!0,resize:!0,cell:IN},{id:"size",header:c("Size"),width:100,sort:!0,resize:!0,template:O=>typeof O=="number"?dc(O):""},{id:"date",header:c("Date"),width:120,sort:!0,resize:!0,template:O=>O?u(O):""}],[c,u]),k=o.useRef(null),N=o.useRef(null),C=o.useMemo(()=>w?["/wx-filemanager-parent-link"]:[...p],[w,p]);function A(O,X){if(X&&X.target&&X.target.className&&X.target.className.indexOf("wx-grip")!==-1)return;const G=X&&(X.ctrlKey||X.metaKey),U=X&&X.shiftKey;if(O==="/wx-filemanager-parent-link"){if(p.length&&(G||U))return;a.exec("select-file",{type:"navigation"});return}let ie=O==="body"&&X?null:O;!k.current&&!N.current?a.exec("select-file",{id:ie,toggle:G,range:U,panel:e}):(k.current=null,N.current=null)}function E(){m.length>1&&a.exec("set-path",{id:m[m.length-2].id,panel:e,selected:[m[m.length-1].id]})}function I(O){if(O==="/wx-filemanager-parent-link")return E();const X=v.find(G=>G.id===O);X&&(X.type==="folder"?a.exec("set-path",{id:X.id,panel:e}):a.exec("open-file",{id:X.id}))}function F(O){const X=O.key,G=g[h];let U=G?"asc":"desc";G&&G.key===X&&(U=G.order==="asc"?"desc":"asc"),a.exec("sort-files",{key:X,order:U,panel:e,path:h})}function M(O){O.intercept("sort-rows",X=>(k.current=!0,F(X),!1)),O.intercept("select-row",()=>!1),O.on("resize-column",()=>N.current=!0),O.intercept("hotkey",()=>!1)}const H=o.useMemo(()=>h!=="/"?[{id:"/wx-filemanager-parent-link",name:c("Back to parent folder")},...v]:v,[h,v,c]),V=o.useMemo(()=>{if(H&&g&&g[h]){const{key:O,order:X}=g[h];return{[O]:{order:X}}}},[H,g,h]),P=o.useRef(null),D=o.useRef();return o.useEffect(()=>{D.current?(D.current.click=A,D.current._dblclick=I):(D.current={click:A,dblclick:O=>D.current._dblclick(O),_dblclick:I},ao(P.current,D.current))},[A,I]),r.jsxs("div",{onClick:n,onContextMenu:s,className:"wx-SSaVhET7 wx-wrapper",children:[r.jsx(ew,{panel:e}),r.jsx("div",{"data-id":mn("body"),className:`wx-SSaVhET7 wx-list ${t?"wx-active":""}`,ref:P,children:r.jsx(tw,{children:r.jsx(AN,{init:M,data:H,columns:y,selectedRows:C,columnStyle:()=>"wx-SSaVhET7 wx-each-cell",sizes:{rowHeight:42,headerHeight:42},sortMarks:V})})})]})}function jN(){const e=o.useContext(hn),t=dt(e,"activePanel");function n(s){e.exec("set-active-panel",{panel:s})}return r.jsxs("div",{className:"wx-L55BfJa2 wx-panels","data-id":mn("body"),children:[r.jsx("div",{className:"wx-L55BfJa2 wx-item","data-panel":0,children:r.jsx(Ip,{panel:0,active:t==0,onClick:()=>n(0),onContextMenu:()=>n(0)})}),r.jsx("div",{className:"wx-L55BfJa2 wx-item","data-panel":1,children:r.jsx(Ip,{panel:1,active:t==1,onClick:()=>n(1),onContextMenu:()=>n(1)})})]})}function nw({folderIcon:e=!1,folder:t={}}){const n=o.useContext(hn),[s,a]=xr(n,"panels"),i=dt(n,"activePanel"),c=o.useMemo(()=>s[i].path,[a,i]),u=o.useContext(fn.i18n),d=o.useMemo(()=>u.getGroup("filemanager"),[u]),p=o.useMemo(()=>!!t.data?.find(w=>w.type==="folder"),[t]),h=o.useMemo(()=>t.id=="/"?d(t.name):t.name,[t,d]),m=o.useMemo(()=>t.$level>1?(t.$level-1)*20:0,[t]),g=t.open;return r.jsxs(r.Fragment,{children:[r.jsxs("li",{"data-id":mn(t.id),className:`wx-NYfhvGIt wx-folder${c===t.id?" wx-selected":""}`,style:{paddingLeft:`${m}px`},children:[p?r.jsx("i",{className:`wx-NYfhvGIt wx-toggle wxi-${g?"angle-down":"angle-right"}`,"data-action":"toggle"}):r.jsx("span",{className:"wx-NYfhvGIt wx-toggle-placeholder"}),r.jsx("i",{className:"wx-NYfhvGIt "+(e||"wxi-folder")}),r.jsxs("span",{className:"wx-NYfhvGIt wx-name",children:[" ",h," "]})]}),g&&t.data&&t.data.length&&p?r.jsx(r.Fragment,{children:t.data.map(w=>w.type==="folder"?r.jsx(nw,{folder:w},w.id):null)}):null]})}function EN(){const e=o.useContext(hn),[t,n]=xr(e,"data"),[s,a]=xr(e,"panels"),i=dt(e,"activePanel"),c=o.useMemo(()=>s[i]._crumbs,[a,i]),u=o.useCallback(w=>{e.exec("open-tree-folder",{id:w,mode:!t.byId(w).open})},[e,n]),d=o.useCallback(w=>{const v=am(w,c);e.exec("set-path",{id:w,panel:i,...v&&{selected:[v]}})},[e,c,i]),[p,h]=o.useState([]);o.useEffect(()=>{h(t.byId(0).data)},[n]);const m=o.useRef(null),g=o.useRef();return o.useEffect(()=>{g.current?(g.current.click=d,g.current.toggle=u):(g.current={click:d,toggle:u},ao(m.current,g.current))},[d,u]),r.jsx("ul",{ref:m,className:"wx-LyHJ6R6A",children:p.map(w=>w.type==="folder"?r.jsx(nw,{folder:w},w.id):null)})}function FN(){const e=o.useContext(hn),t=o.useContext(fn.i18n),n=o.useMemo(()=>t.getGroup("filemanager"),[t]),s=dt(e,"drive"),a=s?s.used:"",i=s?s.total:"";return a&&i?r.jsxs("div",{className:"wx-DetSyKGG wx-drive",children:[r.jsx("progress",{value:a,max:i,className:"wx-DetSyKGG wx-progress"}),r.jsxs("p",{children:[dc(a)," ",n("of")," ",dc(i)," ",n("used")]})]}):null}function DN({option:e}){const t=o.useContext(fn.i18n).getGroup("filemanager"),n=o.useContext(cm),s=o.useCallback(()=>{n.open({})},[n]);return r.jsx("div",{className:"wx-9XiKcxq5 wx-upload-button",onClick:s,children:r.jsx("span",{children:t(e.text)})})}function LN({readonly:e,menuOptions:t}){const n=o.useContext(fn.i18n).getGroup("filemanager"),{showPrompt:s}=o.useContext(om);o.useEffect(()=>{eA("upload",DN)},[]);function a({action:c}){c&&(c.id==="add-file"?s({item:{type:"file",size:0,date:new Date},add:!0}):c.id==="add-folder"&&s({item:{type:"folder",date:new Date},add:!0}))}const i=o.useMemo(()=>t("add").map(c=>(c.text=n(c.text),c)),[t,n]);return r.jsxs("div",{className:"wx-FlucfALM wx-wrapper",children:[!e&&r.jsx("div",{className:"wx-FlucfALM wx-button",children:r.jsx(nA,{options:i,at:"bottom-fit",onClick:a,children:r.jsx(rc,{type:"primary block",children:n("Add New")})})}),r.jsx("div",{className:"wx-FlucfALM wx-tree",children:r.jsx(EN,{})}),r.jsx(FN,{})]})}function _N({value:e="",onSearch:t}){const[n,s]=Lv(e),a=o.useContext(fn.i18n).getGroup("filemanager"),i=o.useRef(null),c=o.useMemo(()=>n!==""?"wxi-close":"wxi-search",[n]);function u(p){const h=p.target.value;s(h),t&&t({value:h})}function d(){s(""),i.current&&i.current.focus(),t&&t({value:""})}return r.jsxs("div",{className:"wx-lUZMtgT1 wx-search-input",children:[r.jsx("i",{className:`wx-lUZMtgT1 wx-icon ${c}`,onClick:d}),r.jsx("input",{type:"text",className:"wx-lUZMtgT1 wx-text",ref:i,value:n,onInput:u,placeholder:a("Search")})]})}function $N({narrowMode:e=!1,onShowTree:t}){const n=o.useContext(hn),s=o.useContext(fn.i18n).getGroup("filemanager"),a=dt(n,"mode"),i=dt(n,"preview"),c=dt(n,"search"),u=[{icon:"wxi-view-sequential",id:"table"},{icon:"wxi-view-grid",id:"cards"},{icon:"wxi-view-column",id:"panels"}];function d({value:m}){n.exec("set-mode",{mode:m})}function p(m){m.preventDefault(),n.exec("show-preview",{mode:!i})}function h(m){n.exec("filter-files",{text:m.value})}return r.jsxs("div",{className:"wx-5PZQQztG wx-toolbar",children:[r.jsxs("div",{className:"wx-5PZQQztG wx-left "+(e?"wx-left-narrow":""),children:[e?a==="panels"||a==="search"?null:r.jsx("div",{className:"wx-5PZQQztG wx-sidebar-icon","data-id":mn("toggle-tree"),children:r.jsx(Qa,{onClick:()=>t&&t(),name:"subtask"})}):r.jsx("div",{className:"wx-5PZQQztG wx-name",children:s("Files")}),r.jsx(_N,{onSearch:h,value:c})]}),r.jsxs("div",{className:"wx-5PZQQztG wx-right",children:[e?null:r.jsx("div",{className:"wx-5PZQQztG wx-preview-icon",children:r.jsx(RM,{onClick:p,value:i,children:r.jsx("i",{className:"wx-5PZQQztG wxi-eye"})})}),r.jsx("div",{className:"wx-5PZQQztG wx-modes",children:r.jsx(SM,{value:a,options:u,onChange:d})})]})]})}function ON(){const e=o.useContext(hn),t=dt(e,"activePanel");return r.jsxs("div",{className:"wx-NwohNJzN wx-wrapper",children:[r.jsx(ew,{panel:t}),r.jsx(tw,{children:r.jsx(Zv,{})})]})}function BN({readonly:e=!1,menuOptions:t,extraInfo:n}){const s=o.useRef(null),a=o.useRef(null),[i,c]=o.useState(void 0),[u,d]=o.useState(void 0),[p,h]=o.useState(!1),m=zv(),g=o.useContext(hn),{showPrompt:w,showConfirm:v}=o.useContext(om),y=o.useContext(fn.i18n),k=o.useMemo(()=>y.getGroup("filemanager"),[y]),N=dt(g,"mode"),C=dt(g,"preview"),A=dt(g,"activePanel"),[E,I]=xr(g,"panels"),F=o.useMemo(()=>(E&&A!=null?E[A]:null)?.selected??[],[I,A]),M=o.useMemo(()=>(E&&A!=null?E[A]:null)?.path,[I,A]),[H,V]=o.useState([]);o.useEffect(()=>{const Q=s.current;if(!Q)return;const ge=new ResizeObserver(oe=>{const me=oe[0]?.borderBoxSize?.[0]?.inlineSize;typeof me=="number"&&d(me<768)});return ge.observe(Q),()=>{ge.disconnect()}},[]);const P=o.useCallback(()=>{h(Q=>!Q)},[]),D=o.useCallback(Q=>{u&&uc(Q)!=="toggle-tree"&&h(!1)},[u]);o.useEffect(()=>{const Q=a.current;if(Q)return ds(Q,D).destroy},[D]),o.useEffect(()=>{const Q=a.current;if(!Q)return;const ge=new ResizeObserver(()=>{Q&&c(Q.clientWidth)});return ge.observe(Q),Q&&c(Q.clientWidth),()=>{ge.disconnect()}},[]);const O=o.useMemo(()=>({icon:"wxi-eye",text:"Preview",id:"preview"}),[]),X=o.useCallback(Q=>{let ge=u?[O]:[];return Q==="file"&&(ge=[...ge,...t().filter(oe=>oe.id==="download")]),ge},[u,O,t]),G=o.useRef(null),U=o.useCallback((Q,ge,oe)=>{const me=oe?[ge.id]:F;switch(Q){case"download":g.exec("download-file",{id:ge.id});break;case"copy":case"move":G.current={action:Q,ids:me};break;case"paste":G.current&&g.exec(G.current.action==="copy"?"copy-files":"move-files",{ids:G.current.ids,target:ge?.type==="folder"?ge.id:M});break;case"rename":w({item:ge});break;case"delete":v({selected:me});break;case"preview":g.exec("show-preview",{mode:!C});break}},[g,F,M,w,v,C]),ie=o.useCallback(()=>E?.[A],[E,A]);o.useEffect(()=>{const Q=s.current;if(!Q)return;const ge=zM(Q,{api:g,menuOptions:e?X:t,performAction:U,getPanel:ie});return()=>{typeof ge=="function"?ge():ge&&typeof ge.destroy=="function"&&ge.destroy()}},[g,e,X,t,U,ie]);const j=o.useCallback((Q,ge)=>{const oe=Q?g.getFile(Q):null,me=ge.target.closest(".tree-item.folder");let Ae;if(e)Ae=X(oe?.type);else{switch(Q){case"body":Ae=t(Q);break;default:if(oe)if(!me&&F.length>1)Ae=u?[O,...t("multiselect")]:t("multiselect");else if(Q==="/")Ae=t("folder",oe).filter(Te=>Te.id==="paste");else{const Te=t(oe.type,oe);Te&&(Ae=u?[O,...Te]:Te)}}N==="search"&&(Ae=Ae?.filter(Te=>Te.id!=="paste"))}if(oe?.id&&(!F.length||!F.some(Te=>Te===oe.id))&&!me&&g.exec("select-file",{id:oe.id}),Ae?.length)return Ae.forEach(Te=>{me&&(Te.hotkey=""),Te.text&&(Te.text=k(Te.text)),Te.hotkey&&(Te.subtext=Te.hotkey)}),V(Ae),oe||{}},[g,e,X,t,F,u,O,N,k]),re=o.useCallback(Q=>{const{action:ge,context:oe}=Q;ge&&U(ge.id,oe,!ge.hotkey)},[U]);async function de(Q){await Promise.resolve();const{name:ge,size:oe}=Q.file;g.exec("create-file",{file:{name:ge,size:oe,date:new Date,file:Q.file},parent:M})}return r.jsx("div",{className:"wx-RJbNonjJ wx-filemanager wx-flex",ref:s,"data-menu-ignore":"false",children:u&&C?r.jsx("div",{className:"wx-RJbNonjJ wx-info-narrow",children:r.jsx(Bd,{narrowMode:u,extraInfo:n})}):r.jsxs(r.Fragment,{children:[r.jsx($N,{narrowMode:u,onShowTree:P}),r.jsx(rA,{dataKey:"id",at:"point",options:H,resolver:j,onClick:re,children:r.jsxs(Wv,{dataKey:"actionId",options:H,resolver:j,onClick:re,children:[r.jsx(cA,{data:m,apiOnly:!0,uploadURL:de}),r.jsx(cm.Provider,{value:m,children:r.jsx("div",{className:"wx-RJbNonjJ wx-content-wrapper wx-flex",children:N!=="panels"&&N!=="search"?r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"wx-RJbNonjJ "+["wx-sidebar",u?"wx-sidebar-narrow":"",p?"wx-sidebar-visible":""].filter(Boolean).join(" "),ref:a,children:r.jsx(LN,{readonly:e,menuOptions:t})}),r.jsxs("div",{className:"wx-RJbNonjJ wx-content",style:{width:`calc(100% - ${i||0}px - 10px)`},children:[r.jsx("div",{className:`wx-RJbNonjJ wx-content-item${C?"":"-fit"}`,"data-id":mn("body"),children:N==="table"?r.jsx(Ip,{panel:A}):r.jsx(ON,{})}),C?r.jsx("div",{className:"wx-RJbNonjJ wx-info",children:r.jsx(Bd,{extraInfo:n})}):null]})]}):r.jsxs(r.Fragment,{children:[r.jsx("div",{className:`wx-RJbNonjJ wx-content-item${C?"":"-fit"}`,children:N==="panels"?r.jsx(jN,{}):r.jsx(PN,{})}),C?r.jsx("div",{className:"wx-RJbNonjJ wx-info",children:r.jsx(Bd,{extraInfo:n})}):null]})})})]})})]})})}const HN=e=>e.split("-").map(t=>t?t.charAt(0).toUpperCase()+t.slice(1):"").join("");function WN(e,t){const{type:n,ext:s}=e;if(n==="folder")return!1;let a;return n&&n!=="file"&&mg[n]?a=n:s?a=mg[s]?s:"file":a="unknown",`https://cdn.svar.dev/icons/filemanager/vivid/${t}/${a}.svg`}const zN=o.forwardRef(function(e,t){const{data:n=[],mode:s="cards",drive:a=null,preview:i=!1,panels:c=null,activePanel:u=0,readonly:d=!1,menuOptions:p=BM,extraInfo:h=null,init:m=null,icons:g=WN,previews:w=null,...v}=e,y=o.useRef();y.current=v;const k=o.useMemo(()=>new OM($v),[]),N=o.useMemo(()=>k.in,[k]),C=o.useRef(null);C.current===null&&(C.current=new jv((I,F)=>{const M="on"+HN(I);y.current&&y.current[M]&&y.current[M](F)}),N.setNext(C.current));const A=o.useMemo(()=>({getState:k.getState.bind(k),getReactiveState:k.getReactive.bind(k),getStores:()=>({data:k}),exec:N.exec,setNext:I=>(C.current=C.current.setNext(I),C.current),intercept:N.intercept.bind(N),on:N.on.bind(N),detach:N.detach.bind(N),getFile:k.getFile.bind(k),serialize:k.serialize.bind(k),templates:{preview:w||(()=>null),icon:g==="simple"?(()=>null):g}}),[k,N]),E=o.useRef(0);return o.useEffect(()=>{if(!E.current)m&&m(A);else{const I=k.getState();k.init({data:n,mode:s,drive:a,preview:i,panels:c||I.panels||[],activePanel:u})}E.current++},[k,n,s,a,i,c,u,m,A]),E.current===0&&k.init({data:n,mode:s,drive:a,preview:i,panels:c||[],activePanel:u}),o.useImperativeHandle(t,()=>({...A}),[A]),r.jsx(hn.Provider,{value:A,children:r.jsx(rm,{words:sm,optional:!0,children:r.jsx(NN,{children:r.jsx(BN,{readonly:d,menuOptions:p,extraInfo:h})})})})});function qN({fonts:e=!0,children:t}){return t?r.jsx(Jf,{fonts:e,children:t}):r.jsx(Jf,{fonts:e})}Yp(nr);function lm(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Invalid Hub ${t} response.`);return e}function gc(e,t,n){const s=lm(e,n);if(!Array.isArray(s[t]))throw new Error(`Invalid Hub ${n} response: ${t} must be an array.`);return s[t]}function UN(e,t,n){const s=lm(e,n);if(!s[t]||typeof s[t]!="object"||Array.isArray(s[t]))throw new Error(`Invalid Hub ${n} response: ${t} must be an object.`);return s[t]}async function VN(e,t=!1){return gc(await Oe(`/api/remote/filesystem/roots${t?"?refresh=1":""}`,void 0,e),"roots","filesystem roots")}async function Hd(e,t){const n=await Oe(`/api/remote/filesystem/entries?id=${encodeURIComponent(e)}`,void 0,t);return{folder:UN(n,"folder","filesystem entries"),entries:gc(n,"entries","filesystem entries")}}async function GN(e,t){return Oe("/api/remote/filesystem/selection/scan",{method:"POST",body:JSON.stringify({itemIds:e})},t)}async function KN(e,t,n,s){return Oe("/api/remote/files/from-hub",{method:"POST",body:JSON.stringify({itemIds:e,deviceIds:t,remoteDirectory:n})},s)}async function QN(e,t=!1){const n=await Oe(`/api/remote/files/jobs?active=${t?"1":"0"}`,void 0,e);return{jobs:gc(n,"jobs","file transfer jobs")}}async function YN(e,t){return Oe(`/api/remote/files/jobs/${encodeURIComponent(e)}`,void 0,t)}async function XN(e,t){return Oe(`/api/remote/files/jobs/${encodeURIComponent(e)}/cancel`,{method:"POST"},t)}async function hg(e){return gc(await Oe("/api/remote/filesystem/shared-folders",void 0,e),"folders","shared folders")}async function JN(e,t){return Oe("/api/remote/filesystem/shared-folders",{method:"POST",body:JSON.stringify({sourceId:e})},t)}async function ZN(e,t,n){return Oe(`/api/remote/filesystem/shared-folders/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)},n)}async function eR(e,t){return Oe(`/api/remote/filesystem/shared-folders/${encodeURIComponent(e)}`,{method:"DELETE"},t)}async function tR(e,t,n,s){const a=await Oe(`/api/remote/filesystem/shared-folders/${encodeURIComponent(e)}/sync`,{method:"POST",body:JSON.stringify({deviceIds:t,remoteDirectory:n})},s),i=lm(a,"shared folder sync");return{ok:i.ok===!0,jobs:gc(a,"jobs","shared folder sync"),files:Number(i.files||0),totalBytes:Number(i.totalBytes||0)}}function nR(e){return{id:String(e.id),parentId:e.parent,name:e.name,type:e.type==="file"?"file":"folder",size:Number(e.size||0),modifiedAt:e.date?.toISOString()||null,displayPath:String(e.displayPath||e.name),hasChildren:e.lazy===!0||!!e.data?.length,locked:e.locked===!0}}function fg(e){if(!Number.isFinite(e)||e<=0)return"0 B";const t=["B","KB","MB","GB","TB"];let n=e,s=0;for(;n>=1024&&s<t.length-1;)n/=1024,s+=1;return`${n.toFixed(s===0||n>=100?0:1)} ${t[s]}`}function Zl(e){return e.driveType==="network"?"network":e.driveType==="removable"?"removable":"local"}function rR(e){const t=e.filter(n=>Zl(n)==="local");return t.find(n=>/\bC:/i.test(`${n.name} ${n.displayPath||""}`))||t[0]||e[0]||null}function sR(e){const t=String(e.displayPath||"").trim();if(t)return t;const n=String(e.name||"").match(/\(([A-Za-z]:)\)/)?.[1];return n?`${n}\\`:e.name}function aR({hubUrl:e,roots:t,loading:n,error:s,onRefreshRoots:a,onImportFiles:i,onImportFolder:c,onSelectionChange:u,onShareItem:d,onAddSyncFolder:p,onNotice:h}){const m=o.useRef(null),g=o.useRef("/"),w=o.useRef(0),v=o.useRef([]),y=o.useRef(new Map),[k,N]=o.useState(null),[C,A]=o.useState([]),[E,I]=o.useState([]),[F,M]=o.useState(0),[H,V]=o.useState(null),[P,D]=o.useState(!1),[O,X]=o.useState(""),[G,U]=o.useState(new Set),ie=t.find(ne=>ne.id===k)||null,j=C[C.length-1]||null,re=ie?j?.svarPath||`/${ie.name}`:null,de=re;o.useEffect(()=>{v.current=C,g.current=de||"/"},[de,C]);const Q=o.useMemo(()=>(y.current.clear(),!ie||!de||C.length===0?[]:(C.forEach(ne=>y.current.set(ne.svarPath,ne.hubId)),[...C.map((ne,ae)=>({id:ne.svarPath,parent:ae===0?"/":C[ae-1].svarPath,type:"folder",name:ne.name,date:ne.modifiedAt?new Date(ne.modifiedAt):void 0,lazy:!1})),...E.map(ne=>{const ae=`${de}/${ne.name}`;return y.current.set(ae,ne.id),{id:ae,parent:de,name:ne.name,type:ne.type==="file"?"file":"folder",...ne.type==="file"?{size:ne.size}:{},date:ne.modifiedAt?new Date(ne.modifiedAt):void 0,lazy:ne.type!=="file"&&ne.hasChildren===!0,displayPath:ne.displayPath,locked:ne.locked,driveType:ne.driveType,totalBytes:ne.totalBytes,freeBytes:ne.freeBytes}})])),[ie,E,de,C]),ge=ne=>y.current.get(String(ne))||String(ne),oe=ne=>nR({...ne,id:ge(String(ne.id)),parent:ge(String(ne.parent))}),me=async(ne,ae)=>{const le=ne[ne.length-1];if(!le)return;const ce=++w.current;D(!0),X("");try{const J=await Hd(le.hubId,e);if(ce!==w.current)return;if(!Array.isArray(J.entries))throw new Error("Invalid Hub filesystem entries response.");const ye={...le,displayPath:J.folder.displayPath||le.displayPath,modifiedAt:J.folder.modifiedAt||le.modifiedAt},ue=[...ne.slice(0,-1),ye];v.current=ue,A(ue),I(J.entries),M(Ee=>Ee+1)}catch(J){if(ce!==w.current)return;console.error("[LiveDesk FS] folder navigation failed",{folderId:le.hubId,error:J}),X(J instanceof Error?`${ae}: ${J.message}`:`${ae}: Unable to read this folder.`)}finally{ce===w.current&&D(!1)}},Ae=async ne=>{const ae={svarPath:`/${ne.name}`,hubId:ne.id,name:ne.name,pathLabel:sR(ne),displayPath:ne.displayPath,modifiedAt:ne.modifiedAt},le=++w.current;N(ne.id),v.current=[ae],A([ae]),g.current=ae.svarPath,I([]),X(""),D(!0),V(ne.id),U(ce=>{const J=new Set(ce);return J.delete(ne.id),J});try{const ce=await Hd(ne.id,e);if(le!==w.current)return;if(!Array.isArray(ce.entries))throw new Error("Invalid Hub filesystem entries response.");const J={...ae,pathLabel:ce.folder.displayPath||ae.pathLabel,displayPath:ce.folder.displayPath||ae.displayPath,modifiedAt:ce.folder.modifiedAt||ae.modifiedAt};v.current=[J],A([J]),I(ce.entries),M(ye=>ye+1)}catch(ce){if(le!==w.current)return;console.error("[LiveDesk FS] getEntries failed",{rootId:ne.id,error:ce}),U(J=>new Set(J).add(ne.id)),X(ce instanceof Error?`${ne.name}: ${ce.message}`:`${ne.name}: Unable to read this drive.`),h(ce instanceof Error?`${ne.name}: ${ce.message}`:`${ne.name}: Unable to read this drive.`)}finally{le===w.current&&(V(null),D(!1))}},Te=ne=>{const ae=v.current;ne<0||ne>=ae.length||ne===ae.length-1||me(ae.slice(0,ne+1),ae[ne].name)},Pe=(ne,ae)=>{if(ne.type!=="folder")return;const le=v.current,ce=le.findIndex(ye=>ye.svarPath===ae);if(ce<0)return;const J={svarPath:`${ae}/${ne.name}`,hubId:ne.id,name:ne.name,pathLabel:ne.name,displayPath:ne.displayPath,modifiedAt:ne.modifiedAt};me([...le.slice(0,ce+1),J],ne.name)},Se=()=>Te(v.current.length-2),te=ne=>{if(ne.key!=="Enter"&&ne.code!=="Enter"&&ne.code!=="NumpadEnter"||ne.target?.closest('button, input, textarea, [contenteditable="true"]'))return;const le=m.current;if(!le)return;const ce=le.getState().panels?.flatMap(ye=>ye.selected||[])||[];if(ce.length!==1)return;const J=le.getFile(String(ce[0]));J?.type==="folder"&&(ne.preventDefault(),ne.stopPropagation(),Pe(oe(J),String(J.parent||g.current)))};o.useEffect(()=>{const ne=t.find(ae=>ae.id===k)||rR(t);if(U(ae=>new Set([...ae].filter(le=>t.some(ce=>ce.id===le)))),!ne){N(null),v.current=[],A([]),I([]);return}Ae(ne)},[t]);const Ce=ne=>{m.current=ne,ne.on("request-data",async({id:ae})=>{const le=String(ae),ce=ge(le);try{const J=await Hd(ce,e);if(!Array.isArray(J.entries))throw new Error("Invalid Hub filesystem entries response.");const ye=J.entries.map(ue=>{const Ee=`${le}/${ue.name}`;return y.current.set(Ee,ue.id),{id:Ee,parent:le,name:ue.name,type:ue.type==="file"?"file":"folder",...ue.type==="file"?{size:ue.size}:{},date:ue.modifiedAt?new Date(ue.modifiedAt):void 0,lazy:ue.type!=="file"&&ue.hasChildren===!0,displayPath:ue.displayPath,locked:ue.locked,driveType:ue.driveType,totalBytes:ue.totalBytes,freeBytes:ue.freeBytes}});await ne.exec("provide-data",{id:le,data:ye})}catch(J){console.error("[LiveDesk FS] nested getEntries failed",{id:ce,error:J}),h(J instanceof Error?J.message:"Unable to read this folder.")}}),ne.intercept("set-path",({id:ae})=>{const le=String(ae),ce=v.current.findIndex(ye=>ye.svarPath===le);if(ce>=0)return Te(ce),!1;const J=ne.getFile(le);if(J?.type==="folder")return Pe(oe(J),String(J.parent||g.current)),!1}),ne.intercept("open-file",()=>!1),ne.on("select-file",()=>{window.setTimeout(()=>{const ce=(ne.getState().panels?.flatMap(J=>J.selected||[])||[]).map(J=>ne.getFile(J)).filter(Boolean).map(J=>oe(J));u(ce.map(J=>J.id),ce)},0)})},Fe=(ne,ae)=>{const le=ae?oe(ae):null,ce=()=>{const J=le?.type==="file"?String(ae?.parent||g.current):String(ae?.id||g.current);m.current?.exec("request-data",{id:J})};return ne==="body"?[{id:"refresh",text:"Refresh",icon:"mdi mdi-refresh",handler:ce},{id:"properties",text:"Properties",icon:"mdi mdi-information-outline",handler:()=>h("Select a file or folder to view its properties.")}]:ne==="multiselect"?[{id:"share",text:"Share to Clients",icon:"mdi mdi-share-variant",handler:()=>{(m.current?.getState().panels?.flatMap(ye=>ye.selected||[])||[]).forEach(ye=>{const ue=m.current?.getFile(ye);ue&&d(oe(ue))})}},{id:"refresh",text:"Refresh",icon:"mdi mdi-refresh",handler:ce}]:le?[{id:"share",text:"Share to Clients",icon:"mdi mdi-share-variant",handler:()=>d(le)},...le.type==="folder"?[{id:"sync",text:"Add folder to Sync",icon:"mdi mdi-folder-sync-outline",handler:()=>p(le)}]:[],{id:"copy-path",text:"Copy path",icon:"mdi mdi-content-copy",handler:()=>{Vl(le.displayPath||le.name)}},{id:"refresh",text:"Refresh",icon:"mdi mdi-refresh",handler:ce},{id:"properties",text:"Properties",icon:"mdi mdi-information-outline",handler:()=>h(`${le.name}
167
+ ${le.displayPath||""}`)}]:[]},Le=async()=>{try{await a()}catch(ne){h(ne instanceof Error?ne.message:"Unable to refresh Hub drives.")}},Ue=[{id:"local",label:"Local drives",icon:Ua,roots:t.filter(ne=>Zl(ne)==="local")},{id:"removable",label:"Removable drives",icon:nx,roots:t.filter(ne=>Zl(ne)==="removable")},{id:"network",label:"Network drives",icon:Lp,roots:t.filter(ne=>Zl(ne)==="network")}];return r.jsxs("section",{className:"hub-file-explorer-panel","aria-label":"Hub file explorer",children:[r.jsxs("div",{className:"hub-file-explorer-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Hub file explorer"}),r.jsxs("strong",{children:[r.jsx(Ua,{size:16})," Browse files on this Hub"]})]}),r.jsxs("div",{className:"hub-file-explorer-heading-actions",children:[r.jsx("button",{className:"icon-button",onClick:i,title:"Import files from this browser",type:"button",children:r.jsx(wb,{size:16})}),r.jsx("button",{className:"icon-button",onClick:c,title:"Import folder from this browser",type:"button",children:r.jsx(rx,{size:16})}),r.jsx("button",{className:"icon-button",onClick:()=>{Le()},title:"Refresh drives",type:"button",children:r.jsx(Xa,{size:16})})]})]}),n?r.jsxs("div",{className:"hub-file-explorer-state",children:[r.jsx(Ua,{size:24}),r.jsx("strong",{children:"Connecting to LiveDesk Hub file system..."})]}):s?r.jsxs("div",{className:"hub-file-explorer-state error",role:"alert",children:[r.jsx(Ns,{size:24}),r.jsx("strong",{children:s})]}):r.jsxs("div",{className:"hub-file-explorer-content",children:[r.jsxs("aside",{className:"hub-file-explorer-drive-sidebar","aria-label":"Hub drives",children:[r.jsxs("div",{className:"hub-drive-sidebar-title",children:[r.jsx(Ua,{size:15}),r.jsx("strong",{children:"This PC"})]}),Ue.map(ne=>ne.roots.length>0&&r.jsxs("section",{className:"hub-drive-group",children:[r.jsxs("h3",{children:[r.jsx(ne.icon,{size:13}),ne.label]}),r.jsx("div",{className:"hub-drive-list",children:ne.roots.map(ae=>{const le=ne.icon,ce=G.has(ae.id)||ae.locked===!0;return r.jsxs("button",{className:`hub-drive-item ${k===ae.id?"active":""} ${ce?"unavailable":""}`,onClick:()=>{Ae(ae)},"aria-pressed":k===ae.id,type:"button",children:[r.jsx("span",{className:"hub-drive-item-icon",children:r.jsx(le,{size:16})}),r.jsxs("span",{className:"hub-drive-item-copy",children:[r.jsx("strong",{children:ae.name}),r.jsx("small",{children:ae.displayPath||ae.name}),r.jsxs("em",{children:[fg(ae.freeBytes||0)," free / ",fg(ae.totalBytes||0)]})]}),H===ae.id?r.jsx(er,{className:"hub-drive-item-status spin",size:15}):ce?r.jsx(Oh,{className:"hub-drive-item-status",size:15}):null]},ae.id)})})]},ne.id)),t.length===0&&r.jsxs("div",{className:"hub-drive-sidebar-empty",children:[r.jsx(Ns,{size:17}),r.jsx("span",{children:"No drives available."})]})]}),r.jsxs("div",{className:"hub-file-explorer-browser",children:[r.jsxs("div",{className:"hub-file-explorer-navigation",children:[r.jsx("nav",{className:"hub-file-explorer-breadcrumbs","aria-label":"Current Hub folder",children:C.map((ne,ae)=>r.jsxs("span",{className:"hub-file-explorer-breadcrumb-item",children:[ae>0&&r.jsx(_p,{size:13,"aria-hidden":"true"}),r.jsx("button",{className:`hub-file-explorer-breadcrumb ${ae===C.length-1?"current":""}`,onClick:()=>Te(ae),title:ne.displayPath||ne.pathLabel,"data-hub-folder-id":ne.hubId,"aria-current":ae===C.length-1?"location":void 0,type:"button",children:ne.pathLabel})]},ne.svarPath))}),r.jsxs("div",{className:"hub-file-explorer-navigation-actions",children:[P&&r.jsx(er,{className:"hub-file-explorer-loading-icon spin",size:15,"aria-label":"Loading folder"}),r.jsx("button",{className:"icon-button",onClick:Se,disabled:C.length<=1||P,title:"Back to parent folder",type:"button",children:r.jsx(mb,{size:16})})]})]}),O&&r.jsxs("div",{className:"hub-file-explorer-folder-error",role:"alert",children:[r.jsx(Oh,{size:15}),r.jsx("span",{children:O})]}),r.jsx("div",{className:"hub-file-explorer-svar",onKeyDownCapture:te,children:r.jsx(qN,{fonts:!1,children:r.jsx(zN,{data:Q,panels:re?[{path:re,selected:[]}]:void 0,readonly:!0,mode:"table",preview:!1,init:Ce,icons:"simple",menuOptions:Fe},`${ie?.id||"no-root"}:${F}`)})})]})]})]})}class iR extends o.Component{state={error:null};static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,n){console.error("[LiveDesk] Share Files runtime error",t,n.componentStack)}render(){return this.state.error?r.jsxs("section",{className:"file-share-error-boundary",role:"alert",children:[r.jsx(vu,{size:24}),r.jsx("strong",{children:"Share Files could not be opened."}),r.jsx("span",{children:this.state.error.message||"An unexpected file explorer error occurred."}),r.jsxs("button",{className:"text-button",onClick:this.props.onRetry,type:"button",children:[r.jsx(Xa,{size:15})," Retry"]})]}):this.props.children}}function oR(e){return e.deviceName||e.hostname||e.deviceId}function cR({devices:e,mode:t,selectedIds:n,onModeChange:s,onToggle:a}){const i=new Set(n);return r.jsxs("section",{className:"distribution-targets",children:[r.jsxs("div",{className:"file-share-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Target"}),r.jsx("strong",{children:t==="all"?`${e.length} connected`:`${n.length} selected`})]}),r.jsxs("div",{className:"file-share-tabs compact","aria-label":"File transfer targets",children:[r.jsxs("button",{className:t==="all"?"active":"",onClick:()=>s("all"),type:"button",children:[r.jsx(oc,{size:14})," All connected"]}),r.jsxs("button",{className:t==="selected"?"active":"",onClick:()=>s("selected"),type:"button",children:[r.jsx(pn,{size:14})," Selected"]})]})]}),r.jsx("div",{className:"file-share-device-list","aria-label":"Connected Client targets",children:e.length===0?r.jsx("div",{className:"file-share-empty-inline",children:"No connected Clients."}):e.map(c=>{const u=t==="all"||i.has(c.deviceId);return r.jsxs("label",{className:`file-share-device-option ${u?"selected":""}`,children:[r.jsx("input",{type:"checkbox",checked:u,disabled:t==="all",onChange:()=>a(c.deviceId)}),r.jsx(pn,{size:20,"aria-hidden":"true"}),r.jsxs("span",{children:[r.jsx("strong",{children:oR(c)}),r.jsxs("small",{children:["Slot ",c.slotNumber?String(c.slotNumber).padStart(3,"0"):"-"," / ",c.platform||"unknown OS"]})]}),r.jsx(En,{size:17,"aria-hidden":"true"})]},c.deviceId)})})]})}function lR(e){if(!Number.isFinite(e)||e<=0)return"0 B";const t=["B","KB","MB","GB","TB"];let n=e,s=0;for(;n>=1024&&s<t.length-1;)n/=1024,s+=1;return`${n.toFixed(s===0||n>=100?0:1)} ${t[s]}`}function uR({folders:e,loading:t,busy:n,canSync:s,onSyncAll:a,onSync:i,onToggleAuto:c,onRemove:u,onAdd:d}){return r.jsxs("section",{className:"file-share-sync-panel",children:[r.jsxs("div",{className:"file-share-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Hub folders"}),r.jsx("strong",{children:"Continuous sync"})]}),r.jsxs("button",{className:"text-button compact",onClick:a,disabled:n||!s||e.length===0,type:"button",children:[r.jsx(tc,{size:15})," ",n?"Syncing":"Sync all"]})]}),t?r.jsx("div",{className:"file-share-empty-state",children:"Loading Hub sync folders..."}):e.length===0?r.jsxs("button",{className:"file-share-empty-state interactive",onClick:d,type:"button",children:[r.jsx(tc,{size:28}),r.jsx("strong",{children:"Add a selected Hub folder"}),r.jsx("span",{children:"Hub keeps the manifest and can sync while this browser is closed."})]}):r.jsx("div",{className:"file-share-sync-list",children:e.map(p=>r.jsxs("article",{className:`file-share-sync-row state-${p.status}`,children:[r.jsx("div",{className:"file-share-sync-icon",children:r.jsx(tc,{size:19})}),r.jsxs("div",{className:"file-share-sync-info",children:[r.jsx("strong",{children:p.name}),r.jsx("span",{children:p.displayPath}),r.jsxs("small",{children:[p.fileCount," files / ",lR(p.totalBytes)," · ",p.lastSyncedAt?`Last sync ${db(p.lastSyncedAt)} ago`:p.message||"Not synced yet"]})]}),r.jsxs("label",{className:"file-share-auto-sync",children:[r.jsx("input",{type:"checkbox",checked:p.autoSync,onChange:()=>c(p)}),r.jsx("span",{children:"Auto"})]}),r.jsxs("button",{className:"text-button compact",onClick:()=>i(p),disabled:n||!s||p.status==="syncing",type:"button",children:[r.jsx(Xa,{size:14})," Sync now"]}),r.jsx("button",{className:"icon-button",onClick:()=>u(p),title:"Remove sync folder",type:"button",children:r.jsx(yb,{size:15})})]},p.id))})]})}function dR(e){const n=(e.targetMode==="all"?e.devices.map(s=>s.deviceId):e.selectedTargetIds).length>0;return r.jsxs("aside",{className:"file-share-distribution-panel",children:[r.jsxs("div",{className:"file-share-distribution-head",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Distribution"}),r.jsx("strong",{children:"Hub → Clients"})]}),r.jsx(ac,{size:18})]}),r.jsxs("div",{className:"file-share-tabs",role:"tablist","aria-label":"Distribution mode",children:[r.jsx("button",{className:e.tab==="send"?"active":"",onClick:()=>e.onTabChange("send"),role:"tab","aria-selected":e.tab==="send",type:"button",children:"Send"}),r.jsx("button",{className:e.tab==="sync"?"active":"",onClick:()=>e.onTabChange("sync"),role:"tab","aria-selected":e.tab==="sync",type:"button",children:"Sync"})]}),e.tab==="send"?r.jsxs(r.Fragment,{children:[r.jsx(cR,{devices:e.devices,mode:e.targetMode,selectedIds:e.selectedTargetIds,onModeChange:e.onTargetModeChange,onToggle:e.onTargetToggle}),r.jsxs("label",{className:"file-share-destination",children:[r.jsx("span",{children:"Destination folder"}),r.jsxs("div",{children:[r.jsx(Ji,{size:15}),r.jsx("input",{value:e.remoteDirectory,onChange:s=>e.onRemoteDirectoryChange(s.target.value),placeholder:"Desktop/LiveDeskFiles"})]}),r.jsx("small",{children:"Blank uses Desktop/LiveDeskFiles."})]}),r.jsxs("div",{className:"file-share-selection-summary",children:[r.jsx("span",{children:"Selected"}),r.jsx("strong",{children:e.selectedSummary})]}),r.jsxs("button",{className:"file-share-share-button",onClick:e.onShare,disabled:!e.canShare,type:"button",children:[r.jsx(ac,{size:17})," Share selected"]}),r.jsxs("button",{className:"file-share-secondary-button",onClick:e.onAddSync,disabled:!e.canAddSync,type:"button",children:[r.jsx(Ji,{size:16})," Add selected folder to Sync"]})]}):r.jsx(uR,{folders:e.folders,loading:e.foldersLoading,busy:e.syncBusy,canSync:n,onSyncAll:e.onSyncAll,onSync:e.onSync,onToggleAuto:e.onToggleAuto,onRemove:e.onRemove,onAdd:e.onAddFolder})]})}function pR(e){if(!Number.isFinite(e)||e<=0)return"0 B";const t=["B","KB","MB","GB","TB"];let n=e,s=0;for(;n>=1024&&s<t.length-1;)n/=1024,s+=1;return`${n.toFixed(s===0||n>=100?0:1)} ${t[s]}`}function gg(e){if(e.state==="completed")return 100;const t=e.totalBytes>0?Math.round(e.sentBytes/e.totalBytes*100):e.totalFiles>0?Math.round(e.completedFiles/e.totalFiles*100):0;return Math.max(0,Math.min(jp(e.state)?100:99,t))}function bg(e){return e.state==="scanning"?"Scanning selected Hub items":e.state==="queued"?"Preparing transfer":e.state==="sending"?`${e.completedFiles}/${e.totalFiles} · ${e.currentPath||"sending"}`:e.state==="completed"?`Sent ${e.totalFiles} file${e.totalFiles===1?"":"s"} to ${e.targetCount} Client${e.targetCount===1?"":"s"}`:e.state==="partially-failed"?`${e.failedTargets.length} Client${e.failedTargets.length===1?"":"s"} failed`:e.state==="cancelled"?"Transfer cancelled":e.error||"Transfer failed"}function jp(e){return["completed","partially-failed","failed","cancelled"].includes(e)}function mR({hubUrl:e,devices:t,localFeatureAccess:n,upgradeNotice:s,remoteDirectory:a,onRemoteDirectoryChange:i,targetMode:c,selectedTargetIds:u,onTargetModeChange:d,onTargetToggle:p,filePickerRef:h,folderPickerRef:m,onBrowserFileImport:g,onBrowserFolderImport:w,onNotice:v,onTransferChange:y}){const k=Array.isArray(t)?t:[],[N,C]=o.useState([]),[A,E]=o.useState(!0),[I,F]=o.useState(""),[M,H]=o.useState([]),[V,P]=o.useState([]),[D,O]=o.useState(null),[X,G]=o.useState(!1),[U,ie]=o.useState([]),[j,re]=o.useState(!0),[de,Q]=o.useState(!1),[ge,oe]=o.useState("send"),[me,Ae]=o.useState([]),Te=o.useRef(new Set),Pe=o.useRef(!1),Se=o.useMemo(()=>c==="all"?k.map(T=>T.deviceId):u.filter(T=>k.some(ve=>ve.deviceId===T)),[k,u,c]),te=me.find(T=>!jp(T.state)),Ce=V.length===1&&V[0].type==="folder"?V[0]:null,Fe=V.length===0?"Select files or folders from the Hub explorer.":X?"Calculating selection size...":D?`${D.files} files, ${D.folders} folders · ${pR(D.totalBytes)}`:`${V.length} item${V.length===1?"":"s"} selected`,Le=T=>{y({id:T.jobId,state:T.state,progress:gg(T),message:bg(T)})},Ue=o.useCallback(async()=>{const T=await VN(e,!0);return C(T),F(""),T},[e]),ne=async()=>{if(!Pe.current){Pe.current=!0;try{const ve=(await QN(e,!0)).jobs||[],De=await Promise.all([...Te.current].map(async $e=>{try{return await YN($e,e)}catch{return null}})),qe=[...ve,...De.filter(Boolean)],_e=[...new Map(qe.map($e=>[$e.jobId,$e])).values()];Ae(_e),_e.forEach(Le),_e.filter($e=>jp($e.state)).forEach($e=>Te.current.delete($e.jobId))}catch{}finally{Pe.current=!1}}};o.useEffect(()=>{let T=!0;E(!0),F(""),Promise.all([Ue(),hg(e).then(De=>{T&&ie(De)})]).catch(De=>{T&&(F(De instanceof Error?"Hub file system is unavailable. Make sure LiveDesk Hub is running on this computer.":"Hub file system is unavailable."),v(De instanceof Error?De.message:"Hub file system is unavailable."))}).finally(()=>{T&&(E(!1),re(!1))}),ne();const ve=window.setInterval(()=>{ne()},800);return()=>{T=!1,window.clearInterval(ve)}},[e,Ue]),o.useEffect(()=>{if(M.length===0){O(null);return}let T=!1;return G(!0),GN(M,e).then(ve=>{T||O(ve)}).catch(ve=>{T||v(ve instanceof Error?ve.message:"Unable to calculate selected size.")}).finally(()=>{T||G(!1)}),()=>{T=!0}},[e,M.join("|")]);const ae=(T,ve)=>{H(T),P(ve)},le=T=>{T.forEach(ve=>Te.current.add(ve.jobId)),Ae(ve=>[...new Map([...ve,...T].map(De=>[De.jobId,De])).values()]),T.forEach(Le)},ce=async()=>{if(!n){v(s);return}if(M.length===0){v("Select files or folders from the Hub explorer.");return}if(Se.length===0){v("Choose at least one connected Client.");return}if(te){v("A Hub transfer is already running.");return}try{const T=await KN(M,Se,a.trim(),e);Te.current.add(T.jobId),v("Hub transfer queued."),await ne()}catch(T){v(T instanceof Error?T.message:"Unable to start Hub transfer.")}},J=async T=>{const ve=T||Ce;if(!ve||ve.type!=="folder"){v("Select one folder to add it to Sync.");return}try{const De=await JN(ve.id,e);ie(qe=>[...qe.filter(_e=>_e.id!==De.folder.id),De.folder]),oe("sync"),v(`${ve.name} is ready for Hub sync.`)}catch(De){v(De instanceof Error?De.message:"Unable to add the Hub folder to Sync.")}},ye=async T=>{if(Se.length===0){v("Choose at least one connected Client.");return}Q(!0),ie(ve=>ve.map(De=>De.id===T.id?{...De,status:"syncing"}:De));try{const ve=await tR(T.id,Se,a.trim(),e);le(ve.jobs||[]),v(ve.jobs?.length?"Hub sync queued.":"No changed files to sync.");const De=await hg(e);ie(De)}catch(ve){v(ve instanceof Error?ve.message:"Unable to sync the Hub folder."),ie(De=>De.map(qe=>qe.id===T.id?{...qe,status:"error",message:"Sync failed"}:qe))}finally{Q(!1)}},ue=async()=>{Q(!0);try{for(const T of U)await ye(T)}finally{Q(!1)}},Ee=async T=>{try{const ve=await ZN(T.id,{autoSync:!T.autoSync},e);ie(De=>De.map(qe=>qe.id===T.id?ve.folder:qe))}catch(ve){v(ve instanceof Error?ve.message:"Unable to update auto sync.")}},nt=async T=>{try{await eR(T.id,e),ie(ve=>ve.filter(De=>De.id!==T.id))}catch(ve){v(ve instanceof Error?ve.message:"Unable to remove the sync folder.")}};return r.jsxs("section",{className:"livedesk-file-explorer",children:[r.jsx("input",{ref:h,className:"hidden-file-input",type:"file",multiple:!0,onChange:T=>{T.currentTarget.files&&g(T.currentTarget.files),T.currentTarget.value=""}}),r.jsx("input",{ref:m,className:"hidden-file-input",type:"file",multiple:!0,webkitdirectory:"",directory:"",onChange:T=>{T.currentTarget.files&&w(T.currentTarget.files),T.currentTarget.value=""}}),r.jsx("div",{className:"file-share-workspace",children:r.jsxs(iR,{onRetry:()=>window.location.reload(),children:[r.jsx(aR,{hubUrl:e,roots:N,loading:A,error:I,onRefreshRoots:Ue,onImportFiles:()=>h.current?.click(),onImportFolder:()=>m.current?.click(),onSelectionChange:ae,onShareItem:T=>{H([T.id]),P([T]),oe("send")},onAddSyncFolder:T=>{H([T.id]),P([T]),J(T)},onNotice:v}),r.jsx(dR,{devices:k,targetMode:c,selectedTargetIds:u,onTargetModeChange:d,onTargetToggle:p,remoteDirectory:a,onRemoteDirectoryChange:i,selectedEntries:V,selectedSummary:Fe,canShare:n&&!te&&M.length>0&&Se.length>0&&!X,onShare:()=>{ce()},canAddSync:!!Ce,onAddSync:()=>{J()},tab:ge,onTabChange:oe,folders:U,foldersLoading:j,syncBusy:de,onSyncAll:()=>{ue()},onSync:T=>{ye(T)},onToggleAuto:T=>{Ee(T)},onRemove:T=>{nt(T)},onAddFolder:()=>{J()}})]})}),te&&r.jsx("footer",{className:"file-share-workspace-footer",children:r.jsxs("span",{children:[bg(te)," · ",gg(te),"% ",r.jsx("button",{className:"icon-button",onClick:()=>{XN(te.jobId,e).then(T=>{Ae(ve=>ve.map(De=>De.jobId===T.jobId?T:De)),Le(T)})},title:"Cancel transfer",type:"button",children:r.jsx(xn,{size:14})})]})})]})}const hR=o.forwardRef(function({value:t,onChange:n,onSubmit:s,onOpenSuggestedTasks:a,suggestedOpen:i=!1,suggestedTaskCount:c,disabled:u=!1,placeholder:d="Ask LiveDesk to work across your machines...",compact:p=!1},h){return r.jsxs("form",{className:"agents-composer",onSubmit:m=>{m.preventDefault(),s()},children:[r.jsx("button",{className:`agents-suggested-trigger ${i?"active":""}`,type:"button","aria-label":c===void 0?"Open Suggested tasks":`Open Suggested tasks (${c} available)`,"aria-expanded":i,onClick:a,disabled:u,children:r.jsx(sx,{size:17})}),r.jsx("textarea",{ref:h,value:t,onChange:m=>n(m.target.value.slice(0,4e3)),placeholder:d,"aria-label":"Ask LiveDesk",rows:p?1:2,disabled:u}),r.jsxs("button",{className:"agents-run-button",type:"submit",disabled:u||!t.trim(),children:[u?r.jsx(er,{className:"spin",size:16}):r.jsx(ac,{size:16}),u?"Running":"Run"]})]})}),fR=["read","processControl","serviceControl","applicationControl","fileRead","fileWrite","fileDelete","shell","script","softwareInstall","network","systemPower","systemConfiguration","userAccount"];function pu(e){return e.deviceName?.trim()||e.hostname?.trim()||e.deviceId}function mu(e){return e.connected!==!0?!1:e.synthetic===!0?!0:!e.channels||e.channels.control===!0}function gR(e){return e==="running"||e==="completed"||e==="failed"||e==="cancelled"?e:"queued"}function bR(e){switch(e){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 vR(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Zn(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function _l(e){const t=Zn(e);return t===null?"":t<1024**2?`${Math.round(t/1024)}K`:t<1024**3?`${(t/1024**2).toFixed(0)}M`:`${(t/1024**3).toFixed(1)}G`}function vg(e){const t=Zn(e);return t===null?"":`${Math.round((t<=1?t:t/100)*100)}%`}function wR(e){return!e||/^(?:[\w .-]+ )?collected(?:\.)?$/i.test(e.trim())?"":e.trim()}function hu(e,t){if(t.error)return t.error;const n=vR(t.data),s=wR(t.result||"");if(!n)return s||t.stage||t.status;if(e==="system.health"){const a=typeof n.machine=="string"?n.machine:"",i=vg(n.cpuUsageRatio),c=Zn(n.cores),u=_l(n.freeMemoryBytes),d=_l(n.totalMemoryBytes),p=Zn(n.totalMemoryBytes)&&Zn(n.freeMemoryBytes)!==null?`${Math.round(Zn(n.freeMemoryBytes)/Zn(n.totalMemoryBytes)*100)}% RAM free`:"";return[a,i&&`CPU ${i}`,c!==null&&`${Math.round(c)} cores`,u&&d?`RAM ${u}/${d}`:"",p,typeof n.platform=="string"?n.platform:""].filter(Boolean).join(" · ")||s||t.status}if(e==="disk.status"){const a=typeof n.root=="string"?n.root:"",i=_l(n.freeBytes),c=Zn(n.totalBytes)&&Zn(n.freeBytes)!==null?`${Math.round(Zn(n.freeBytes)/Zn(n.totalBytes)*100)}% free`:"";return[a,i&&`${i} free`,c].filter(Boolean).join(" · ")||s||t.status}if(e==="gpu.status"){const a=typeof n.name=="string"&&n.name?n.name:"No GPU detected",i=vg(n.usageRatio),c=Zn(n.temperatureC)!==null?`${Math.round(Zn(n.temperatureC))}°C`:"",u=_l(n.freeMemoryBytes);return[a,i&&`GPU ${i}`,c,u&&`${u} free`].filter(Boolean).join(" · ")||s||t.status}if(e==="process.list"){const a=Zn(n.count);return a!==null?`${a} matching process${a===1?"":"es"}`:s||t.status}if(e==="network.status"){const a=Array.isArray(n.adapters)?n.adapters.length:null;return a!==null?`${a} active adapter${a===1?"":"s"}`:s||t.status}return s||t.stage||t.status}function wg(e,t){const n=hu(e,t);return t.status==="failed"||t.status==="cancelled"||/\b(?:warning|failed|error|offline|not running|low|timeout|timed out)\b/i.test(`${t.result||""} ${n}`)}function yR({state:e,operation:t}){const n=e.status==="completed"?Rs:e.status==="failed"||e.status==="cancelled"?xn:e.status==="running"?er:xb,s=e.status==="running"?e.stage||"Working":e.status==="completed"?t?hu(t,e):e.result||"Completed":e.status==="failed"?e.error||"Failed":e.status==="cancelled"?"Cancelled":"Queued";return r.jsxs("div",{className:`agent-target-row status-${e.status}`,"data-agent-target-id":e.deviceId,children:[r.jsx("span",{className:"agent-target-status","aria-hidden":"true",children:r.jsx(n,{size:15})}),r.jsx("strong",{children:e.deviceName}),r.jsx("span",{className:"agent-target-state",children:e.status[0].toUpperCase()+e.status.slice(1)}),r.jsx("small",{children:s})]})}function xR({operation:e,states:t,status:n,onCancel:s,onRetry:a,busy:i=!1}){const c=["running","queued"].includes(n),[u,d]=o.useState(!1),[p,h]=o.useState("all"),m=o.useMemo(()=>({total:t.length,completed:t.filter(A=>A.status==="completed").length,failed:t.filter(A=>A.status==="failed").length,running:t.filter(A=>A.status==="running").length,queued:t.filter(A=>A.status==="queued").length,cancelled:t.filter(A=>A.status==="cancelled").length}),[t]),g=t.filter(A=>wg(e,A)),w=g.filter(A=>A.status==="completed").length,v=m.failed>0,y=g.length>0,k=t.filter(A=>p==="issues"?wg(e,A):p==="running"?A.status==="running"||A.status==="queued":p==="completed"?A.status==="completed":p==="failed"?A.status==="failed":!0),N=y&&!c||n==="completed-with-failures"?"Completed with issues":n[0]?.toUpperCase()+n.slice(1),C=t.filter(A=>A.status==="completed").map(A=>hu(e,A)).filter(Boolean).filter((A,E,I)=>I.indexOf(A)===E).slice(0,2);return r.jsxs("section",{className:"agent-task-block","aria-label":"Task execution",children:[r.jsxs("div",{className:"agent-task-head",children:[r.jsxs("div",{children:[r.jsx("span",{children:"LiveDesk Agent"}),r.jsx("strong",{children:bR(e)})]}),r.jsx("span",{className:`agent-task-status status-${y?"completed-with-failures":n}`,children:N})]}),r.jsxs("div",{className:"agent-task-summary","aria-label":"Task summary",children:[r.jsxs("strong",{children:[m.total," targets"]}),r.jsxs("span",{className:"summary-completed",children:[m.completed," completed"]}),m.running>0&&r.jsxs("span",{className:"summary-running",children:[m.running," running"]}),m.queued>0&&r.jsxs("span",{children:[m.queued," queued"]}),v&&r.jsxs("span",{className:"summary-failed",children:[m.failed," failed"]}),w>0&&r.jsxs("span",{className:"summary-cancelled",children:[w," warning"]}),m.cancelled>0&&r.jsxs("span",{className:"summary-cancelled",children:[m.cancelled," cancelled"]})]}),C.length>0&&r.jsxs("div",{className:"agent-task-result-preview",title:C.join(" · "),children:[r.jsx("span",{children:"Result"}),C.join(" · ")]}),r.jsx("div",{className:"agent-target-chips","aria-label":"Target status overview",children:t.map((A,E)=>{const I=A.status==="completed"?"✓":A.status==="failed"?"×":A.status==="cancelled"?"!":A.status==="running"?"…":"·";return r.jsxs("span",{className:`agent-target-chip status-${A.status}`,title:`${A.deviceName}: ${hu(e,A)}`,"aria-label":`${E+1}. ${A.deviceName}: ${A.status}`,children:[r.jsx("b",{children:String(E+1).padStart(2,"0")}),r.jsx("span",{children:I})]},A.deviceId)})}),t.length>0&&r.jsx("div",{className:"agent-task-details-toggle",children:r.jsxs("button",{type:"button",onClick:()=>d(A=>!A),"aria-expanded":u,children:[u?r.jsx(ax,{size:14}):r.jsx(Sb,{size:14}),u?"Hide details":"Show details"]})}),u&&r.jsxs("div",{className:"agent-task-details",children:[r.jsx("div",{className:"agent-task-filters",role:"tablist","aria-label":"Task result filter",children:["all","issues","running","completed","failed"].map(A=>r.jsx("button",{className:p===A?"active":"",onClick:()=>h(A),role:"tab","aria-selected":p===A,type:"button",children:A==="all"?"All":A==="issues"?"Issues only":A[0].toUpperCase()+A.slice(1)},A))}),r.jsx("div",{className:"agent-task-rows",children:k.length>0?k.map(A=>r.jsx(yR,{operation:e,state:A},A.deviceId)):r.jsx("small",{className:"agent-task-no-results",children:"No targets match this filter."})})]}),(c||v)&&r.jsxs("div",{className:"agent-task-actions",children:[c&&s&&r.jsxs("button",{onClick:s,disabled:i,type:"button",children:[r.jsx(ix,{size:14})," Cancel"]}),!c&&v&&a&&r.jsxs("button",{onClick:a,disabled:i,type:"button",children:[r.jsx(sp,{size:14})," Retry failed"]})]})]})}function SR(e){try{return JSON.stringify(e,null,2).slice(0,6e3)}catch{return"{}"}}function CR({approval:e,busy:t=!1,onApprove:n,onReject:s}){return r.jsxs("article",{className:"agent-approval-card","aria-label":"Agent approval required",children:[r.jsxs("div",{className:"agent-approval-head",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Approval required"}),r.jsx("strong",{children:e.toolName})]}),r.jsx("span",{className:`agent-approval-risk risk-${e.risk}`,children:e.risk})]}),r.jsx("p",{children:e.description}),r.jsx("pre",{children:SR(e.arguments)}),r.jsxs("small",{children:["Permission: ",e.permissionMode," · Scope: selected devices only · Expires in 5 minutes"]}),r.jsxs("div",{className:"agent-approval-actions",children:[r.jsxs("button",{className:"reject",disabled:t,onClick:s,type:"button",children:[r.jsx(xn,{size:14})," Reject"]}),r.jsxs("button",{disabled:t,onClick:()=>n("once"),type:"button",children:[r.jsx(Rs,{size:14})," Once"]}),r.jsx("button",{disabled:t,onClick:()=>n("same-action-this-run"),type:"button",children:"Allow same action"}),r.jsx("button",{disabled:t,onClick:()=>n("category-this-run"),type:"button",children:"Allow category"})]}),r.jsxs("div",{className:"agent-approval-scope",children:[r.jsx(vu,{size:13})," Approval is bound to this run, tool, arguments, selected devices, and policy hash."]})]})}function kR(e){return e==="queued"?"Request queued":e==="checking-codex"?"Checking Codex":e==="preparing-tools"?"Preparing tools":e==="thinking"?"Preparing answer":e==="tool-running"?"Working on computers":e==="recovering"?"Retrying safely":e==="waiting-approval"?"Waiting for approval":"Working"}function MR({items:e,onCancel:t,onRetry:n,busyBatchId:s,approvals:a,onApprove:i,onReject:c,busyApprovalId:u,progress:d,emptyTitle:p="Ask LiveDesk to work across your machines.",emptyBody:h="Start with a read-only request such as “현재 대상에서 CPU와 메모리 상태를 확인해줘”."}){const m=o.useRef(null),g=o.useRef(!0),w=o.useRef(""),v=e[e.length-1];return o.useLayoutEffect(()=>{const y=m.current;y&&(v?.type==="user"&&v.id!==w.current&&(g.current=!0),w.current=v?.id||"",g.current&&(y.scrollTop=y.scrollHeight))},[a,e,v?.id,v?.type,d?.message,d?.stage]),r.jsxs("section",{className:"agents-conversation","aria-live":"polite",ref:m,onScroll:y=>{const k=y.currentTarget;g.current=k.scrollHeight-k.scrollTop-k.clientHeight<72},children:[a.filter(y=>y.status==="pending").map(y=>r.jsx(CR,{approval:y,busy:u===y.approvalId,onApprove:k=>i(y,k),onReject:()=>c(y)},y.approvalId)),e.length===0&&r.jsxs("div",{className:"agents-empty-conversation",children:[r.jsx("strong",{children:p}),r.jsx("span",{children:h})]}),e.map(y=>{if(y.type==="task"){const k=y;return r.jsx(xR,{operation:k.operation,states:k.states,status:k.status,onCancel:()=>t(k.batchId,k.agentRunId),onRetry:()=>n(k.batchId),busy:s===k.batchId},k.id)}return r.jsxs("article",{className:`agents-message ${y.type}`,children:[r.jsx("span",{children:y.type==="user"?"You":"LiveDesk Agent"}),r.jsx("p",{children:y.text})]},y.id)}),d&&r.jsxs("article",{className:"agents-message agent agents-progress-message",role:"status",children:[r.jsxs("span",{children:[r.jsx(er,{"aria-hidden":"true",size:15}),kR(d.stage)]}),r.jsx("p",{children:d.message})]})]})}const yg=["Recommended","Health & capacity","Processes & services","Files & configuration","Software & automation","Network & connectivity","Power & maintenance","Troubleshooting & recovery"],Lt=["windows","macos","linux"],Xs={"system.health":{label:"system health",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:Lt},"gpu.status":{label:"GPU status",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:Lt},"disk.status":{label:"disk status",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:Lt},"process.list":{label:"process inspection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:Lt},"service.status":{label:"service inspection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:Lt},"diagnostics.collect":{label:"diagnostics collection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:Lt},"process.control":{label:"process control",permissionCategory:"processControl",readOnly:!1,risk:"high",supportedPlatforms:Lt},"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:Lt},"application.close":{label:"application close",permissionCategory:"applicationControl",readOnly:!1,risk:"medium",supportedPlatforms:Lt},"file.read":{label:"file reading",permissionCategory:"fileRead",readOnly:!0,risk:"low",supportedPlatforms:Lt},"file.write":{label:"file writing",permissionCategory:"fileWrite",readOnly:!1,risk:"high",supportedPlatforms:Lt},"file.delete":{label:"file deletion",permissionCategory:"fileDelete",readOnly:!1,risk:"critical",supportedPlatforms:Lt},"file.list":{label:"directory listing",permissionCategory:"fileRead",readOnly:!0,risk:"low",supportedPlatforms:Lt},"file.search":{label:"file name search",permissionCategory:"fileRead",readOnly:!0,risk:"low",supportedPlatforms:Lt},"directory.create":{label:"directory creation",permissionCategory:"fileWrite",readOnly:!1,risk:"medium",supportedPlatforms:Lt},"command.run":{label:"command execution",permissionCategory:"shell",readOnly:!1,risk:"critical",supportedPlatforms:Lt},"script.run":{label:"script execution",permissionCategory:"script",readOnly:!1,risk:"high",supportedPlatforms:Lt},"software.install":{label:"software installation",permissionCategory:"softwareInstall",readOnly:!1,risk:"high",supportedPlatforms:Lt},"network.status":{label:"network inspection",permissionCategory:"network",readOnly:!0,risk:"low",supportedPlatforms:Lt},"system.power":{label:"power control",permissionCategory:"systemPower",readOnly:!1,risk:"critical",supportedPlatforms:Lt},"system.configure":{label:"system configuration",permissionCategory:"systemConfiguration",readOnly:!1,risk:"critical",supportedPlatforms:Lt},"logs.collect":{label:"log collection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:Lt}};new Set(Object.keys(Xs));const AR={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","문제해결","복구","장애"]},xg=["low","medium","high","critical"];function NR(e){return e.reduce((t,n)=>{const s=Xs[n].risk;return xg.indexOf(s)>xg.indexOf(t)?s:t},"low")}function RR(e){return Lt.filter(t=>e.every(n=>Xs[n].supportedPlatforms.includes(t)))}function ze(e,t,n,s,a,i,c={}){const u=c.description||s,d=a.flatMap(h=>h.split(".")),p=[...new Set([...AR[t],...i,...d])];return{id:e,category:t,title:n,prompt:s,description:u,requiredOperations:a,risk:c.risk||NR(a),targetSupport:c.targetSupport||"single-or-multiple",supportedPlatforms:c.supportedPlatforms||RR(a),keywords:p,recommended:c.recommended??!1,enabled:!0}}const rw=[ze("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}),ze("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}),ze("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}),ze("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}),ze("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}),ze("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}),ze("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}),ze("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}),ze("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","높은 사용량"]),ze("health-uptime","Health & capacity","Review Client uptime","Show uptime, boot time, and current system health for the target Clients.",["system.health"],["uptime","boot","가동시간"]),ze("health-gpu-temperature","Health & capacity","Check GPU temperature","Check GPU temperature and thermal warnings on the current targets.",["gpu.status"],["thermal","temperature","발열"]),ze("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"]),ze("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","디스크"]),ze("health-gpu-compare","Health & capacity","Compare GPU capacity","Compare GPU model, memory, temperature, and utilization across the current targets.",["gpu.status"],["compare","graphics","capacity"]),ze("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","경고"]),ze("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"]),ze("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","실행 중"]),ze("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"]),ze("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"}),ze("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"}),ze("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"}),ze("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"}),ze("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","서비스 상태"]),ze("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"}),ze("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"}),ze("files-search-name","Files & configuration","Search files by name","Search for files or folders containing [name] under [path] on the target Client.",["file.search"],["search","find","filename","파일 찾기"],{targetSupport:"single"}),ze("files-create-directory","Files & configuration","Create a directory","Create directory [path] on the target Client and report the final path.",["directory.create"],["create","directory","folder","폴더 만들기"],{targetSupport:"single"}),ze("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","구성"]),ze("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"]),ze("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"}),ze("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"}),ze("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"]),ze("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"}),ze("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"}),ze("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"]}),ze("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"]}),ze("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"]}),ze("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"}),ze("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"}),ze("software-run-command","Software & automation","Run a shell command on one target","Run [command] with [PowerShell, cmd, bash, zsh, sh, or pwsh] on the target Client and return its exit status, duration, and output.",["command.run"],["command","powershell","shell","terminal"],{targetSupport:"single"}),ze("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"]),ze("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"}),ze("network-adapter-status","Network & connectivity","Check network adapters","Show adapter state, address, and link information for the current targets.",["network.status"],["adapter","ethernet","wifi","네트워크 상태"]),ze("network-disconnected","Network & connectivity","Find disconnected targets","Find current targets with disconnected or degraded network adapters.",["network.status"],["disconnected","offline","연결 끊김"]),ze("network-link-speed","Network & connectivity","Check link speed","Report network link speed and duplex information for the current targets.",["network.status"],["speed","bandwidth","duplex"]),ze("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"]),ze("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"]),ze("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"]),ze("network-compare","Network & connectivity","Compare target connectivity","Compare adapter state, addresses, and link speed across the current targets.",["network.status"],["compare","inventory","connectivity"]),ze("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"]),ze("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"}),ze("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"}),ze("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"}),ze("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"}),ze("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"}),ze("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"}),ze("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"}),ze("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"}),ze("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"}),ze("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"}),ze("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"}),ze("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"}),ze("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"}),ze("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"}),ze("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"}),ze("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","장애 보고서"])],Wd={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 TR(e,t){return e==="safe-auto"?Wd:e==="full-access"?{...Wd,processControl:"allow",serviceControl:"allow",applicationControl:"allow",fileDelete:"allow",shell:"allow",script:"allow",softwareInstall:"allow",systemPower:"allow",systemConfiguration:"allow"}:e==="custom"&&t?t:{...Wd,processControl:"ask",serviceControl:"ask",applicationControl:"ask",fileWrite:"ask",network:"ask"}}function PR(e,t,n){const s=TR(t,n),a=e.requiredOperations.map(i=>s[Xs[i].permissionCategory]);if(a.includes("deny")){const i=e.requiredOperations.find(c=>s[Xs[c].permissionCategory]==="deny");return{state:"blocked",label:"Blocked",reason:`This task requires ${Xs[i].label}, which is blocked by the current permission policy.`}}return a.includes("ask")?{state:"approval",label:"Approval required",reason:"This task requires approval before the requested changes can reach a Client."}:e.requiredOperations.every(i=>Xs[i].readOnly)?{state:"read-only",label:"Read only"}:t==="full-access"?{state:"full-access",label:"Full Access"}:{state:"auto",label:"Auto allowed"}}function IR(e){const t=String(e||"").trim().toLowerCase();return t==="windows"||t==="win32"||t==="win32nt"?"windows":t==="macos"||t==="macosx"||t==="darwin"||t==="osx"?"macos":t==="linux"?"linux":null}function jR(e,t,n){const s=new Set(n);return e.filter(a=>a.connected&&(t==="all"||t==="auto"||s.has(a.deviceId)))}function ER(e,t){const n=IR(e.platform);if(!n||!t.supportedPlatforms.includes(n))return!1;const s=e.capabilities?.agentTools;return!Array.isArray(s)||s.length===0?t.requiredOperations.every(a=>Xs[a].readOnly):t.requiredOperations.every(a=>s.includes(a))}function sw(e,t,n,s,a,i){const c=PR(e,a,i),u=jR(t,n,s),d=u.map(w=>w.deviceId),p={...c,available:!1,availableDeviceIds:[],unsupportedDeviceIds:d,risk:e.risk,supportedPlatforms:e.supportedPlatforms};if(u.length===0)return{...p,reason:"Select at least one connected Client."};if(e.targetSupport==="single"&&u.length!==1)return{...p,reason:"This task supports one Client at a time."};if(c.state==="blocked")return p;const h=u.filter(w=>ER(w,e)),m=h.map(w=>w.deviceId),g=d.filter(w=>!m.includes(w));return h.length===0?{...p,unsupportedDeviceIds:g,reason:"No current target supports the required platform and client capabilities."}:{...p,available:!0,availableDeviceIds:m,unsupportedDeviceIds:g}}function FR(e,t,n,s,a,i){return e.filter(c=>c.enabled&&sw(c,t,n,s,a,i).available).length}const zd="livedesk.agentPromptRecent",qd="livedesk.agentPromptFavorites",DR={Recommended:Zs,"Health & capacity":Zi,"Processes & services":ux,"Files & configuration":lx,"Software & automation":bb,"Network & connectivity":Lp,"Power & maintenance":Zt,"Troubleshooting & recovery":cx};function Sg(e){if(typeof window>"u")return[];try{const t=JSON.parse(window.localStorage.getItem(e)||"[]");return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}catch{return[]}}function $l(e,t){try{window.localStorage.setItem(e,JSON.stringify(t))}catch{}}function Ud(e){return e==="all"?"All tasks":e==="recent"?"Recent":e==="favorites"?"Favorites":e==="read-only"?"Read only":e==="auto"?"Auto allowed":e==="approval"?"Approval required":e==="full-access"?"Full Access":e==="available"?"Available":e==="unavailable"?"Unavailable":e}function LR(e){return e==="all"?"All":e==="recent"?"Recent":e==="favorites"?"Favorites":e==="read-only"?"Read only":e==="auto"?"Auto":e==="approval"?"Approval":e==="full-access"?"Full access":e==="available"?"Available":e==="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"}[e]}function _R(e,t,n){if(!n.trim())return!0;const s=n.trim().toLowerCase();return[e.title,e.prompt,e.description,e.category,e.risk,t.label,...e.keywords,...e.requiredOperations,...e.supportedPlatforms].join(" ").toLowerCase().includes(s)}function $R(e){return`permission-${e}`}function OR(e){return e==="low"?"Low risk":e==="medium"?"Medium risk":e==="high"?"High risk":"Critical risk"}function BR(e){return e==="windows"?"Windows":e==="macos"?"macOS":"Linux"}function HR({devices:e,targetMode:t,selectedIds:n,permissionMode:s,customCategories:a,onSelectPrompt:i,onClose:c}){const[u,d]=o.useState(""),[p,h]=o.useState("all"),[m,g]=o.useState(()=>Sg(zd)),[w,v]=o.useState(()=>Sg(qd)),[y,k]=o.useState(0),[N,C]=o.useState(""),A=o.useRef(null),E=o.useRef(null),I=o.useMemo(()=>rw.filter(U=>U.enabled),[]),F=o.useMemo(()=>new Map(I.map(U=>[U.id,sw(U,e,t,n,s,a)])),[a,e,s,n,t,I]),M=o.useMemo(()=>[...F.values()].filter(U=>U.available).length,[F]),H=o.useMemo(()=>e.filter(U=>U.connected&&(t==="all"||t==="auto"||n.includes(U.deviceId))).length,[e,n,t]),V=o.useMemo(()=>{const U=I.filter(ie=>_R(ie,F.get(ie.id),u));return p==="recent"?m.map(ie=>U.find(j=>j.id===ie)).filter(ie=>!!ie):p==="favorites"?w.map(ie=>U.find(j=>j.id===ie)).filter(ie=>!!ie):p==="all"?U:U.filter(ie=>{const j=F.get(ie.id);return p==="read-only"?j.state==="read-only":p==="auto"?j.state==="auto":p==="approval"?j.state==="approval":p==="full-access"?j.state==="full-access":p==="available"?j.available:p==="unavailable"?!j.available:ie.category===p})},[F,w,p,m,u,I]),P=o.useMemo(()=>p!=="all"?[{category:Ud(p),templates:V}]:yg.map(U=>({category:U,templates:V.filter(ie=>ie.category===U)})).filter(U=>U.templates.length>0),[p,V]);o.useEffect(()=>{k(U=>Math.min(U,Math.max(0,V.length-1)))},[V.length]),o.useEffect(()=>{$l(zd,m)},[m]),o.useEffect(()=>{$l(qd,w)},[w]),o.useEffect(()=>{E.current?.focus();const U=j=>{j.target instanceof Node&&!A.current?.contains(j.target)&&c()},ie=j=>{j.key==="Escape"&&(j.preventDefault(),c())};return document.addEventListener("pointerdown",U),document.addEventListener("keydown",ie),()=>{document.removeEventListener("pointerdown",U),document.removeEventListener("keydown",ie)}},[c]);const D=U=>{const ie=F.get(U.id);if(!ie.available){C(ie.reason||"This task is not available for the current targets and permission policy.");return}const j=[U.id,...m.filter(re=>re!==U.id)].slice(0,10);g(j),$l(zd,j),i(U.prompt),c()},O=U=>{v(ie=>{const j=ie.includes(U)?ie.filter(re=>re!==U):[U,...ie];return $l(qd,j),j})},X=U=>{U.key==="ArrowDown"?(U.preventDefault(),k(ie=>Math.min(ie+1,Math.max(0,V.length-1)))):U.key==="ArrowUp"?(U.preventDefault(),k(ie=>Math.max(ie-1,0))):U.key==="Enter"&&V[y]&&(U.preventDefault(),D(V[y]))};let G=-1;return r.jsxs("section",{className:"agents-suggested-tasks",ref:A,"aria-label":"Suggested tasks",children:[r.jsxs("header",{className:"agents-suggested-header",children:[r.jsxs("div",{children:[r.jsxs("span",{className:"agents-suggested-title",children:[r.jsx(Zs,{size:15})," Suggested tasks"]}),r.jsxs("small",{children:[M," available · ",I.length," total. Choose a task, edit it, then run it."]})]}),r.jsx("button",{className:"agents-suggested-close",type:"button","aria-label":"Close suggested tasks",onClick:c,children:r.jsx(xn,{size:16})})]}),r.jsxs("label",{className:"agents-suggested-search",children:[r.jsx(ox,{size:15,"aria-hidden":"true"}),r.jsx("input",{ref:E,value:u,onChange:U=>d(U.target.value),onKeyDown:X,placeholder:"Search tasks...","aria-label":"Search suggested tasks"})]}),r.jsx("div",{className:"agents-suggested-filters","aria-label":"Task categories and availability filters",children:["all","recent","favorites","read-only","auto","approval","full-access","available","unavailable",...yg].map(U=>{const ie=U==="recent"?gb:U==="favorites"?ap:U==="all"?Zs:U==="available"?En:U==="unavailable"?Cb:U==="read-only"||U==="auto"||U==="approval"||U==="full-access"?Zt:DR[U];return r.jsxs("button",{className:p===U?"active":"",type:"button",title:Ud(U),"aria-label":Ud(U),"aria-pressed":p===U,onClick:()=>{h(U),k(0),C("")},children:[r.jsx(ie,{size:12})," ",LR(U)]},U)})}),N&&r.jsx("div",{className:"agents-suggested-notice",role:"status",children:N}),r.jsxs("div",{className:"agents-suggested-list",role:"listbox","aria-label":"Suggested tasks",children:[P.map(U=>r.jsxs("div",{className:"agents-suggested-group",children:[r.jsx("strong",{children:U.category}),U.templates.map(ie=>{G+=1;const j=G===y,re=w.includes(ie.id),de=F.get(ie.id),Q=de.availableDeviceIds.length+de.unsupportedDeviceIds.length||H,ge=de.available?`Available on ${de.availableDeviceIds.length} of ${Q} target${Q===1?"":"s"}`:`Unavailable: ${de.reason||"not supported by the current targets"}`;return r.jsxs("div",{className:`agents-suggested-item ${j?"active":""} ${de.available?"":"unavailable"}`,children:[r.jsxs("button",{className:"agents-suggested-prompt",type:"button",role:"option","aria-selected":j,"aria-disabled":!de.available,onClick:()=>D(ie),children:[r.jsx("span",{children:ie.title}),r.jsx("small",{className:"agents-suggested-description",children:ie.description}),r.jsxs("span",{className:"agents-suggested-meta",children:[r.jsx("em",{children:ie.category}),r.jsx("em",{className:$R(de.state),children:de.label}),r.jsx("em",{className:`risk-${ie.risk}`,children:OR(ie.risk)}),r.jsx("em",{children:ie.supportedPlatforms.map(BR).join(" · ")}),r.jsx("em",{className:de.available?"availability-ok":"availability-unavailable",children:ge}),de.available&&de.unsupportedDeviceIds.length>0&&r.jsxs("em",{className:"availability-warning",children:["Unsupported on ",de.unsupportedDeviceIds.length]})]})]}),r.jsx("button",{className:`agents-suggested-favorite ${re?"favorite":""}`,type:"button","aria-label":re?`Remove ${ie.title} from favorites`:`Add ${ie.title} to favorites`,"aria-pressed":re,onClick:()=>O(ie.id),children:r.jsx(ap,{size:14,fill:re?"currentColor":"none"})})]},ie.id)})]},U.category)),V.length===0&&r.jsx("p",{className:"agents-suggested-empty",children:"No tasks match this search or current filter."})]})]})}function WR({devices:e,mode:t,selectedIds:n,onModeChange:s,onToggle:a,permissionMode:i,onPermissionModeChange:c}){const u=e.filter(mu),d=n.filter(p=>u.some(h=>h.deviceId===p)).length;return r.jsxs("section",{className:"agents-target-picker","aria-label":"Agent targets",children:[r.jsxs("div",{className:"agents-target-toolbar",children:[r.jsx("span",{className:"agents-section-label",children:"Targets"}),r.jsxs("div",{className:"agents-target-modes",children:[r.jsxs("button",{className:t==="all"?"active":"",onClick:()=>s("all"),type:"button",children:[r.jsx(oc,{size:14})," All connected ",r.jsx("small",{children:u.length})]}),r.jsxs("button",{className:t==="selected"?"active":"",onClick:()=>s("selected"),type:"button",children:[r.jsx(Rs,{size:14})," Selected ",d]}),r.jsxs("button",{className:t==="auto"?"active":"",onClick:()=>s("auto"),type:"button",children:[r.jsx(Zs,{size:14})," Auto"]}),r.jsxs("button",{type:"button",disabled:!0,title:"Saved Client groups are coming next.",children:[r.jsx(oc,{size:14})," Group ",r.jsx("small",{children:"Soon"})]})]}),r.jsxs("label",{className:`agents-permission-picker permission-${i}`,children:[r.jsx(vu,{size:14}),r.jsx("span",{children:"Permission"}),r.jsxs("select",{value:i,onChange:p=>c(p.target.value),"aria-label":"Agent permission mode",children:[r.jsx("option",{value:"ask",children:"Ask"}),r.jsx("option",{value:"safe-auto",children:"Safe Auto"}),r.jsx("option",{value:"full-access",children:"Full Access"}),r.jsx("option",{value:"custom",children:"Custom"})]}),r.jsx(Sb,{size:13,"aria-hidden":"true"})]})]}),r.jsx("div",{className:"agents-target-list",children:e.length===0?r.jsx("span",{className:"agents-target-empty",children:"No Clients discovered."}):e.map(p=>{const h=mu(p),m=t==="all"||t==="auto"?h:n.includes(p.deviceId);return r.jsxs("label",{className:`agents-target-option ${m?"selected":""} ${h?"":"offline"}`,children:[r.jsx("input",{type:"checkbox",checked:m,disabled:!h||t!=="selected",onChange:()=>a(p.deviceId)}),r.jsx("span",{className:"agents-target-icon",children:r.jsx(pn,{size:15})}),r.jsxs("span",{children:[r.jsx("strong",{children:pu(p)}),r.jsx("small",{children:h?"Ready":p.connected?"Agent reconnecting":"Offline"})]}),m&&r.jsx(Rs,{className:"agents-target-check",size:15,"aria-hidden":"true"})]},p.deviceId)})})]})}const zR=800,Cg=5e3;function qR(){return typeof document>"u"||document.visibilityState==="visible"}function UR(e){return typeof document>"u"?()=>{}:(document.addEventListener("visibilitychange",e),()=>document.removeEventListener("visibilitychange",e))}function kg({poll:e,onResult:t,onError:n,intervalMs:s=zR,isVisible:a=qR,subscribeVisibility:i=UR,setTimeoutImpl:c=globalThis.setTimeout.bind(globalThis),clearTimeoutImpl:u=globalThis.clearTimeout.bind(globalThis),createAbortController:d=()=>new AbortController}){if(typeof e!="function")throw new TypeError("Agent polling requires a poll function.");const p={current:null};let h=!0,m=0,g=null,w=null;const v=()=>{g!==null&&(u(g),g=null)},y=()=>{!h||!a()||g!==null||p.current||(g=c(()=>{g=null,k()},s))},k=()=>{if(!h||!a()||p.current)return p.current;const E=++m,I=d();w=I;const F=Ya(p,()=>e(I.signal));return F.then(M=>{h&&E===m&&!I.signal.aborted&&t?.(M)},M=>{h&&E===m&&!I.signal.aborted&&n?.(M)}).finally(()=>{w===I&&(w=null),h&&a()&&y()}).catch(()=>{}),F},N=async()=>{if(!h)throw new Error("LiveDesk Agent polling owner is closed.");v(),m+=1;const E=p.current;if(w&&!w.signal.aborted&&w.abort(new Error("LiveDesk Agent polling was superseded by an explicit refresh.")),E)try{await E}catch{}if(!(!h||!a()))return v(),k()},A=i(()=>{if(v(),!a()){m+=1,w&&!w.signal.aborted&&w.abort(new Error("LiveDesk Agent polling paused while hidden."));return}k()});return k(),{refresh:N,stop(){h&&(h=!1,m+=1,v(),A?.(),w&&!w.signal.aborted&&w.abort(new Error("LiveDesk Agent polling owner closed.")))}}}async function VR(e,t){return Oe("/api/settings/agent/run",{method:"POST",body:JSON.stringify(t)},e)}async function GR(e,t,n={}){return Oe(`/api/settings/agent/runs/${encodeURIComponent(t)}`,n,e)}async function KR(e,t){return Oe(`/api/settings/agent/runs/${encodeURIComponent(t)}/cancel`,{method:"POST",body:JSON.stringify({})},e)}async function QR(e){return Oe("/api/settings/agent/runs/cancel-all",{method:"POST",body:JSON.stringify({})},e)}async function YR(e,t,n,s){return Oe(`/api/settings/agent/runs/${encodeURIComponent(t)}/approvals/${encodeURIComponent(n)}/approve`,{method:"POST",body:JSON.stringify({scope:s})},e)}async function XR(e,t,n,s="User rejected this action."){return Oe(`/api/settings/agent/runs/${encodeURIComponent(t)}/approvals/${encodeURIComponent(n)}/reject`,{method:"POST",body:JSON.stringify({reason:s})},e)}async function JR(e,t,n){return Oe(`/api/settings/agent/policies/${encodeURIComponent(t)}`,{method:"PUT",body:JSON.stringify({categories:n})},e)}async function ZR(e,t,n={}){return Oe(`/api/remote/tasks/${encodeURIComponent(t)}`,n,e)}async function eT(e,t){return Oe(`/api/remote/tasks/${encodeURIComponent(t)}/cancel`,{method:"POST",body:JSON.stringify({})},e)}async function tT(e,t){return Oe(`/api/remote/tasks/${encodeURIComponent(t)}/retry`,{method:"POST",body:JSON.stringify({failedOnly:!0})},e)}function Vo(e){return`${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function Vd(e,t){const n=new Map(t.map(s=>[s.deviceId,pu(s)]));return e.results.map(s=>({deviceId:s.deviceId,deviceName:s.deviceName||n.get(s.deviceId)||s.deviceId,status:gR(s.status),stage:s.stage||(s.status==="running"?"Checking processes":void 0),result:s.result,data:s.data,error:s.error,sequence:Number.isSafeInteger(s.sequence)?s.sequence:0}))}function nT(e,t){const n=new Map(t.map(s=>[s.deviceId,s]));return e.map(s=>{const a=n.get(s.deviceId);return!a||a.sequence<=s.sequence?s:a})}const rT={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 sT(e){return e==="safe-auto"?"Safe Auto":e==="full-access"?"Full Access":e==="custom"?"Custom":"Ask"}function aT(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase())}function iT(e){const t=e instanceof Error?e.message:String(e);return/agent-disabled/i.test(t)?"Enable Codex Agent in Settings before running commands.":/agent-no-target-devices|agent-target-not-connected|device-not-connected/i.test(t)?"The selected Client is reconnecting. Wait until its Agent status is Ready and try again.":/codex-auth-required/i.test(t)?"Codex sign-in is required on the Hub. Open Settings > Agent and test the Codex connection.":t}function Mg({hubUrl:e,devices:t,launchRequest:n,variant:s="page",selectedDeviceIds:a=[]}){const i=s==="dock",[c,u]=o.useState(i?a.length>0?"selected":"auto":"all"),[d,p]=o.useState(a),[h,m]=o.useState("auto"),[g,w]=o.useState(""),[v,y]=o.useState([]),[k,N]=o.useState(""),[C,A]=o.useState(""),[E,I]=o.useState(""),[F,M]=o.useState("safe-auto"),[H]=o.useState("custom-default"),[V,P]=o.useState(rT),[D,O]=o.useState([]),[X,G]=o.useState(""),[U,ie]=o.useState(!1),[j,re]=o.useState(null),[de,Q]=o.useState(!1),[ge,oe]=o.useState(""),[me,Ae]=o.useState(!1),[Te,Pe]=o.useState(null),Se=o.useRef(null),te=o.useRef(null),Ce=o.useRef(null),Fe=o.useRef(new Set),Le=o.useRef(new Set),Ue=o.useMemo(()=>t.filter(mu).map(Y=>Y.deviceId),[t]),ne=o.useMemo(()=>FR(rw,t,c,d,F,V),[V,t,F,d,c]);o.useEffect(()=>{i&&p(a)},[i,a]),o.useEffect(()=>{n?.deviceId&&(u("selected"),p([n.deviceId]),w(n.instruction),Ae(!1),window.requestAnimationFrame(()=>{Se.current?.focus(),Se.current?.setSelectionRange(n.instruction.length,n.instruction.length)}))},[n]);const ae=o.useCallback(Y=>{const K=Vd(Y,t);y(ee=>ee.map(R=>R.type==="task"&&R.batchId===Y.batchId?{...R,states:nT(R.states,K),status:Y.status}:R)),["running","queued"].includes(Y.status)||N(ee=>ee===Y.batchId?"":ee)},[t]),le=o.useCallback((Y,K)=>{Le.current.has(Y.batchId)||(Le.current.add(Y.batchId),y(ee=>[...ee,{type:"task",id:Vo("task"),batchId:Y.batchId,agentRunId:K,operation:Y.operation||"diagnostics.collect",instruction:Y.instructionPreview,states:Vd(Y,t),status:Y.status}])),ae(Y)},[t,ae]),ce=o.useCallback((Y,K)=>{for(const R of K.taskBatches||[])le(R,Y);O(K.approvals||[]);const ee=["running","queued","waiting-approval"].includes(K.status);if(Pe(ee?{runId:Y,stage:K.stage||K.status,message:K.progressMessage||(K.status==="waiting-approval"?"Review the requested action to continue.":"Codex is preparing the answer.")}:R=>R?.runId===Y?null:R),!ee&&!Fe.current.has(Y)){Fe.current.add(Y);const R=[K.error,K.errorMessage].filter(Boolean).join(" — "),se=K.finalResponse?.trim()||(K.status==="cancelled"?"Codex 작업을 취소했습니다.":R?`Codex 작업이 완료되지 않았습니다: ${R}`:"Codex 작업이 완료되었습니다.");y(Ie=>[...Ie,{type:K.status==="failed"?"error":"agent",id:Vo("agent-run-result"),text:se}])}},[le]),J=o.useCallback(async Y=>{const K=te.current;if(!(!K||K.id!==Y))try{return await K.owner.refresh()}catch(ee){if(te.current!==K)return;throw ee}},[]);o.useEffect(()=>{if(!C){te.current=null;return}const Y=C,K=kg({poll:R=>GR(e,Y,{signal:R,timeoutMs:Cg}),onResult:R=>{ce(Y,R),["running","queued","waiting-approval"].includes(R.status)||(A(se=>se===Y?"":se),Q(!1))},onError:R=>{oe(R instanceof Error?R.message:String(R))}}),ee={id:Y,owner:K};return te.current=ee,()=>{K.stop(),te.current===ee&&(te.current=null)}},[C,e,ce]),o.useEffect(()=>{if(!k){Ce.current=null;return}const Y=k,K=kg({poll:R=>ZR(e,Y,{signal:R,timeoutMs:Cg}),onResult:R=>{ae(R),["running","queued"].includes(R.status)||N(se=>se===Y?"":se)},onError:R=>{oe(R instanceof Error?R.message:String(R))}}),ee={id:Y,owner:K};return Ce.current=ee,()=>{K.stop(),Ce.current===ee&&(Ce.current=null)}},[k,e,ae]);const ye=async(Y="",K,ee=!1)=>{const R=(Y||g).trim();if(!R||k||C)return;const se=K||(c==="all"||c==="auto"?Ue:d.filter(xe=>Ue.includes(xe)));if(se.length===0){oe("Select at least one connected Client.");return}if(F==="full-access"&&!de&&!ee){re({instruction:R,targetIds:se});return}if(y(xe=>[...xe,{type:"user",id:Vo("user"),text:R}]),w(""),Ae(!1),oe(""),se.length===0){y(xe=>[...xe,{type:"error",id:Vo("no-targets"),text:"연결된 대상 장비를 하나 이상 선택해 주세요."}]);return}const He=h==="ask"?`Read-only request. Inspect and answer without changing Client state.
168
168
 
169
169
  ${R}`:h==="plan"?`Plan only. Produce a safe execution plan, but do not change Client state.
170
170
 
@@ -172,7 +172,7 @@ ${R}`:h==="execute"?`Execute this request within the configured LiveDesk approva
172
172
 
173
173
  ${R}`:R,Be=c==="auto"?`Auto target selection is enabled. Inspect the allowed Clients and use only the most suitable target or targets for this request.
174
174
 
175
- ${He}`:He;try{if(F==="custom"){const Ge=await QR(e,H,V);if(!Ge.ok)throw new Error(Ge.error||"Custom Agent policy could not be saved.")}const xe=await zR(e,{instruction:Be,deviceIds:se,permissionMode:F,customPolicyId:H});if(!xe.ok||!xe.runId)throw new Error(xe.error||"Codex Agent run could not be started.");O(xe.approvals||[]),Pe({runId:xe.runId,stage:xe.stage||xe.status||"queued",message:xe.progressMessage||"Codex request queued on the Hub."}),A(xe.runId)}catch(xe){y(Ge=>[...Ge,{type:"error",id:zo("codex-run-error"),text:rT(xe)}])}},ue=async(Y,K)=>{G(Y.approvalId);try{const ee=await GR(e,Y.runId,Y.approvalId,K);if(!ee.ok)throw new Error(ee.error||"Agent approval could not be applied.");await J(Y.runId)}catch(ee){oe(ee instanceof Error?ee.message:String(ee))}finally{G("")}},Ee=async Y=>{G(Y.approvalId);try{const K=await KR(e,Y.runId,Y.approvalId);if(!K.ok)throw new Error(K.error||"Agent approval could not be rejected.");await J(Y.runId)}catch(K){oe(K instanceof Error?K.message:String(K))}finally{G("")}},nt=async(Y,K)=>{I(Y);try{if(K){const R=await UR(e,K);for(const se of R.taskBatches||[])ae(se);A(se=>se===K?"":se),Pe(se=>se?.runId===K?null:se);return}const ee=await XR(e,Y);ae(ee),N(R=>R===Y?"":R)}catch(ee){oe(ee instanceof Error?ee.message:String(ee))}finally{I("")}},T=async()=>{if(!(U||!k&&!C)){ie(!0);try{const Y=await VR(e);if(!Y.ok)throw new Error(Y.error||"모든 Agent 작업을 취소하지 못했습니다.");N(""),A(""),Pe(null),O([]),y(K=>K.map(ee=>ee.type==="task"&&["queued","running"].includes(ee.status)?{...ee,status:"cancelled",states:ee.states.map(R=>["queued","running"].includes(R.status)?{...R,status:"cancelled",stage:"Cancelled",error:"Cancelled by user."}:R)}:ee))}catch(Y){oe(Y instanceof Error?Y.message:String(Y))}finally{ie(!1)}}},ve=async Y=>{I(Y);try{const K=await JR(e,Y);if(!K.ok||!K.batch||!K.batchId)throw new Error(K.error||"재시도하지 못했습니다.");y(ee=>ee.map(R=>R.type==="task"&&R.batchId===Y?{...R,batchId:K.batchId,states:Ud(K.batch,t),status:K.batch.status}:R)),N(K.batchId)}catch(K){oe(K instanceof Error?K.message:String(K))}finally{I("")}},De=Y=>{w(Y),Ae(!1),window.requestAnimationFrame(()=>Se.current?.focus())},qe=o.useMemo(()=>t.filter(mu),[t]),_e=o.useMemo(()=>qe.filter(Y=>d.includes(Y.deviceId)),[qe,d]),$e=c==="auto"?`Auto · ${qe.length} available`:c==="all"?`All ${qe.length} computers`:_e.length===1?pu(_e[0]):`${_e.length} selected`,mt=c==="auto"?"LiveDesk chooses the best computer for each task.":c==="all"?"The Agent may coordinate every connected computer.":_e.length>0?_e.map(pu).join(" · "):"Select one or more computers on the Wall.",ct=c==="selected"&&_e.length===1?["Diagnose this computer","Analyze recent errors","Summarize running applications","Check disk and GPU capacity"]:c==="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"],z=c==="selected"?_e.length>0?"What should this computer do?":"Choose a computer or use Auto.":c==="all"?"Use all your computers together.":"What should LiveDesk handle?",pe=c==="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 r.jsxs("section",{className:`agents-page ${i?"agents-dock-console":""}`,children:[i&&r.jsxs("header",{className:"agent-console-header",children:[r.jsxs("div",{className:"agent-console-title",children:[r.jsx("span",{className:"agent-console-mark",children:r.jsx(Xs,{size:16})}),r.jsxs("div",{children:[r.jsx("small",{children:"Hub Codex Agent"}),r.jsx("strong",{children:"Command Console"})]}),r.jsx("i",{children:"Ready"})]}),r.jsxs("section",{className:"agent-console-target","aria-label":"Agent target scope",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Target"}),r.jsx("strong",{children:$e}),r.jsx("small",{children:mt})]}),r.jsxs("div",{className:"agent-console-target-modes",children:[r.jsxs("button",{className:c==="selected"?"active":"",onClick:()=>u("selected"),type:"button",children:[r.jsx(Ns,{size:12})," Selected"]}),r.jsxs("button",{className:c==="all"?"active":"",onClick:()=>u("all"),type:"button",children:[r.jsx(sc,{size:12})," All"]}),r.jsxs("button",{type:"button",disabled:!0,title:"Saved Client groups are coming next.",children:[r.jsx(sc,{size:12})," Group"]}),r.jsxs("button",{className:c==="auto"?"active":"",onClick:()=>u("auto"),type:"button",children:[r.jsx(Xs,{size:12})," Auto"]})]})]}),r.jsx("div",{className:"agent-console-interaction-modes","aria-label":"Agent interaction mode",children:["auto","ask","plan","execute"].map(Y=>r.jsxs("button",{className:h===Y?"active":"",onClick:()=>m(Y),type:"button",children:[Y==="auto"?r.jsx(Xs,{size:12}):Y==="execute"?r.jsx(pn,{size:12}):null,Y[0].toUpperCase()+Y.slice(1)]},Y))})]}),r.jsxs("div",{className:"agents-workspace",children:[(k||C)&&r.jsxs("div",{className:"agents-page-status",children:[r.jsxs("span",{children:[Ue.length," Clients · ",tT(F)]}),r.jsx("button",{type:"button",className:"agents-stop-all",onClick:()=>{T()},disabled:U,children:U?"Stopping…":"Stop all"})]}),j&&r.jsx("div",{className:"agents-permission-modal-backdrop",role:"presentation",children:r.jsxs("section",{className:"agents-permission-modal",role:"dialog","aria-modal":"true","aria-labelledby":"full-access-title",children:[r.jsx("span",{className:"agents-permission-modal-icon",children:r.jsx(vu,{size:20})}),r.jsx("h3",{id:"full-access-title",children:"Confirm Full Access"}),r.jsx("p",{children:"Codex may change files, run commands, manage applications, and modify system state on the selected Clients. This run is still limited to the selected devices, the fixed policy, and the tool budget."}),r.jsxs("div",{className:"agents-permission-modal-actions",children:[r.jsx("button",{type:"button",onClick:()=>re(null),children:"Cancel"}),r.jsx("button",{type:"button",className:"danger",onClick:()=>{const Y=j;re(null),Q(!0),ye(Y.instruction,Y.targetIds,!0)},children:"Run with Full Access"})]})]})}),ge&&r.jsx("div",{className:"agents-error",role:"alert",children:ge}),r.jsx(SR,{items:v,onCancel:nt,onRetry:ve,busyBatchId:E,approvals:D,onApprove:ue,onReject:Ee,busyApprovalId:X,progress:Te,emptyTitle:i?z:void 0,emptyBody:i?pe:void 0}),i&&v.length===0&&!Te&&r.jsx("div",{className:"agent-console-suggestions","aria-label":"Suggested Agent commands",children:ct.map(Y=>r.jsx("button",{type:"button",onClick:()=>De(Y),children:Y},Y))}),r.jsxs("div",{className:"agents-composer-shell",children:[me&&r.jsx($R,{devices:t,targetMode:c,selectedIds:d,permissionMode:F,customCategories:V,onSelectPrompt:De,onClose:()=>Ae(!1)}),r.jsx(dR,{ref:Se,value:g,onChange:w,onSubmit:()=>{ye()},onOpenSuggestedTasks:()=>Ae(Y=>!Y),suggestedOpen:me,suggestedTaskCount:ne,disabled:!!k||!!C,placeholder:i?"Tell LiveDesk what outcome you want...":void 0,compact:i})]})]}),!i&&r.jsxs("aside",{className:"agents-target-sidebar","aria-label":"Agent targets and permissions",children:[r.jsx(OR,{devices:t,mode:c,selectedIds:d,onModeChange:u,onToggle:Y=>p(K=>K.includes(Y)?K.filter(ee=>ee!==Y):[...K,Y]),permissionMode:F,onPermissionModeChange:Y=>{M(Y),Y!=="full-access"&&Q(!1)}}),F==="custom"&&r.jsxs("section",{className:"agents-custom-policy","aria-label":"Custom Agent permissions",children:[r.jsxs("div",{className:"agents-custom-policy-head",children:[r.jsxs("div",{children:[r.jsx("span",{className:"agents-section-label",children:"Custom policy"}),r.jsx("strong",{children:"Choose what Codex may do automatically."})]}),r.jsx("span",{children:"Denied actions never reach a device."})]}),r.jsx("div",{className:"agents-custom-policy-grid",children:pR.map(Y=>r.jsxs("label",{children:[r.jsx("span",{children:nT(Y)}),r.jsxs("select",{value:V[Y],onChange:K=>P(ee=>({...ee,[Y]:K.target.value})),children:[r.jsx("option",{value:"allow",children:"Allow automatically"}),r.jsx("option",{value:"ask",children:"Ask every time"}),r.jsx("option",{value:"deny",children:"Deny"})]})]},Y))})]})]})]})}function rw(e){return{type:e.type,deviceIds:e.deviceIds,monitorIndex:e.monitorIndex,label:e.label}}async function sw(e){try{return(await e.json()).error||`${e.status} ${e.statusText}`}catch{return`${e.status} ${e.statusText}`}}async function aw(e,t,n){const s=encodeURIComponent(JSON.stringify({kind:t.kind,fileName:t.fileName,mimeType:e.type||"application/octet-stream",durationMs:t.durationMs,target:rw(t.target)})),a=await ub(`/api/captures?metadata=${s}`,{method:"POST",headers:{"Content-Type":e.type||"application/octet-stream"},body:e},n);if(!a.ok)throw new Error(await sw(a));return await a.json()}async function sT(e,t){return await Oe("/api/capture-sessions",{method:"POST",body:JSON.stringify({...e,target:rw(e.target)})},t)}async function aT(e,t,n,s){const a=await ub(`/api/capture-sessions/${encodeURIComponent(e)}/chunks/${t}`,{method:"PUT",headers:{"Content-Type":n.type||"application/octet-stream"},body:n},s);if(!a.ok)throw new Error(await sw(a));return await a.json()}async function iT(e,t,n){return await Oe(`/api/capture-sessions/${encodeURIComponent(e)}/finalize`,{method:"POST",body:JSON.stringify({durationMs:t})},n)}async function kg(e,t){await Oe(`/api/capture-sessions/${encodeURIComponent(e)}`,{method:"DELETE"},t)}async function oT(e){return await Oe("/api/captures",void 0,e)}function Mg(e,t){return`${cb(t)}/api/captures/${encodeURIComponent(e)}/content`}async function cT(e,t){return await Oe(`/api/captures/${encodeURIComponent(e)}`,{method:"DELETE"},t)}function lT({hubUrl:e,onToast:t}){const[n,s]=o.useState([]),[a,i]=o.useState(!0),c=o.useCallback(async()=>{i(!0);try{s((await oT(e)).captures||[])}catch(d){t(d instanceof Error?d.message:String(d))}finally{i(!1)}},[e,t]);o.useEffect(()=>{c()},[c]);const u=async d=>{const p=Mg(d.id,e);if(navigator.share)try{await navigator.share({title:d.fileName,url:p});return}catch{}window.open(p,"_blank","noopener,noreferrer")};return r.jsxs("section",{className:"capture-gallery",children:[r.jsxs("header",{children:[r.jsxs("div",{children:[r.jsx("span",{className:"settings-eyebrow",children:"Capture Gallery"}),r.jsx("h2",{children:"Saved captures"})]}),r.jsxs("button",{className:"text-button",onClick:()=>{c()},type:"button",children:[r.jsx(Ya,{size:15})," Refresh"]})]}),a?r.jsx("p",{className:"settings-help",children:"Loading captures..."}):n.length===0?r.jsx("p",{className:"settings-help",children:"No captures saved yet."}):r.jsx("div",{className:"capture-gallery-grid",children:n.map(d=>{const p=Mg(d.id,e);return r.jsxs("article",{className:"capture-gallery-card",children:[d.mimeType.startsWith("image/")?r.jsx("img",{src:p,alt:d.target.label}):r.jsx("video",{src:p,controls:!0,preload:"metadata"}),r.jsxs("div",{className:"capture-gallery-card-body",children:[r.jsx("strong",{children:d.fileName}),r.jsxs("small",{children:[d.target.label," · ",new Date(d.createdAt).toLocaleString()," · ",Math.ceil(d.sizeBytes/1024)," KB"]}),r.jsxs("div",{children:[r.jsx("button",{className:"icon-button",title:"Open","aria-label":"Open",onClick:()=>window.open(p,"_blank","noopener,noreferrer"),type:"button",children:r.jsx(cx,{size:15})}),r.jsx("a",{className:"icon-button",title:"Download","aria-label":"Download",href:`${p}?download=1`,download:d.fileName,children:r.jsx(rc,{size:15})}),r.jsx("button",{className:"icon-button",title:"Share","aria-label":"Share",onClick:()=>{u(d)},type:"button",children:r.jsx(Sb,{size:15})}),r.jsx("button",{className:"icon-button danger",title:"Delete","aria-label":"Delete",onClick:()=>{window.confirm(`Delete ${d.fileName}?`)&&cT(d.id,e).then(()=>c()).catch(h=>t(h instanceof Error?h.message:String(h)))},type:"button",children:r.jsx(vb,{size:15})})]})]})]},d.id)})})]})}function Ol(e){if(!e)return"";const t=Math.max(0,Math.floor((Date.now()-e)/1e3)),n=Math.floor(t/3600),s=Math.floor(t%3600/60),a=t%60;return n>0?`${String(n).padStart(2,"0")}:${String(s).padStart(2,"0")}:${String(a).padStart(2,"0")}`:`${String(s).padStart(2,"0")}:${String(a).padStart(2,"0")}`}function Ag({controller:e,compact:t=!1,onFirstRollingUse:n,onError:s}){const{state:a,settings:i,videoSupported:c}=e,u=async m=>{try{await m()}catch(g){s?.(g instanceof Error?g.message:String(g))}},d=async()=>{if(i.rollingEnabled){e.setRollingEnabled(!1);return}(n?await n():window.confirm(`Keep the most recent 30 seconds in memory temporarily?
176
- Nothing is saved until you press Save Last 30s.`))&&e.setRollingEnabled(!0)},p=a.recording?`Stop recording · ${Ol(a.recordingStartedAt)}`:`Start recording · ${a.targetLabel}`,h=a.timelapse?`Stop timelapse · ${Ol(a.timelapseStartedAt)}`:`Start timelapse · ${i.timelapseIntervalSeconds}s interval`;return r.jsxs("div",{className:`capture-toolbar ${t?"compact":""} ${a.recording?"recording-active":""}`,"aria-label":"Capture actions",children:[r.jsx("button",{className:"capture-action","aria-label":`Take screenshot · ${a.targetLabel}`,title:`Take screenshot · ${a.targetLabel}`,disabled:a.busy,onClick:()=>{u(e.takeScreenshot)},type:"button",children:r.jsx(lx,{size:17})}),r.jsx("button",{className:`capture-action ${a.recording?"active":""}`,"aria-label":p,title:p,disabled:!c||a.busy||a.timelapse,onClick:()=>{u(a.recording?e.stopRecording:e.startRecording)},type:"button",children:a.recording?r.jsxs(r.Fragment,{children:[r.jsx(Oh,{size:14,fill:"currentColor"}),r.jsx("span",{children:Ol(a.recordingStartedAt)})]}):r.jsx(wb,{size:18})}),r.jsxs("button",{className:"capture-action","aria-label":a.bufferEnabled?`Save last 30 seconds · ${a.bufferSeconds}s ready`:"Enable Last 30s memory buffer",title:a.bufferEnabled?`Save last 30 seconds · ${a.bufferSeconds}s ready`:"Enable Last 30s memory buffer",disabled:!c||a.recording||a.timelapse||a.busy||a.bufferEnabled&&a.bufferSeconds<1,onClick:()=>a.bufferEnabled?void u(e.saveLast30Seconds):void d(),type:"button",children:[r.jsx(ux,{size:17}),r.jsx("small",{children:"30s"})]}),r.jsx("button",{className:`capture-action ${a.timelapse?"timelapse-active":""}`,"aria-label":h,title:h,disabled:!c||a.busy||a.recording,onClick:()=>{u(a.timelapse?e.stopTimelapse:e.startTimelapse)},type:"button",children:a.timelapse?r.jsxs(r.Fragment,{children:[r.jsx(Oh,{size:14,fill:"currentColor"}),r.jsx("span",{children:Ol(a.timelapseStartedAt)})]}):r.jsx(dx,{size:17})})]})}function iw({state:e}){return e==="ok"?r.jsx(En,{size:15,"aria-hidden":"true"}):r.jsx(xb,{size:15,"aria-hidden":"true"})}function Ng({active:e,refreshing:t,onClick:n}){return r.jsx("button",{className:`remote-status-button ${e?"active":""}`,type:"button",title:"Check Remote Status","aria-label":"Check Remote Status","aria-pressed":e,"aria-busy":t,onClick:n,children:t?r.jsx("span",{className:"remote-status-spinner","aria-hidden":"true"}):r.jsx(px,{size:18,"aria-hidden":"true"})})}function Rg({active:e,refreshing:t,onClick:n}){return r.jsx("button",{className:`remote-status-button debug-status-button ${e?"active":""}`,type:"button",title:"Check Debug Status","aria-label":"Check Debug Status","aria-pressed":e,"aria-busy":t,onClick:n,children:t?r.jsx("span",{className:"remote-status-spinner","aria-hidden":"true"}):r.jsx(pb,{size:18,"aria-hidden":"true"})})}function Tg({active:e,refreshing:t,onClick:n}){return r.jsx("button",{className:`remote-status-button hub-status-button ${e?"active":""}`,type:"button",title:"Check Hub Status","aria-label":"Check Hub Status","aria-pressed":e,"aria-busy":t,onClick:n,children:t?r.jsx("span",{className:"remote-status-spinner","aria-hidden":"true"}):r.jsx(os,{size:18,"aria-hidden":"true"})})}function ow({items:e,mode:t="remote"}){return r.jsx("span",{className:`remote-status-lines mode-${t}`,role:"status","aria-label":t==="debug"?"Debug status":"Remote status",onPointerDown:t==="debug"?n=>n.stopPropagation():void 0,onClick:t==="debug"?n=>n.stopPropagation():void 0,onDoubleClick:t==="debug"?n=>n.stopPropagation():void 0,children:e.map(n=>r.jsxs("span",{className:`remote-status-line state-${n.state}`,title:n.detail,children:[r.jsx(iw,{state:n.state}),r.jsxs("span",{children:[r.jsx("strong",{children:n.label}),r.jsx("small",{children:n.detail})]})]},n.id))})}function uT({items:e,collectedAt:t,onClose:n}){return r.jsxs("section",{className:"remote-status-dialog hub-status-dialog",role:"dialog","aria-modal":"false","aria-labelledby":"hub-status-dialog-title",children:[r.jsxs("header",{children:[r.jsx("span",{className:"remote-status-dialog-mark","aria-hidden":"true",children:r.jsx(os,{size:19})}),r.jsxs("span",{children:[r.jsx("small",{children:"Hub measurements"}),r.jsx("h2",{id:"hub-status-dialog-title",children:"Hub Status"})]}),r.jsx("button",{type:"button",onClick:n,title:"Close Hub status","aria-label":"Close Hub status",children:r.jsx(xn,{size:17})})]}),r.jsx("p",{children:"LiveDesk collects these Hub and browser signals continuously. This check refreshed the latest snapshot instead of starting a one-time benchmark."}),r.jsx("div",{className:"remote-status-dialog-list",children:e.map(s=>r.jsxs("article",{className:`remote-status-dialog-row state-${s.state}`,children:[r.jsx(iw,{state:s.state}),r.jsxs("span",{children:[r.jsx("strong",{children:s.label}),r.jsx("small",{children:s.detail})]})]},s.id))}),r.jsxs("footer",{children:["Checked ",new Date(t).toLocaleTimeString()]})]})}const dT=/(nvenc|videotoolbox|qsv|quick\s*sync|amf|vaapi|v4l2m2m|mediafoundation|h264_mf)/i,pT=/(libx264|openh264|software|cpu)/i,jp=2,mT=256,$a=new Map,ut=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 kt(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function lm(e,t){let n=e;for(const s of String(t).split(".")){if(!n||typeof n!="object")return;n=n[s]}return n}function Je(e,...t){for(const n of t){const s=lm(e,n);if(s==null||s==="")continue;const a=Number(s);if(Number.isFinite(a))return a}}function ft(e,...t){for(const n of t){const s=lm(e,n);if(typeof s=="string"&&s.trim())return s.trim()}return""}function cw(e,...t){for(const n of t){const s=lm(e,n);if(typeof s=="boolean")return s;if(s===1||s==="1"||String(s).toLowerCase()==="true")return!0;if(s===0||s==="0"||String(s).toLowerCase()==="false")return!1}}function Fr(e,...t){const n=Je(e,...t);if(n!==void 0)return Math.max(0,Math.min(1,n>1?n/100:n))}function Re(e,t,n,s){return{id:e,state:t,label:n,detail:s}}function lw(e){const t=kt(e),n=Je(t,"helperCount"),s=Je(t,"helperOwnedIoTaskCount"),a=Je(t,"helperUndisposedProcessCount"),i=Je(t,"helperOwnedExitObserverCount"),c=Je(t,"helperQuarantineCount"),u=Je(t,"utilityQuarantineCount"),d=Je(t,"utilityOwnedIoTaskCount"),p=Je(t,"utilityUndisposedProcessCount"),h=Number(Je(t,"helperDisposeFailureCount")||0),m=Number(Je(t,"utilityDisposeFailureCount")||0),g=Math.max(0,Number(n||0)),w=Number(s||0),v=Number(a||0),y=Number(i||0),k=Math.max(0,Number(c||0)),N=Math.max(0,Number(u||0)),C=Number(d||0),A=Number(p||0),E=[s,a,i,c,u,d,p].every(M=>M!==void 0),I=E&&(w<0||v<0||y<0||v!==g||y!==0||g===0&&w!==0||g>0&&w===0),F=E&&(C<0||A<0||A!==N||C!==N*2);return{telemetryAvailable:E,helperOwnedIoTaskCount:w,helperUndisposedProcessCount:v,helperOwnedExitObserverCount:y,helperQuarantineCount:k,helperDisposeFailureCount:h,helperLastDisposeFailure:ft(t,"helperLastDisposeFailure"),helperLedgerMismatch:I,utilityQuarantineCount:N,utilityOwnedIoTaskCount:C,utilityUndisposedProcessCount:A,utilityQuarantinePids:Array.isArray(t.utilityQuarantinePids)?t.utilityQuarantinePids.map(M=>Number(M)).filter(M=>Number.isSafeInteger(M)&&M>0):[],utilityQuarantineProfiles:Array.isArray(t.utilityQuarantineProfiles)?t.utilityQuarantineProfiles.map(M=>String(M||"").trim()).filter(Boolean).slice(0,4):[],utilityQuarantineStartCount:Math.max(0,Number(Je(t,"utilityQuarantineStartCount")||0)),utilityQuarantineStopCount:Math.max(0,Number(Je(t,"utilityQuarantineStopCount")||0)),utilityDisposeFailureCount:m,utilityLastDisposeFailure:ft(t,"utilityLastDisposeFailure"),utilityLedgerMismatch:F,historicalCleanupFailure:h!==0||m!==0,currentProblem:k>0||N>0||I||F}}function uw({key:e,sampleId:t,mismatch:n}){if(!e)return{count:0,confirmed:!1};if(!n)return $a.delete(e),{count:0,confirmed:!1};const s=String(t||"").trim();if(!s)return{count:0,confirmed:!1};const a=tc(s),i=$a.get(e);if(i?.sampleId===s)return{count:i.count,confirmed:i.count>=jp};const c=i&&a!==void 0&&i.sampleEpochMs!==void 0&&a>i.sampleEpochMs,u=i&&c?i.count+1:1;return!$a.has(e)&&$a.size>=mT&&$a.delete($a.keys().next().value),$a.set(e,{sampleId:s,sampleEpochMs:a,count:u}),{count:u,confirmed:u>=jp}}function tc(e){const t=Date.parse(String(e||""));return Number.isFinite(t)&&t>0?t:void 0}function Pg(e){return`${(Math.max(0,Number(e||0))/1024**3).toFixed(1)} GB`}function qs(e){const t=Number(e);return Number.isFinite(t)?`${(Math.max(0,t)/1024**2).toFixed(0)} MB`:"-"}function Us(e){const t=Number(e);return Number.isFinite(t)?`${(Math.max(0,t)*100).toFixed(1)}%`:"-"}function Bl(e){const t=Number(e);return Number.isFinite(t)?`${Math.max(0,t).toFixed(1)}%`:"-"}function hT(e){const t=String(e||"").replace(/^::ffff:/,"").trim().toLowerCase();if(!t||t==="::1"||t==="localhost"||t==="127.0.0.1"||/^10\./.test(t)||/^192\.168\./.test(t))return!0;const n=t.match(/^172\.(\d{1,3})\./);return!!n&&Number(n[1])>=16&&Number(n[1])<=31||t.startsWith("fe80:")||t.startsWith("fc")||t.startsWith("fd")}function dw(e){const t=kt(e),n=ft(t,"controlTransport").toLowerCase();return n==="encrypted-rendezvous-relay"||/relay/.test(n)?"encrypted-rendezvous-relay":n==="direct-tcp"||/direct|tcp/.test(n)?"direct-tcp":""}function Ig(e){const t=String(e||"").trim();if(!t)return"";try{return new URL(t.includes("://")?t:`relay://${t}`).host}catch{return t.replace(/[?#].*$/,"").replace(/^[a-z][a-z0-9+.-]*:\/\//i,"").split("@").pop().split("/")[0].slice(0,256)}}function fT(e){const t=dw(e);return t==="encrypted-rendezvous-relay"?Re("control-transport","ok","Control connection: Encrypted rendezvous relay","Commands and remote input use the end-to-end encrypted rendezvous relay."):t==="direct-tcp"?Re("control-transport","ok","Control connection: Direct TCP","Commands and remote input use the direct Hub connection."):Re("control-transport","warning","Control connection is not identified","Waiting for Direct TCP or encrypted rendezvous relay status.")}function gT(e,t){const n=kt(e),s=kt(t),a=dw(n);if(a==="encrypted-rendezvous-relay"){const i=ft(s,"state")||(s.connected===!0?"registered":"unknown"),c=Ig(ft(s,"endpoint"))||Ig(ft(n,"relayEndpoint")),u=n.connected!==!0||s.connected===!1||/(connecting|reconnect|failed|error|degraded|unavailable|disabled)/.test(i);return Re("debug-control-transport",u?"warning":"ok",`Encrypted rendezvous relay control · ${i}`,[`endpoint ${c||"-"}`,`state ${i}`,`reconnect ${Math.max(0,Number(s.reconnectCount||0))}`,`handshake ${Math.max(0,Number(s.handshakeCount||0))}`,`peers ${Math.max(0,Number(s.peerCount||0))}`,ft(s,"lastError")].filter(Boolean).join(" · "))}if(a==="direct-tcp"){const i=ft(n,"remoteAddress"),c=Je(n,"remotePort"),u=i?`${i}${c?`:${c}`:""}`:"-";return Re("debug-control-transport",n.connected===!0?"ok":"warning","Direct TCP control",`peer ${u} · protocol ${ft(n,"protocol")||"-"} v${Je(n,"protocolVersion")??"-"} · input ${kt(n.channels).input===!1?"shared control channel":"dedicated channel"}`)}return Re("debug-control-transport","warning","Control transport is not identified","No Direct TCP or encrypted rendezvous relay metadata is available.")}function pw(e,t){const n=Number(e?.browserReceivedEpochMs);return Number.isFinite(n)&&n>0?Math.max(0,t-n):Number.POSITIVE_INFINITY}function mw(e,t,n){const s=kt(t?.frameTransport),a=ft(e,"frameTransportChangedAt"),i=ft(s,"changedAt"),c=tc(a),u=tc(i),d=u!==void 0&&(c===void 0||u>c),p=d?s:e,h=d?e:s,m=ft(e,"transport").toLowerCase(),g=ft(p,d?"active":"frameTransportActive")||ft(h,d?"frameTransportActive":"active"),w=ft(p,d?"protocol":"frameTransportProtocol")||ft(h,d?"frameTransportProtocol":"protocol"),y=(d?ft(s,"videoTransport","activeTransport")||[g,w].filter(Boolean).join("-")||ft(e,"videoTransport"):ft(e,"videoTransport")||ft(s,"videoTransport","activeTransport")||[g,w].filter(Boolean).join("-")).toLowerCase(),k=/(?:^|[-_])ws(?:$|[-_])|websocket/.test(y)||/(?:^|[-_])ws(?:$|[-_])|websocket/.test(m),C=/relay/.test(y)||/relay/.test(m)?"encrypted-relay":/p2p|udp/.test(y)||m==="udp-p2p"?"p2p-udp":/direct|tcp|ws|websocket/.test(y)||m==="binary"||k?k?"direct-ws":"direct-tcp":"",A=(ft(p,d?"state":"frameTransportState")||ft(h,d?"frameTransportState":"state")||(C?"active":"")).toLowerCase(),E=ft(p,d?"reason":"frameTransportReason")||ft(h,d?"frameTransportReason":"reason"),I=d?i||a:a||i,F=tc(I),M=F===void 0?void 0:Math.max(0,n-F),H=M===void 0?"":M<1e3?"changed now":M<6e4?`changed ${Math.round(M/1e3)}s ago`:M<36e5?`changed ${Math.round(M/6e4)}m ago`:`changed ${I}`,V=d?s.switchCount??e?.frameTransportSwitchCount:e?.frameTransportSwitchCount??s.switchCount,P=d?s.tcpFailureCount??e?.frameTransportTcpFailureCount:e?.frameTransportTcpFailureCount??s.tcpFailureCount,D=d?typeof s.p2pReady=="boolean"?s.p2pReady:e?.frameTransportP2pReady===!0:typeof e?.frameTransportP2pReady=="boolean"?e.frameTransportP2pReady:s.p2pReady===!0;return{rawTransport:m,videoTransport:C,state:A,reason:E,changedAt:I,changedLabel:H,switchCount:Math.max(0,Number(V??0)||0),tcpFailureCount:Math.max(0,Number(P??0)||0),p2pReady:D}}function bT(e,t,n){const s=mw(e,t,n),a=/(connecting|recovering|failed|error|degraded|unavailable)/.test(s.state);if(s.videoTransport==="encrypted-relay")return Re("transport",a?"warning":"ok",a?"Encrypted TCP relay fallback needs attention":"Encrypted TCP relay fallback",a?`End-to-end encrypted TCP relay is ${s.state||"not ready"}; open Debug Status for the technical reason${s.changedLabel?` · ${s.changedLabel}`:""}.`:`End-to-end encrypted TCP relay fallback is active${s.changedLabel?` · ${s.changedLabel}`:""}.`);if(s.videoTransport==="p2p-udp")return Re("transport",a?"warning":"ok",a?"P2P video connection needs attention":"P2P video connection",a?`Encrypted UDP P2P is ${s.state||"not ready"}; open Debug Status for the technical reason${s.changedLabel?` · ${s.changedLabel}`:""}.`:`Encrypted UDP P2P fallback is active${s.changedLabel?` · ${s.changedLabel}`:""}.`);if(s.videoTransport==="direct-tcp"||s.videoTransport==="direct-ws"){const i=s.videoTransport==="direct-ws"?"WebSocket":"TCP";return Re("transport",a?"warning":"ok",a?"Direct video connection needs attention":"Direct video connection",a?`Direct ${i} to Hub is ${s.state||"not ready"}; open Debug Status for the technical reason${s.changedLabel?` · ${s.changedLabel}`:""}.`:`Direct ${i} to Hub is active${s.changedLabel?` · ${s.changedLabel}`:""}.`)}return Re("transport","warning","Video transport is not identified",s.reason||"Waiting for Direct TCP, encrypted UDP P2P, or encrypted TCP relay transport data.")}const vT=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 hw(e){const n=String(e?.platformProfile||"").toLowerCase().includes("macos-screencapturekit"),s=Number(e?.nativeCaptureTelemetryVersion)>=5&&vT.every(i=>Je(e,i)!==void 0)&&typeof e?.nativeOutputQueueAwaitingKeyFrame=="boolean"&&e?.nativeCopyTelemetryAvailable===!0,a=e?.nativeCaptureTelemetryAvailable===!0&&e?.nativeCaptureResourceTelemetryAvailable===!0&&s;return{required:n,available:a,pending:Math.max(0,Number(e?.nativeEncodePendingFrameCount||0)),timestampOwners:Math.max(0,Number(e?.nativeEncodeTimestampOwnerCount||0)),timestampOwnerHighWatermark:Math.max(0,Number(e?.nativeEncodeTimestampOwnerHighWatermark||0)),coalesced:Math.max(0,Number(e?.nativeBackpressureCoalescedFrameCount||0)),pendingReplaced:Math.max(0,Number(e?.nativeEncodePendingReplacedFrameCount||0)),vtActive:Math.max(0,Number(e?.nativeVideoToolboxActiveSessionCount||0)),vtHighWatermark:Math.max(0,Number(e?.nativeVideoToolboxSessionHighWatermark||0)),outputOldestAgeMs:Math.max(0,Number(e?.nativeOutputQueueOldestAgeMs||0)),nativeAndPipeResidenceAgeMs:Math.max(0,Number(e?.nativeAndPipeResidenceAgeMs||0)),handoffDropped:Math.max(0,Number(e?.handoffDroppedFrameCount||0)),handoffRecoveryRequests:Math.max(0,Number(e?.handoffRecoveryKeyFrameRequestCount||0)),handoffOldestAgeMs:Math.max(0,Number(e?.handoffOldestFrameAgeMs||0)),annexBAllocations:Math.max(0,Number(e?.nativeAnnexBAccessUnitAllocationCount||0)),annexBPayloadCopies:Math.max(0,Number(e?.nativeAnnexBPayloadCopyCount||0)),annexBPayloadCopiedBytes:Math.max(0,Number(e?.nativeAnnexBPayloadCopiedBytes||0)),pipePayloadAllocations:Math.max(0,Number(e?.pipePayloadAllocationCount||0)),pipePayloadCopies:Math.max(0,Number(e?.pipePayloadCopyCount||0)),pipePayloadCopiedBytes:Math.max(0,Number(e?.pipePayloadCopiedBytes||0))}}function wT(e){const t=String(e?.frameMode||e?.mode||e?.codec||"").toLowerCase(),n=[e?.hardwareEncoder,e?.platformProfile].filter(Boolean).join(" · "),s=cw(e,"nativeEncoderHardwareAccelerated"),a=e?.nativeEncoderHardwareAccelerationKnown===!0||s!==void 0,i=hw(e);return!e||!/h264/.test(t)?Re("encoder","warning","Video encoder unavailable","Waiting for an H.264 frame."):i.required&&!i.available?Re("encoder","warning","H.264 encoder resource status is unavailable",`${n||"Native encoder"} has not provided complete VideoToolbox v5 ownership, queue, and copy telemetry.`):i.required&&(i.vtActive!==1||i.vtHighWatermark>1||i.timestampOwners>2||i.timestampOwnerHighWatermark>2)?Re("encoder","warning","VideoToolbox encoder ownership needs attention",`${i.vtActive} active session(s); high-water ${i.vtHighWatermark}; timestamp owners ${i.timestampOwners}/2 (HWM ${i.timestampOwnerHighWatermark})`):i.required&&i.coalesced>0?Re("encoder","warning","Hardware H.264 encoding is under load",`${i.coalesced} current-window frame(s) were coalesced while the encoder was busy.`):a&&s===!1?Re("encoder","warning","H.264 hardware acceleration is not active",`${n||"Native encoder"} is running without confirmed hardware acceleration.`):a&&s===!0?Re("encoder","ok","Hardware H.264 encoding",`${n||"Native encoder"} · hardware acceleration confirmed`):dT.test(n)?Re("encoder","ok","Hardware H.264 encoding",n):pT.test(n)?Re("encoder","warning","Software H.264 encoding",`${n||"CPU encoder"} may limit frame rate.`):Re("encoder","warning","H.264 encoder not identified",n||"The Client has not reported its active encoder profile.")}function yT({device:e,frame:t,receiveStat:n,paintStat:s,codec:a,selectedMonitorIndex:i=0,control:c=!1,controlInputReady:u=!1,controlBinding:d,hubRelay:p,capturePaused:h=!1,capturePauseConfirmed:m=!0,capturePauseError:g="",clientHeartbeatMs:w=5e3,now:v=Date.now()}={}){const y=kt(e),k=kt(y.status),N=kt(s?.lastInfo),C=[],A=pw(t,v);C.push(fT(y)),C.push(h?m?Re("connection","ok","Video capture is paused","Client screen capture and video encoder shutdown were confirmed by the Client."):Re("connection","warning","Video stop needs attention",String(g||"The Hub is blocking video restart, but the Client did not confirm screen capture and video encoder shutdown.")):y.connected===!0&&A<=ut.frameAgeWarningMs?Re("connection","ok","Video connection is current",`${Math.round(A)}ms since the latest frame.`):Re("connection","warning",y.connected===!0?"Video frame is stale":"Client is offline",y.connected===!0&&Number.isFinite(A)?`${Math.round(A)}ms since the latest frame.`:String(y.lastDisconnectReason||"No current Client session."))),C.push(bT(t,k,v)),C.push(wT(t));const E=lw(k.capture),I=kt(k.capture),F=uw({key:`${String(y.deviceId||y.id||"")}:capture-cleanup`,sampleId:ft(I,"sampledAt"),mismatch:E.helperLedgerMismatch||E.utilityLedgerMismatch});(E.helperQuarantineCount>0||E.utilityQuarantineCount>0||F.confirmed)&&C.push(Re("capture-cleanup","warning","Video capture cleanup needs attention",`capture quarantine ${E.helperQuarantineCount} · utility quarantine ${E.utilityQuarantineCount} · owned I/O ${E.helperOwnedIoTaskCount+E.utilityOwnedIoTaskCount} · exit observers ${E.helperOwnedExitObserverCount} · undisposed processes ${E.helperUndisposedProcessCount+E.utilityUndisposedProcessCount}`));const M=Math.max(0,Number(t?.requestedFps||t?.effectiveFps||0)),H=Math.max(0,Number(n?.framesPerSecond||0));Math.max(0,Number(t?.sourceGapMs||0));const V=Math.max(0,Number(t?.nativeCaptureFps||0)),P=Math.max(0,Number(t?.nativeEncodedFps||0)),D=Math.max(0,Number(t?.nativeCaptureSampleCount||0)),O=Math.max(0,Number(t?.nativeCaptureTelemetryVersion||0)),X=Je(t,"nativeCaptureTelemetryAgeMs"),U=Math.max(0,Number(X||0))+(Number.isFinite(A)?A:0),ie=O<2||X!==void 0&&U<=ut.nativeTelemetryStaleMs,j=Math.max(0,Number(t?.nativeBackpressureSkippedFrameCount||0)),re=Math.max(0,Number(t?.nativeIdleSkippedFrameCount||0)),de=t?.nativeCaptureTelemetryAvailable===!0&&D>0&&ie,Q=Je(t,"captureP95Ms","captureAverageMs","captureStageMs"),ge=Math.max(0,Number(Q||0)),oe=t?.captureTimingAvailable===!0&&M>0&&Number(n?.sampleMs||0)>0&&Q!==void 0,me=oe||de,Ae=Math.max(ut.minimumCaptureBudgetMs,M>0?1e3/M*ut.captureBudgetMultiplier:0),Te=M>0?1e3/M:100,Pe=M>0&&V>=M*ut.receiveRatioWarning,Se=P>0&&P<M*ut.receiveRatioWarning,te=de&&Pe&&Se&&P>=1&&re>=Math.max(10,V*.6)&&j===0,Ce=de&&M>0&&(V<M*ut.receiveRatioWarning||!te&&P>0&&P<M*ut.receiveRatioWarning),Fe=de?Ce:oe&&ge>Ae;C.push(me?Fe?Re("capture","warning","Screen capture cannot keep target speed",de?`${V.toFixed(1)} native capture · ${P.toFixed(1)} encoded · ${M||"?"} requested fps`:`${ge?`capture p95 ${Math.round(ge)}ms`:"capture timing unavailable"} · ${H.toFixed(1)}/${M||"?"} fps`):Re("capture","ok","Screen capture speed is healthy",de?`${V.toFixed(1)} native capture · ${P.toFixed(1)} encoded · ${M||"?"} requested fps${te?" · idle optimized":""}`:`${ge?`capture p95 ${Math.round(ge)}ms`:"no slow capture reported"}${M?` · ${H.toFixed(1)}/${M} fps`:""}`):Re("capture","warning","Screen capture data is still collecting","A current frame-rate and capture-time sample is required."));const Le=Je(t,"hubPacketTransitAgeMs"),Ue=Math.max(0,Number(Le||0)),ne=Math.max(0,Number(t?.agentSendGapMs||0)),ae=Math.max(0,Number(t?.agentSendDurationMs||0)),le=!hT(y.remoteAddress),ce=Fr(k,"network.usageRatio"),J=Je(k,"network.latencyMs"),ye=(ce??0)>=ut.networkUsageWarningRatio||(J??0)>=ut.networkLatencyWarningMs,ue=t?.hubClientQueueTelemetryAvailable===!0||Je(t,"hubClientDropped")!==void 0&&Je(t,"hubClientQueueDepth")!==void 0&&Je(t,"hubClientQueueLimit")!==void 0&&Je(t,"hubClientBufferedBytes")!==void 0,Ee=ue?Math.max(0,Number(t?.hubClientQueueDepth||0)):0,nt=ue?Math.max(0,Number(t?.hubClientQueueLimit||0)):0,T=ue&&nt>0&&Ee>=nt,ve=Le!==void 0&&Number(n?.sampleMs||0)>0,De=!te&&M>0&&Number(n?.sampleMs||0)>0&&H<M*ut.deliveryRatioWarning,qe=!te&&ne>Math.max(ut.networkDelayWarningMs,Te*3),_e=Ue>ut.networkDelayWarningMs||qe||ae>ut.networkDelayWarningMs||De||A>ut.frameAgeWarningMs||ye||T;C.push(ve?_e||le?Re("network","warning",le?"External network route may add delay":ye?"Client network adapter needs attention":T?"Hub browser video queue needs attention":"Video delivery is uneven",[Ue?`${Math.round(Ue)}ms Hub-to-browser`:"",ne?`${Math.round(ne)}ms Client send gap`:"",ae?`${Math.round(ae)}ms Client send time`:"",De?`${H.toFixed(1)} of ${M} requested fps`:"",J!==void 0?`${Math.round(J)}ms Client network latency`:"",ce!==void 0?`${Math.round(ce*100)}% Client link use`:"",ue&&nt>0?`Hub queue ${Ee}/${nt}`:"",le?String(y.remoteAddress||"external route"):""].filter(Boolean).join(" · ")||"Frame delivery is not current."):Re("network","ok","Network delivery is healthy",`${Math.round(Ue)}ms Hub-to-browser · ${te?`idle optimized at ${P.toFixed(1)} fps`:"the current video rate is on target."}`):Re("network","warning","Network delivery data is still collecting","A calibrated Hub-to-browser transit sample is required."));const $e=Fr(k,"cpu.usageRatio","cpu.usedRatio","cpu.percent"),mt=Fr(k,"memory.usedRatio","usedMemRatio"),ct=Fr(k,"gpu.usageRatio"),z=Fr(k,"gpu.memory.usedRatio"),pe=Je(k,"gpu.temperatureC","thermal.gpuC"),Y=$e!==void 0&&mt!==void 0,K=tc(y.lastStatusAt),ee=K===void 0?Number.POSITIVE_INFINITY:Math.max(0,v-K),R=Math.max(ut.minimumClientStatusFreshMs,Math.max(1e3,Number(w||0))*ut.clientStatusFreshMultiplier),se=ee<=R,Ie=($e??0)>=ut.cpuWarningRatio||(mt??0)>=ut.memoryWarningRatio||(ct??0)>=ut.gpuWarningRatio||(z??0)>=ut.gpuMemoryWarningRatio||(pe??0)>=ut.gpuTemperatureWarningC;C.push(Y?se?Ie?Re("computer","warning",(ct??0)>=ut.gpuWarningRatio||(z??0)>=ut.gpuMemoryWarningRatio||(pe??0)>=ut.gpuTemperatureWarningC?"Client GPU is under load":"Client computer is under load",[`CPU ${Math.round($e*100)}%`,`memory ${Math.round(mt*100)}%`,ct!==void 0?`GPU ${Math.round(ct*100)}%`:"",z!==void 0?`GPU memory ${Math.round(z*100)}%`:"",pe!==void 0?`GPU ${Math.round(pe)}C`:""].filter(Boolean).join(" · ")):Re("computer","ok","Client computer has working capacity",[`CPU ${Math.round($e*100)}%`,`memory ${Math.round(mt*100)}%`,ct!==void 0?`GPU ${Math.round(ct*100)}%`:""].filter(Boolean).join(" · ")):Re("computer","warning","Client performance snapshot is stale",Number.isFinite(ee)?`The latest CPU and memory report is ${Math.round(ee/1e3)} seconds old.`:"No current Client performance heartbeat has been received."):Re("computer","warning","Client performance data is unavailable","CPU and memory telemetry have not been reported yet."));const He=Number(t?.monitorIndex),Be=Number.isInteger(He)&&He===Number(i),xe=kt(y.channels),Ge=kt(y.capabilities),rt=xe.input!==!1&&Ge.remoteInput!==!1&&Ge.accessibilityPermission!==!1,Ke=Ge.screenRecordingPermission!==!1,gt=kt(d),_=!c||String(t?.sessionId||"")&&String(t?.sessionId||"")===String(gt.sessionId||"")&&String(t?.commandId||"")&&String(t?.commandId||"")===String(gt.commandId||"")&&Number(t?.captureGeneration||0)>0&&Number(t?.captureGeneration||0)===Number(gt.captureGeneration||0)&&Number(t?.monitorIndex)===Number(gt.monitorIndex),je=!c||u&&_;C.push(Be&&je&&rt&&Ke?Re("display","ok",c?"Display and remote input are bound":"Display and remote input are available",`Display ${Number(i)+1} · generation ${Number(t?.captureGeneration||0)||"current"}.`):Re("display","warning",Ke?rt?c?"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(i)+1}; latest frame ${Number.isInteger(He)?He+1:"not available"}.`));const Qe=kt(a),Ye=Array.isArray(Qe.canvases)?kt(Qe.canvases[0]):{},Gt=Math.max(0,Number(s?.decoderInputFps||0)),en=Math.max(0,Number(s?.decoderOutputFps||0)),zn=Gt>0&&Number(s?.sampleMs||n?.sampleMs||0)>0,Sr=H>0&&Number(n?.sampleMs||0)>0&&Number(s?.sampleMs||0)>0&&Gt<H*ut.decoderInputRatioWarning,qn=Gt>0?en/Gt:0,Fn=ft(Ye,"configuredAcceleration","requestedAcceleration")||ft(N,"h264DecodeAcceleration"),Sn=ft(Ye,"softwareFallbackReason"),nr=!!Sn||Fn==="prefer-software";return C.push(Sr?Re("decoder","warning","Browser decoder input is dropping frames",`${H.toFixed(1)} received / ${Gt.toFixed(1)} decoder input / ${en.toFixed(1)} output fps.`):zn?nr||qn<ut.decoderOutputRatioWarning?Re("decoder","warning",nr?"Browser is using software H.264 fallback":"Browser decoder output is slow",`${Sn||String(N.decoderLabel||Fn||"decoder")} · ${Gt.toFixed(1)} in / ${en.toFixed(1)} out fps.`):Re("decoder","ok",Fn==="prefer-hardware"?"Browser requests hardware H.264":"Browser H.264 path is responsive",`${Gt.toFixed(1)} in / ${en.toFixed(1)} out fps. Chrome does not expose definitive hardware acceptance.`):Re("decoder","warning","Browser decoder data is still collecting","Decoder input and output samples are required before this path can be marked healthy.")),C}function ns(e){const t=String(e||"").trim();return t?t.length<=14?t:`${t.slice(0,6)}…${t.slice(-5)}`:"-"}function Pt(e,t=1){const n=Number(e);return Number.isFinite(n)?n.toFixed(t):"-"}function xT({device:e,frame:t,receiveStat:n,paintStat:s,codec:a,selectedMonitorIndex:i=0,control:c=!1,controlInputReady:u=!1,controlBinding:d,hubRelay:p,now:h=Date.now()}={}){const m=kt(e),g=kt(m.status),w=kt(g.runtimeProcess),v=kt(g.capture),y=lw(v),k=kt(d),N=kt(s?.lastInfo),C=kt(a),A=Array.isArray(C.canvases)?kt(C.canvases[0]):{},E=[],I=Number(i),F=Number(t?.monitorIndex),M=Number.isInteger(F)&&F===I,H=Number(t?.captureGeneration||0),V=Number(k.captureGeneration||0),P=!c||M&&String(t?.sessionId||"")===String(k.sessionId||"")&&String(t?.commandId||"")===String(k.commandId||"")&&H>0&&H===V,D=Math.max(0,Number(t?.requestedFps||t?.effectiveFps||0)),O=Math.max(0,Number(n?.framesPerSecond||0)),X=Math.max(0,Number(s?.framesPerSecond||0)),G=Math.max(0,Number(s?.decoderInputFps||0)),U=Math.max(0,Number(s?.decoderOutputFps||0)),ie=Number(n?.sampleMs||0)>0&&Number(s?.sampleMs||0)>0,j=D>0&&ie&&Math.min(O,X||O,U||O)<D*ut.deliveryRatioWarning,re=Math.max(0,Number(t?.sourceGapMs||0)),de=Math.max(0,Number(t?.agentSendGapMs||0)),Q=Math.max(0,Number(t?.agentSendDurationMs||0)),ge=Math.max(0,Number(t?.agentSendDurationFrameSeq||0)),oe=Math.max(0,Number(t?.agentQueueBeforePaceMs||0)),me=Math.max(0,Number(t?.agentFrameAgeMs||0)),Ae=Je(t,"hubPacketTransitAgeMs"),Te=Math.max(0,Number(t?.droppedByAgent||0)),Pe=Math.max(0,Number(t?.hubIngressDropped||0)),Se=t?.hubClientQueueTelemetryAvailable===!0||Je(t,"hubClientDropped")!==void 0&&Je(t,"hubClientQueueDepth")!==void 0&&Je(t,"hubClientQueueLimit")!==void 0&&Je(t,"hubClientBufferedBytes")!==void 0,te=Se?Math.max(0,Number(t?.hubClientDropped||0)):0,Ce=Se?Math.max(0,Number(t?.hubClientQueueDepth||0)):0,Fe=Se?Math.max(0,Number(t?.hubClientQueueLimit||0)):0,Le=Se?Math.max(0,Number(t?.hubClientBufferedBytes||0)):0,Ue=Math.max(0,Number(t?.udpIncompleteFrames||0)),ne=Te+Pe+te,ae=pw(t,h),le=ft(A,"configuredAcceleration","requestedAcceleration")||ft(N,"h264DecodeAcceleration"),ce=ft(A,"softwareFallbackReason"),J=Math.max(0,Number(C.hardwareReleaseGeneration||0)),ye=Math.max(0,Number(C.hardwareRecoveryProbeCount||0)),ue=Number(C.lastHardwareRecoveryProbeAt),Ee=Number.isFinite(ue)&&ue>0?Math.max(0,h-ue):void 0,nt=`hardware releases ${J} · recovery probes ${ye} · last probe ${Ee===void 0?"-":`${Math.round(Ee)}ms ago`}`,T=ie&&O>0&&G<O*ut.decoderInputRatioWarning,ve=mw(t,g,h),De=ft(m,"deviceId")||ft(t,"deviceId"),qe=ft(t,"sessionId")||ft(m,"sessionId"),_e=ft(m,"productVersion")||ft(g,"productVersion","runtime.productVersion"),$e=ft(m,"agentVersion")||ft(g,"agentVersion","runtime.agentVersion"),mt=Je(m,"pid","runtimePid")??Je(g,"pid","runtimePid","process.pid"),ct=Je(w,"pid"),z=Fr(w,"cpuUsageRatio"),pe=Je(w,"cpuCorePercent"),Y=Je(w,"workingSetBytes"),K=Je(w,"privateMemoryBytes"),ee=Math.max(Y||0,K||0),R=(ct??0)>0&&(Y??0)>0,se=R&&(mt??0)>0&&ct!==mt,Ie=(z??0)>=ut.runtimeProcessCpuWarningRatio||ee>=ut.runtimeProcessMemoryWarningBytes,He=Fr(g,"cpu.usageRatio"),Be=Fr(g,"memory.usedRatio","usedMemRatio"),xe=Math.max(0,Number(Je(v,"videoStreamCount")||0)),Ge=Math.max(0,Number(Je(v,"audioStreamCount")||0)),rt=Je(v,"helperCount"),Ke=Math.max(0,Number(rt||0)),gt=Je(v,"helperAliveCount"),_=gt===void 0?Ke:Math.max(0,Number(gt||0)),je=Je(v,"helperExitedOwnedCount"),Qe=Math.max(0,Number(je||0)),Ye=Je(v,"helperMaxConcurrent"),Gt=Math.max(Ke,Number(Ye||0)),en=Array.isArray(v.helperPids)?v.helperPids.map(Fs=>Number(Fs)).filter(Fs=>Number.isSafeInteger(Fs)&&Fs>0):[],zn=Array.isArray(v.helperProfiles)?v.helperProfiles.map(Fs=>String(Fs||"").trim()).filter(Boolean).slice(0,4):[],on=Fr(v,"helperCpuUsageRatio"),Sr=Je(v,"helperCpuCorePercent"),qn=Je(v,"helperWorkingSetBytes"),Fn=Je(v,"helperPrivateMemoryBytes"),Sn=Math.max(qn||0,Fn||0),nr=Math.max(0,Number(Je(v,"helperStartCount")||0)),bt=Math.max(0,Number(Je(v,"helperStopCount")||0)),Z=rt!==void 0,be=gt!==void 0&&je!==void 0,We=Z&&nr>=bt&&(nr-bt!==Ke||be&&_+Qe!==Ke),lt=Ke>1||_>1||Gt>1||xe>1||We||y.currentProblem,It=Z&&(xe>0&&_===0||xe===0&&_>0),At=uw({key:De&&qe?`${De}:${qe}`:"",sampleId:ft(v,"sampledAt"),mismatch:It}),et=It&&!At.confirmed,Mt=lt||At.confirmed,Cn=(on??0)>=ut.captureHelperCpuWarningRatio||Sn>=ut.captureHelperMemoryWarningBytes,zt=!!(De&&qe&&_e&&$e&&(mt??0)>0),kn=t?.nativeCaptureTelemetryAvailable===!0,Nt=Math.max(0,Number(t?.nativeCaptureTelemetryVersion||0)),cn=Nt>=2,ht=hw(t),we=!ht.required||ht.available,Ot=Je(t,"nativeCaptureTelemetryAgeMs"),tn=Math.max(0,Number(Ot||0))+(Number.isFinite(ae)?ae:0),us=Ot===void 0?"-":`${Math.round(tn)}ms`,Ps=!cn||Ot!==void 0&&tn<=ut.nativeTelemetryStaleMs,Bt=kn&&!Ps,ds=cw(t,"nativeEncoderHardwareAccelerated"),hc=t?.nativeEncoderHardwareAccelerationKnown===!0||ds!==void 0,Za=ft(t,"nativeEncoderHardwareQueryStatus"),sa=Za==="0"?"confirmed":Za,fc=Math.max(0,Number(t?.nativeCaptureDisplayId||0)),ur=Math.max(0,Number(t?.nativeCaptureFps||0)),ei=Math.max(0,Number(t?.nativeCompressionOutputCount||0)),dr=Math.max(0,Number(t?.nativeCompressionFps||0)),pr=Math.max(0,Number(t?.nativeEncodedFps||0)),rr=cn||ei>0?dr:pr,nn=Math.max(0,Number(t?.nativeCaptureSampleCount||0)),aa=Math.max(0,Number(t?.nativeEncodableFrameCount||0)),qt=Math.max(0,Number(t?.nativeSkippedFrameCount||0)),ia=Math.max(0,Number(t?.nativeEncodedFrameCount||0)),Un=Math.max(0,Number(t?.nativeEncodeFramesInFlight||0)),oa=ht.pending,_r=ht.timestampOwners,ps=ht.timestampOwnerHighWatermark,gc=ht.coalesced,Is=Math.max(0,Number(t?.nativeBackpressureSkippedFrameCount||0)),Cr=ht.pendingReplaced,$r=Math.max(0,Number(t?.nativeIdleSkippedFrameCount||0)),bc=ht.vtActive,Or=ht.vtHighWatermark,ao=Math.max(0,Number(t?.nativeOutputQueueDepth||0)),ca=Math.max(0,Number(t?.nativeOutputQueueBytes||0)),Br=ht.outputOldestAgeMs,dm=Math.max(0,Number(t?.nativeOutputQueueHighWatermark||0)),Pu=Math.max(0,Number(t?.nativeOutputQueueDroppedCount||0)),ms=t?.nativeOutputQueueAwaitingKeyFrame===!0,io=ht.nativeAndPipeResidenceAgeMs,ot=ht.handoffDropped,oo=ht.handoffRecoveryRequests,rn=ht.handoffOldestAgeMs,la=Un>2||oa>1||_r>2||ps>2||gc>0||Un>=2&&Is>0,Ct=ht.required&&ht.available&&(bc!==1||Or>1||_r>2||ps>2),ti=ao>=3||ca>=6*1024*1024||Br>120||Pu>0||ms||io>250||ot>0||oo>0||rn>120,co=`in-flight ${Un}/2 · backpressure skipped ${Is} · idle skipped ${$r} · stdout queue ${ao} AU/${Math.round(ca/1024)} KB/${Math.round(Br)}ms · HWM ${dm} · dropped ${Pu} · awaiting key ${ms?"yes":"no"} · native+pipe ${Math.round(io)}ms · handoff ${Math.round(rn)}ms/drop ${ot}/recovery ${oo}`,js=`pending ${oa}/1; timestamp owners ${_r}/2 (HWM ${ps}); coalesced ${gc}; pending replaced ${Cr}; VideoToolbox ${bc} active/HWM ${Or}`,vc=ht.available&&ht.annexBAllocations>0&&ht.annexBPayloadCopies>=ht.annexBAllocations&&ht.annexBPayloadCopiedBytes>0&&ht.pipePayloadAllocations>0&&ht.pipePayloadCopies>=ht.pipePayloadAllocations&&ht.pipePayloadCopiedBytes>0,vt=`Annex-B allocation/copy ${ht.annexBAllocations}/${ht.annexBPayloadCopies} (${Math.round(ht.annexBPayloadCopiedBytes/1024)} KB) · pipe allocation/read ${ht.pipePayloadAllocations}/${ht.pipePayloadCopies} (${Math.round(ht.pipePayloadCopiedBytes/1024)} KB)`,ln=kn&&nn>0&&Ps,ni=D>0?1e3/D:100,lo=D>0&&ur>=D*ut.receiveRatioWarning,uo=rr>0&&rr<D*ut.receiveRatioWarning,Hr=ln&&lo&&uo&&rr>=1&&pr>=1&&$r>=Math.max(10,ur*.6)&&Is===0,ri=j&&!Hr,Dn=!Hr&&de>Math.max(ut.networkDelayWarningMs,ni*3),ua=ln&&D>0&&ur<D*ut.receiveRatioWarning,Es=ln&&!Hr&&ur>0&&(cn&&rr<=0||rr>0&&rr<ur*ut.receiveRatioWarning),wc=ln&&ei>0&&rr>0&&pr<rr*ut.receiveRatioWarning,Iu=Bt?"Native capture telemetry is stale":we?Ct?"VideoToolbox encoder ownership needs attention":ln?ua?"Native screen capture is below request":Es||la?"VideoToolbox compression is behind capture":wc||ti?"Native stdout delivery is backpressured":ds===!1?"Native hardware encoder is unavailable":"Native capture or encoder needs attention":"Native capture telemetry is unavailable":"Native encoder resource telemetry is unavailable";E.push(gT(m,p)),E.push(zt?Re("debug-runtime","ok",`LiveDesk ${_e} · Agent ${$e}`,`pid ${mt} · session ${ns(qe)} · device ${ns(De)}`):Re("debug-runtime","warning","Runtime identity is incomplete",`LiveDesk ${_e||"-"} · Agent ${$e||"-"} · pid ${mt??"-"} · session ${ns(qe)} · device ${ns(De)}`)),E.push(R&&!se&&!Ie?Re("debug-process-load","ok","RemoteFast process load is healthy",`pid ${ct} · CPU ${Us(z)} machine / ${Bl(pe)} core · RSS ${qs(Y)} · private ${qs(K)} · system CPU ${Us(He)} · memory ${Us(Be)}`):Re("debug-process-load","warning",R?se?"RemoteFast process identity does not match":"RemoteFast process load needs attention":"RemoteFast process telemetry is collecting",`runtime pid ${ct??"-"} · reported pid ${mt??"-"} · CPU ${Us(z)} machine / ${Bl(pe)} core · RSS ${qs(Y)} · private ${qs(K)} · system CPU ${Us(He)} · memory ${Us(Be)}`)),E.push(t?Re("debug-frame","ok",`Frame #${Number(t.frameSeq||0)} · ${String(t.streamPurpose||(c?"control":"wall"))}`,`stream ${ns(t.streamId)} · ${t.width||0}x${t.height||0} · ${Math.round(Number(t.byteLength||0)/1024)} KB · age ${Number.isFinite(ae)?Math.round(ae):"-"}ms`):Re("debug-frame","warning","No current frame",`Device ${ns(m.deviceId)} has not produced a frame.`));const ju=/(connecting|recovering|failed|error|degraded|unavailable)/.test(ve.state);E.push(ve.videoTransport&&!ju?Re("debug-transport","ok",`${ve.videoTransport==="encrypted-relay"?"Encrypted TCP relay fallback":ve.videoTransport==="p2p-udp"?"P2P UDP":ve.videoTransport==="direct-ws"?"Direct WebSocket":"Direct TCP"} · ${ve.state||"active"}`,[`raw ${ve.rawTransport||"-"}`,`P2P ${ve.p2pReady?"ready":"standby unavailable"}`,`switch ${ve.switchCount}`,`TCP failure ${ve.tcpFailureCount}`,ve.changedLabel,ve.reason].filter(Boolean).join(" · ")):Re("debug-transport","warning",ve.videoTransport?`Video transport ${ve.state||"needs attention"}`:"Video transport is not identified",[ve.videoTransport||"no active path",`raw ${ve.rawTransport||"-"}`,`P2P ${ve.p2pReady?"ready":"not ready"}`,ve.changedLabel,ve.reason].filter(Boolean).join(" · "))),E.push(M?Re("debug-monitor","ok",`Monitor selected ${I+1} · frame ${F+1}`,`reported ${Number(t?.monitorCount||0)||"?"} displays · generation ${H||"-"}`):Re("debug-monitor","warning",`Monitor mismatch: selected ${I+1} · frame ${Number.isInteger(F)?F+1:"-"}`,`reported ${Number(t?.monitorCount||0)||"?"} displays · generation ${H||"-"}`)),E.push(P&&(!c||u)?Re("debug-binding","ok",c?"Control generation is bound":"Wall capture generation is current",`session ${ns(t?.sessionId)} · command ${ns(t?.commandId)} · generation ${H||"-"}`):Re("debug-binding","warning",c?"Control generation is not bound":"Wall capture generation is unavailable",`frame ${ns(t?.commandId)}/${H||"-"} · expected ${ns(k.commandId)}/${V||"-"} · input ${u?"ready":"waiting"}`)),E.push(ie&&!ri?Re("debug-cadence","ok",`Cadence ${Pt(O)} rx · ${Pt(X)} paint · ${Pt(U)} decode`,`requested ${Pt(D)} · decoder input ${Pt(G)} fps · receive p95 ${Pt(n?.p95IntervalMs)}ms${Hr?" · idle optimized":""}`):Re("debug-cadence","warning",ie?"Frame cadence is below request":"Frame cadence sample is collecting",`requested ${Pt(D)} · receive ${Pt(O)} · paint ${Pt(X)} · decode ${Pt(U)} fps`)),E.push(ln&&we&&!ua&&!Es&&!wc&&!la&&!Ct&&!ti&&ds!==!1?Re("debug-native-capture","ok",`Native capture ${Pt(ur)} fps · compress ${Pt(rr)} fps · stdout ${Pt(pr)} fps${Hr?" · idle optimized":""}`,`telemetry v${Nt||1} · age ${us} · hardware ${hc?ds?"yes":"no":"unknown"}${sa?` (${sa})`:""} · display ${fc||"-"} · capture samples ${nn} · encodable ${aa} · skipped ${qt} · compression outputs ${ei} · stdout written ${ia} · ${co} · encoded AU output gap ${Math.round(re)}ms`):Re("debug-native-capture","warning",Iu,`telemetry ${kn?`v${Nt||1}`:"no"} · age ${us} · hardware ${hc?ds?"yes":"no":"unknown"}${sa?` (${sa})`:""} · display ${fc||"-"} · capture ${Pt(ur)} fps · compress ${Pt(rr)} fps · stdout ${Pt(pr)} fps · capture samples ${nn} · encodable ${aa} · skipped ${qt} · compression outputs ${ei} · stdout written ${ia} · ${co} · encoded AU output gap ${Math.round(re)}ms`)),ht.required&&(E.push(we&&!la&&!Ct?Re("debug-native-resource","ok","VideoToolbox resource ownership is bounded",js):Re("debug-native-resource","warning",we?Ct?"VideoToolbox session ownership is not exclusive":"VideoToolbox encode lane is coalescing":"VideoToolbox resource telemetry is unavailable",js)),E.push(we&&vc?Re("debug-native-copy","ok","Capture copy accounting is current",vt):Re("debug-native-copy","warning",we?"Capture copy accounting needs attention":"Capture copy accounting is unavailable",vt))),E.push(Z&&!Mt&&!Cn?Re("debug-capture-ownership","ok",et?"Capture ownership transition is settling":_>0?"Capture helper ownership is exclusive":"Capture helpers are idle",`video ${xe} · audio ${Ge} · helpers ${Ke} owned / ${_} alive / ${Qe} exiting (max ${Gt||"-"}) · pid ${en.join(",")||"-"} · profile ${zn.join(", ")||"-"} · CPU ${Us(on)} machine / ${Bl(Sr)} core · RSS ${qs(qn)} · private ${qs(Fn)} · starts ${nr} / stops ${bt}${et?` · mismatch samples ${At.count}/${jp}`:""}`):Re("debug-capture-ownership","warning",Z?Ke>1||_>1||Gt>1?"Duplicate capture helpers detected":Mt?"Capture stream and helper ownership do not match":"Capture helper load needs attention":"Capture process telemetry is collecting",`video ${xe} · audio ${Ge} · helpers ${Ke} owned / ${_} alive / ${Qe} exiting (max ${Gt||"-"}) · pid ${en.join(",")||"-"} · profile ${zn.join(", ")||"-"} · CPU ${Us(on)} machine / ${Bl(Sr)} core · RSS ${qs(qn)} · private ${qs(Fn)} · starts ${nr} / stops ${bt}`));const yc=`helper I/O ${y.helperOwnedIoTaskCount} | exit observers ${y.helperOwnedExitObserverCount} | undisposed ${y.helperUndisposedProcessCount} | quarantine ${y.helperQuarantineCount} | dispose failures ${y.helperDisposeFailureCount} | utility I/O ${y.utilityOwnedIoTaskCount} | undisposed ${y.utilityUndisposedProcessCount} | quarantine ${y.utilityQuarantineCount} | utility pid ${y.utilityQuarantinePids.join(",")||"-"} | profile ${y.utilityQuarantineProfiles.join(", ")||"-"} | utility starts ${y.utilityQuarantineStartCount} / stops ${y.utilityQuarantineStopCount} | dispose failures ${y.utilityDisposeFailureCount}${y.helperLastDisposeFailure?` | helper last ${y.helperLastDisposeFailure}`:""}${y.utilityLastDisposeFailure?` | utility last ${y.utilityLastDisposeFailure}`:""}`;E.push(y.telemetryAvailable&&!y.currentProblem&&!y.historicalCleanupFailure?Re("debug-capture-cleanup","ok",Ke>0?"Capture cleanup ownership is exact":"Capture cleanup is idle",yc):Re("debug-capture-cleanup","warning",y.telemetryAvailable?y.currentProblem?"Capture cleanup is quarantined or mismatched":"Capture cleanup recorded a disposal failure":"Capture cleanup telemetry is collecting",yc)),E.push(Se?ne===0&&Ue===0&&(Fe<=0||Ce<Fe)&&!Dn&&Q<=ut.networkDelayWarningMs&&me<=ut.networkDelayWarningMs&&(Ae===void 0||Ae<=ut.networkDelayWarningMs)?Re("debug-delivery","ok","Delivery counters are clear",`encoded AU output gap ${Math.round(re)}ms · Client send gap ${Math.round(de)}ms · Client send time ${Math.round(Q)}ms (frame ${ge||"-"}) · Agent queue ${Math.round(oe)}ms · Agent age ${Math.round(me)}ms · Agent drop ${Te} · Hub transit ${Ae===void 0?"-":Math.round(Ae)}ms · Hub ingress drop ${Pe} · browser queue drop ${te} (${Ce}/${Fe||"-"}) · buffered ${Math.round(Le/1024)} KB · UDP incomplete ${Ue}${Hr?" · idle optimized":""}`):Re("debug-delivery","warning","Delivery counters show loss or delay",`encoded AU output gap ${Math.round(re)}ms · Client send gap ${Math.round(de)}ms · Client send time ${Math.round(Q)}ms (frame ${ge||"-"}) · Agent queue ${Math.round(oe)}ms · Agent age ${Math.round(me)}ms · Agent drop ${Te} · Hub transit ${Ae===void 0?"-":Math.round(Ae)}ms · Hub ingress drop ${Pe} · browser queue drop ${te} (${Ce}/${Fe||"-"}) · buffered ${Math.round(Le/1024)} KB · UDP incomplete ${Ue}`):Re("debug-delivery","warning","Browser queue counters are available in Hub Status",`encoded AU output gap ${Math.round(re)}ms · Client send gap ${Math.round(de)}ms · Agent drop ${Te} · Hub ingress drop ${Pe} · per-browser lane counters are intentionally collected outside video packets.`));const po=Je(t,"captureP95Ms");return E.push(t?.captureTimingAvailable===!0&&po!==void 0?Re("debug-capture","ok",`Capture p95 ${Pt(po)}ms · avg ${Pt(t?.captureAverageMs)}ms`,`stage ${Pt(t?.captureStageMs)}ms · slow ${Number(t?.slowFrameCount||0)} · helper restart ${Number(t?.captureHelperRestarts||0)} · source skip ${Number(t?.captureSourceSkipped||0)}`):ln&&cn?Re("debug-capture","ok","Capture latency is not instrumented; native cadence is current",`ScreenCaptureKit ${Pt(ur)} fps · VideoToolbox ${Pt(rr)} fps · stdout ${Pt(pr)} fps · telemetry age ${us}`):Re("debug-capture","warning","Capture timing sample is unavailable",`stage ${Pt(t?.captureStageMs)}ms · helper restart ${Number(t?.captureHelperRestarts||0)} · source serial ${Number(t?.captureSourceSerial||0)}`)),E.push(!ce&&le!=="prefer-software"&&!T?Re("debug-decoder","ok",`Decoder ${le||"acceleration unknown"}`,`${String(t?.frameMode||t?.codec||"-")} · ${String(t?.hardwareEncoder||"-")} · ${String(t?.platformProfile||"-")} · ${nt}`):Re("debug-decoder","warning",T?"Decoder input is losing received frames":"Decoder software fallback is active",T?`${Pt(O)} received / ${Pt(G)} decoder input / ${Pt(U)} output fps · ${nt}`:`${ce||le||"software"} · ${Pt(G)} in / ${Pt(U)} out fps · ${nt}`)),E}function ST({status:e,deviceDiagnostics:t=[],codec:n,browser:s,frameStats:a}={}){const i=kt(e),c=kt(i.diagnostics),u=kt(c.system),d=kt(c.network),p=kt(n),h=kt(s),m=Array.isArray(t)?t:[],g=m.reduce((me,Ae)=>me+(Array.isArray(Ae)&&Ae.some(Te=>Te?.state==="warning")?1:0),0),w=Fr(u,"cpuUsageRatio","processCpuRatio"),v=Fr(u,"memoryUsedRatio"),y=Je(u,"totalMemoryBytes"),k=Je(u,"cpuLogicalCores")??Je(h,"hardwareConcurrency"),N=Je(h,"deviceMemory"),C=(k??0)>0&&w!==void 0&&v!==void 0&&(y??0)>0,A=(y??0)>0&&y<ut.hubMinimumTotalMemoryBytes,E=(N??0)>0&&N<ut.hubMinimumBrowserMemoryGb,I=(k??0)>0&&k<4||(w??0)>=ut.cpuWarningRatio||(v??0)>=ut.memoryWarningRatio||A||E,F=Math.max(0,Number(p.activeSoftwareFallbackCount??p.softwareFallbackCount??0)),M=Math.max(0,Number(p.activeDecoderCount||0)),H=Math.max(0,Number(a?.bytesPerSecond||0)*8/1e6),V=Je(d,"externalDeviceCount"),P=ft(d,"route"),D=V!==void 0&&!!P,O=(V??0)>0||P==="external",X=kt(i.frameLanes),G=kt(X.packetFanout),U=["packetBuilds","metadataSerializations","payloadCopyOperations","fanoutEligibleSubscribers"].every(me=>Je(G,me)!==void 0),ie=Array.isArray(X.clients)?X.clients.map(kt):[],j=Je(X,"clientCount")!==void 0&&Array.isArray(X.clients)&&U,re=ie.some(me=>{const Ae=Math.max(0,Number(me.queueDepth||0)),Te=Math.max(0,Number(me.queueLimit||0)),Pe=Math.max(0,Number(me.queuedBytes||0)),Se=Math.max(0,Number(me.queueByteLimit||0));return Math.max(0,Number(me.droppedPackets||0))>0||Te>0&&Ae>=Te||Se>0&&Pe>=Se||Array.isArray(me.backpressuredDeviceIds)&&me.backpressuredDeviceIds.length>0}),de=Math.max(0,Number(G.packetBuilds||0)),Q=Math.max(0,Number(G.metadataSerializations||0)),ge=Math.max(0,Number(G.payloadCopyOperations||0)),oe=Math.max(0,Number(G.fanoutEligibleSubscribers||0));return[i.started&&!i.lastError?Re("hub-runtime","ok","Hub runtime is ready",`${i.connectedDeviceCount||0} Clients connected.`):Re("hub-runtime","warning","Hub runtime needs attention",String(i.lastError||"Hub is not ready.")),C?I?Re("hub-computer","warning",A?"Hub has limited system memory":E?"Browser reports limited memory capacity":"Hub computer may limit remote performance",[`${k||"?"} logical cores`,`${Pg(y)} RAM`,N!==void 0?`${N} GB browser memory class`:"",`CPU ${w===void 0?"?":Math.round(w*100)}%`,`memory ${v===void 0?"?":Math.round(v*100)}%`].filter(Boolean).join(" · ")):Re("hub-computer","ok","Hub computer capacity is healthy",`${k||"?"} logical cores · ${Pg(y)} RAM · CPU ${w===void 0?"not reported":`${Math.round(w*100)}%`}.`):Re("hub-computer","warning","Hub performance data is unavailable","Logical-core, CPU, used-memory, and total-memory telemetry are required."),M<=0?Re("hub-codec","warning","No active browser H.264 decoder to check","Open Wall or Control and wait for a video frame."):F>0?Re("hub-codec","warning","Some browser decoders use software fallback",`${M} active H.264 decoders · ${F} software fallbacks. Chrome does not expose definitive hardware acceptance.`):Re("hub-codec","ok","All active streams request hardware H.264",`${M} active decoders. Chrome hardware acceptance is inferred from health, not directly exposed.`),j?re?Re("hub-frame-lanes","warning","A Hub browser video lane needs attention",`${ie.length}/${X.clientCount||0} lanes reported · packet builds ${de} · metadata serializations ${Q} · payload copies ${ge} · fanout deliveries ${oe}.`):Re("hub-frame-lanes","ok","Hub browser video lanes are bounded",`${ie.length}/${X.clientCount||0} lanes reported · packet builds ${de} · metadata serializations ${Q} · payload copies ${ge} · fanout deliveries ${oe}.`):Re("hub-frame-lanes","warning","Hub browser queue data is unavailable","Per-browser queue, drop, buffered-byte, and packet-allocation evidence is required."),g>0?Re("hub-clients","warning",`${g} Clients need attention`,"Open the matching Wall slot lines for the exact cause."):Re("hub-clients","ok","Connected Clients report healthy remote paths",`${m.length} Client reports checked.`),Re("hub-network",!D||O||H>120?"warning":"ok",D?O?`${V} Clients use an external network route`:H>120?"Hub receive load is high":"Hub receive load is within range":"Hub network route data is unavailable",D?`${P.toUpperCase()} route · ${H.toFixed(H>=10?0:1)} Mbps received by this browser.`:"The Hub has not reported LAN/external route classification yet.")]}async function CT(e,t={}){const n=e.filter(m=>m.canvas&&m.canvas.width>0&&m.canvas.height>0),s=Math.max(320,t.maxWidth||1920),a=Math.max(180,t.maxHeight||1080),i=n.length<=1?1:n.length<=4?2:n.length<=9?3:4,c=Math.max(1,Math.ceil(Math.max(1,n.length)/i)),u=Math.floor(s/i),d=Math.floor(a/c),p=document.createElement("canvas");p.width=Math.max(320,u*i),p.height=Math.max(180,d*c);const h=p.getContext("2d",{alpha:!1});if(!h)return p;h.fillStyle="#0b1220",h.fillRect(0,0,p.width,p.height),h.font="600 14px system-ui, sans-serif",h.textBaseline="bottom";for(let m=0;m<n.length;m+=1){const g=n[m],w=m%i,v=Math.floor(m/i),y=w*u,k=v*d,N=g.canvas,C=Math.min(u/N.width,d/N.height),A=Math.max(1,Math.floor(N.width*C)),E=Math.max(1,Math.floor(N.height*C)),I=y+Math.floor((u-A)/2),F=k+Math.floor((d-E)/2);h.drawImage(N,I,F,A,E),t.includeLabels!==!1&&(h.fillStyle="rgba(4, 10, 20, .74)",h.fillRect(y,k+d-28,u,28),h.fillStyle="#f8fafc",h.fillText(g.label,y+9,k+d-9))}return p}function kT(e){return e?.signature||"none"}function MT(e){return e?.label||"No capture target"}function jg(e){return{...e,deviceIds:[...e.deviceIds],sourceCanvas:e.sourceCanvas||null}}function AT(){const e=new Date,t=n=>String(n).padStart(2,"0");return`${e.getFullYear()}${t(e.getMonth()+1)}${t(e.getDate())}_${t(e.getHours())}${t(e.getMinutes())}${t(e.getSeconds())}`}function NT(e){return e.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"Wall"}function RT(e){return`LiveDesk_${e.type==="wall"||e.type==="selection"?"Wall":`${NT(e.label)}_Monitor-${Number(e.monitorIndex||0)+1}`}_${AT()}.png`}async function TT(e,t,n){const s=await new Promise((i,c)=>e.toBlob(u=>u?i(u):c(new Error("Screenshot could not be encoded.")),"image/png")),a=await aw(s,{kind:"screenshot",fileName:RT(t),target:t},n);try{await navigator.clipboard.write([new ClipboardItem({"image/png":s})])}catch{}return a.capture}function fw(){return["video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm"].find(t=>typeof MediaRecorder<"u"&&MediaRecorder.isTypeSupported(t))||""}function PT(e,t){const n=new Date().toISOString().replace(/[-:]/g,"").replace(/\.\d{3}Z$/,"").replace("T","_"),s=t.label.replace(/[^a-zA-Z0-9._-]+/g,"-").slice(0,70)||"Wall";return e==="timelapse"?`LiveDesk_Timelapse_${s}_${n}.webm`:`LiveDesk_Recording_${s}_${n}.webm`}async function gw(e){if(typeof MediaRecorder>"u"||typeof e.canvas.captureStream!="function")throw new Error("This browser does not support video recording.");const t=fw();if(!t)throw new Error("This browser does not support WebM recording.");const n=e.kind||"recording",s=await sT({kind:n,fileName:PT(n,e.target),mimeType:t,target:e.target},e.hubUrl),a=e.canvas.captureStream(e.frameRequests?0:e.fps),i=new MediaRecorder(a,{mimeType:t,videoBitsPerSecond:n==="timelapse"?2e6:4e6}),c=performance.now();let u=0,d=!1,p=null,h=Promise.resolve();return i.ondataavailable=m=>{if(!m.data||m.data.size===0)return;const g=u++;h=h.then(()=>aT(s.sessionId,g,m.data,e.hubUrl).then(()=>{})).catch(w=>{p=p||(w instanceof Error?w:new Error(String(w))),e.onError?.(p)})},i.onerror=()=>{p=new Error("Video recording stopped unexpectedly."),e.onError?.(p)},i.start(1e3),{requestFrame:()=>{a.getVideoTracks()[0]?.requestFrame?.()},stop:async()=>{if(!d){if(d=!0,await new Promise(m=>{i.addEventListener("stop",()=>m(),{once:!0}),i.stop()}),a.getTracks().forEach(m=>m.stop()),await h,p)throw await kg(s.sessionId,e.hubUrl).catch(()=>{}),p;await iT(s.sessionId,Math.max(0,performance.now()-c),e.hubUrl)}},cancel:async()=>{d||(d=!0,i.stop(),a.getTracks().forEach(m=>m.stop()),await kg(s.sessionId,e.hubUrl).catch(()=>{}))}}}class IT{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(t,n){if(this.recorder&&this.targetSignature===n.signature)return;if(this.stop(),typeof MediaRecorder>"u"||typeof t.captureStream!="function")throw new Error("This browser does not support Last 30s.");const s=fw();if(!s)throw new Error("This browser does not support WebM recording.");this.targetSignature=n.signature,this.stream=t.captureStream(20),this.recorder=new MediaRecorder(this.stream,{mimeType:s,videoBitsPerSecond:3e6}),this.startedAt=performance.now(),this.recorder.ondataavailable=a=>{if(!a.data.size)return;const i=performance.now();for(this.segments.push({blob:a.data,at:i}),this.totalBytes+=a.data.size;this.segments.length>1&&(i-this.segments[0].at>this.maxDurationMs||this.totalBytes>this.maxBytes);){const c=this.segments.shift();this.totalBytes-=c.blob.size}},this.recorder.start(1e3)}stop(){const t=this.recorder;this.recorder=null,t&&t.state!=="inactive"&&(t.ondataavailable=null,t.stop()),this.stream?.getTracks().forEach(n=>n.stop()),this.stream=null,this.segments=[],this.totalBytes=0,this.startedAt=0}async save(t,n){if(this.segments.length===0)throw new Error("The Last 30s buffer is not ready yet.");const s=new Blob(this.segments.map(c=>c.blob),{type:this.segments[0].blob.type||"video/webm"}),i=`LiveDesk_Last30s_${t.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 aw(s,{kind:"last-30s",fileName:i,target:t,durationMs:Math.min(3e4,this.segments.length*1e3)},n)}}async function jT(e,t,n,s,a){const i=await gw({canvas:e,target:t,kind:"timelapse",fps:30,frameRequests:!0,hubUrl:s,onError:a});i.requestFrame?.();const c=window.setInterval(()=>i.requestFrame?.(),Math.max(5,n)*1e3);return{stop:async()=>{window.clearInterval(c),await i.stop()},cancel:async()=>{window.clearInterval(c),await i.cancel()}}}const bw="livedesk.captureSettings";function ET(){const e={rollingEnabled:!1,recordingQuality:"standard",timelapseIntervalSeconds:10,includeRemoteCursor:!0};try{const t=JSON.parse(localStorage.getItem(bw)||"null");return{...e,...t&&typeof t=="object"?t:{}}}catch{return e}}function FT(e){const[t,n]=o.useState(ET),[s,a]=o.useState(0),[i,c]=o.useState(0),[u,d]=o.useState(0),[p,h]=o.useState(!1),m=o.useRef(void 0),g=o.useRef(!1),w=o.useRef(""),v=o.useRef(null),y=o.useRef(null),k=o.useRef(null),N=o.useRef(null),C=o.useRef(new IT),A=e.sourceRegistry.resolveCurrentTarget(),E=kT(A),I=MT(A),F=typeof MediaRecorder<"u"&&typeof HTMLCanvasElement<"u"&&"captureStream"in HTMLCanvasElement.prototype;o.useEffect(()=>{if(localStorage.setItem(bw,JSON.stringify(t)),!g.current)return;const re=JSON.stringify(t);re!==w.current&&(w.current=re,Oe("/api/settings",{method:"PATCH",body:JSON.stringify({revision:m.current,filesAudio:{rollingBufferEnabled:t.rollingEnabled,recordingQuality:t.recordingQuality,timelapseIntervalSeconds:t.timelapseIntervalSeconds,includeRemoteCursor:t.includeRemoteCursor}})},e.hubUrl).then(de=>{m.current=Number(de.revision||m.current||0)}).catch(()=>{}))},[e.hubUrl,t]),o.useEffect(()=>{let re=!0;return Oe("/api/settings",void 0,e.hubUrl).then(de=>{if(!re)return;const Q=de.settings?.filesAudio||{},ge=typeof Q.rollingBufferEnabled=="boolean"?Q.rollingBufferEnabled:t.rollingEnabled,oe=Q.recordingQuality==="high"?"high":"standard",me=[5,10,30,60].includes(Number(Q.timelapseIntervalSeconds))?Number(Q.timelapseIntervalSeconds):t.timelapseIntervalSeconds,Ae=typeof Q.includeRemoteCursor=="boolean"?Q.includeRemoteCursor:t.includeRemoteCursor,Te={rollingEnabled:ge,recordingQuality:oe,timelapseIntervalSeconds:me,includeRemoteCursor:Ae};m.current=Number(de.revision||0),w.current=JSON.stringify(Te),g.current=!0,n(Te)}).catch(()=>{g.current=!0}),()=>{re=!1}},[e.hubUrl]);const M=o.useCallback(async re=>{if(re.sourceCanvas&&re.sourceCanvas.width>0&&re.sourceCanvas.height>0)return{target:jg(re),canvas:re.sourceCanvas,cleanup:()=>{}};const de=await e.sourceRegistry.composeWall(re.deviceIds,{maxWidth:1920,maxHeight:1080,includeLabels:!0});let Q=!1;const ge=window.setInterval(async()=>{if(Q)return;const oe=await e.sourceRegistry.composeWall(re.deviceIds,{maxWidth:1920,maxHeight:1080,includeLabels:!0}).catch(()=>null);!oe||Q||((de.width!==oe.width||de.height!==oe.height)&&(de.width=oe.width,de.height=oe.height),de.getContext("2d")?.drawImage(oe,0,0))},100);return{target:jg(re),canvas:de,cleanup:()=>{Q=!0,window.clearInterval(ge)}}},[e.sourceRegistry]);o.useEffect(()=>{const re=C.current;if(!t.rollingEnabled||!A||!F){re.stop(),d(0);return}let de=!1,Q=null;return(async()=>{try{if(Q=await M(A),de)return;await re.start(Q.canvas,Q.target);const oe=window.setInterval(()=>d(Math.round(re.seconds)),500),me=()=>{window.clearInterval(oe),Q?.cleanup()};re.__cleanup=me}catch(oe){de||e.onToast(oe instanceof Error?oe.message:String(oe))}})(),()=>{de=!0,re.stop(),re.__cleanup?.(),re.__cleanup=void 0,d(0)}},[M,e.onToast,t.rollingEnabled,E,F]);const H=o.useCallback(re=>n(de=>({...de,rollingEnabled:re})),[]),V=o.useCallback(re=>n(de=>({...de,recordingQuality:re})),[]),P=o.useCallback(re=>n(de=>({...de,timelapseIntervalSeconds:re})),[]),D=o.useCallback(async()=>{const re=e.sourceRegistry.resolveCurrentTarget();if(!re)throw new Error("화면이 준비된 후 다시 시도하세요.");h(!0);let de=null;try{de=await M(re),await TT(de.canvas,de.target,e.hubUrl),e.onToast("Screenshot saved")}finally{de?.cleanup(),h(!1)}},[M,e.hubUrl,e.onToast,e.sourceRegistry]),O=o.useCallback(async()=>{if(k.current)throw new Error("Stop the timelapse before recording.");const re=e.sourceRegistry.resolveCurrentTarget();if(!re)throw new Error("화면이 준비된 후 다시 시도하세요.");const de=await M(re),Q=await gw({canvas:de.canvas,target:de.target,fps:re.type==="control"?30:15,hubUrl:e.hubUrl,onError:ge=>e.onToast(ge.message)});y.current=de.cleanup,v.current=Q,a(Date.now()),e.onToast("Recording started")},[M,e.hubUrl,e.onToast,e.sourceRegistry]),X=o.useCallback(async()=>{const re=v.current;if(re){h(!0);try{await re.stop(),e.onToast("Recording saved")}finally{v.current=null,y.current?.(),y.current=null,a(0),h(!1)}}},[e.onToast]),G=o.useCallback(async()=>{if(v.current||k.current)throw new Error("Last 30s is unavailable during a recording.");const re=e.sourceRegistry.resolveCurrentTarget();if(!re)throw new Error("화면이 준비된 후 다시 시도하세요.");h(!0);try{await C.current.save(re,e.hubUrl),e.onToast("Last 30 seconds saved")}finally{h(!1)}},[e.hubUrl,e.onToast,e.sourceRegistry]),U=o.useCallback(async()=>{if(v.current)throw new Error("Stop the recording before starting a timelapse.");const re=e.sourceRegistry.resolveCurrentTarget();if(!re)throw new Error("화면이 준비된 후 다시 시도하세요.");const de=await M(re),Q=await jT(de.canvas,de.target,t.timelapseIntervalSeconds,e.hubUrl,ge=>e.onToast(ge.message));N.current=de.cleanup,k.current=Q,c(Date.now()),e.onToast("Timelapse started")},[M,e.hubUrl,e.onToast,e.sourceRegistry,t.timelapseIntervalSeconds]),ie=o.useCallback(async()=>{const re=k.current;if(re){h(!0);try{await re.stop(),e.onToast("Timelapse saved")}finally{k.current=null,N.current?.(),N.current=null,c(0),h(!1)}}},[e.onToast]);return o.useEffect(()=>{const re=de=>{!v.current&&!k.current||(de.preventDefault(),de.returnValue="")};return window.addEventListener("beforeunload",re),()=>window.removeEventListener("beforeunload",re)},[]),o.useEffect(()=>()=>{C.current.stop(),v.current?.cancel(),k.current?.cancel(),y.current?.(),N.current?.()},[]),{state:o.useMemo(()=>({recording:!!v.current,recordingStartedAt:s,timelapse:!!k.current,timelapseStartedAt:i,bufferSeconds:u,bufferEnabled:t.rollingEnabled,busy:p,targetLabel:I}),[u,p,s,t.rollingEnabled,I,i]),settings:t,videoSupported:F,targetKey:E,setRollingEnabled:H,setRecordingQuality:V,setTimelapseInterval:P,takeScreenshot:D,startRecording:O,stopRecording:X,saveLast30Seconds:G,startTimelapse:U,stopTimelapse:ie}}function DT(){if(typeof window>"u")return{isIos:!1,isAndroid:!1,isSafari:!1,browserName:"browser"};const e=window.navigator.userAgent,t=window.navigator.standalone,n=nk(e,window.navigator.platform,window.navigator.maxTouchPoints,t),s=/Android/i.test(e),a=n&&/CriOS/i.test(e),i=n&&/Safari/i.test(e)&&!/(CriOS|FxiOS|EdgiOS|OPiOS|DuckDuckGo)/i.test(e);return{isIos:n,isAndroid:s,isSafari:i,browserName:a?"Chrome":i?"Safari":"browser"}}const LT=120,_T=999,vw="livedesk.remoteDirectory",Ep="livedesk.localHubAccessEnabled",$T="livedesk.streamSettings",OT=18,BT="livedesk.controlStreamSettings",HT=10,ww="livedesk.wallCadence",yw="livedesk.wallViewScale",xw="livedesk.mobileWallStatsVisible",WT=1e3,Sw="livedesk.wallMonitorSelections",Cw=2,Vd=512*1024,zT=250,qT=15e3,UT=!1;function VT(){return typeof navigator>"u"?!1:/Mac|iPhone|iPad|iPod/i.test(`${navigator.platform} ${navigator.userAgent}`)}function GT(e){let t="";for(let n=0;n<e.length;n+=32*1024)t+=String.fromCharCode(...e.subarray(n,Math.min(e.length,n+32*1024)));return window.btoa(t)}function Eg(e){const t=window.atob(String(e||"")),n=new Uint8Array(t.length);for(let s=0;s<t.length;s+=1)n[s]=t.charCodeAt(s);return n}async function kw(e){const t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t),n=>n.toString(16).padStart(2,"0")).join("")}async function KT(e){const t=navigator.clipboard;let n="text",s="clipboard.txt",a="text/plain",i=null;if(typeof t?.read=="function"){const u=await t.read(),d=u.find(p=>p.types.includes("image/png"));if(d){const p=await d.getType("image/png");n="image",s="clipboard.png",a="image/png",i=new Uint8Array(await p.arrayBuffer())}else{const p=u.find(h=>h.types.includes("text/plain"));if(p){const h=await p.getType("text/plain");i=new TextEncoder().encode(await h.text())}}}if(!i&&typeof t?.readText=="function"&&(i=new TextEncoder().encode(await t.readText())),!i)throw new Error("The browser did not provide text or a PNG image from the clipboard.");return{manifest:wp({operationId:e,contentKind:n,totalBytes:i.byteLength,items:[{itemIndex:0,kind:n,name:s,mimeType:a,size:i.byteLength,lastModified:Date.now(),sha256:await kw(i),storageName:"item-0.bin"}]},e),payloads:[i]}}async function QT(e){const{manifest:t,payloads:n}=e,s=n[0];if(!s||t.items.length!==1)throw new Error("clipboard-browser-snapshot-invalid");if(t.contentKind==="text"){await navigator.clipboard.writeText(new TextDecoder().decode(s));return}if(t.contentKind==="image"&&typeof ClipboardItem<"u"){await navigator.clipboard.write([new ClipboardItem({"image/png":new Blob([s],{type:"image/png"})})]);return}throw new Error("Multiple files require the LiveDesk desktop app.")}"".trim();"".trim();const YT=Object.freeze([{code:"ShiftLeft",label:"Shift"},{code:"ControlLeft",label:"Ctrl"},{code:"AltLeft",label:"Alt"},{code:"MetaLeft",label:"Win"}]),XT=1e3/60,Gd=1500,JT=650,ZT=1800,eP=650,tP=2500,Kd=1500,Fg=15e3,Dg=120,nP=.72,Mw=6,rP=640*360,sP=8;function aP(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t=Math.imul(t^e.charCodeAt(n),16777619);return(t>>>0)%Mw}const Lg=100,_g=20,iP=6e4,oP=6e4,$g=240,cP=1024,lP=640,uP=360,Og="Connected LiveDesk clients are updating in batches. Hub will restart after every target reconnects on the requested versions.",Hl="LiveDesk is replacing the Hub and verifying the requested version.",Wl=5*6e4,dP=5e3,Bg=2e3,pP=8e3;function Hg(e,t){return`${e}:${t.deviceId}:${t.completedAt||t.candidateSessionId||t.commandId||"completed"}`}function Oa({label:e,tooltip:t,disabled:n=!1,active:s=!1,danger:a=!1,pressed:i,onClick:c,children:u}){return r.jsx("span",{className:`manual-action-tooltip ${n?"disabled":""}`.trim(),"data-tooltip":t,children:r.jsx("button",{className:`manual-action ${s?"active":""} ${a?"danger":""}`.trim(),onClick:c,disabled:n,"aria-label":e,"aria-pressed":i,type:"button",children:u})})}function mP(e,t){if(t.deviceId!==e.deviceId)return!1;const n=Number(t.browserReceivedEpochMs);if(!Number.isFinite(n)||n<e.startedAtEpochMs)return!1;const s=Number(t.monitorIndex);if(Number.isFinite(s)&&Math.floor(s)!==e.monitorIndex)return!1;const a=String(t.frameMode||t.mode||"").trim().toLowerCase();return!a||a===e.frameMode}const hP={"mode3-h264-hw":30};function Wg(e,t){const n=c=>{const d=String(c||"").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(!d)return null;const p=d[4]?d[4].split(".").map(h=>/^\d+$/.test(h)?h.length>1&&h.startsWith("0")?Number.NaN:Number(h):h):[];return p.some(h=>typeof h=="number"&&!Number.isFinite(h))?null:{core:[Number(d[1]),Number(d[2]),Number(d[3])],prerelease:p}},s=n(e),a=n(t);if(!s||!a)return!1;for(let c=0;c<3;c+=1){if(s.core[c]>a.core[c])return!0;if(s.core[c]<a.core[c])return!1}if(s.prerelease.length===0||a.prerelease.length===0)return s.prerelease.length===0;const i=Math.max(s.prerelease.length,a.prerelease.length);for(let c=0;c<i;c+=1){const u=s.prerelease[c],d=a.prerelease[c];if(u===void 0||d===void 0)return d===void 0;if(u!==d){if(typeof u=="number"&&typeof d=="number")return u>d;if(typeof u=="number")return!1;if(typeof d=="number"||u>d)return!0;if(u<d)return!1}}return!0}const fP=1024;function Ut(e,t){return`${e}:${t}`}function rs(e){return[e.deviceId,e.sessionId||"",e.streamId||"",e.commandId||"",Number(e.captureGeneration||0),Number(e.monitorIndex??-1),e.streamPurpose||""].join("|")}const gP={frameMode:"mode3-h264-hw",h264DecodeAcceleration:"prefer-hardware",fps:hP["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},bP={frameMode:"mode3-h264-hw",h264DecodeAcceleration:"prefer-hardware",fps:30,maxWidth:3840,maxHeight:2160,quality:75,showScreenStatus:!1},zg={maxWidth:3840,maxHeight:2160};function qo(e,t){if(e.length===0)return 0;const n=[...e].sort((a,i)=>a-i),s=Math.max(0,Math.min(n.length-1,Math.ceil(n.length*t)-1));return n[s]}function Aw(e,t){e.push(t),e.length>$g&&e.splice(0,e.length-$g)}function zl(e,t){e.sampleFrames=0,e.sampleStartedAt=t,e.intervalCount=0,e.intervalSumMs=0,e.minIntervalMs=Number.POSITIVE_INFINITY,e.maxIntervalMs=0,e.intervalSamplesMs.length=0,e.seqGapCount=0,e.maxSeqGap=0}function qg(e,t,n){if(e.lastAt!==void 0){const s=Math.max(0,t-e.lastAt);e.intervalCount+=1,e.intervalSumMs+=s,e.minIntervalMs=Math.min(e.minIntervalMs,s),e.maxIntervalMs=Math.max(e.maxIntervalMs,s),Aw(e.intervalSamplesMs,s)}if(e.lastFrameSeq!==void 0){const s=n-e.lastFrameSeq;s!==1&&(e.seqGapCount+=1,e.maxSeqGap=Math.max(e.maxSeqGap,Math.abs(s)))}e.lastAt=t,e.lastFrameSeq=n}function Ug(e){return!e||e.intervalCount<=0?"waiting":`${Math.round(e.averageIntervalMs)}ms avg / p95 ${Math.round(e.p95IntervalMs)}ms / max ${Math.round(e.maxIntervalMs)}ms`}function Vg(e){return!e||e.seqGapCount<=0?"none":`${e.seqGapCount} gaps / max ${e.maxSeqGap}`}function vP(e){return Number.isFinite(e)?String(e):"30+"}const Nw=[1,2,5,8,12,20,30],Gg={large:{maxWidth:1920,maxHeight:1080},medium:{maxWidth:1280,maxHeight:720},list:{maxWidth:960,maxHeight:540}},Er={visibleRootMargin:"520px 0px 760px 0px",fallbackVisibleCounts:{large:12,medium:18,list:32},maxWallBytesPerSecond:80*1024*1024,maxFrameGapMs:280,downshiftCooldownMs:1800,downshiftStableSampleMs:$t.adaptiveDownshiftStableMs,downshiftConsecutiveSamples:$t.adaptiveDownshiftConsecutiveSamples,recoveryCooldownMs:14e3,minFps:5},Kg=2200,wP=2500,yP=8e3,xP=3500,SP=7e3,CP=2,kP=2500,MP=7e3,AP=2600,NP=4200,RP=750,TP=2,Qg=2500,Yg=4200,Xg=2200;function Jg(e,t){return Math.min(3e4,e*2**Math.min(3,Math.max(0,t)))}function Yi(e,t){const n=e.capabilities?.[t];return typeof n=="boolean"?n:/^(1|true|yes|on)$/i.test(String(n||"").trim())}function dn(e){return e.deviceName||e.hostname||e.deviceId}function PP(){return"npx -y --prefer-online livedesk@latest client"}function IP(){return"npx -y --prefer-online livedesk@latest"}function jP(){try{return localStorage.getItem(vw)||""}catch{return""}}function EP(){try{return localStorage.getItem(Ep)==="1"}catch{return!1}}function Gi(e){try{e?localStorage.setItem(Ep,"1"):localStorage.removeItem(Ep)}catch{}}function Dr(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function as(e){const t=Dr(e.status),n=Dr(t.screens),s=Dr(e.capabilities),a=Dr(e.latestLiveFrame),i=Dr(e.activeLiveStream),u=[t.monitorCount,t.screenCount,n.count,s.monitorCount,s.screenCount,a.monitorCount,i.monitorCount,Array.isArray(n.displays)?n.displays.length:0,Array.isArray(t.displays)?t.displays.length:0,Array.isArray(t.monitors)?t.monitors.length:0].map(Number).filter(d=>Number.isFinite(d)&&d>0).map(d=>Math.max(1,Math.min(64,Math.floor(d))));return u.length>0?Math.max(...u):1}function Ys(e){const t=Number(e);return Number.isFinite(t)&&t>0?Math.floor(t):0}function Rw(e){const t=Dr(e.status),s=[Dr(t.screens).displays,t.displays,t.monitors];for(const a of s)if(!(!Array.isArray(a)||a.length===0))return a.map(i=>Dr(i));return[]}function um(e,t){const n=Rw(e),s=n.find(d=>Number(d.index)===t)||n[t]||n[0]||{},a=Ys(s.width),i=Ys(s.height),c=[s.name,s.displayName,s.deviceName,s.id].find(d=>typeof d=="string"&&d.trim()),u=typeof c=="string"?c.trim():`Display ${t+1}`;return{index:t,name:u,width:a,height:i,primary:s.primary===!0||s.isPrimary===!0}}function FP(e){const t=as(e);return Array.from({length:t},(n,s)=>um(e,s))}function DP(e){const t=Rw(e);if(t.length===0)return"";const n=t.map((s,a)=>{const i=Number(s.index),c=[s.name,s.displayName,s.deviceName,s.id].find(d=>typeof d=="string"&&d.trim()),u=d=>{const p=Number(d);return Number.isFinite(p)?p:null};return[Number.isFinite(i)?Math.floor(i):a,typeof c=="string"?c.trim().toLowerCase():"",u(s.left),u(s.top),u(s.width),u(s.height),s.primary===!0||s.isPrimary===!0]}).sort((s,a)=>s[0]-a[0]);return JSON.stringify(n)}function LP(e){const t=[e.name||`Display ${e.index+1}`];return e.width>0&&e.height>0&&t.push(`${e.width}x${e.height}`),e.primary&&t.push("Primary"),t.join(" - ")}function Tw(e,t){const n=um(e,t);if(n.width>0&&n.height>0)return{width:n.width,height:n.height};const s=Dr(e.status),a=Ys(s.screenWidth||s.width),i=Ys(s.screenHeight||s.height);return a>0&&i>0?{width:a,height:i}:null}function Pw(e){if(!e)return null;const t=Ys(e.sourceWidth)||Ys(e.width),n=Ys(e.sourceHeight)||Ys(e.height);return t>0&&n>0?{width:t,height:n}:null}function _P(e,t,n){const i=((typeof t?.monitorIndex=="number"?Ko(t.monitorIndex,Math.max(1,t.monitorCount||1)):n)===n?Pw(t):null)||Tw(e,n);return i?Math.max(.25,Math.min(4,i.width/i.height)):16/9}const ql=16/9;function Ko(e,t){const n=Math.max(1,Math.min(64,Math.floor(Number(t)||1))),s=Math.floor(Number(e));return Number.isFinite(s)?Math.max(0,Math.min(n-1,s)):0}function cr(e,t){return K0(t,as(e),e.platform)}function $P(){try{const e=localStorage.getItem(Sw);if(!e)return{selections:{},topologyFingerprints:{}};const t=JSON.parse(e),n=t&&typeof t=="object"&&!Array.isArray(t)?t.selections:void 0;if(Number(t?.version)!==Cw||!n||typeof n!="object"||Array.isArray(n))return{selections:{},topologyFingerprints:{}};const s={},a={};for(const[i,c]of Object.entries(n)){const u=i.trim(),d=Dr(c),p=d.monitorIndex,h=Math.floor(Number(p));if(!u||!Number.isFinite(h))continue;s[u]=Math.max(0,Math.min(63,h));const m=typeof d.topologyFingerprint=="string"?d.topologyFingerprint.trim():"";m&&(a[u]=m)}return{selections:s,topologyFingerprints:a}}catch{return{selections:{},topologyFingerprints:{}}}}function OP(e,t){try{const n=Object.fromEntries(Object.entries(e).map(([s,a])=>[s,{monitorIndex:a,topologyFingerprint:t[s]||""}]));localStorage.setItem(Sw,JSON.stringify({version:Cw,selections:n}))}catch{}}function BP(){return{...gP}}function HP(e){try{localStorage.setItem($T,JSON.stringify({...e,version:OT}))}catch{}}function WP(){return{...bP}}function zP(e){try{localStorage.setItem(BT,JSON.stringify({...e,version:HT}))}catch{}}function qP(){try{return localStorage.getItem(ww)==="slow"?"slow":"fast"}catch{return"fast"}}function UP(e){try{localStorage.setItem(ww,e)}catch{}}function VP(){try{return localStorage.getItem(xw)==="true"}catch{return!1}}function GP(e){try{localStorage.setItem(xw,String(e))}catch{}}function KP(){try{const e=localStorage.getItem(yw);return e===null?Ja:dc(Number(e))}catch{return Ja}}function QP(e){try{localStorage.setItem(yw,String(dc(e)))}catch{}}function Qd(e,t){return e.length!==t.length?!1:e.every((n,s)=>n===t[s])}function Yd(e){return[...new Set(e.filter(Boolean))].sort()}function YP(e){return Er.fallbackVisibleCounts[e]||Er.fallbackVisibleCounts.large}function Zg(e,t,n){if(e.frameMode==="mode4-h264-atlas")return e.atlasTileSizeMode==="auto"?t==="large"?{maxWidth:640,maxHeight:360}:{maxWidth:320,maxHeight:180}:{maxWidth:e.atlasTileWidth,maxHeight:e.atlasTileHeight};if(!e.adaptiveSizeByWall)return{maxWidth:e.maxWidth,maxHeight:e.maxHeight};const s=Gg[t]||Gg.large;return{maxWidth:Math.min(e.maxWidth,s.maxWidth),maxHeight:Math.min(e.maxHeight,s.maxHeight)}}function XP(e,t=Er.minFps){const n=[...Nw].sort((a,i)=>a-i),s=Math.max(t,Math.floor(e/2));return[...n].reverse().find(a=>a<e&&a>=t)||s}function JP(e,t){return[...Nw].sort((s,a)=>s-a).find(s=>s>e&&s<=t)||t}function Qo(e){if(!Number.isFinite(e)||e<=0)return"0 B";const t=["B","KB","MB","GB","TB"];let n=e,s=0;for(;n>=1024&&s<t.length-1;)n/=1024,s+=1;const a=s===0||n>=100?0:1;return`${n.toFixed(a)} ${t[s]}`}function eb(e){if(!Number.isFinite(e)||!e||e<=0)return"0GB";const t=1024**4,n=1024**3;return e>=t?`${Math.max(1,Math.round(e/t))}TB`:`${Math.max(1,Math.round(e/n))}GB`}function Xd(e,t){if(!Number.isFinite(e)||!e||e<=0)return"not reported";const n=Math.max(0,e-Math.max(0,Number(t||0)));return`${eb(n)} / ${eb(e)}`}function ZP(e){const t=new Uint8Array(e),n=32768;let s="";for(let a=0;a<t.length;a+=n){const i=t.subarray(a,a+n);s+=String.fromCharCode(...i)}return btoa(s)}function tb(e){return Array.from(e).filter(t=>t.size>=0).map(t=>{const n=t.webkitRelativePath||t.name;return{file:t,relativePath:n,fingerprint:`${t.size}:${t.lastModified}`}})}function eI(e){return e===1?"middle":e===2?"right":"left"}function nb(e,...t){for(const n of t){const s=e?.[n];if(typeof s=="string"&&s.trim())return s.trim()}return""}function rb(e){const t=Number(e);return Number.isInteger(t)&&t>=1&&t<=_T?t:0}const tI={cpu:"CPU",memory:"MEM",disk:"Disk",gpu:"GPU",vram:"VRAM",npu:"NPU",temp:"Temp",network:"Net"};function nI(e,t,n){if(e==="online")return"Online";if(e==="busy")return"Busy";if(e==="stale")return"Stale";if(e==="offline")return"Offline";if(n==="failed")return"Task failed";const s=e==="critical"?"critical":"warn",a=t.find(c=>c.state===s)||t.find(c=>c.state==="critical"||c.state==="warn");if(!a)return e==="critical"?"Issue":"Check";const i=tI[a.id]||a.label;return a.value&&a.value!=="-"?`${i} ${a.value}`:i}function Iw(e,t){const n=t.split(".");let s=e;for(const a of n){if(s==null)return;if(Array.isArray(s)){const i=Number(a);s=Number.isInteger(i)?s[i]:void 0;continue}if(typeof s=="object"){s=s[a];continue}return}return s}function Wt(e,...t){for(const n of t){const s=Iw(e,n),a=Number(s);if(Number.isFinite(a))return a}}function ss(e,...t){for(const n of t){const s=Iw(e,n);if(typeof s=="string"&&s.trim())return s.trim();if(typeof s=="number"&&Number.isFinite(s))return String(s)}return""}function Ms(e){const t=Number(e);if(Number.isFinite(t))return Math.max(0,Math.min(1,t>1?t/100:t))}function Jd(e,t){if(!(typeof e!="number"||typeof t!="number"||!Number.isFinite(e)||!Number.isFinite(t)||e<=0))return Ms((e-Math.max(0,t))/e)}function Ki(e){return e===void 0?"-":`${Math.round(e*100)}%`}function Zd(e){return e===void 0||!Number.isFinite(e)?"":e>=1e3?`${(e/1e3).toFixed(e>=1e4?0:1)}Gb/s`:`${Math.round(e)}Mb/s`}function Ba(e,t=.92,n=.78){return e===void 0?"unknown":e>=t?"critical":e>=n?"warn":"good"}function rI(e){return!Number.isFinite(e)||!e||e<=0?"-":e<3600?`${Math.round(e/60)}m`:e<86400?`${Math.round(e/3600)}h`:`${Math.round(e/86400)}d`}function jw(e){const t=e.status||{},n=Wt(t,"cpu.cores","cpuCores","processorCount"),s=Wt(t,"loadavg.0","cpu.load1"),a=Ms(Wt(t,"cpu.usedRatio","cpu.usageRatio","cpu.ratio","cpu.usedPct","cpu.usagePct","cpu.percent")??(n&&s!==void 0?s/Math.max(1,n):void 0)),i=Wt(t,"memory.totalBytes","totalMem"),c=Wt(t,"memory.freeBytes","freeMem"),u=Ms(Wt(t,"memory.usedRatio","memory.usedPct","usedMemRatio"))??Jd(i,c),d=Wt(t,"disk.totalBytes","rootDisk.totalBytes","storage.totalBytes"),p=Wt(t,"disk.freeBytes","rootDisk.freeBytes","storage.freeBytes"),h=Ms(Wt(t,"disk.usedRatio","disk.usedPct","rootDisk.usedRatio","storage.usedRatio"))??Jd(d,p),m=Wt(t,"thermal.cpuC","temperatureC","cpu.temperatureC","gpu.temperatureC"),g=Ms(Wt(t,"gpu.usedRatio","gpu.usageRatio","gpu.usedPct","gpu.usagePct","gpu.percent","accelerators.gpu.usageRatio")),w=ss(t,"gpu.name","gpu.model","accelerators.gpu.name"),v=Wt(t,"gpu.memory.totalBytes","gpu.totalMemoryBytes","gpu.vramTotalBytes"),y=Wt(t,"gpu.memory.freeBytes","gpu.freeMemoryBytes","gpu.vramFreeBytes"),k=Ms(Wt(t,"gpu.memory.usedRatio","gpu.vramUsedRatio"))??Jd(v,y),N=Wt(t,"gpu.temperatureC","thermal.gpuC"),C=Ms(Wt(t,"npu.usedRatio","npu.usageRatio","npu.usedPct","npu.usagePct","npu.percent","accelerators.npu.usageRatio")),A=ss(t,"npu.name","npu.model","accelerators.npu.name"),E=Wt(t,"npu.tops","npu.topsInt8","accelerators.npu.tops"),I=Wt(t,"network.rxMbps","network.receiveMbps","network.downMbps"),F=Wt(t,"network.txMbps","network.transmitMbps","network.upMbps"),M=Wt(t,"network.latencyMs","network.rttMs"),H=Ms(Wt(t,"network.usedRatio","network.usageRatio","network.saturationRatio")),V=ss(t,"network.link","network.interface","network.name"),P=Math.max(m??Number.NEGATIVE_INFINITY,N??Number.NEGATIVE_INFINITY),D=Number.isFinite(P)?P:void 0,O=D===void 0?void 0:Ms((D-35)/60),X=m!==void 0&&N!==void 0?`CPU ${Math.round(m)}° · GPU ${Math.round(N)}°`:m!==void 0?`CPU ${Math.round(m)}°`:N!==void 0?`GPU ${Math.round(N)}°`:"-",G=ss(t,"workload.role","role","lane")||(Yi(e,"taskDispatch")?"Command-ready Client":"Local machine"),U=ss(e.latestTask,"status")||ss(t,"workload.status")||"idle",ie=ss(e.latestTask,"title","instructionPreview")||ss(t,"workload.title"),j=ss(e.latestTask,"resultSummary","error","instructionPreview")||ss(t,"workload.summary"),re=Date.parse(e.lastSeenAt||e.connectedAt||""),de=Number.isFinite(re)?Date.now()-re:0;let Q="online";e.connected?de>5*6e4?Q="stale":(m??0)>=86||(N??0)>=88||(a??0)>=.94||(g??0)>=.96||(k??0)>=.96||(C??0)>=.96||(u??0)>=.94||(h??0)>=.94||(M??0)>=200||U==="failed"?Q="critical":(m??0)>=78||(N??0)>=80||(a??0)>=.82||(g??0)>=.86||(k??0)>=.88||(C??0)>=.86||(u??0)>=.82||(h??0)>=.86||(M??0)>=80?Q="warn":["queued","running","targeted"].includes(U)&&(Q="busy"):Q="offline";const ge=[{id:"cpu",label:"CPU",value:Ki(a),detail:n?`${n} cores`:s!==void 0?`load ${s.toFixed(1)}`:"not reported",ratio:a,state:Ba(a,.92,.78)},{id:"memory",label:"RAM",value:Ki(u),detail:Xd(i,c),ratio:u,state:Ba(u,.92,.78)},{id:"disk",label:"DISK",value:Ki(h),detail:Xd(d,p),ratio:h,state:Ba(h,.92,.82)},{id:"gpu",label:"GPU",value:Ki(g),detail:w||(v&&y!==void 0?`${Qo(y)} VRAM free`:N!==void 0?`${Math.round(N)}C`:"not reported"),ratio:g,state:N!==void 0&&N>=88?"critical":N!==void 0&&N>=80?"warn":Ba(g,.96,.86)},{id:"vram",label:"VRAM",value:Ki(k),detail:Xd(v,y),ratio:k,state:Ba(k,.96,.88)},{id:"npu",label:"NPU",value:C!==void 0?Ki(C):E!==void 0?`${Math.round(E)} TOPS`:"-",detail:A||(E!==void 0?"neural engine":"not reported"),ratio:C,state:Ba(C,.96,.86)},{id:"temp",label:"TEMP",value:X,detail:`uptime ${rI(Wt(t,"uptimeSec"))}`,ratio:O,state:D===void 0?"unknown":D>=86?"critical":D>=78?"warn":"good"},{id:"network",label:"NET",value:Zd(I)||(M!==void 0?`${Math.round(M)}ms`:V||"-"),detail:Zd(F)?`${Zd(F)} up`:V||"not reported",ratio:H,state:M!==void 0&&M>=200?"critical":M!==void 0&&M>=80?"warn":Ba(H,.9,.75)}];return{state:Q,label:nI(Q,ge,U),role:G,taskLabel:ie||(U==="idle"?"idle":U),taskStatus:U,taskSummary:j,metrics:ge}}const sI=[{id:"slow",label:"Slow",fps:Mp("slow")},{id:"fast",label:"Fast",fps:Mp("fast")}],aI=[{id:"list",label:"List"},{id:"medium",label:"Small"},{id:"large",label:"Large"}],iI=[{id:"sync-server",label:"Hub",icon:os,accent:"blue",tooltip:"hub"},{id:"wall",label:"Wall",icon:Cb,accent:"blue",tooltip:"wall"},{id:"control",label:"Control",icon:Uo,accent:"red",tooltip:"control"},{id:"share-files",label:"Share Files",icon:Jo,accent:"green",tooltip:"share-files"},{id:"agents",label:"Agents",icon:Gl,accent:"violet",tooltip:"agents"}],oI=[{id:"doc",label:"Doc",icon:tu,accent:"amber"},{id:"support",label:"Support",icon:Yo,accent:"violet"},{id:"pricing",label:"Pricing",icon:Xo,accent:"green"}];function cI(e){return e.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 _t(e){return cI(e).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 Ha(e){return e.map(t=>_t(t))}function In(e){return{languageName:e.languageName,languageLabel:e.languageLabel,eyebrow:e.eyebrow,title:_t(e.title),intro:_t(e.intro),sections:[{title:_t(e.managerTitle),body:_t(e.managerBody),points:Ha(e.managerPoints)},{title:_t(e.clientTitle),body:_t(e.clientBody),points:Ha(e.clientPoints)},{title:_t(e.syncTitle),body:_t(e.syncBody),points:Ha(e.syncPoints)},...e.agentTitle&&e.agentBody&&e.agentPoints?[{title:_t(e.agentTitle),body:_t(e.agentBody),points:Ha(e.agentPoints)}]:[],{title:_t(e.platformTitle),body:_t(e.platformBody),points:Ha(e.platformPoints)}],sync:{title:_t(e.syncTitle),body:_t(e.syncBody),points:Ha(e.syncPoints)},firewall:{title:_t(e.firewallTitle),body:_t(e.firewallBody),points:Ha(e.firewallPoints)},commands:{title:_t(e.commandsTitle),body:_t(e.commandsBody),manager:_t(e.managerCommandLabel),primary:_t(e.clientCommandLabel),slot:_t(e.slotCommandLabel),manual:_t(e.manualCommandLabel)}}}const to={ko:In({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:In({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:In({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":In({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":In({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:In({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:In({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:In({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":In({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:In({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:In({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:In({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:In({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:In({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:In({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:In({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ı"})},lI=Object.entries(to).map(([e,t])=>({id:e,label:t.languageName}));function uI(){if(typeof navigator>"u")return"en";const e=navigator.languages?.length?navigator.languages:[navigator.language];for(const t of e){const n=t.toLowerCase();if(to[t])return t;if(n.startsWith("zh-tw")||n.startsWith("zh-hk"))return"zh-TW";if(n.startsWith("pt"))return"pt-BR";const s=n.split("-")[0];if(to[s])return s}return"en"}function sb({index:e}){const t=e+1;return r.jsx("article",{className:"device-tile placeholder-tile","aria-label":`Empty slot ${t}`,children:r.jsxs("div",{className:"tile-screen","aria-hidden":"true",children:[r.jsx("span",{className:"slot-grid","aria-hidden":"true"}),r.jsxs("span",{className:"empty-screen",children:[r.jsx(pn,{size:24}),r.jsxs("strong",{children:["Slot ",String(t).padStart(3,"0")]})]})]})})}const dI=["cpu","gpu","memory","vram","network","disk","temp"];function pI({device:e,slotNumber:t,selected:n,updateIndicator:s,remoteDiagnostics:a,diagnosticsMode:i="remote",onSelect:c,onOpenControl:u}){const d=jw(e),p=new Map(d.metrics.map(m=>[m.id,m])),h=s?.label||d.label;return r.jsxs("div",{className:`wall-device-list-row state-${d.state} ${n?"selected":""}`,role:"row","aria-selected":n,tabIndex:0,onClick:c,onDoubleClick:m=>{m.preventDefault(),u()},onKeyDown:m=>{(m.key==="Enter"||m.key===" ")&&(m.preventDefault(),c())},children:[r.jsxs("span",{className:"wall-device-name",role:"gridcell",children:[r.jsx("span",{className:"wall-device-icon","aria-hidden":"true",children:r.jsx(pn,{size:17})}),r.jsxs("span",{children:[r.jsx("strong",{children:dn(e)}),r.jsxs("small",{children:["Slot ",String(t).padStart(3,"0"),e.platform?` · ${e.platform}`:"",e.arch?` · ${e.arch}`:""]})]}),n&&r.jsx(Ns,{size:16,strokeWidth:3,"aria-label":"Selected"})]}),r.jsxs("span",{className:`wall-device-list-status state-${d.state} ${s?`update-${s.state}`:""}`,role:"gridcell",title:s?.error||h,children:[r.jsx("i",{"aria-hidden":"true"}),r.jsx("strong",{children:h})]}),dI.map(m=>{const g=p.get(m);return r.jsxs("span",{className:`wall-device-list-metric state-${g?.state||"unknown"}`,role:"gridcell",title:g?`${g.label}: ${g.value} · ${g.detail}`:"Not reported",children:[r.jsx("strong",{children:g?.value||"-"}),r.jsx("small",{children:g?.detail||"not reported"}),g?.ratio!==void 0&&r.jsx("i",{style:{width:`${Math.round(g.ratio*100)}%`},"aria-hidden":"true"})]},m)}),a&&r.jsx("span",{className:"wall-device-list-diagnostics",role:"gridcell",children:r.jsx(ow,{items:a,mode:i})})]})}function mI(e){if(!e)return!1;const t=String(e.platform||"").trim().toLowerCase();return is(t)&&e.capabilities?.screenRecordingPermission===!1}function is(e){const t=String(e||"").trim().toLowerCase();return t==="macos"||t==="darwin"||t==="mac"||t==="macosx"}function hI(e){const t=String(e||"").trim().toLowerCase();return t==="linux"||t.startsWith("linux ")}function ab(e){const t=String(e||"").trim().toLowerCase();return["win32","windows","win32nt"].includes(t)?"mode5-lzo-delta":is(t)?"mode1-jpeg":""}function ep({device:e,frame:t,selected:n,controlEnabled:s,showStatus:a,showDeviceTitle:i=!0,monitorIndex:c,monitorCount:u,onSelect:d,onFocusDevice:p,onOpenControl:h,onCycleMonitor:m,onCanvasReady:g,sendInput:w,remoteModifierState:v,updateIndicator:y,presentationReady:k,showPresentationSpinner:N=!1,remoteDiagnostics:C,diagnosticsMode:A="remote"}){const E=o.useRef(null),I=o.useRef(null),F=o.useRef(null),M=o.useRef(0),H=o.useRef(null),V=o.useRef(null),P=o.useRef(new Map),D=o.useRef(null),O=o.useRef(E0()),X=o.useRef(ou()),G=o.useRef(null),U=o.useRef(null),ie=jw(e),j=["cpu","gpu","memory","vram"].map(R=>ie.metrics.find(se=>se.id===R)).filter(R=>!!R),re=Gp(c),de=u>1,Q=k??!!t,ge=mI(e)&&!Q,oe=N&&e.connected&&!Q&&!ge,me=_P(e,t,re),Ae=me>=ql?100:me/ql*100,Te=me>=ql?ql/me*100:100,Pe={"--screen-aspect":me.toFixed(5),"--screen-content-width":`${Math.max(1,Math.min(100,Ae)).toFixed(3)}%`,"--screen-content-height":`${Math.max(1,Math.min(100,Te)).toFixed(3)}%`},Se=s?{transformOrigin:"0 0",transform:`translate3d(${X.current.translateX.toFixed(2)}px, ${X.current.translateY.toFixed(2)}px, 0) scale(${X.current.scale.toFixed(4)})`}:void 0,te=o.useCallback(R=>{X.current=R;const se=E.current;se&&(se.style.transformOrigin="0 0",se.style.transform=`translate3d(${R.translateX.toFixed(2)}px, ${R.translateY.toFixed(2)}px, 0) scale(${R.scale.toFixed(4)})`,se.dataset.touchZoom=R.scale.toFixed(2))},[]),Ce=o.useCallback(R=>{if(E.current=R,R&&s){const se=X.current;R.style.transformOrigin="0 0",R.style.transform=`translate3d(${se.translateX.toFixed(2)}px, ${se.translateY.toFixed(2)}px, 0) scale(${se.scale.toFixed(4)})`,R.dataset.touchZoom=se.scale.toFixed(2)}g(e.deviceId,R)},[s,e.deviceId,g]),Fe=(R,se,Ie)=>j0(R,se,Ie.getBoundingClientRect()),Le=R=>Fe(R.clientX,R.clientY,R.currentTarget),Ue=R=>H0(R,v),ne=o.useCallback(()=>{H.current!==null&&(window.cancelAnimationFrame(H.current),H.current=null)},[]),ae=o.useCallback(()=>{const R=G.current;R&&(window.clearTimeout(R.timerId),G.current=null);const se=U.current;se&&window.clearTimeout(se.timerId),U.current=null},[]),le=o.useCallback(()=>{const R=F.current;if(!R)return;F.current=null;const se=Number(R.input.normalizedX),Ie=Number(R.input.normalizedY);if(!Number.isFinite(se)||!Number.isFinite(Ie))return;w(e.deviceId,{...R.input,normalizedX:se,normalizedY:Ie})&&(M.current=performance.now())},[e.deviceId,w]),ce=o.useCallback(()=>{H.current===null&&(H.current=window.requestAnimationFrame(()=>{H.current=null,le()}))},[le]);o.useEffect(()=>{const R=ou();return te(R),()=>{ne(),ae(),F.current=null,V.current=null,P.current.clear(),D.current=null}},[re,te,ae,ne,s,e.deviceId]);const J=(R,se)=>{if(!s)return;const Ie={...R,type:se};if(se==="pointermove"){const He=performance.now();F.current={input:Ie},He-M.current>=XT&&(ne(),le()),ce();return}F.current&&(ne(),le()),w(e.deviceId,Ie)},ye=(R,se)=>{J({monitorIndex:re,...Le(R),button:eI(R.button),...Ue(R)},se)},ue=(R,se)=>{w(e.deviceId,{...R,type:"pointerdown",button:se}),w(e.deviceId,{...R,type:"pointerup",button:se})},Ee=(R,se,Ie)=>({monitorIndex:re,...Fe(R,se,Ie),shiftKey:!!v?.shiftKey,ctrlKey:!!v?.ctrlKey,altKey:!!v?.altKey,metaKey:!!v?.metaKey}),nt=(R,se)=>{const Ie=G.current;Ie&&(window.clearTimeout(Ie.timerId),G.current=null,ue(Ie.input,"left"));const He={tap:R,input:se,timerId:0};He.timerId=window.setTimeout(()=>{G.current===He&&(G.current=null,ue(se,"left"))},yp),G.current=He},T=(R,se,Ie)=>{if(P.current.set(R,{clientX:se,clientY:Ie}),D.current)return;const He=V.current;if(He&&He.pointerId!==R){const rt=P.current.get(He.pointerId),Ke=P.current.get(R),gt=I.current?.getBoundingClientRect();rt&&Ke&&gt&&(ne(),F.current=null,ae(),V.current=null,D.current={gesture:F0(rt,Ke,X.current,gt),pointerIds:[He.pointerId,R]});return}const Be=performance.now(),xe=G.current,Ge={clientX:se,clientY:Ie,at:Be};if(xe&&Sf(xe.tap,Ge)){window.clearTimeout(xe.timerId),G.current=null;const rt={...xe,timerId:0};rt.timerId=window.setTimeout(()=>{U.current===rt&&(U.current=null,ue(rt.input,"left"))},Math.max(0,xe.tap.at+yp-Be)),U.current=rt}else U.current=null,xe&&(window.clearTimeout(xe.timerId),G.current=null,ue(xe.input,"left"));V.current=L0(R,se,Ie),p()},ve=(R,se,Ie,He)=>{P.current.set(R,{clientX:se,clientY:Ie});const Be=D.current;if(Be){const rt=P.current.get(Be.pointerIds[0]),Ke=P.current.get(Be.pointerIds[1]);rt&&Ke&&te(D0(Be.gesture,rt,Ke));return}const xe=V.current;if(!xe||xe.pointerId!==R)return;const Ge=hv(xe,R,se,Ie);if(V.current=Ge,Ge?.dragged&&U.current){const rt=U.current;window.clearTimeout(rt.timerId),U.current=null,ue(rt.input,"left")}Ge?.dragged&&J(Ee(se,Ie,He),"pointermove")},De=(R,se,Ie,He)=>{if(P.current.set(R,{clientX:se,clientY:Ie}),D.current){P.current.delete(R),P.current.size===0&&(D.current=null);return}const Be=_0(V.current,R,se,Ie,performance.now());if(P.current.delete(R),Be.kind==="ignore")return;Be.kind==="drag"&&(J(Ee(se,Ie,He),"pointermove"),ne(),le()),V.current=null;const xe=U.current;if(xe&&window.clearTimeout(xe.timerId),U.current=null,Be.kind==="tap"&&Be.tap){const Ge=Ee(se,Ie,He);xe&&Sf(xe.tap,Be.tap)?ue(Ge,"right"):(xe&&ue(xe.input,"left"),nt(Be.tap,Ge))}else xe&&ue(xe.input,"left")},qe=R=>{if(P.current.delete(R),D.current){P.current.size===0&&(D.current=null);return}if(V.current?.pointerId===R){ne(),F.current=null,V.current=null;const se=U.current;se&&(window.clearTimeout(se.timerId),ue(se.input,"left")),U.current=null}},_e=R=>{if(R.pointerType!=="touch")return!1;if(R.preventDefault(),R.stopPropagation(),O.current.shouldHandlePointerEvent()){T(R.pointerId,R.clientX,R.clientY);try{R.currentTarget.setPointerCapture(R.pointerId)}catch{}}return!0},$e=R=>R.pointerType!=="touch"?!1:(R.preventDefault(),O.current.shouldHandlePointerEvent()&&ve(R.pointerId,R.clientX,R.clientY,R.currentTarget),!0),mt=R=>R.pointerType!=="touch"?!1:(R.preventDefault(),R.stopPropagation(),O.current.shouldHandlePointerEvent()&&De(R.pointerId,R.clientX,R.clientY,R.currentTarget),R.currentTarget.hasPointerCapture(R.pointerId)&&R.currentTarget.releasePointerCapture(R.pointerId),!0),ct=R=>R.pointerType!=="touch"?!1:(R.preventDefault(),R.stopPropagation(),O.current.shouldHandlePointerEvent()&&qe(R.pointerId),R.currentTarget.hasPointerCapture(R.pointerId)&&R.currentTarget.releasePointerCapture(R.pointerId),!0),z=R=>{if(s){R.preventDefault(),R.stopPropagation(),O.current.shouldHandlePointerEvent()&&(O.current.claimNativeTouchEvents(),V.current=null,P.current.clear(),D.current=null);for(const se of Array.from(R.changedTouches))T(se.identifier,se.clientX,se.clientY)}},pe=R=>{if(!s)return;R.preventDefault(),R.stopPropagation();for(const He of Array.from(R.touches))P.current.set(He.identifier,{clientX:He.clientX,clientY:He.clientY});const se=V.current?.pointerId,Ie=Array.from(R.touches).find(He=>He.identifier===se)||R.touches.item(0);Ie&&ve(Ie.identifier,Ie.clientX,Ie.clientY,R.currentTarget)},Y=R=>{if(s){R.preventDefault(),R.stopPropagation();for(const se of Array.from(R.changedTouches))De(se.identifier,se.clientX,se.clientY,R.currentTarget)}},K=R=>{if(s){R.preventDefault(),R.stopPropagation();for(const se of Array.from(R.changedTouches))qe(se.identifier)}},ee=o.useCallback(R=>{const se=document.activeElement;se instanceof HTMLElement&&R.contains(se)&&se.classList.contains("monitor-cycle-button")&&se.blur()},[]);return r.jsx("article",{className:`device-tile ${n?"selected":""} ${e.connected?"online":"offline"}`,"data-live-device-id":e.deviceId,style:Pe,children:r.jsxs("div",{className:`tile-screen ${Q?"has-frame":"is-empty"}`,role:"button",tabIndex:s?-1:0,"aria-pressed":n,onClick:R=>{R.target instanceof Element&&R.target.closest(".monitor-cycle")||s||d()},onKeyDown:R=>{R.target instanceof Element&&R.target.closest(".monitor-cycle")||s||(R.key==="Enter"||R.key===" ")&&(R.preventDefault(),d())},onDoubleClick:R=>{if(!(R.target instanceof Element&&R.target.closest(".monitor-cycle"))){if(R.preventDefault(),s){R.stopPropagation();return}h()}},onPointerLeave:R=>ee(R.currentTarget),children:[r.jsx("span",{ref:I,className:`screen-content ${Q?"has-frame":"is-empty"}`,children:r.jsx("canvas",{ref:Ce,className:`remote-canvas ${Q?"has-frame":"is-empty"} ${s?"control-input-enabled":""}`,"data-monitor-index":re,"data-touch-zoom":X.current.scale.toFixed(2),style:Se,tabIndex:s?0:-1,onPointerDown:R=>{s&&(_e(R)||(R.preventDefault(),R.stopPropagation(),p(),R.currentTarget.focus(),R.currentTarget.setPointerCapture(R.pointerId),ye(R,"pointerdown")))},onPointerMove:R=>{s&&R.preventDefault(),!$e(R)&&ye(R,"pointermove")},onPointerLeave:R=>{s&&R.pointerType!=="touch"&&(ye(R,"pointermove"),ne(),le())},onPointerUp:R=>{s&&(mt(R)||(R.preventDefault(),R.stopPropagation(),ye(R,"pointerup"),R.currentTarget.hasPointerCapture(R.pointerId)&&R.currentTarget.releasePointerCapture(R.pointerId)))},onPointerCancel:R=>{ct(R)||(s&&(R.preventDefault(),R.stopPropagation(),ye(R,"pointerup")),R.currentTarget.hasPointerCapture(R.pointerId)&&R.currentTarget.releasePointerCapture(R.pointerId))},onTouchStart:z,onTouchMove:pe,onTouchEnd:Y,onTouchCancel:K,onWheel:R=>{s&&(R.preventDefault(),w(e.deviceId,{type:"wheel",monitorIndex:re,...Le(R),deltaX:R.deltaX,deltaY:R.deltaY,...Ue(R)}))},onContextMenu:R=>s&&R.preventDefault(),onDoubleClick:R=>{s&&(R.preventDefault(),R.stopPropagation())}},`${e.deviceId}:monitor:${re}`)}),!Q&&r.jsx("span",{className:"empty-screen",children:r.jsx(pn,{size:26})}),i&&r.jsx("span",{className:"wall-device-title",title:dn(e),children:dn(e)}),oe&&r.jsxs("span",{className:"wall-presentation-loading",role:"status","aria-live":"polite",children:[r.jsx("span",{className:"wall-presentation-spinner","aria-hidden":"true"}),r.jsx("strong",{children:"Preparing video"})]}),ge&&r.jsxs("span",{className:"wall-presentation-loading permission-required",role:"status","aria-live":"polite",children:[r.jsx(Zt,{size:24,"aria-hidden":"true"}),r.jsx("strong",{children:"Screen Recording permission required"}),r.jsx("small",{children:"Allow the terminal app on this Mac, then restart LiveDesk."})]}),y&&r.jsxs("span",{className:`wall-update-status state-${y.state}`,role:"status","aria-live":"polite",title:y.error||y.label,children:[y.state==="updated"?r.jsx(En,{size:20,"aria-hidden":"true"}):y.state==="failed"?r.jsx(xn,{size:22,"aria-hidden":"true"}):y.state==="offline"?r.jsx(bu,{size:22,"aria-hidden":"true"}):r.jsx("span",{className:"wall-update-spinner","aria-hidden":"true"}),r.jsx("strong",{children:y.label}),y.error?r.jsx("small",{children:y.error}):null]}),a&&r.jsxs(r.Fragment,{children:[r.jsx("span",{className:`tile-health-pill state-${ie.state}`,children:ie.label}),r.jsx("span",{className:"tile-metrics","aria-label":`${dn(e)} status`,children:j.map(R=>r.jsxs("span",{className:`tile-metric state-${R.state}`,children:[r.jsx("b",{children:R.label}),r.jsx("em",{children:R.value}),R.ratio!==void 0&&r.jsx("i",{style:{width:`${Math.round(R.ratio*100)}%`}})]},R.id))})]}),C&&r.jsx(ow,{items:C,mode:A}),de&&r.jsxs("span",{className:"monitor-cycle","aria-label":`${dn(e)} display ${re+1} of ${u}`,onPointerDown:R=>R.stopPropagation(),onClick:R=>R.stopPropagation(),onDoubleClick:R=>R.stopPropagation(),children:[r.jsx("button",{className:"monitor-cycle-button previous",onClick:R=>{R.preventDefault(),R.stopPropagation(),m(-1),R.currentTarget.blur()},title:"Previous display",type:"button",children:r.jsx(kb,{size:18})}),r.jsxs("span",{className:"monitor-cycle-count",children:["Screen ",re+1,"/",u]}),r.jsx("button",{className:"monitor-cycle-button next",onClick:R=>{R.preventDefault(),R.stopPropagation(),m(1),R.currentTarget.blur()},title:"Next display",type:"button",children:r.jsx(Lp,{size:18})})]})]})})}function fI({visible:e}){const t=UT;return o.useEffect(()=>{},[t]),null}function gI({runtimeBaseUrl:e=""}){const t=typeof window<"u"&&!!window.liveDesk,{session:n,loading:s}=a0();_y(n?{accessToken:n.access_token,refreshToken:n.refresh_token,expiresAt:n.expires_at,user:{id:n.user.id,email:n.user.email}}:null);const{target:a,error:i,refresh:c}=o0(n),u=o.useMemo(()=>{if(!a?.active)return null;const l=a.expires_at?Date.parse(a.expires_at):Number.POSITIVE_INFINITY;return Number.isFinite(l)&&l<=Date.now()?null:a},[a]),d=o.useMemo(()=>Eh(u),[u]),p=eu(),h=e.trim().replace(/\/+$/,""),m=o.useMemo(()=>[...new Set((p?d:[h,...d,an]).filter(Boolean))],[p,d,h]),[g,w]=o.useState(null),[v]=o.useState(DT),[y,k]=o.useState(!1),[N,C]=o.useState(()=>typeof window>"u"?!1:!!window.navigator.standalone||window.matchMedia("(display-mode: standalone), (display-mode: fullscreen)").matches),[A,E]=o.useState(()=>typeof window<"u"&&If(window.matchMedia(Tf).matches,N,window.matchMedia("(pointer: coarse)").matches));o.useEffect(()=>{if(!p){w(null);return}const l=window.matchMedia("(display-mode: standalone), (display-mode: fullscreen)"),f=()=>C(l.matches||!!window.navigator.standalone),b=S=>{S.preventDefault(),w(S)},x=()=>{w(null),C(!0)};return f(),l.addEventListener("change",f),window.addEventListener("beforeinstallprompt",b),window.addEventListener("appinstalled",x),()=>{l.removeEventListener("change",f),window.removeEventListener("beforeinstallprompt",b),window.removeEventListener("appinstalled",x)}},[p]);const I=o.useCallback(async()=>{const l=g;if(!l){v.isIos&&k(!0);return}w(null);try{await l.prompt(),(await l.userChoice).outcome==="accepted"&&C(!0)}catch(f){w(l),console.warn("[LiveDesk] PWA install prompt failed.",f)}},[v.isIos,g]);o.useEffect(()=>{const l=window.matchMedia(Tf),f=window.matchMedia("(pointer: coarse)"),b=()=>E(If(l.matches,N,f.matches));return b(),l.addEventListener("change",b),f.addEventListener("change",b),()=>{l.removeEventListener("change",b),f.removeEventListener("change",b)}},[N]),o.useLayoutEffect(()=>{const l=document.documentElement,f=()=>{l.classList.remove("livedesk-mobile-console-active"),l.style.removeProperty("--livedesk-mobile-viewport-height"),l.style.removeProperty("--livedesk-mobile-viewport-top"),l.style.removeProperty("--livedesk-mobile-viewport-width"),l.style.removeProperty("--livedesk-mobile-viewport-left"),l.style.removeProperty("--livedesk-mobile-ios-top-guard")};if(!A){f();return}l.classList.add("livedesk-mobile-console-active");const b=window.visualViewport,x=document.createElement("div");x.setAttribute("aria-hidden","true"),x.style.cssText="position:fixed;visibility:hidden;pointer-events:none;padding-top:env(safe-area-inset-top);",document.body.appendChild(x);let S=0;const $=()=>{S=0;const B=Math.max(window.innerHeight,document.documentElement.clientHeight),q=ik(b,B,window.innerWidth,N||v.isIos,N||v.isIos||v.isAndroid),W=Number.parseFloat(window.getComputedStyle(x).paddingTop),ke=ak({isIos:v.isIos,standalone:N,safeAreaTop:W,screenHeight:window.screen.height,layoutViewportHeight:B});l.style.setProperty("--livedesk-mobile-viewport-height",`${q.height}px`),l.style.setProperty("--livedesk-mobile-viewport-top",`${q.offsetTop}px`),l.style.setProperty("--livedesk-mobile-viewport-width",`${q.width}px`),l.style.setProperty("--livedesk-mobile-viewport-left",`${q.offsetLeft}px`),l.style.setProperty("--livedesk-mobile-ios-top-guard",`${ke}px`)},L=()=>{S||(S=window.requestAnimationFrame($))};return $(),b?.addEventListener("resize",L),b?.addEventListener("scroll",L),window.addEventListener("resize",L),window.addEventListener("orientationchange",L),window.addEventListener("pageshow",L),()=>{S&&window.cancelAnimationFrame(S),b?.removeEventListener("resize",L),b?.removeEventListener("scroll",L),window.removeEventListener("resize",L),window.removeEventListener("orientationchange",L),window.removeEventListener("pageshow",L),x.remove(),f()}},[v.isAndroid,v.isIos,A,N]);const[F,M]=o.useState(EP),H=o.useMemo(()=>m.some(l=>!!Ul(l)),[m]),V=p?!!n:!H||F,{status:P,devices:D,error:O,refresh:X,hubBaseUrl:G}=i0(m,V,n?.access_token||""),[U,ie]=o.useState(!1);o.useEffect(()=>{if(!P?.started){ie(!1);return}const l=new AbortController;return Oe("/api/settings",{signal:l.signal},G).then(f=>{ie(f.settings?.connection?.showThisComputer===!0)}).catch(f=>{l.signal.aborted||(ie(!1),console.warn("[LiveDesk] Computer visibility setting could not be loaded.",f))}),()=>l.abort()},[G,P?.started]);const{entitlement:j,licensed:re,loading:de,error:Q,refresh:ge}=c0(n),[oe,me]=o.useState([]),[Ae,Te]=o.useState(""),[Pe,Se]=o.useState(""),[te,Ce]=o.useState(""),[Fe,Le]=o.useState(""),[Ue,ne]=o.useState(""),[ae,le]=o.useState("idle"),[ce,J]=o.useState(!1),[ye,ue]=o.useState(""),[Ee,nt]=o.useState(null),T=o.useRef(null),[ve,De]=o.useState(""),qe=o.useRef("");qe.current=Fe;const[_e,$e]=o.useState(!1),[mt,ct]=o.useState([]),z=o.useRef(null),pe=o.useRef(null),Y=o.useRef(null),K=o.useRef(!1),ee=o.useRef({key:"",source:"",at:0}),[R,se]=o.useState(!1),[Ie,He]=o.useState(!1),Be=o.useRef(""),xe=o.useRef(new Map),Ge=o.useRef(0),rt=o.useRef(!1),Ke=o.useRef(""),gt=o.useRef(null);gt.current||(gt.current=ck());const _=o.useRef(document.visibilityState==="visible"),[je,Qe]=o.useState({}),Ye=o.useRef({}),Gt=o.useRef(new Set),en=o.useRef(new Map),zn=o.useRef(new Map),[on,Sr]=o.useState({}),qn=o.useMemo(()=>new Set(Object.keys(je)),[je]),Fn=o.useCallback((l,f)=>{if(!l)return;const b={...Ye.current};f?b[l]=f:delete b[l],Ye.current=b,Qe(b)},[]),Sn=o.useCallback((l,f)=>{l&&Sr(b=>{if(!!b[l]===f)return b;const x={...b};return f?x[l]=!0:delete x[l],x})},[]),nr=o.useCallback((l,f)=>{l&&zn.current.set(l,{paused:f,expiresAt:Date.now()+pP})},[]),[bt,Z]=o.useState(""),[be,We]=o.useState(""),[lt,It]=o.useState(!1),At=o.useRef(null),et=o.useRef(null);o.useEffect(()=>{bt==="auth"&&n?.access_token&&Z("")},[bt,n?.access_token]);const[Mt,Cn]=o.useState(""),[zt,kn]=o.useState(null),Nt=o.useRef(null),cn=o.useRef(0),ht=o.useCallback((l,f,b)=>{const x=String(l||"").trim();if(Cn(x),Nt.current!==null&&(window.clearTimeout(Nt.current),Nt.current=null),!x){kn(null);return}const S=++cn.current;if(kn({id:S,message:x,tone:f}),!b)return;const $=window.setTimeout(()=>{kn(L=>L?.id===S?null:L),Nt.current===$&&(Nt.current=null)},5e3);Nt.current=$},[]),we=o.useCallback((l,f="info")=>{ht(l,f,!0)},[ht]),Ot=o.useCallback(l=>{ht(l,"progress",!1)},[ht]);o.useEffect(()=>()=>{Nt.current!==null&&window.clearTimeout(Nt.current)},[]);const[jt,tn]=o.useState(()=>typeof window>"u"?"wall":window.location.pathname.startsWith("/support")?"support":new URLSearchParams(window.location.search).get("view")==="pricing"?"pricing":"wall");o.useEffect(()=>{const l=()=>{tn(window.location.pathname.startsWith("/support")?"support":f=>f==="support"?"wall":f)};return window.addEventListener("popstate",l),()=>window.removeEventListener("popstate",l)},[]);const[us,Ps]=o.useState(KP),Bt=Mk(us),ds=o.useCallback(l=>{const f=dc(l);Ps(f),QP(f)},[]),hc=o.useCallback(l=>{ds(l==="list"?lu:l==="medium"?Sk:Ja)},[ds]),Za=Ak(us),sa=o.useMemo(()=>({"--wall-tile-min-width":`${Za}px`}),[Za]),fc=Bt==="list"?"List view":`${Bt==="medium"?"Small":"Large"} tiles, ${Za} pixel minimum width`,[ur,ei]=o.useState(qP),dr=Mp(ur),[pr,rr]=o.useState(VP),[nn,aa]=o.useState(!1),[qt,ia]=o.useState(!1),[Un,oa]=o.useState(!1),[_r,ps]=o.useState(!1),[gc,Is]=o.useState(Date.now),Cr=o.useRef(null);o.useEffect(()=>()=>{Cr.current!==null&&window.clearTimeout(Cr.current)},[]);const[$r,bc]=o.useState(uI),[Or,ao]=o.useState(!1),[ca,Br]=o.useState(!1),[dm,Pu]=o.useState(!1),[ms,io]=o.useState(jP),[ot]=o.useState(BP),oo=A?pr:ot.showScreenStatus,[rn]=o.useState(WP),[la]=o.useState($P),[Ct,ti]=o.useState(la.selections),co=o.useRef({...la.topologyFingerprints}),js=o.useRef({}),vc=o.useRef({...la.selections}),[vt,ln]=o.useState(null),[ni,lo]=o.useState({}),uo=o.useRef(new Set),[Hr,ri]=o.useState([]),[Dn,ua]=o.useState(dr),[Es,wc]=o.useState(""),[Iu,ju]=o.useState(0),[yc,po]=o.useState(0),[Fs,Ew]=o.useState(0),[Eu,mo]=o.useState(()=>new Set),Tt=o.useRef(new Map),Ln=o.useRef(new Map),hs=o.useRef(new Map),Ht=o.useRef(new Map),da=o.useRef(null),pa=o.useRef(new Map),fs=o.useRef(new Set),Ds=o.useRef(new Map),si=o.useRef(new Map),ma=o.useRef(new Map),Wr=o.useRef(new Map),xc=o.useRef(new WeakMap),Sc=o.useRef(new WeakMap),Ls=o.useRef(""),Vn=o.useRef(null),pm=o.useRef(Promise.resolve()),Cc=o.useRef(0),ai=o.useRef(null),sr=o.useRef(null),ho=o.useRef(""),gn=o.useRef(new Map),ii=o.useRef(null),fo=o.useRef(0),gs=o.useRef(new Map),kc=o.useRef(typeof window<"u"&&new URLSearchParams(window.location.search).get("livedeskTransmissionProbe")==="1"),Mc=o.useRef(new Map),Fu=o.useRef([]),mm=o.useRef(0),[Ac,Du]=o.useState({}),_s=o.useRef(new Map),[Nc,Rc]=o.useState({}),Tc=o.useRef(null),[Lu,_n]=o.useState(!1),Pc=o.useRef(null),Fw=o.useRef(0),bs=o.useRef(null),hm=o.useRef(new Map),kr=o.useRef(null),mr=o.useRef(null),ar=o.useRef(null),go=o.useRef(!1),fm=o.useRef(0),Kt=o.useRef(0),Mn=o.useRef(""),gm=o.useRef(Promise.resolve()),oi=o.useRef(""),it=o.useRef(null),hr=o.useRef(""),ha=o.useRef(null),ci=o.useRef(0),bo=o.useRef(""),$s=o.useRef(new Map),fa=o.useRef(new Map),Ic=o.useRef(performance.now()),li=o.useRef(new Map),zr=o.useRef(new Map),ga=o.useRef(new Map),ba=o.useRef(new Map),ui=o.useRef(new Map),va=o.useRef(new Map),Mr=o.useRef(document.visibilityState==="visible"),qr=o.useRef(1),_u=o.useRef([]),[$n,Dw]=o.useState(document.visibilityState==="visible"),[di,Lw]=o.useState(0),vo=o.useRef(0),jc=o.useRef(0),Ec=o.useRef(0),Fc=o.useRef(0),$u=o.useRef(0),Ou=o.useRef(new Map),wo=o.useRef([]),bm=o.useRef(new Map),vm=o.useRef(new Map),vs=o.useRef(new Map),Dc=o.useRef(new Set),pi=o.useCallback(l=>gC(xc.current,l),[]),mi=o.useCallback(l=>Hp(Sc.current,l),[]),wa=o.useCallback((l,f)=>sf(Sc.current,l,f),[]),sn=o.useCallback(l=>{const f=rf(xc.current,l);return rf(Sc.current,l),f},[]),hi=o.useCallback((l,f)=>sf(xc.current,l,f),[]),wm=o.useCallback(l=>sr.current===l||da.current===l?!0:[Tt.current,Ln.current,hs.current,Ht.current,gn.current].some(b=>Array.from(b.values()).some(x=>x===l)),[]),On=o.useCallback(l=>{l&&(sn(l),Dc.current.add(l),wC(l,{isCurrent:wm,dispose:Wi,schedule:f=>queueMicrotask(()=>{try{f()}finally{Dc.current.delete(l)}})}))},[wm,sn]),Bn=o.useCallback(l=>(sn(l),Cu(l,Wi)),[sn]),ym=o.useCallback(()=>{const l=sr.current,f=da.current,b=[...Dc.current];sr.current=null,da.current=null,Dc.current.clear(),xc.current=new WeakMap,Sc.current=new WeakMap,Wr.current.clear(),ho.current="",vC([Tt.current,Ln.current,hs.current,Ht.current,gn.current],[l,f,...b],Wi),ii.current=null,fo.current=0,pa.current.clear(),fs.current.clear(),Ds.current.clear(),si.current.clear(),ma.current.clear(),gs.current.clear(),Mc.current.clear(),Fu.current.length=0,_s.current.clear(),Gt.current.clear()},[]);o.useEffect(()=>()=>{ym()},[ym]);const bn=o.useCallback((l,f)=>{const b=Ut(l,f),x=performance.now();$s.current.delete(b),fa.current.delete(b),li.current.delete(b),zr.current.delete(b),va.current.delete(b),vs.current.delete(b),_s.current.delete(b),gs.current.delete(b),Rc(S=>{if(!Object.prototype.hasOwnProperty.call(S,b))return S;const $={...S};return delete $[b],$}),Du(S=>{if(!Object.prototype.hasOwnProperty.call(S,b))return S;const $={...S};return delete $[b],$}),l==="control"?(ga.current.delete(b),ba.current.set(b,x)):ui.current.set(b,x)},[]),[ya,Os]=o.useState(null),[_w,Bu]=o.useState(!1),[xI,$w]=o.useState([]),[fi,Ow]=o.useState("all"),[gi,Hu]=o.useState([]),[SI,CI]=o.useState(!1),[kI,Bw]=o.useState(!0),xm=o.useRef(null),Sm=o.useRef(null),Hw=o.useRef(null),Ww=o.useRef(null),zw=o.useRef(!1),Wu=o.useRef(!1),Lc=o.useRef(0),ws=o.useRef(0),ys=o.useRef(0),Ur=o.useRef(0),_c=o.useRef(0),$c=o.useRef(""),yo=jt==="settings",Cm=jt==="pricing",km=jt==="doc",Mm=jt==="support",xa=jt==="share-files",Oc=jt==="agents",Sa=!yo&&!Cm&&!km&&!Mm&&!xa&&!Oc,Xe=jt==="control",Am=dk(jt),Ar=$n&&jt==="wall",Nm=o.useRef(Ar);Nm.current=Ar;const qw=Am&&wo.current.length>0,Ca=$n&&(jt==="wall"||Xe||qw),bi=o.useRef(Ca);bi.current=Ca;const Bc=$n&&(Xe||Ar),vi=$n&&(Bc||Am&&(ae==="connecting"||ae==="active")),zu=o.useRef({active:Ca,epoch:qr.current});zu.current.active!==Ca&&(qr.current+=1,zu.current={active:Ca,epoch:qr.current}),o.useEffect(()=>{Sa||(aa(!1),ia(!1),oa(!1))},[Sa]);const St=ot.frameMode==="mode4-h264-atlas",fr=Ue||rn.frameMode,xo=fr!=="mode3-h264-hw"?Math.min(30,rn.fps):rn.fps,wi=D.find(l=>l.deviceId===Pe),Uw=wi?.platform,Vw=wi?cr(wi,Ct[wi.deviceId]):0,Hc=wi?um(wi,Vw):null,Rm=hI(Uw)?{maxWidth:1280,maxHeight:720}:zg,Tm=fr!=="mode3-h264-hw"?{maxWidth:1920,maxHeight:1080}:zg,Wc={maxWidth:Math.min(Tm.maxWidth,Rm.maxWidth,rn.maxWidth),maxHeight:Math.min(Tm.maxHeight,Rm.maxHeight,rn.maxHeight)},Vr={maxWidth:Hc?.width?Math.min(Wc.maxWidth,Hc.width):Wc.maxWidth,maxHeight:Hc?.height?Math.min(Wc.maxHeight,Hc.height):Wc.maxHeight};o.useEffect(()=>{if(P?.started){if(!n?.access_token){Oe("/api/remote/license",{method:"DELETE"},G).catch(()=>{});return}Oe("/api/remote/license/sync",{method:"POST",headers:{Authorization:`Bearer ${n.access_token}`}},G).catch(l=>{console.warn("[LiveDesk] Hub license sync failed",l)})}},[j?.updated_at,G,n?.access_token,P?.started]),o.useEffect(()=>{!n?.access_token||!P?.started||P.runtimeRole!=="hub"||!P.deviceId||(async()=>{try{const{data:l,error:f}=await pt.rpc("register_livedesk_device",{p_device_id:P.deviceId,p_device_name:P.deviceName||P.deviceId,p_role:"hub",p_assigned_hub_id:null,p_platform:navigator.platform||navigator.userAgent,p_os_version:navigator.userAgent,p_app_version:P.managerVersion||P.managerPackage||""}),b=Array.isArray(l)?l[0]:l;(f||b?.ok===!1)&&console.warn("[LiveDesk] Hub device role registration failed",f||b?.reason||"unknown-error")}catch(l){console.warn("[LiveDesk] Hub device role registration failed",l)}})()},[n?.access_token,P?.deviceId,P?.deviceName,P?.managerPackage,P?.managerVersion,P?.runtimeRole,P?.started]);const qu=P?.runtimeRole==="hub"?String(P.deviceId||"").trim():"",Ze=o.useMemo(()=>D.filter(l=>l.connected&&(A||U||!qu||l.deviceId!==qu)),[D,qu,A,U]);o.useEffect(()=>{const l={...Ye.current},f=Date.now();let b=!1;Sr(x=>{const S={...x};let $=!1;for(const L of D){const B=String(L.liveCapturePause?.token||"").trim(),q=zn.current.get(L.deviceId);if(q)if((q.paused?!!B:!B)||q.expiresAt<=f)zn.current.delete(L.deviceId);else continue;const W=!!B&&(L.liveCapturePause?.captureStopConfirmed!==!0||L.liveCapturePause?.phase==="stop-unconfirmed");!!S[L.deviceId]!==W&&($=!0,W?S[L.deviceId]=!0:delete S[L.deviceId])}return $?S:x});for(const x of D){const S=String(x.liveCapturePause?.token||"").trim(),$=String(l[x.deviceId]||""),L=zn.current.get(x.deviceId);if(L)if((L.paused?!!S:!S)||L.expiresAt<=f)zn.current.delete(x.deviceId);else continue;S&&S!==$?(l[x.deviceId]=S,b=!0):!S&&$&&(delete l[x.deviceId],en.current.delete(x.deviceId),b=!0)}b&&(Ye.current=l,Qe(l))},[D]);const Pm=fi==="all"?Ze.length:gi.filter(l=>Ze.some(f=>f.deviceId===l)).length,Gw=o.useMemo(()=>Ze.reduce((l,f)=>Math.max(l,rb(f.slotNumber)),0),[Ze]),Uu=Math.max(LT,Ze.length,Gw),ka=o.useMemo(()=>{const l=Array(Uu).fill(null),f=[];for(const b of Ze){const x=rb(b.slotNumber);x>0&&x<=Uu&&!l[x-1]?l[x-1]=b:f.push(b)}for(const b of f){const x=l.findIndex(S=>!S);x<0?l.push(b):l[x]=b}return l},[Ze]),Im=o.useMemo(()=>ka.flatMap((l,f)=>l?[{device:l,slotNumber:f+1}]:[]),[ka]),zc=o.useMemo(()=>Ze.map(l=>l.deviceId),[Ze]),Ma=o.useMemo(()=>new Set(oe),[oe]),An=o.useMemo(()=>Ze.filter(l=>Ma.has(l.deviceId)),[Ze,Ma]),yi=o.useMemo(()=>D.find(l=>l.deviceId===Ae)||An[0]||null,[D,Ae,An]),vn=o.useMemo(()=>D.find(l=>l.deviceId===Pe)||null,[Pe,D]),Nr=vn?cr(vn,Ct[vn.deviceId]):0,fe=Xe?vn:yi,jm=o.useMemo(()=>new Set(gi),[gi]),Kw=o.useMemo(()=>fi==="all"?Ze.map(l=>l.deviceId):Ze.filter(l=>jm.has(l.deviceId)).map(l=>l.deviceId),[Ze,jm,fi]),Qw=fe?Yi(fe,"control"):!1,Vu=is(fe?.platform)&&(fe?.capabilities?.controlPermission===!1||fe?.capabilities?.accessibilityPermission===!1),Rr=fe?Yi(fe,"audio")||Yi(fe,"remoteAudio"):!1,Aa=(Array.isArray(fe?.capabilities?.agentTools)?fe.capabilities.agentTools.map(String):[]).includes("system.power"),Qt=re?j?.plan==="pro"?"pro":"ltd":"free",Em=ks[Qt],Gu=Em.limit,Gr=o.useMemo(()=>new Set(fk(Ze,Gu)),[Gu,Ze]),Yw=!fe||Gr.has(fe.deviceId),Xw=Qt==="free",Rt=Yw,xi=Qt==="ltd"?`Plus includes up to ${$o} Clients. Upgrade to Pro for commercial use and larger walls.`:`Free includes up to ${yl} Clients. Upgrade to Plus for ${$o} devices and no ads.`,Jw=Qt==="free",Tr=Rt&&!!fe&&Qw,Ku=Rt&&!!fe&&Rr,So=o.useMemo(()=>Xe?fe?[fe]:[]:An.length>0?An:fe?[fe]:[],[fe,An,Xe]),Gn=o.useMemo(()=>So.filter(l=>Gr.has(l.deviceId)),[Gr,So]),qc=Gn.some(l=>String(je[l.deviceId]||"").startsWith("pending:")||on[l.deviceId]===!0),xs=!(Gn.length>0&&Gn.every(l=>{const f=String(je[l.deviceId]||"");return!!f&&!f.startsWith("pending:")&&on[l.deviceId]!==!0}))||qc,Uc=o.useMemo(()=>ka.filter(l=>!!l?.connected).slice(0,YP(Bt)).map(l=>l.deviceId),[ka,Bt]),Vc=o.useMemo(()=>Ca?Ar?St||Bt==="list"?zc:ot.visibleOnlyLive?Hr.length>0?Hr:Uc:zc:wo.current.length>0?wo.current:zc:[],[Uc,St,Hr,ot.visibleOnlyLive,zc,Ca,Ar,Bt]),gr=o.useMemo(()=>Yd(Vc.filter(l=>Gr.has(l))),[Gr,Vc]);wo.current=gr;const Kr=o.useMemo(()=>gr.filter(l=>l!==Es&&!qn.has(l)),[qn,gr,Es]),Gc=o.useMemo(()=>new Map(Ze.map(l=>[l.deviceId,l.platform])),[Ze]),Co=o.useMemo(()=>Object.fromEntries(Ze.map(l=>[l.deviceId,String(l.sessionId||"").trim()])),[Ze]),Qr=gk(St,gr.length),Kn=o.useMemo(()=>St?Kr.filter(l=>Bo({mode4Enabled:St,directMode4WallEnabled:Qr,isMac:is(Gc.get(l))})==="atlas"):[],[Qr,St,Gc,Kr]),ir=o.useMemo(()=>Kr.filter(l=>Bo({mode4Enabled:St,directMode4WallEnabled:Qr,isMac:is(Gc.get(l))})==="direct"),[Qr,St,Gc,Kr]),Fm=o.useMemo(()=>{const l=ot.autoStartLive?Kr.map(f=>Ut("wall",f)):[];return vi&&Rt&&te&&Gr.has(te)&&(ae==="connecting"||ae==="active"||ae==="warm")&&l.push(Ut("control",te)),[...new Set(l)].sort()},[vi,te,ae,Rt,Gr,ot.autoStartLive,Kr]);o.useEffect(()=>{const l=new Set(gr);mo(f=>{let b=!1;const x=new Set;for(const S of f)l.has(S)?x.add(S):b=!0;return b?x:f})},[gr]);const Zw=o.useMemo(()=>{const l=S=>Ze.find($=>$.deviceId===S)||null,f=S=>{const $=l(S);return $?cr($,Ct[S]):0},b=(S,$=f(S))=>S===te&&(ae==="connecting"||ae==="active"||ae==="warm")?Ht.current.get(S)||Ln.current.get(S)||null:St?gn.current.get(S)||Tt.current.get(S)||null:Tt.current.get(S)||null,x=(S,$=f(S))=>{const L=l(S);return`${L?dn(L):S} · Monitor ${$+1}`};return{resolveCurrentTarget(){if(Xe&&vn){const q=Nr;return{type:"control",deviceIds:[vn.deviceId],monitorIndex:q,label:`${dn(vn)} · Monitor ${q+1}`,sourceCanvas:b(vn.deviceId,q),signature:`control:${vn.deviceId}:${q}:${rn.frameMode}`}}const S=An.map(q=>q.deviceId).filter(q=>Kr.includes(q)),$=yi&&Kr.includes(yi.deviceId)?yi.deviceId:"",L=S.length>0?S:$?[$]:Kr,B=S.length===0&&!$;if(L.length===0)return null;if(L.length===1){const q=L[0],W=f(q);return{type:B?"wall":S.length>1?"selection":"device",deviceIds:L,monitorIndex:W,label:B?"Wall":x(q,W),sourceCanvas:B?null:b(q,W),signature:`${B?"wall":"device"}:${q}:${W}:${St?"atlas":"direct"}`}}return{type:S.length>1?"selection":"wall",deviceIds:L,label:S.length>1?`${L.length} selected Clients`:"Wall",sourceCanvas:null,signature:`${S.length>1?"selection":"wall"}:${L.join(",")}:${Bt}`}},getDeviceCanvas:b,composeWall(S,$={}){return CT(S.map(L=>{const B=f(L);return{deviceId:L,label:x(L,B),canvas:b(L,B)}}),$)}}},[Ze,vn,te,ae,rn.frameMode,Tt,St,Ct,Nr,An,Xe,Kr,yi,Bt]),Dm=FT({hubUrl:G,sourceRegistry:Zw,onToast:we}),Si=o.useMemo(()=>pk({captureOwnershipActive:vi,localFeatureAccess:Rt,controlSessionDeviceId:te,planAllowed:Gr.has(te),sessionState:ae,controlFocusVisible:Xe,presentationCanvasMounted:ye===te,wallPresentationVisible:Ar,wallPresentationCanvasMounted:Tt.current.has(te)||gn.current.has(te),decoderOwnerExists:Ht.current.has(te)})?[te]:[],[vi,te,ae,Rt,ye,Gr,Xe,Ar]),Qu=o.useMemo(()=>Yd([...gr,...Si]),[Si,gr]),Kc=o.useMemo(()=>Zg(ot,Bt),[ot,Bt]),Ci=o.useMemo(()=>Zg(ot,"large"),[ot]),Qc=bk({mode4Enabled:St,directMode4WallEnabled:Qr,adaptiveFps:Dn,directDeviceCount:ir.length,adaptive:ot.adaptiveLoadShedding}),Nn=rk({fps:Qc,maxWidth:Ci.maxWidth,maxHeight:Ci.maxHeight,quality:ot.quality},A),Yu=yk({deviceCount:Kn.length,targetFps:Dn,adaptive:ot.adaptiveLoadShedding});St&&Kn.length>0;const Ss=o.useCallback((l,f,b,x=1)=>{if(l.width<=0||l.height<=0)return!1;if(l===f)return!0;const S=b?Math.min(1,b.maxWidth/l.width,b.maxHeight/l.height):1,$=Math.max(1,Math.round(l.width*S)),L=Math.max(1,Math.round(l.height*S)),B=f.width!==$||f.height!==L;B&&(f.width=$,f.height=L);const q=f.getContext("2d",{alpha:!1});if(!q)return!1;q.imageSmoothingEnabled=!0,q.imageSmoothingQuality="low";const W=q.globalAlpha;q.globalAlpha=B?1:Math.max(.05,Math.min(1,x));try{q.drawImage(l,0,0,l.width,l.height,0,0,f.width,f.height)}finally{q.globalAlpha=W}return!0},[]),Yc=o.useCallback((l,f)=>{const b=Math.max(0,Number(f.clientWidth||0)),x=Math.max(0,Number(f.clientHeight||0)),S=Math.max(1,Number(window.devicePixelRatio||1)),$=b>0&&x>0?{maxWidth:Math.ceil(b*S),maxHeight:Math.ceil(x*S)}:void 0;return Ss(l,f,$)},[Ss]),Xc=o.useCallback((l,f,b)=>{const x=Math.max(0,Math.floor(Number(l?.frameSeq||0))),S=f||(l?Tt.current.get(l.deviceId):null),$=b||S,L=Math.max(0,Number($?.width||0))*Math.max(0,Number($?.height||0)),B=Math.max(Tt.current.size,gn.current.size);return t&&x>0&&(x+aP(l?.deviceId||""))%Mw===0&&B<=sP&&yS(S)&&L>0&&L<=rP?nP:1},[t]),ki=o.useCallback((l,f,b)=>{if(!kc.current)return;const x=`${l}:${f.deviceId}`,S=Mc.current.get(x)||{bindingKey:"",totalPaints:0,lastPaintAt:0,lastFrameSeq:0};S.bindingKey=rs(f),S.totalPaints+=1,S.lastPaintAt=performance.now(),S.lastFrameSeq=Number(f.frameSeq||0),Mc.current.set(x,S);const $=++mm.current,L={sequence:$,scope:l,deviceId:f.deviceId,bindingKey:S.bindingKey,frameSeq:S.lastFrameSeq,paintedAt:S.lastPaintAt,sourceGapMs:Number(f.sourceGapMs||0),agentSendGapMs:Number(f.agentSendGapMs||0),agentSendDurationMs:Number(f.agentSendDurationMs||0),agentSendDurationFrameSeq:Number(f.agentSendDurationFrameSeq||0),agentFrameAgeMs:Number(f.agentFrameAgeMs||0),timestampUs:Number(f.timestampUs||0),queuedForMs:Number(b?.queuedForMs||0),decodedForMs:Number(b?.decodedForMs||0),scheduledForMs:Number(b?.scheduledForMs||0),interactiveBurstOutputWindowMs:Number(b?.interactiveBurstOutputWindowMs||0),interactiveBurstTailHoldCount:Number(b?.interactiveBurstTailHoldCount||0)};Fu.current[($-1)%fP]=L},[]),Yr=o.useCallback(l=>{l&&mo(f=>{if(f.has(l))return f;const b=new Set(f);return b.add(l),b})},[]),Xr=o.useCallback(l=>{l&&mo(f=>{if(!f.has(l))return f;const b=new Set(f);return b.delete(l),b})},[]),Na=o.useCallback((l,f)=>{if(!f||f.width<=0||f.height<=0)return!1;const b=document.createElement("canvas");if(b.width=f.width,b.height=f.height,!Ss(f,b))return On(b),!1;const x=hs.current.get(l);return hs.current.set(l,b),x&&x!==b&&Bn(x),Yr(l),!0},[Yr,Ss,Bn,On]),un=o.useCallback(l=>{bC(hs.current,l,Wi)},[]),Jc=o.useCallback((l,f)=>{const b=hs.current.get(l),x=Tt.current.get(l)===f||gn.current.get(l)===f;return Ye.current[l]?(un(l),!1):!b||!x||b.width<=0||b.height<=0?!1:Ss(b,f)?!0:(un(l),!1)},[Ss,un]),Cs=o.useCallback((l,f=!1,b)=>{if(Ye.current[l]||!fs.current.has(l))return!1;const x=Math.max(1,Math.min(dr,$t.controlWallReuseMaxFps,xo)),S=performance.now(),$=si.current.get(l)||0,L=Ht.current.get(l)||Ln.current.get(l),B=Tt.current.get(l)||gn.current.get(l);if(!L||!B||!B.isConnected)return!1;const q=hk({cadenceCredit:Ds.current.get(l)||0,targetFps:x,sourceFps:xo,elapsedSincePaintMs:$>0?S-$:0,nowMs:S,scheduledPaintAtMs:ma.current.get(l)||0,force:f});if(!q.shouldPaint)return Ds.current.set(l,q.nextCadenceCredit),!1;const W=Math.max(0,Number(B.clientWidth||0)),ke=Math.max(0,Number(B.clientHeight||0)),Me=Math.max(1,Number(window.devicePixelRatio||1)),he=W>0&&ke>0?{maxWidth:Math.min(Kc.maxWidth,Math.ceil(W*Me)),maxHeight:Math.min(Kc.maxHeight,Math.ceil(ke*Me))}:Kc;return Ss(L,B,he,b?Xc(b,L,B):1)?(Ds.current.set(l,q.nextCadenceCredit),q.nextScheduledPaintAtMs>0&&ma.current.set(l,q.nextScheduledPaintAtMs),si.current.set(l,performance.now()),q.sourceCadencePassthrough&&(Ds.current.delete(l),ma.current.delete(l)),b&&ki("wall-reuse-visible",b),Yr(l),un(l),!0):!1},[xo,Kc,Yr,Ss,ki,un,Xc,dr]);o.useEffect(()=>{Ls.current=Es},[Es]);const Zc=o.useCallback((l,f)=>{const b=bs.current;if(!b||b.deviceId!==l)return;const x=Date.now();hm.current.set(l,{...b,source:f,completedAtEpochMs:x,durationMs:Math.max(0,performance.now()-b.startedAt)}),bs.current=null},[]),Lm=o.useCallback((l,f)=>{const b=Tt.current.get(l);if(f&&b&&b!==f&&Na(l,b),f){if(Tt.current.set(l,f),b&&b!==f&&On(b),Ye.current[l]){un(l),Bn(f),Xr(l);return}hs.current.get(l)&&Jc(l,f)&&Yr(l),Cs(l,!0);return}if(b&&bi.current&&wo.current.includes(l)){Na(l,b),Tt.current.delete(l),On(b);return}Tt.current.delete(l),un(l),On(b),Xr(l)},[Xr,Yr,Cs,Jc,Na,Bn,un,On]),ey=o.useCallback((l,f)=>{const b=Ln.current.get(l);if(f){Ln.current.set(l,f),ue(l),b&&b!==f&&On(b);const x=te===l&&ce?Ht.current.get(l):null;x&&Yc(x,f)&&l===Pe&&(Zc(l,"warm-reuse"),_n(!0)),x&&x!==f&&mk({decodeWidth:x.width,decodeHeight:x.height,presentationCssWidth:f.getBoundingClientRect().width,presentationCssHeight:f.getBoundingClientRect().height,devicePixelRatio:window.devicePixelRatio,sourceWidth:Vr.maxWidth,sourceHeight:Vr.maxHeight})&&(Ht.current.set(l,f),On(x));return}Ln.current.delete(l),ue(x=>x===l?"":x),On(b)},[Zc,Pe,te,ce,Vr.maxHeight,Vr.maxWidth,Yc,On]),el=o.useCallback((l,f,b)=>{const x=performance.now(),S=Ut(l,b.deviceId);let $=b;if(l==="control"&&b.visualChanged){const q=String(f.inputFeedbackEventId||""),W=Number(f.inputFeedbackInputSeq||0),ke=Number(f.inputFeedbackIssuedAtEpochMs||0),Me=Number(f.browserReceivedEpochMs||0),he=bm.current.get(b.deviceId)||"",tt=ke>0?Math.max(0,Date.now()-ke):Number.POSITIVE_INFINITY;if(q.length>0&&W>0&&q!==he&&tt<=Kd){const at=vm.current.get(b.deviceId)||[];at.push(tt),at.length>Dg&&at.splice(0,at.length-Dg),vm.current.set(b.deviceId,at),$={...b,inputFeedbackSeq:W,inputFeedbackMs:tt,inputFeedbackAt:x,inputFeedbackExact:!0,inputFeedbackEventId:q,inputFeedbackInputType:f.inputFeedbackInputType,inputFeedbackInputToFrameMs:Me>0?Math.max(0,Me-ke):void 0,inputFeedbackFrameToPaintMs:Me>0?Math.max(0,Date.now()-Me):void 0,inputFeedbackAgentApplyMs:f.inputFeedbackAgentApplyMs,inputFeedbackApplyToCaptureMs:f.inputFeedbackApplyToCaptureMs,inputFeedbackSampleCount:at.length,inputFeedbackP50Ms:qo(at,.5),inputFeedbackP95Ms:qo(at,.95)},bm.current.set(b.deviceId,q),Ou.current.set(b.deviceId,W)}else if(!q){const at=f0(b.deviceId),wt=Ou.current.get(b.deviceId)||0,Et=at?x-at.sentAt:Number.POSITIVE_INFINITY;at&&at.inputSeq>wt&&Et<=Kd&&($={...b,inputFeedbackSeq:at.inputSeq,inputFeedbackMs:Math.max(0,Et),inputFeedbackAt:x,inputFeedbackExact:!1},Ou.current.set(b.deviceId,at.inputSeq))}}fa.current.set(S,x),va.current.delete(S),vs.current.delete(S);const L=gs.current.get(S)||{totalFrames:0,totalChangedFrames:0,sampleFrames:0,sampleChangedFrames:0,sampleStartedAt:x,intervalCount:0,intervalSumMs:0,minIntervalMs:Number.POSITIVE_INFINITY,maxIntervalMs:0,intervalSamplesMs:[],seqGapCount:0,maxSeqGap:0,sampleDecoderInputBase:0,sampleDecoderOutputBase:0},B=rs(f);L.bindingKey!==B&&(L.bindingKey=B,L.lastAt=void 0,L.lastFrameSeq=void 0,L.sampleChangedFrames=0,L.sampleDecoderInputBase=Number(b.decoderInputCount||0),L.sampleDecoderOutputBase=Number(b.decoderOutputCount||0),zl(L,x)),l==="control"&&$.inputFeedbackMs===void 0&&L.lastInfo?.inputFeedbackMs!==void 0&&L.lastInfo.inputFeedbackAt!==void 0&&x-L.lastInfo.inputFeedbackAt<=Kd&&($={...$,inputFeedbackSeq:L.lastInfo.inputFeedbackSeq,inputFeedbackMs:L.lastInfo.inputFeedbackMs,inputFeedbackAt:L.lastInfo.inputFeedbackAt,inputFeedbackExact:L.lastInfo.inputFeedbackExact,inputFeedbackEventId:L.lastInfo.inputFeedbackEventId,inputFeedbackInputType:L.lastInfo.inputFeedbackInputType,inputFeedbackInputToFrameMs:L.lastInfo.inputFeedbackInputToFrameMs,inputFeedbackFrameToPaintMs:L.lastInfo.inputFeedbackFrameToPaintMs,inputFeedbackAgentApplyMs:L.lastInfo.inputFeedbackAgentApplyMs,inputFeedbackApplyToCaptureMs:L.lastInfo.inputFeedbackApplyToCaptureMs,inputFeedbackSampleCount:L.lastInfo.inputFeedbackSampleCount,inputFeedbackP50Ms:L.lastInfo.inputFeedbackP50Ms,inputFeedbackP95Ms:L.lastInfo.inputFeedbackP95Ms}),L.totalFrames+=1,L.sampleFrames+=1,qg(L,x,$.frameSeq),$.visualChanged&&(L.totalChangedFrames+=1,L.sampleChangedFrames+=1),L.lastInfo=$,gs.current.set(S,L)},[]),tl=o.useCallback((l,f)=>{if(Ye.current[l.deviceId]||Ls.current===l.deviceId)return;el("wall",l,f);const b=ce&&te===l.deviceId,x=Tt.current.get(l.deviceId)||gn.current.get(l.deviceId);kc.current&&!Xe&&!b&&x?.isConnected&&ki("wall-visible",l,f),l.kind==="live"&&(Yr(l.deviceId),un(l.deviceId)),Ls.current!==l.deviceId&&!b&&(fs.current.delete(l.deviceId),Ds.current.delete(l.deviceId),si.current.delete(l.deviceId),ma.current.delete(l.deviceId))},[te,ce,Yr,el,ki,un,Xe]),_m=o.useCallback((l,f)=>{if(Ye.current[l.deviceId]||Dt(ar.current,it.current)||!Ed(l,it.current))return;el("control",l,f),De(L=>L&&"");const b=Ht.current.get(l.deviceId),x=Ln.current.get(l.deviceId);let S=!1;b&&b.width>0&&b.height>0&&(x&&Xe&&l.deviceId===Pe&&(S=Yc(b,x),S&&ki("control-visible",l,f)),pa.current.set(l.deviceId,za(l)),fs.current.add(l.deviceId),l.deviceId===te&&(J(!0),le(L=>L==="connecting"?"active":L)),Cs(l.deviceId,!1,l));const $=Pc.current;!$||!mP($,l)||!S||(Zc(l.deviceId,"fresh-frame"),_n(!0))},[Zc,Pe,te,Cs,Yc,el,ki,Xe]),Ra=o.useCallback((l,f)=>{const b=performance.now(),x=Ut(l,f.deviceId);$s.current.set(x,b),zr.current.delete(x),l==="control"?ga.current.delete(x):ui.current.delete(x);const S=_s.current.get(x)||{totalFrames:0,sampleFrames:0,sampleStartedAt:b,intervalCount:0,intervalSumMs:0,minIntervalMs:Number.POSITIVE_INFINITY,maxIntervalMs:0,intervalSamplesMs:[],seqGapCount:0,maxSeqGap:0,sampleBytes:0,sampleH264Frames:0,sampleTinyFrames:0,sampleRepeatedFrames:0,sourceSendIntervalsMs:[]},$=rs(f);if(S.bindingKey!==$&&(S.bindingKey=$,S.lastAt=void 0,S.lastFrameSeq=void 0,S.lastContentHash=void 0,S.sampleBytes=0,S.sampleH264Frames=0,S.sampleTinyFrames=0,S.sampleRepeatedFrames=0,S.sourceSendIntervalsMs.length=0,zl(S,b)),S.totalFrames+=1,S.sampleFrames+=1,S.sampleBytes+=Math.max(0,Number(f.byteLength||0)),String(f.frameMode||f.mode||f.codec||f.mimeType||"").toLowerCase().includes("h264")){S.sampleH264Frames+=1,Number(f.byteLength||0)<=cP&&(S.sampleTinyFrames+=1);const W=String(f.contentHash||"");W&&S.lastContentHash===W&&(S.sampleRepeatedFrames+=1),S.lastContentHash=W}const q=Number(f.agentSendGapMs||0);q>0&&q<1e3&&Aw(S.sourceSendIntervalsMs,q),S.lastFrame=za(f),qg(S,b,f.frameSeq),_s.current.set(x,S)},[]);o.useEffect(()=>{const l=new Set(Fm);for(const x of gs.current.keys())l.has(x)||gs.current.delete(x);for(const x of _s.current.keys())l.has(x)||_s.current.delete(x);const f=x=>{const S=Object.entries(x).filter(([$])=>l.has($));return S.length===Object.keys(x).length?x:Object.fromEntries(S)};if(Du(f),Rc(f),l.size===0)return;const b=window.setInterval(()=>{const x=performance.now(),S={},$={};for(const L of l){const B=gs.current.get(L);if(B){const Me=Math.max(1,x-B.sampleStartedAt);S[L]={bindingKey:B.bindingKey||"",totalFrames:B.totalFrames,totalChangedFrames:B.totalChangedFrames,framesPerSecond:B.sampleFrames*1e3/Me,changedFramesPerSecond:B.sampleChangedFrames*1e3/Me,averageIntervalMs:B.intervalCount>0?B.intervalSumMs/B.intervalCount:0,minIntervalMs:Number.isFinite(B.minIntervalMs)?B.minIntervalMs:0,maxIntervalMs:B.maxIntervalMs,p95IntervalMs:qo(B.intervalSamplesMs,.95),intervalCount:B.intervalCount,seqGapCount:B.seqGapCount,maxSeqGap:B.maxSeqGap,decoderInputFps:Math.max(0,(Number(B.lastInfo?.decoderInputCount||0)-B.sampleDecoderInputBase)*1e3/Me),decoderOutputFps:Math.max(0,(Number(B.lastInfo?.decoderOutputCount||0)-B.sampleDecoderOutputBase)*1e3/Me),sampleMs:Me,lastInfo:B.lastInfo},B.sampleDecoderInputBase=Number(B.lastInfo?.decoderInputCount||0),B.sampleDecoderOutputBase=Number(B.lastInfo?.decoderOutputCount||0),B.sampleChangedFrames=0,zl(B,x)}const q=_s.current.get(L);if(!q)continue;const W=Math.max(1,x-q.sampleStartedAt),ke=q.lastFrame?za(q.lastFrame):void 0;q.lastFrame=ke,$[L]={totalFrames:q.totalFrames,framesPerSecond:q.sampleFrames*1e3/W,averageIntervalMs:q.intervalCount>0?q.intervalSumMs/q.intervalCount:0,minIntervalMs:Number.isFinite(q.minIntervalMs)?q.minIntervalMs:0,maxIntervalMs:q.maxIntervalMs,p95IntervalMs:qo(q.intervalSamplesMs,.95),intervalCount:q.intervalCount,seqGapCount:q.seqGapCount,maxSeqGap:q.maxSeqGap,averageFrameBytes:q.sampleFrames>0?q.sampleBytes/q.sampleFrames:0,tinyFrameRatio:q.sampleH264Frames>0?q.sampleTinyFrames/q.sampleH264Frames:0,repeatedFrameRatio:q.sampleH264Frames>0?q.sampleRepeatedFrames/q.sampleH264Frames:0,sourceSendAverageMs:q.sourceSendIntervalsMs.length>0?q.sourceSendIntervalsMs.reduce((Me,he)=>Me+he,0)/q.sourceSendIntervalsMs.length:0,sourceSendP95Ms:qo(q.sourceSendIntervalsMs,.95),sourceSendSampleCount:q.sourceSendIntervalsMs.length,sampleMs:W,lastFrame:ke},q.sampleBytes=0,q.sampleH264Frames=0,q.sampleTinyFrames=0,q.sampleRepeatedFrames=0,q.sourceSendIntervalsMs.length=0,zl(q,x)}Du(S),Rc($)},1e3);return Tc.current=b,()=>{window.clearInterval(b),Tc.current===b&&(Tc.current=null)}},[Fm]);const $m=o.useCallback(l=>{const f=l.deviceId,b=rs(l);if(Ye.current[f]||Ls.current===f||l.currentGenerationVerified!==!0||Wr.current.get(f)!==b)return;Ra("wall",l);const x=Tt.current.get(f);if(!x)return;const S=pi(x),$=mi(x),L=()=>Tt.current.get(f)!==x||!hi(x,S)||!!Ye.current[f]||Ls.current===f||Wr.current.get(f)!==b,B=()=>L()||!wa(x,$),q=xk(St,ot.h264DecodeAcceleration);Rd(x,l,B,tl,q.acceleration,q.latencyMode,L,Xc).catch(()=>{})},[pi,wa,hi,mi,tl,St,Ra,Xc,ot.h264DecodeAcceleration]),Om=o.useCallback(l=>{const f=l.deviceId;if(Ye.current[f]||Dt(ar.current,it.current)||!Ed(l,it.current))return;let b=Ht.current.get(f);if(!b){const he=Ln.current.get(f),tt=da.current;b=he||tt||document.createElement("canvas"),he&&tt&&tt!==he&&Bn(tt),da.current=null,b!==he&&b.setAttribute("aria-hidden","true"),Ht.current.set(f,b)}const x=b,S=l,$=pi(x),L=mi(x),B=()=>Ht.current.get(f)!==x||!hi(x,$)||!!Ye.current[f]||!Ed(S,it.current),q=()=>B()||!wa(x,L),W=qe.current,ke=String(l.frameMode||l.mode||l.codec||l.mimeType||"").toLowerCase().includes("h264");ke||Ra("control",l);const Me=Rd(x,l,q,_m,rn.h264DecodeAcceleration,"interactive",B);ke&&Ra("control",l),Me.catch(he=>{qe.current!==W||Ht.current.get(f)!==x||!wa(x,L)||B()||te!==f||De(he instanceof Error?he.message:String(he||"Control H.264 decode failed"))})},[pi,wa,hi,mi,te,rn.h264DecodeAcceleration,_m,Ra,Bn]),ty=o.useCallback(l=>{const f=sr.current;sr.current=l,f&&f!==l&&On(f),vo.current=0,jc.current=0,Ec.current=0,Fc.current=0,$u.current=0,fo.current=0},[On]),Mi=o.useCallback(()=>{const l=new Set,f=sr.current,b=ii.current;if(!f||!b||f.width<=0||f.height<=0||fo.current!==b.layoutVersion)return l;for(const x of b.tiles){if(Ye.current[x.deviceId])continue;const S=gn.current.get(x.deviceId);if(!S||x.width<=0||x.height<=0)continue;const $=Math.max(1,Math.round(x.width)),L=Math.max(1,Math.round(x.height)),B=lP,q=uP;(S.width!==B||S.height!==q)&&(S.width=B,S.height=q);const W=S.getContext("2d",{alpha:!1});if(W){W.imageSmoothingEnabled=!0,W.imageSmoothingQuality="high";try{W.drawImage(f,Math.round(x.x),Math.round(x.y),$,L,0,0,B,q),l.add(x.deviceId)}catch{}}}return l},[]),ny=o.useCallback((l,f)=>{const b=gn.current.get(l);if(f&&b&&b!==f&&Na(l,b),f){if(gn.current.set(l,f),b&&b!==f&&On(b),Ye.current[l]){un(l),Bn(f),Xr(l);return}hs.current.get(l)&&Jc(l,f)&&Yr(l),window.requestAnimationFrame(()=>{Mi().has(l)&&un(l)}),window.requestAnimationFrame(()=>Cs(l,!0));return}gn.current.delete(l),un(l),On(b),Xr(l)},[Xr,Yr,Mi,Cs,Jc,Na,Bn,un,On]),Bm=o.useCallback((l,f)=>{Ec.current=performance.now(),fo.current=Number(l.layoutVersion||0),Mi();const b=ii.current?.tiles||[],x=b.length>0?Math.round(l.byteLength/b.length):l.byteLength;for(const S of b){if(Ye.current[S.deviceId])continue;const $={...l,deviceId:S.deviceId,width:S.width,height:S.height,sourceWidth:S.width,sourceHeight:S.height,byteLength:x};tl($,{...f,deviceId:S.deviceId,width:S.width,height:S.height,byteLength:x}),Ls.current===S.deviceId&&Cs(S.deviceId,!0)}},[tl,Mi,Cs]),ry=o.useCallback(l=>{const f=performance.now();vo.current<=0&&(vo.current=f),jc.current=f;const b=sr.current;if(!b)return;const x=rs(l);ho.current!==x&&(ho.current=x,sn(b));const S=pi(b),$=mi(b),L=()=>sr.current!==b||ho.current!==x||!hi(b,S),B=()=>L()||!wa(b,$),q=ii.current?.tiles||[],W=q.length>0?Math.round(l.byteLength/q.length):l.byteLength;for(const ke of q)Ye.current[ke.deviceId]||Ra("wall",{...l,deviceId:ke.deviceId,width:ke.width,height:ke.height,sourceWidth:ke.width,sourceHeight:ke.height,byteLength:W});Rd(b,l,B,Bm,void 0,"smooth",L).catch(()=>{})},[pi,wa,hi,mi,Bm,Ra,sn]),Hm=o.useCallback(l=>{if(l.streamPurpose!=="wall"||Ye.current[l.deviceId])return;const f=rs(l);Wr.current.get(l.deviceId)!==f&&(Wr.current.set(l.deviceId,f),sn(Tt.current.get(l.deviceId)))},[sn]),sy=o.useMemo(()=>({fps:Nn.fps,maxWidth:Nn.maxWidth,maxHeight:Nn.maxHeight,quality:Nn.quality,mode:St?"mode3-h264-hw":ot.frameMode,frameMode:St?"mode3-h264-hw":ot.frameMode,streamPurpose:"wall",configurationRefreshMs:WT,forceRestart:di>0,forceRestartToken:di>0?`document-presentation-resume-${di}`:"",restartReason:di>0?"document-presentation-resume":"",connectionSessionIds:Co,monitorSelections:Ct,onFrame:$m,onStreamReady:Hm}),[Co,di,$m,Hm,St,Ct,ot.frameMode,Nn.fps,Nn.maxHeight,Nn.maxWidth,Nn.quality]),Wm=o.useCallback(l=>{const f=it.current;if(Ye.current[l.deviceId]||!f||Dt(ar.current,f)||f.deviceId!==l.deviceId||l.deviceId!==te||l.streamPurpose!=="control"||l.monitorIndex!==Nr)return;const b=Ze.find(S=>S.deviceId===l.deviceId);if(!b?.sessionId||b.sessionId!==l.sessionId)return;const x=T.current;(!x||rs(x)!==rs(l))&&sn(Ht.current.get(l.deviceId)),it.current=jd(f.deviceId,f.transitionGeneration,l),T.current=l,nt(l),le(S=>S==="connecting"?"active":S)},[Ze,te,sn,Nr]);o.useEffect(()=>{sn(Ht.current.get(te)),T.current=null,nt(null)},[te,Fe,fr,sn,Nr]);const nl=Fe?`${Fe}-monitor-${Nr}`:"",ay=o.useMemo(()=>({fps:xo,maxWidth:Vr.maxWidth,maxHeight:Vr.maxHeight,quality:rn.quality,mode:fr,frameMode:fr,streamPurpose:"control",forceRestart:nl!=="",forceRestartToken:nl,restartReason:nl?"control-session-or-monitor-change":"",connectionSessionIds:Co,monitorSelections:Ct,onFrame:Om,onStreamReady:Wm}),[Co,nl,rn.quality,Om,xo,fr,Vr.maxHeight,Vr.maxWidth,Wm,Ct]),{frames:zm,state:ko,error:qm,stats:Ta,restartLive:rl,reconnectLive:Um}=hf(ir,ot.autoStartLive&&ir.length>0,G,sy);o.useEffect(()=>{const l=new Set(ir);for(const f of Wr.current.keys())l.has(f)||(Wr.current.delete(f),sn(Tt.current.get(f)))},[ir,sn]);const{frame:Ai,layout:Pa,state:Xu,stats:iy,refreshInputs:Vm}=y0(Kn,St&&ot.autoStartLive&&Kn.length>0,G,{fps:$t.atlasOutputFps,inputFps:Yu,width:1920,height:1080,tileWidth:Ci.maxWidth,tileHeight:Ci.maxHeight,captureDeviceIds:Kn,connectionSessionIds:Co,monitorSelections:Ct,onFrame:ry});o.useEffect(()=>{ii.current=Pa,Pa&&window.requestAnimationFrame(Mi)},[Pa,Mi]),o.useEffect(()=>{if(!St||Xu!=="open"){vo.current=0,jc.current=0,Ec.current=0;return}const l=window.setInterval(()=>{const f=sr.current,b=performance.now();if(!f||document.visibilityState!=="visible"||b-Ic.current<Gd)return;const x=jc.current,S=vo.current;if(x<=0||S<=0||b-x>500)return;const $=Ec.current||S,L=b-$;if(L>=ZT&&b-$u.current>=tP){zi(f)&&($u.current=b,Fc.current=b);return}L>=JT&&b-Fc.current>=eP&&uC(f)&&(Fc.current=b)},250);return()=>window.clearInterval(l)},[Xu,St]);const{frames:Mo,state:Ju,error:Ao,stats:oy,restartLive:sl,reconnectLive:No}=hf(Si,Si.length>0,G,ay);o.useEffect(()=>{const l=vc.current,f=new Set([...Object.keys(l),...Object.keys(Ct)]);for(const b of f){const x=Math.max(0,Math.floor(Number(l[b])||0)),S=Math.max(0,Math.floor(Number(Ct[b])||0));x!==S&&(Wr.current.delete(b),sn(Tt.current.get(b)),sn(Ht.current.get(b)),sn(gn.current.get(b)),bn("wall",b),bn("control",b),zi(Tt.current.get(b)||null),zi(Ht.current.get(b)||null))}f.size>0&&(sn(sr.current),zi(sr.current)),vc.current={...Ct}},[Ct,bn,sn]);const Ni=o.useMemo(()=>{const l=(b,x)=>{const S=Ze.find(L=>L.deviceId===b),$=S?cr(S,Ct[b]):0;return!Number.isFinite(Number(x.monitorIndex))||Number(x.monitorIndex)===$},f=new Map;for(const[b,x]of zm.entries())l(b,x)&&f.set(b,x);if(St&&Ai&&Kn.length>0){const b=new Map((Pa?.tiles||[]).map(S=>[S.deviceId,S])),x=Math.max(1,b.size);for(const S of Kn){const $=b.get(S);$&&f.set(S,{...Ai,deviceId:S,width:$.width,height:$.height,sourceWidth:$.width,sourceHeight:$.height,byteLength:Math.round(Ai.byteLength/x)})}}for(const[b,x]of Mo.entries())l(b,x)&&f.set(b,x);for(const b of Vc){if(!fs.current.has(b)||f.has(b))continue;const x=pa.current.get(b);x&&l(b,x)&&f.set(b,x)}return f},[Ai,Pa,Ze,Mo,Kn,St,Ct,zm,Vc,Fs]),Zu=Xe&&Si.length>0?Ju:Kn.length>0?Xu:ko,al=Xe&&Si.length>0?oy:Kn.length>0?iy:Ta;o.useCallback((l,f="browser-stale")=>{const b=rl(l,f),x=sl(l,f);return b||x},[sl,rl]),o.useEffect(()=>{St&&Kn.length>0&&!Xe&&Vm()},[Kn.length,St,Vm,Xe]);const Ri=o.useCallback((l,f,b)=>{const x=f==="control"?Ht.current.get(l)||null:Tt.current.get(l)||null;if(!x)return!1;zi(x);const S=performance.now();return va.current.set(Ut(f,l),S),!0},[]),Ro=o.useCallback(l=>{if(fr!=="mode3-h264-hw"||!te||Ue)return!1;const f=Ze.find(B=>B.deviceId===te)||vn,b=ab(f?.platform);if(!b)return!1;const x=Ut("control",te),S=performance.now();ba.current.set(x,S),$s.current.delete(x),fa.current.delete(x),li.current.delete(x),ga.current.delete(x),vs.current.delete(x),zi(Ht.current.get(te)||null),No([te],"control-decode-fallback"),ne(b),Le(`control-${b}-fallback-${te}-${Date.now()}`),J(!1),_n(!1);const $=l==="no first frame"||l==="control-first-frame-timeout",L=b==="mode1-jpeg"?"Mode 1 JPEG":"Mode 5";return De(B=>B||($?`Control frame transport timeout; retrying Control with ${L} (${l})`:`H.264 decode failed; retrying Control with ${L} (${l})`)),le("connecting"),!0},[Ze,vn,te,Ue,fr,No]);o.useEffect(()=>{const l=Xe?vn:null;if(l){Pc.current={deviceId:l.deviceId,monitorIndex:Nr,frameMode:fr,startedAtEpochMs:Date.now()},_n(te===l.deviceId&&ce);return}Pc.current=null,_n(!1)},[vn?.sessionId,Pe,te,ce,fr,Nr,Xe]);const Gm=o.useCallback(async(l,f)=>{const b=String(f.streamId||"").trim(),x=String(f.streamPurpose||"").trim(),S=String(f.sessionId||"").trim(),$=String(f.commandId||"").trim(),L=Number(f.captureGeneration||0),B=Number(f.monitorIndex??-1);if(!b||!["wall","atlas"].includes(x)||!S||!$||!Number.isSafeInteger(L)||L<=0||!Number.isSafeInteger(B)||B<0)throw new Error("wall-start-owner-incomplete");const q=performance.now()+3e3;for(;;){const W=await Oe(`/api/remote/devices/${encodeURIComponent(l)}/live/stop`,{method:"POST",body:JSON.stringify({streamId:b,streamPurpose:x,expectedSessionId:S,expectedCommandId:$,expectedCaptureGeneration:L,expectedMonitorIndex:B,requireNoPresentationOwner:!0,reason:"wall-start-presentation-revoked"})},G);if(W?.ok===!1)throw new Error(W.error||"revoked-wall-start-stop-failed");if(W?.captureStopConfirmed===!0||W?.alreadyStopped===!0||W?.staleOwner===!0)return W;if(W?.presentationOwnerActive===!0||W?.retainedForPresentation===!0){if(Mr.current&&bi.current)return W;if(performance.now()<q){await new Promise(ke=>window.setTimeout(ke,50));continue}throw new Error("revoked-wall-start-presentation-owner-did-not-release")}throw new Error("revoked-wall-start-stop-unconfirmed")}},[G]),Ia=o.useCallback(async l=>{if(Ye.current[l])throw new Error("LIVE_CAPTURE_PAUSED");if(!Mr.current||!bi.current)return{ok:!0,skipped:!0,reason:"wall-capture-owner-hidden"};const f=qr.current,b=D.find(L=>L.deviceId===l);Bo({mode4Enabled:St,directMode4WallEnabled:Qr,isMac:is(b?.platform)});const x=b?cr(b,Ct[l]):0,S={fps:Nn.fps,maxWidth:Nn.maxWidth,maxHeight:Nn.maxHeight,quality:Nn.quality,mode:St?"mode3-h264-hw":ot.frameMode,frameMode:St?"mode3-h264-hw":ot.frameMode,streamPurpose:"wall",monitorIndex:x},$=await Oe(`/api/remote/devices/${encodeURIComponent(l)}/live/start`,{method:"POST",body:JSON.stringify(S)},G);if($?.ok===!1)throw new Error($.error||"wall-stream-start-failed");return f!==qr.current||!Mr.current||!bi.current?(await Gm(l,$),{...$,skipped:!0,reason:"wall-presentation-owner-revoked",compensated:!0}):$},[Yu,D,Qr,G,St,Ct,Gm,ot.frameMode,Ci.maxHeight,Ci.maxWidth,Nn.fps,Nn.maxHeight,Nn.maxWidth,Nn.quality]),Km=o.useCallback(async l=>{const f=D.find(x=>x.deviceId===l);Bo({mode4Enabled:St,directMode4WallEnabled:Qr,isMac:is(f?.platform)});const b=await Oe(`/api/remote/devices/${encodeURIComponent(l)}/live/stop`,{method:"POST",body:JSON.stringify({streamPurpose:"wall",reason:"control-active"})},G);if(b?.ok===!1)throw new Error(b.error||"wall-stream-stop-failed");return b},[D,Qr,G,St]),Qm=o.useCallback(async(l,f="control-session-stop")=>{const b=await Oe(`/api/remote/devices/${encodeURIComponent(l)}/live/stop`,{method:"POST",body:JSON.stringify({streamPurpose:"control",reason:f})},G);if(b?.ok===!1)throw new Error(b.error||"control-stream-stop-failed");return b},[G]),Qn=o.useCallback((l,f={})=>{ar.current?.deviceId===l&&(ar.current=null);const b=Ht.current.get(l);if(b){const S=hs.current.has(l)||Tt.current.has(l)||gn.current.has(l);f.preservePresentation!==!1&&!S&&Na(l,b),Ht.current.delete(l),Bn(b),!(Ln.current.get(l)||Tt.current.get(l)||gn.current.get(l))&&!da.current&&(da.current=b)}const x=Ln.current.get(l);x&&Wi(x),pa.current.delete(l),fs.current.delete(l),Ds.current.delete(l),si.current.delete(l),ma.current.delete(l)},[Na,Bn]),il=o.useCallback(l=>{const f=[Ut("wall",l),Ut("control",l)];for(const b of f){const x=_s.current.get(b);x?.lastFrame&&(x.lastFrame=za(x.lastFrame))}Rc(b=>{let x=!1;const S={...b};for(const $ of f){const L=b[$];!L?.lastFrame||L.lastFrame.payload.byteLength===0||(S[$]={...L,lastFrame:za(L.lastFrame)},x=!0)}return x?S:b})},[]),ed=o.useCallback(l=>{Wr.current.delete(l),un(l),Qn(l,{preservePresentation:!1});const f=new Set;for(const b of[Ln.current.get(l),Tt.current.get(l),gn.current.get(l)])b&&f.add(b);for(const b of f)Bn(b);Xr(l),te===l&&(Pc.current=null,_n(!1),J(!1)),Gt.current.add(l),il(l)},[Xr,te,Bn,Qn,il,un]);o.useEffect(()=>{const l=new Set(Object.keys(je));for(const f of l)Gt.current.has(f)||ed(f);for(const f of Gt.current)l.has(f)||Gt.current.delete(f)},[ed,je]);const Ti=o.useCallback(l=>{const f=Rf(pm.current,l);return pm.current=f.tail,f.result},[]),br=o.useCallback(l=>{const f=Rf(gm.current,l);return gm.current=f.tail,f.result},[]),vr=o.useCallback(l=>{Vn.current=l,Cc.current=0;const f=l?.deviceId||"";Ls.current=f,wc(f),f&&fs.current.add(f)},[]),Pi=o.useCallback(l=>Ti(async()=>{if(Ye.current[l.deviceId])return!1;const f=Vn.current;return!Dt(f,l)||!Tl(l.deviceId,l,it.current)?!1:(await Ia(l.deviceId),Dt(Vn.current,l)&&vr(null),!0)}),[vr,Ti,Ia]),Ym=o.useCallback((l,f,b)=>Ti(async()=>{const x=Vn.current;if(Dt(x,l))return b.stoppedWallDeviceId=l.deviceId,!0;if(x)if(Ye.current[x.deviceId])Dt(Vn.current,x)&&vr(null);else{if(!Tl(x.deviceId,x,it.current))return!1;await Ia(x.deviceId),Dt(Vn.current,x)&&vr(null)}if(!f())return!1;if(await Km(l.deviceId),b.stoppedWallDeviceId=l.deviceId,!f()){if(Tl(b.stoppedWallDeviceId,l,it.current))try{await Ia(b.stoppedWallDeviceId)}catch(S){throw vr(l),S}finally{b.stoppedWallDeviceId=""}return!1}return Wi(Tt.current.get(l.deviceId)||null),vr(l),!0}),[vr,Ti,Ia,Km]),ol=o.useCallback(async(l,f)=>{if(f.stoppedWallDeviceId){if(Dt(Vn.current,l)){try{await Pi(l)}catch(b){we(b instanceof Error?b.message:String(b))}finally{f.stoppedWallDeviceId=""}return}await Ti(async()=>{if(!f.stoppedWallDeviceId||!Tl(f.stoppedWallDeviceId,l,it.current))return;const b=f.stoppedWallDeviceId;try{await Ia(b)}catch(x){vr(l),we(x instanceof Error?x.message:String(x))}finally{f.stoppedWallDeviceId=""}})}},[vr,Ti,Pi,we,Ia]),wr=o.useCallback(async(l,f,b={})=>{const x=b.allowStopFailure===!0,S=b.resumeWall!==!1;try{await Qm(l.deviceId,f)}catch($){if(!x)throw $}if(!Dt(it.current,l))return!1;if(it.current=null,T.current=null,nt(null),Qn(l.deviceId),J(!1),Le(""),ne(""),De(""),Ce($=>$===l.deviceId?"":$),!S)return Dt(Vn.current,l)&&vr(null),!0;try{await Pi(l)}catch($){we($ instanceof Error?$.message:String($))}return!0},[vr,Qn,Pi,we,Qm]),Xm=($n&&Xe&&Rt&&Pe&&!qn.has(Pe)&&Ze.find(l=>l.deviceId===Pe)||null)?.deviceId||"";o.useEffect(()=>{oi.current=Xm},[Xm]),o.useEffect(()=>{const l=Pe&&Ze.find($=>$.deviceId===Pe)||null;if(!$n||!Xe||!Rt||!l){Mn.current&&(++Kt.current,Mn.current="");return}if(Ye.current[l.deviceId]){Mn.current&&(++Kt.current,Mn.current=""),te===l.deviceId&&le("paused");return}if(hr.current){if(hr.current===l.deviceId)return;hr.current=""}if(te===l.deviceId&&(ae==="active"||ae==="warm"||ae==="connecting")){le($=>$==="warm"?"active":$);return}if(Mn.current===l.deviceId)return;const f=++Kt.current,b=jd(l.deviceId,f,{sessionId:l.sessionId,monitorIndex:Nr});Mn.current=l.deviceId;const x={stoppedWallDeviceId:""},S=()=>f===Kt.current&&oi.current===b.deviceId;br(async()=>{if(!S())return;const $=it.current;if($){le("stopping");try{await wr($,"control-session-switch")}catch(q){S()&&(le("error"),we(q instanceof Error?q.message:String(q)));return}if(!S()){it.current||le("idle");return}}try{if(!await Ym(b,S,x)||!S()){await ol(b,x),it.current||le("idle");return}}catch(q){await ol(b,x),S()&&(le("error"),we(q instanceof Error?q.message:String(q)));return}if(!S()){await ol(b,x);return}it.current=b,ar.current=null,hr.current="",ha.current=null,ci.current=0,bo.current="",x.stoppedWallDeviceId="";const L=Ut("control",b.deviceId),B=`control-session-${f}-${b.deviceId}`;ba.current.set(L,performance.now()),$s.current.delete(L),fa.current.delete(L),vs.current.delete(L),ga.current.delete(L),ne(""),De(""),Le(B),Ce(b.deviceId),J(!1),le("connecting")}).catch($=>{S()&&(le("error"),we($ instanceof Error?$.message:String($)))}).finally(()=>{Kt.current===f&&Mn.current===b.deviceId&&(Mn.current="")})},[Ze,Pe,te,ae,$n,br,Rt,Ym,ol,Nr,we,Xe,wr,je]),o.useEffect(()=>{if(!te||Ze.some(b=>b.deviceId===te))return;const l=te;++Kt.current,Mn.current="";const f=it.current;le("stopping"),br(async()=>{f&&f.deviceId===l?await wr(f,"control-device-disconnected",{allowStopFailure:!0}):(Qn(l),Ce(b=>b===l?"":b)),it.current||le("idle")})},[Ze,te,br,Qn,wr]),o.useEffect(()=>{if(mr.current!==null&&(window.clearTimeout(mr.current),mr.current=null),!Ar||Xe||!te||Ye.current[te]||ae!=="connecting"&&ae!=="active"&&ae!=="warm")return;const l=te,f=it.current;if(!f||f.deviceId!==l)return;const b=window.setTimeout(()=>{mr.current===b&&(mr.current=null);const x=it.current;if(oi.current||Ye.current[l]||!Dt(x,f))return;ar.current=f;const S=++Kt.current;Mn.current="",le("stopping"),br(async()=>{if(S!==Kt.current||oi.current||!Dt(it.current,f)){Dt(ar.current,f)&&(ar.current=null),Dt(it.current,f)&&oi.current===l&&le("active");return}try{await wr(f,"control-session-wall-downshift")}catch($){Dt(ar.current,f)&&(ar.current=null),S===Kt.current&&!oi.current&&Dt(it.current,f)&&(le("active"),we($ instanceof Error?$.message:String($)));return}ar.current=null,S===Kt.current&&!it.current&&le("idle")})},oP);return mr.current=b,()=>{mr.current===b&&(window.clearTimeout(b),mr.current=null)}},[te,ae,br,we,Xe,wr,je,Ar]);const cl=o.useCallback(l=>{if(fm.current===l)return;fm.current=l;const f=it.current,b=f?.deviceId||te,x=++Kt.current;Mn.current="",T.current=null,go.current=!0,nt(null),J(!1),_n(!1),b&&(bn("control",b),Qn(b,{preservePresentation:!1}),le("stopping"),br(async()=>{if(f&&f.deviceId===b)try{await wr(f,"control-session-document-hidden",{resumeWall:!1})}catch(S){!Mr.current&&qr.current===l&&(le("error"),we(S instanceof Error?S.message:String(S)));return}else Qn(b,{preservePresentation:!1}),Ce(S=>S===b?"":S);!it.current&&Kt.current===x&&le("idle")}))},[te,br,Qn,bn,we,wr]);o.useEffect(()=>{if(kr.current!==null&&(window.clearTimeout(kr.current),kr.current=null),!te||ae==="idle"||ae==="paused"||ae==="error")return;if(!$n){cl(qr.current);return}if(ae==="stopping"||vi){te&&Bc&&ae==="connecting"&&(go.current=!1),te&&Bc&&go.current&&(ae==="warm"||ae==="active")&&(go.current=!1,T.current=null,nt(null),J(!1),_n(!1),bn("control",te),Le(`control-presentation-resume-${Date.now()}-${te}`),le("connecting"));return}T.current=null,go.current=!0,nt(null),J(!1),_n(!1),le(f=>f==="idle"||f==="stopping"?f:"warm");const l=te;return Qn(l,{preservePresentation:!1}),kr.current=window.setTimeout(()=>{kr.current=null,++Kt.current,Mn.current="";const f=it.current;le("stopping"),br(async()=>{if(f&&f.deviceId===l)try{await wr(f,"control-session-warm-timeout")}catch(b){le("error"),we(b instanceof Error?b.message:String(b));return}else Qn(l),Ce(b=>b===l?"":b);it.current||le("idle")})},iP),()=>{kr.current!==null&&(window.clearTimeout(kr.current),kr.current=null)}},[vi,Bc,te,ae,$n,br,Qn,cl,bn,we,wr]),o.useEffect(()=>()=>{kr.current!==null&&window.clearTimeout(kr.current),mr.current!==null&&(window.clearTimeout(mr.current),mr.current=null),ar.current=null},[]);const ll=o.useCallback(()=>{const l=new Set(_u.current),f=it.current?.deviceId||"";te&&l.add(te),f&&l.add(f),_u.current=[];for(const x of l){Wr.current.delete(x),un(x),Qn(x,{preservePresentation:!1});for(const S of[Tt.current.get(x),Ln.current.get(x),gn.current.get(x)])S&&Bn(S);Xr(x),bn("wall",x),bn("control",x),il(x)}const b=sr.current;b&&Bn(b),ho.current="",ii.current=null,fo.current=0},[Xr,te,Bn,Qn,il,un,bn]);o.useEffect(()=>{if($n){_u.current=[...Qu];return}ll()},[$n,Qu,ll]),o.useEffect(()=>{const l=Vn.current,f=it.current;if(!Ar||!l||Ye.current[l.deviceId]||f&&f.deviceId===l.deviceId){Cc.current=0;return}const b=Cc.current,x=Math.min(5e3,500*2**Math.min(b,4)),S=window.setTimeout(()=>{ai.current===S&&(ai.current=null);const $=Vn.current;!Nm.current||!$||Ye.current[$.deviceId]||!Dt($,l)||(Cc.current=b+1,Pi($).catch(L=>{we(L instanceof Error?L.message:String(L)),Dt(Vn.current,$)&&!it.current&&ju(B=>B+1)}))},x);return ai.current=S,()=>{window.clearTimeout(S),ai.current===S&&(ai.current=null)}},[ae,Pi,we,Ar,Iu,Es]);const Bs=te&&Ze.find(l=>l.deviceId===te)||null,Ii=!!(Xe&&_e&&ae==="active"&&ce&&Bs?.sessionId&&Ee?.deviceId===Bs.deviceId&&Ee.sessionId===Bs.sessionId&&Ee.streamPurpose==="control"&&Ee.commandId&&Ee.captureGeneration>0&&Ee.monitorIndex===Nr),Jm=Bs?.capabilities?.clipboardProtocol==="livedesk.clipboard.v1",Zm=Jm&&Yi(Bs,"clipboardCopy"),eh=Jm&&Yi(Bs,"clipboardPaste"),{state:To,connectionId:ja,sendInput:th,stats:Jr,error:nh}=x0($n&&Tr&&Ii,G),ji=Bs?.deviceId||"",Ei=Bs?.sessionId||"",Fi=Ee?.commandId||"",Di=Number(Ee?.captureGeneration||0),Po=Number(Ee?.monitorIndex||0),Io=o.useCallback((l,f)=>!Mr.current||!Ii||!ji||!Ei||!Fi||Di<=0||l!==ji?!1:th(l,{...f,monitorIndex:Po,controlSessionId:Ei,controlCommandId:Fi,captureGeneration:Di}),[Ii,Di,Fi,ji,Po,Ei,th]),ul=[ji,Ei,Fi,Di,Po,ja].join("|"),td=o.useRef(ul);td.current=ul;const dl=o.useRef(null),Hn=o.useCallback(async(l,f,b,x,S=15e3)=>{if(!ja||td.current!==x)throw new Error("Remote Control changed before the clipboard transfer completed.");const $=await Oe(`/api/remote/devices/${encodeURIComponent(ji)}/clipboard`,{method:"POST",timeoutMs:S,body:JSON.stringify({action:l,hubConnectionId:ja,operationId:f,binding:{sessionId:Ei,commandId:Fi,captureGeneration:Di,monitorIndex:Po},payload:b})},G);if(td.current!==x)throw new Error("Remote Control changed before the clipboard transfer completed.");if($?.ok===!1)throw new Error($.error||"Remote clipboard transfer failed.");return $},[Di,Fi,ji,Po,Ei,ja,G]),rh=o.useCallback(async(l,f)=>{const b=window.liveDesk?.clipboard;let x=!1,S=!1;try{await Hn("clipboard.prepare",l,{clipboardDirection:"copy"},f),await Hn("clipboard.copy",l,{clipboardDirection:"copy"},f),S=!0;const $=await Hn("clipboard.copy.begin",l,{},f),L=wp($.manifest,l);if(b?.beginWrite&&b.writeChunk&&b.commitWrite){await b.beginWrite(L),x=!0;for(const B of L.items)for(const q of Pd(B.size)){const W=await Hn("clipboard.copy.chunk",l,{itemIndex:B.itemIndex,offset:q.offset,maxBytes:Ql},f),ke=Eg(String(W.dataBase64||""));if(Number(W.itemIndex)!==B.itemIndex||Number(W.offset)!==q.offset||Number(W.bytes)!==q.byteLength||ke.byteLength!==q.byteLength||W.final===!0!==q.final)throw new Error("Remote clipboard chunk did not match the requested file range.");await b.writeChunk({operationId:l,itemIndex:B.itemIndex,offset:q.offset,dataBase64:String(W.dataBase64||""),final:q.final})}await b.commitWrite(l),x=!1}else{if(L.contentKind==="files")throw new Error("Multiple files require the LiveDesk desktop app.");const B=[];for(const q of L.items){const W=new Uint8Array(q.size);for(const ke of Pd(q.size)){const Me=await Hn("clipboard.copy.chunk",l,{itemIndex:q.itemIndex,offset:ke.offset,maxBytes:Ql},f),he=Eg(String(Me.dataBase64||""));if(he.byteLength!==ke.byteLength)throw new Error("Remote clipboard chunk was incomplete.");W.set(he,ke.offset)}if(await kw(W)!==q.sha256)throw new Error("Remote clipboard content check failed.");B.push(W)}await QT({manifest:L,payloads:B})}await Hn("clipboard.copy.end",l,{},f),S=!1,we(L.contentKind==="files"?`${L.items.length} remote file${L.items.length===1?"":"s"} copied.`:L.contentKind==="image"?"Remote image copied.":"Remote text copied.","success")}catch($){throw x&&await b?.cancelWrite?.(l).catch(()=>{}),S&&await Hn("clipboard.copy.end",l,{},f).catch(()=>{}),$}},[Hn,we]),sh=o.useCallback(async(l,f)=>{const b=window.liveDesk?.clipboard;let x=null,S,$=!1;try{b?.readSnapshot&&b.readChunk?S=wp(await b.readSnapshot(l),l):(x=await KT(l),S=x.manifest),await Hn("clipboard.prepare",l,{clipboardDirection:"paste",manifest:S},f),$=!0,await Hn("clipboard.paste.begin",l,{manifest:S},f);for(const q of S.items)for(const W of Pd(q.size)){const ke=b?.readChunk?await b.readChunk({operationId:l,itemIndex:q.itemIndex,offset:W.offset,maxBytes:W.byteLength||Ql}):{operationId:l,itemIndex:q.itemIndex,offset:W.offset,byteLength:W.byteLength,dataBase64:GT(x.payloads[q.itemIndex].subarray(W.offset,W.offset+W.byteLength)),final:W.final};if(ke.offset!==W.offset||ke.byteLength!==W.byteLength||ke.final!==W.final)throw new Error("Local clipboard changed during transfer.");const Me=await Hn("clipboard.paste.chunk",l,{itemIndex:q.itemIndex,offset:W.offset,dataBase64:ke.dataBase64,final:W.final},f);if(Number(Me.itemIndex)!==q.itemIndex||Number(Me.offset)!==W.offset||Number(Me.bytes)!==W.byteLength||Me.final===!0!==W.final)throw new Error("Remote clipboard did not confirm the requested file range.")}await Hn("clipboard.paste",l,{clipboardDirection:"paste"},f);const L=Date.now()+qT;let B=!1;for(;Date.now()<L;){const q=await Hn("clipboard.operation.status",l,{},f,Math.max(250,L-Date.now())),W=String(q.status||"").toLowerCase();if(["completed","complete","applied","pasted"].includes(W)){B=!0;break}if(["failed","cancelled","expired"].includes(W))throw new Error(`Remote clipboard paste ${W}.`);await new Promise(ke=>window.setTimeout(ke,zT))}if(!B)throw new Error("Remote clipboard paste confirmation timed out.");$=!1,we(S.contentKind==="files"?`${S.items.length} file${S.items.length===1?"":"s"} pasted on the remote computer.`:S.contentKind==="image"?"Image pasted on the remote computer.":"Text pasted on the remote computer.","success")}catch(L){throw $&&await Hn("clipboard.paste.cancel",l,{},f).catch(()=>{}),L}finally{await b?.releaseRead?.(l).catch(()=>{})}},[Hn,we]),ah=o.useCallback(async l=>{if(!Ii||To!=="open"||!ja){we("Remote input is not ready for clipboard transfer.","error");return}if(dl.current){we("Another clipboard transfer is still running.");return}const f=P0(l),b=ul;dl.current={operationId:f,direction:l,bindingKey:b};try{Ot(l==="copy"?"Copying from the remote computer…":"Pasting on the remote computer…"),l==="copy"?await rh(f,b):await sh(f,b)}catch(x){we(x instanceof Error?x.message:String(x),"error")}finally{dl.current?.operationId===f&&(dl.current=null)}},[ul,Ii,rh,ja,To,sh,we,Ot]),Zr=$n&&Mr.current&&Ii&&To==="open"&&!!ja,nd={shiftKey:mt.includes("ShiftLeft"),ctrlKey:mt.includes("ControlLeft"),altKey:mt.includes("AltLeft"),metaKey:mt.includes("MetaLeft")},Pr=o.useCallback(l=>gt.current.enqueueStop(l),[]),Ea=o.useCallback(l=>gt.current.enqueueStart(l),[]),Rn=o.useCallback((l,f=Ke.current)=>(rt.current=l,Ke.current=l?String(f||""):"",Ge.current+=1,Ge.current),[]),Ir=o.useCallback((l,f,b)=>lk({generation:l,currentGeneration:Ge.current,enabled:rt.current,deviceId:f,currentDeviceId:Ke.current,documentVisible:Mr.current,presentationVisible:_.current,streamId:b,currentStreamId:xe.current.get(f)||""}),[]),yr=o.useCallback(async(l,f,b)=>{if(!f)return{ok:!0,alreadyStopped:!0,captureStopConfirmed:!0,noExactOwner:!0};const S=await(L=>Oe(`/api/remote/devices/${encodeURIComponent(l)}/audio/stop`,{method:"POST",body:JSON.stringify({...L?{streamId:L}:{},reason:b})},G))(f),$=uk(S);if($.staleOwner)return S;if(!$.confirmed)throw new Error(S?.error||"Remote audio capture stop was not confirmed.");return S},[G]),rd=o.useCallback(async(l,f)=>{const b=await Oe(`/api/remote/devices/${encodeURIComponent(l)}/audio/stop`,{method:"POST",body:JSON.stringify({reason:f})},G);if(b?.ok===!1||b?.captureStopConfirmed!==!0&&b?.alreadyStopped!==!0)throw new Error(b?.error||"Remote audio stop-all was not confirmed.");return b},[G]),cy=o.useCallback(l=>{const f=Ge.current,b=xe.current.get(l)||"";return Pr(()=>yr(l,b,"remote-audio-automatic-restart")).then(()=>Ea(async()=>{if(f!==Ge.current||!rt.current||Ke.current!==l||!Mr.current||!_.current||!Rt||!Rr||(Be.current||fe?.deviceId||"")!==l)return"";const x=`audio-restart-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;if(xe.current.set(l,x),!Ir(f,l,x))return xe.current.delete(l),"";const S=await Oe(`/api/remote/devices/${encodeURIComponent(l)}/audio/start`,{method:"POST",body:JSON.stringify({streamId:x,mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},G);if(S?.ok===!1)throw xe.current.get(l)===x&&xe.current.delete(l),new Error(S.error||"Remote audio restart failed.");return Ir(f,l,x)?x:(await yr(l,x,"remote-audio-stale-restart-compensation"),xe.current.get(l)===x&&xe.current.delete(l),"")}))},[Ea,Pr,Rt,G,Ir,Rr,fe?.deviceId,yr]),ih=fe?.deviceId&&xe.current.get(fe.deviceId)||"",ly=o.useCallback(async(l,f,b)=>{Rn(!1),He(!1),await Pr(()=>yr(l,f,b)),xe.current.get(l)===f&&xe.current.delete(l)},[Pr,Rn,yr]),{state:sd,lastFrame:ad,stats:Ft,error:id}=k0(fe?.deviceId||"",$n&&Ku&&Ie,G,di,nn||qt||kc.current,ih,cy,ly),jo=o.useRef(new Map);o.useEffect(()=>{const l=[["hub",O],["registry",i],["license",Q],["wall-stream",qm],["control-stream",Ao],["control-decode",ve],["remote-input",nh],["remote-audio",id]];for(const[f,b]of l){const x=String(b||"").trim(),S=it.current;if(f==="wall-stream"&&x==="CONTROL_CAPTURE_OWNS_DEVICE"&&!!S&&Ls.current===S.deviceId){jo.current.delete(f);continue}if(f==="hub"&&vt?.requiresHubRestart&&vt.stage==="updating"){jo.current.delete(f);continue}if(!x){jo.current.delete(f);continue}jo.current.get(f)!==x&&(jo.current.set(f,x),we(x))}},[id,ve,Ao,O,nh,Q,i,we,qm,vt]);const pl=fe?.deviceId||"",oh=fe?cr(fe,Ct[pl]):0;o.useEffect(()=>{if(!_e||!Tr||!Zr||!pl)return;const l=q0(),f=pl,b=oh,x=he=>{if(!he)return!1;const tt=Io(f,{...he,monitorIndex:b});return!tt&&he.type!=="keyboard.reset"&&(l.reset("browser-input-send-rejected"),ct([])),tt},S=(he,tt)=>{const yt=he.target,at=yt?.tagName?.toLowerCase(),wt=yt?.isContentEditable||at==="input"||at==="textarea"||at==="select",Et=l.isPressed(he);if(wt&&(tt==="keydown"||!Et))return;const Yn=tt==="keydown"?T0(he,VT()):"";if(Yn&&(Yn==="copy"?Zm:Yn==="paste"?eh:!1)){he.preventDefault(),he.stopPropagation();const Hi=l.reset("remote-clipboard-shortcut",!0);Hi&&x(Hi),ct([]),ah(Yn);return}const Hs=l.event(he,tt);Hs&&(he.preventDefault(),he.stopPropagation(),x(Hs))},$=he=>S(he,"keydown"),L=he=>S(he,"keyup"),B=(he,tt=!1)=>{const yt=l.reset(he,tt);yt&&(x(yt),ct([]))};z.current=he=>{const tt=l.snapshot().latchedCodes.includes(he),yt=l.modifier(he,!tt);yt&&(x(yt),ct(at=>tt?at.filter(wt=>wt!==he):[...at.filter(wt=>wt!==he),he]))};const q=he=>{const tt=Rl(he);if(!tt)return!1;const yt=l.snapshot(),at={...tt,shiftKey:yt.shiftKey,ctrlKey:yt.ctrlKey,altKey:yt.altKey,metaKey:yt.metaKey},wt=l.event(at,"keydown");if(!wt||!x(wt))return!1;const Et=l.event(at,"keyup");return!!Et&&x(Et)};pe.current={sendKey:q,sendText:he=>{let tt=!1;const yt=String(he??"").split(/(\r\n|\r|\n)/);for(const at of yt)if(at){if(at==="\r"||at===`
175
+ ${He}`:He;try{if(F==="custom"){const Ge=await JR(e,H,V);if(!Ge.ok)throw new Error(Ge.error||"Custom Agent policy could not be saved.")}const xe=await VR(e,{instruction:Be,deviceIds:se,permissionMode:F,customPolicyId:H});if(!xe.ok||!xe.runId)throw new Error(xe.error||"Codex Agent run could not be started.");O(xe.approvals||[]),Pe({runId:xe.runId,stage:xe.stage||xe.status||"queued",message:xe.progressMessage||"Codex request queued on the Hub."}),A(xe.runId)}catch(xe){y(Ge=>[...Ge,{type:"error",id:Vo("codex-run-error"),text:iT(xe)}])}},ue=async(Y,K)=>{G(Y.approvalId);try{const ee=await YR(e,Y.runId,Y.approvalId,K);if(!ee.ok)throw new Error(ee.error||"Agent approval could not be applied.");await J(Y.runId)}catch(ee){oe(ee instanceof Error?ee.message:String(ee))}finally{G("")}},Ee=async Y=>{G(Y.approvalId);try{const K=await XR(e,Y.runId,Y.approvalId);if(!K.ok)throw new Error(K.error||"Agent approval could not be rejected.");await J(Y.runId)}catch(K){oe(K instanceof Error?K.message:String(K))}finally{G("")}},nt=async(Y,K)=>{I(Y);try{if(K){const R=await KR(e,K);for(const se of R.taskBatches||[])ae(se);A(se=>se===K?"":se),Pe(se=>se?.runId===K?null:se);return}const ee=await eT(e,Y);ae(ee),N(R=>R===Y?"":R)}catch(ee){oe(ee instanceof Error?ee.message:String(ee))}finally{I("")}},T=async()=>{if(!(U||!k&&!C)){ie(!0);try{const Y=await QR(e);if(!Y.ok)throw new Error(Y.error||"모든 Agent 작업을 취소하지 못했습니다.");N(""),A(""),Pe(null),O([]),y(K=>K.map(ee=>ee.type==="task"&&["queued","running"].includes(ee.status)?{...ee,status:"cancelled",states:ee.states.map(R=>["queued","running"].includes(R.status)?{...R,status:"cancelled",stage:"Cancelled",error:"Cancelled by user."}:R)}:ee))}catch(Y){oe(Y instanceof Error?Y.message:String(Y))}finally{ie(!1)}}},ve=async Y=>{I(Y);try{const K=await tT(e,Y);if(!K.ok||!K.batch||!K.batchId)throw new Error(K.error||"재시도하지 못했습니다.");y(ee=>ee.map(R=>R.type==="task"&&R.batchId===Y?{...R,batchId:K.batchId,states:Vd(K.batch,t),status:K.batch.status}:R)),N(K.batchId)}catch(K){oe(K instanceof Error?K.message:String(K))}finally{I("")}},De=Y=>{w(Y),Ae(!1),window.requestAnimationFrame(()=>Se.current?.focus())},qe=o.useMemo(()=>t.filter(mu),[t]),_e=o.useMemo(()=>qe.filter(Y=>d.includes(Y.deviceId)),[qe,d]),$e=c==="auto"?`Auto · ${qe.length} available`:c==="all"?`All ${qe.length} computers`:_e.length===1?pu(_e[0]):`${_e.length} selected`,mt=c==="auto"?"LiveDesk chooses the best computer for each task.":c==="all"?"The Agent may coordinate every connected computer.":_e.length>0?_e.map(pu).join(" · "):"Select one or more computers on the Wall.",ct=c==="selected"&&_e.length===1?["Diagnose this computer","Analyze recent errors","Summarize running applications","Check disk and GPU capacity"]:c==="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"],z=c==="selected"?_e.length>0?"What should this computer do?":"Choose a computer or use Auto.":c==="all"?"Use all your computers together.":"What should LiveDesk handle?",pe=c==="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 r.jsxs("section",{className:`agents-page ${i?"agents-dock-console":""}`,children:[i&&r.jsxs("header",{className:"agent-console-header",children:[r.jsxs("div",{className:"agent-console-title",children:[r.jsx("span",{className:"agent-console-mark",children:r.jsx(Zs,{size:16})}),r.jsxs("div",{children:[r.jsx("small",{children:"Hub Codex Agent"}),r.jsx("strong",{children:"Command Console"})]}),r.jsx("i",{children:"Ready"})]}),r.jsxs("section",{className:"agent-console-target","aria-label":"Agent target scope",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Target"}),r.jsx("strong",{children:$e}),r.jsx("small",{children:mt})]}),r.jsxs("div",{className:"agent-console-target-modes",children:[r.jsxs("button",{className:c==="selected"?"active":"",onClick:()=>u("selected"),type:"button",children:[r.jsx(Rs,{size:12})," Selected"]}),r.jsxs("button",{className:c==="all"?"active":"",onClick:()=>u("all"),type:"button",children:[r.jsx(oc,{size:12})," All"]}),r.jsxs("button",{type:"button",disabled:!0,title:"Saved Client groups are coming next.",children:[r.jsx(oc,{size:12})," Group"]}),r.jsxs("button",{className:c==="auto"?"active":"",onClick:()=>u("auto"),type:"button",children:[r.jsx(Zs,{size:12})," Auto"]})]})]}),r.jsx("div",{className:"agent-console-interaction-modes","aria-label":"Agent interaction mode",children:["auto","ask","plan","execute"].map(Y=>r.jsxs("button",{className:h===Y?"active":"",onClick:()=>m(Y),type:"button",children:[Y==="auto"?r.jsx(Zs,{size:12}):Y==="execute"?r.jsx(pn,{size:12}):null,Y[0].toUpperCase()+Y.slice(1)]},Y))})]}),r.jsxs("div",{className:"agents-workspace",children:[(k||C)&&r.jsxs("div",{className:"agents-page-status",children:[r.jsxs("span",{children:[Ue.length," Clients · ",sT(F)]}),r.jsx("button",{type:"button",className:"agents-stop-all",onClick:()=>{T()},disabled:U,children:U?"Stopping…":"Stop all"})]}),j&&r.jsx("div",{className:"agents-permission-modal-backdrop",role:"presentation",children:r.jsxs("section",{className:"agents-permission-modal",role:"dialog","aria-modal":"true","aria-labelledby":"full-access-title",children:[r.jsx("span",{className:"agents-permission-modal-icon",children:r.jsx(vu,{size:20})}),r.jsx("h3",{id:"full-access-title",children:"Confirm Full Access"}),r.jsx("p",{children:"Codex may change files, run commands, manage applications, and modify system state on the selected Clients. This run is still limited to the selected devices, the fixed policy, and the tool budget."}),r.jsxs("div",{className:"agents-permission-modal-actions",children:[r.jsx("button",{type:"button",onClick:()=>re(null),children:"Cancel"}),r.jsx("button",{type:"button",className:"danger",onClick:()=>{const Y=j;re(null),Q(!0),ye(Y.instruction,Y.targetIds,!0)},children:"Run with Full Access"})]})]})}),ge&&r.jsx("div",{className:"agents-error",role:"alert",children:ge}),r.jsx(MR,{items:v,onCancel:nt,onRetry:ve,busyBatchId:E,approvals:D,onApprove:ue,onReject:Ee,busyApprovalId:X,progress:Te,emptyTitle:i?z:void 0,emptyBody:i?pe:void 0}),i&&v.length===0&&!Te&&r.jsx("div",{className:"agent-console-suggestions","aria-label":"Suggested Agent commands",children:ct.map(Y=>r.jsx("button",{type:"button",onClick:()=>De(Y),children:Y},Y))}),r.jsxs("div",{className:"agents-composer-shell",children:[me&&r.jsx(HR,{devices:t,targetMode:c,selectedIds:d,permissionMode:F,customCategories:V,onSelectPrompt:De,onClose:()=>Ae(!1)}),r.jsx(hR,{ref:Se,value:g,onChange:w,onSubmit:()=>{ye()},onOpenSuggestedTasks:()=>Ae(Y=>!Y),suggestedOpen:me,suggestedTaskCount:ne,disabled:!!k||!!C,placeholder:i?"Tell LiveDesk what outcome you want...":void 0,compact:i})]})]}),!i&&r.jsxs("aside",{className:"agents-target-sidebar","aria-label":"Agent targets and permissions",children:[r.jsx(WR,{devices:t,mode:c,selectedIds:d,onModeChange:u,onToggle:Y=>p(K=>K.includes(Y)?K.filter(ee=>ee!==Y):[...K,Y]),permissionMode:F,onPermissionModeChange:Y=>{M(Y),Y!=="full-access"&&Q(!1)}}),F==="custom"&&r.jsxs("section",{className:"agents-custom-policy","aria-label":"Custom Agent permissions",children:[r.jsxs("div",{className:"agents-custom-policy-head",children:[r.jsxs("div",{children:[r.jsx("span",{className:"agents-section-label",children:"Custom policy"}),r.jsx("strong",{children:"Choose what Codex may do automatically."})]}),r.jsx("span",{children:"Denied actions never reach a device."})]}),r.jsx("div",{className:"agents-custom-policy-grid",children:fR.map(Y=>r.jsxs("label",{children:[r.jsx("span",{children:aT(Y)}),r.jsxs("select",{value:V[Y],onChange:K=>P(ee=>({...ee,[Y]:K.target.value})),children:[r.jsx("option",{value:"allow",children:"Allow automatically"}),r.jsx("option",{value:"ask",children:"Ask every time"}),r.jsx("option",{value:"deny",children:"Deny"})]})]},Y))})]})]})]})}function aw(e){return{type:e.type,deviceIds:e.deviceIds,monitorIndex:e.monitorIndex,label:e.label}}async function iw(e){try{return(await e.json()).error||`${e.status} ${e.statusText}`}catch{return`${e.status} ${e.statusText}`}}async function ow(e,t,n){const s=encodeURIComponent(JSON.stringify({kind:t.kind,fileName:t.fileName,mimeType:e.type||"application/octet-stream",durationMs:t.durationMs,target:aw(t.target)})),a=await pb(`/api/captures?metadata=${s}`,{method:"POST",headers:{"Content-Type":e.type||"application/octet-stream"},body:e},n);if(!a.ok)throw new Error(await iw(a));return await a.json()}async function oT(e,t){return await Oe("/api/capture-sessions",{method:"POST",body:JSON.stringify({...e,target:aw(e.target)})},t)}async function cT(e,t,n,s){const a=await pb(`/api/capture-sessions/${encodeURIComponent(e)}/chunks/${t}`,{method:"PUT",headers:{"Content-Type":n.type||"application/octet-stream"},body:n},s);if(!a.ok)throw new Error(await iw(a));return await a.json()}async function lT(e,t,n){return await Oe(`/api/capture-sessions/${encodeURIComponent(e)}/finalize`,{method:"POST",body:JSON.stringify({durationMs:t})},n)}async function Ag(e,t){await Oe(`/api/capture-sessions/${encodeURIComponent(e)}`,{method:"DELETE"},t)}async function uT(e){return await Oe("/api/captures",void 0,e)}function Ng(e,t){return`${ub(t)}/api/captures/${encodeURIComponent(e)}/content`}async function dT(e,t){return await Oe(`/api/captures/${encodeURIComponent(e)}`,{method:"DELETE"},t)}function pT({hubUrl:e,onToast:t}){const[n,s]=o.useState([]),[a,i]=o.useState(!0),c=o.useCallback(async()=>{i(!0);try{s((await uT(e)).captures||[])}catch(d){t(d instanceof Error?d.message:String(d))}finally{i(!1)}},[e,t]);o.useEffect(()=>{c()},[c]);const u=async d=>{const p=Ng(d.id,e);if(navigator.share)try{await navigator.share({title:d.fileName,url:p});return}catch{}window.open(p,"_blank","noopener,noreferrer")};return r.jsxs("section",{className:"capture-gallery",children:[r.jsxs("header",{children:[r.jsxs("div",{children:[r.jsx("span",{className:"settings-eyebrow",children:"Capture Gallery"}),r.jsx("h2",{children:"Saved captures"})]}),r.jsxs("button",{className:"text-button",onClick:()=>{c()},type:"button",children:[r.jsx(Xa,{size:15})," Refresh"]})]}),a?r.jsx("p",{className:"settings-help",children:"Loading captures..."}):n.length===0?r.jsx("p",{className:"settings-help",children:"No captures saved yet."}):r.jsx("div",{className:"capture-gallery-grid",children:n.map(d=>{const p=Ng(d.id,e);return r.jsxs("article",{className:"capture-gallery-card",children:[d.mimeType.startsWith("image/")?r.jsx("img",{src:p,alt:d.target.label}):r.jsx("video",{src:p,controls:!0,preload:"metadata"}),r.jsxs("div",{className:"capture-gallery-card-body",children:[r.jsx("strong",{children:d.fileName}),r.jsxs("small",{children:[d.target.label," · ",new Date(d.createdAt).toLocaleString()," · ",Math.ceil(d.sizeBytes/1024)," KB"]}),r.jsxs("div",{children:[r.jsx("button",{className:"icon-button",title:"Open","aria-label":"Open",onClick:()=>window.open(p,"_blank","noopener,noreferrer"),type:"button",children:r.jsx(dx,{size:15})}),r.jsx("a",{className:"icon-button",title:"Download","aria-label":"Download",href:`${p}?download=1`,download:d.fileName,children:r.jsx(ic,{size:15})}),r.jsx("button",{className:"icon-button",title:"Share","aria-label":"Share",onClick:()=>{u(d)},type:"button",children:r.jsx(kb,{size:15})}),r.jsx("button",{className:"icon-button danger",title:"Delete","aria-label":"Delete",onClick:()=>{window.confirm(`Delete ${d.fileName}?`)&&dT(d.id,e).then(()=>c()).catch(h=>t(h instanceof Error?h.message:String(h)))},type:"button",children:r.jsx(yb,{size:15})})]})]})]},d.id)})})]})}function Ol(e){if(!e)return"";const t=Math.max(0,Math.floor((Date.now()-e)/1e3)),n=Math.floor(t/3600),s=Math.floor(t%3600/60),a=t%60;return n>0?`${String(n).padStart(2,"0")}:${String(s).padStart(2,"0")}:${String(a).padStart(2,"0")}`:`${String(s).padStart(2,"0")}:${String(a).padStart(2,"0")}`}function Rg({controller:e,compact:t=!1,onFirstRollingUse:n,onError:s}){const{state:a,settings:i,videoSupported:c}=e,u=async m=>{try{await m()}catch(g){s?.(g instanceof Error?g.message:String(g))}},d=async()=>{if(i.rollingEnabled){e.setRollingEnabled(!1);return}(n?await n():window.confirm(`Keep the most recent 30 seconds in memory temporarily?
176
+ Nothing is saved until you press Save Last 30s.`))&&e.setRollingEnabled(!0)},p=a.recording?`Stop recording · ${Ol(a.recordingStartedAt)}`:`Start recording · ${a.targetLabel}`,h=a.timelapse?`Stop timelapse · ${Ol(a.timelapseStartedAt)}`:`Start timelapse · ${i.timelapseIntervalSeconds}s interval`;return r.jsxs("div",{className:`capture-toolbar ${t?"compact":""} ${a.recording?"recording-active":""}`,"aria-label":"Capture actions",children:[r.jsx("button",{className:"capture-action","aria-label":`Take screenshot · ${a.targetLabel}`,title:`Take screenshot · ${a.targetLabel}`,disabled:a.busy,onClick:()=>{u(e.takeScreenshot)},type:"button",children:r.jsx(px,{size:17})}),r.jsx("button",{className:`capture-action ${a.recording?"active":""}`,"aria-label":p,title:p,disabled:!c||a.busy||a.timelapse,onClick:()=>{u(a.recording?e.stopRecording:e.startRecording)},type:"button",children:a.recording?r.jsxs(r.Fragment,{children:[r.jsx(Bh,{size:14,fill:"currentColor"}),r.jsx("span",{children:Ol(a.recordingStartedAt)})]}):r.jsx(xb,{size:18})}),r.jsxs("button",{className:"capture-action","aria-label":a.bufferEnabled?`Save last 30 seconds · ${a.bufferSeconds}s ready`:"Enable Last 30s memory buffer",title:a.bufferEnabled?`Save last 30 seconds · ${a.bufferSeconds}s ready`:"Enable Last 30s memory buffer",disabled:!c||a.recording||a.timelapse||a.busy||a.bufferEnabled&&a.bufferSeconds<1,onClick:()=>a.bufferEnabled?void u(e.saveLast30Seconds):void d(),type:"button",children:[r.jsx(mx,{size:17}),r.jsx("small",{children:"30s"})]}),r.jsx("button",{className:`capture-action ${a.timelapse?"timelapse-active":""}`,"aria-label":h,title:h,disabled:!c||a.busy||a.recording,onClick:()=>{u(a.timelapse?e.stopTimelapse:e.startTimelapse)},type:"button",children:a.timelapse?r.jsxs(r.Fragment,{children:[r.jsx(Bh,{size:14,fill:"currentColor"}),r.jsx("span",{children:Ol(a.timelapseStartedAt)})]}):r.jsx(hx,{size:17})})]})}function cw({state:e}){return e==="ok"?r.jsx(En,{size:15,"aria-hidden":"true"}):r.jsx(Cb,{size:15,"aria-hidden":"true"})}function Tg({active:e,refreshing:t,onClick:n}){return r.jsx("button",{className:`remote-status-button ${e?"active":""}`,type:"button",title:"Check Remote Status","aria-label":"Check Remote Status","aria-pressed":e,"aria-busy":t,onClick:n,children:t?r.jsx("span",{className:"remote-status-spinner","aria-hidden":"true"}):r.jsx(fx,{size:18,"aria-hidden":"true"})})}function Pg({active:e,refreshing:t,onClick:n}){return r.jsx("button",{className:`remote-status-button debug-status-button ${e?"active":""}`,type:"button",title:"Check Debug Status","aria-label":"Check Debug Status","aria-pressed":e,"aria-busy":t,onClick:n,children:t?r.jsx("span",{className:"remote-status-spinner","aria-hidden":"true"}):r.jsx(hb,{size:18,"aria-hidden":"true"})})}function Ig({active:e,refreshing:t,onClick:n}){return r.jsx("button",{className:`remote-status-button hub-status-button ${e?"active":""}`,type:"button",title:"Check Hub Status","aria-label":"Check Hub Status","aria-pressed":e,"aria-busy":t,onClick:n,children:t?r.jsx("span",{className:"remote-status-spinner","aria-hidden":"true"}):r.jsx(ls,{size:18,"aria-hidden":"true"})})}function lw({items:e,mode:t="remote"}){return r.jsx("span",{className:`remote-status-lines mode-${t}`,role:"status","aria-label":t==="debug"?"Debug status":"Remote status",onPointerDown:t==="debug"?n=>n.stopPropagation():void 0,onClick:t==="debug"?n=>n.stopPropagation():void 0,onDoubleClick:t==="debug"?n=>n.stopPropagation():void 0,children:e.map(n=>r.jsxs("span",{className:`remote-status-line state-${n.state}`,title:n.detail,children:[r.jsx(cw,{state:n.state}),r.jsxs("span",{children:[r.jsx("strong",{children:n.label}),r.jsx("small",{children:n.detail})]})]},n.id))})}function mT({items:e,collectedAt:t,onClose:n}){return r.jsxs("section",{className:"remote-status-dialog hub-status-dialog",role:"dialog","aria-modal":"false","aria-labelledby":"hub-status-dialog-title",children:[r.jsxs("header",{children:[r.jsx("span",{className:"remote-status-dialog-mark","aria-hidden":"true",children:r.jsx(ls,{size:19})}),r.jsxs("span",{children:[r.jsx("small",{children:"Hub measurements"}),r.jsx("h2",{id:"hub-status-dialog-title",children:"Hub Status"})]}),r.jsx("button",{type:"button",onClick:n,title:"Close Hub status","aria-label":"Close Hub status",children:r.jsx(xn,{size:17})})]}),r.jsx("p",{children:"LiveDesk collects these Hub and browser signals continuously. This check refreshed the latest snapshot instead of starting a one-time benchmark."}),r.jsx("div",{className:"remote-status-dialog-list",children:e.map(s=>r.jsxs("article",{className:`remote-status-dialog-row state-${s.state}`,children:[r.jsx(cw,{state:s.state}),r.jsxs("span",{children:[r.jsx("strong",{children:s.label}),r.jsx("small",{children:s.detail})]})]},s.id))}),r.jsxs("footer",{children:["Checked ",new Date(t).toLocaleTimeString()]})]})}const hT=/(nvenc|videotoolbox|qsv|quick\s*sync|amf|vaapi|v4l2m2m|mediafoundation|h264_mf)/i,fT=/(libx264|openh264|software|cpu)/i,Ep=2,gT=256,Oa=new Map,ut=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 kt(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function um(e,t){let n=e;for(const s of String(t).split(".")){if(!n||typeof n!="object")return;n=n[s]}return n}function Je(e,...t){for(const n of t){const s=um(e,n);if(s==null||s==="")continue;const a=Number(s);if(Number.isFinite(a))return a}}function ft(e,...t){for(const n of t){const s=um(e,n);if(typeof s=="string"&&s.trim())return s.trim()}return""}function uw(e,...t){for(const n of t){const s=um(e,n);if(typeof s=="boolean")return s;if(s===1||s==="1"||String(s).toLowerCase()==="true")return!0;if(s===0||s==="0"||String(s).toLowerCase()==="false")return!1}}function Dr(e,...t){const n=Je(e,...t);if(n!==void 0)return Math.max(0,Math.min(1,n>1?n/100:n))}function Re(e,t,n,s){return{id:e,state:t,label:n,detail:s}}function dw(e){const t=kt(e),n=Je(t,"helperCount"),s=Je(t,"helperOwnedIoTaskCount"),a=Je(t,"helperUndisposedProcessCount"),i=Je(t,"helperOwnedExitObserverCount"),c=Je(t,"helperQuarantineCount"),u=Je(t,"utilityQuarantineCount"),d=Je(t,"utilityOwnedIoTaskCount"),p=Je(t,"utilityUndisposedProcessCount"),h=Number(Je(t,"helperDisposeFailureCount")||0),m=Number(Je(t,"utilityDisposeFailureCount")||0),g=Math.max(0,Number(n||0)),w=Number(s||0),v=Number(a||0),y=Number(i||0),k=Math.max(0,Number(c||0)),N=Math.max(0,Number(u||0)),C=Number(d||0),A=Number(p||0),E=[s,a,i,c,u,d,p].every(M=>M!==void 0),I=E&&(w<0||v<0||y<0||v!==g||y!==0||g===0&&w!==0||g>0&&w===0),F=E&&(C<0||A<0||A!==N||C!==N*2);return{telemetryAvailable:E,helperOwnedIoTaskCount:w,helperUndisposedProcessCount:v,helperOwnedExitObserverCount:y,helperQuarantineCount:k,helperDisposeFailureCount:h,helperLastDisposeFailure:ft(t,"helperLastDisposeFailure"),helperLedgerMismatch:I,utilityQuarantineCount:N,utilityOwnedIoTaskCount:C,utilityUndisposedProcessCount:A,utilityQuarantinePids:Array.isArray(t.utilityQuarantinePids)?t.utilityQuarantinePids.map(M=>Number(M)).filter(M=>Number.isSafeInteger(M)&&M>0):[],utilityQuarantineProfiles:Array.isArray(t.utilityQuarantineProfiles)?t.utilityQuarantineProfiles.map(M=>String(M||"").trim()).filter(Boolean).slice(0,4):[],utilityQuarantineStartCount:Math.max(0,Number(Je(t,"utilityQuarantineStartCount")||0)),utilityQuarantineStopCount:Math.max(0,Number(Je(t,"utilityQuarantineStopCount")||0)),utilityDisposeFailureCount:m,utilityLastDisposeFailure:ft(t,"utilityLastDisposeFailure"),utilityLedgerMismatch:F,historicalCleanupFailure:h!==0||m!==0,currentProblem:k>0||N>0||I||F}}function pw({key:e,sampleId:t,mismatch:n}){if(!e)return{count:0,confirmed:!1};if(!n)return Oa.delete(e),{count:0,confirmed:!1};const s=String(t||"").trim();if(!s)return{count:0,confirmed:!1};const a=sc(s),i=Oa.get(e);if(i?.sampleId===s)return{count:i.count,confirmed:i.count>=Ep};const c=i&&a!==void 0&&i.sampleEpochMs!==void 0&&a>i.sampleEpochMs,u=i&&c?i.count+1:1;return!Oa.has(e)&&Oa.size>=gT&&Oa.delete(Oa.keys().next().value),Oa.set(e,{sampleId:s,sampleEpochMs:a,count:u}),{count:u,confirmed:u>=Ep}}function sc(e){const t=Date.parse(String(e||""));return Number.isFinite(t)&&t>0?t:void 0}function jg(e){return`${(Math.max(0,Number(e||0))/1024**3).toFixed(1)} GB`}function Vs(e){const t=Number(e);return Number.isFinite(t)?`${(Math.max(0,t)/1024**2).toFixed(0)} MB`:"-"}function Gs(e){const t=Number(e);return Number.isFinite(t)?`${(Math.max(0,t)*100).toFixed(1)}%`:"-"}function Bl(e){const t=Number(e);return Number.isFinite(t)?`${Math.max(0,t).toFixed(1)}%`:"-"}function bT(e){const t=String(e||"").replace(/^::ffff:/,"").trim().toLowerCase();if(!t||t==="::1"||t==="localhost"||t==="127.0.0.1"||/^10\./.test(t)||/^192\.168\./.test(t))return!0;const n=t.match(/^172\.(\d{1,3})\./);return!!n&&Number(n[1])>=16&&Number(n[1])<=31||t.startsWith("fe80:")||t.startsWith("fc")||t.startsWith("fd")}function mw(e){const t=kt(e),n=ft(t,"controlTransport").toLowerCase();return n==="encrypted-rendezvous-relay"||/relay/.test(n)?"encrypted-rendezvous-relay":n==="direct-tcp"||/direct|tcp/.test(n)?"direct-tcp":""}function Eg(e){const t=String(e||"").trim();if(!t)return"";try{return new URL(t.includes("://")?t:`relay://${t}`).host}catch{return t.replace(/[?#].*$/,"").replace(/^[a-z][a-z0-9+.-]*:\/\//i,"").split("@").pop().split("/")[0].slice(0,256)}}function vT(e){const t=mw(e);return t==="encrypted-rendezvous-relay"?Re("control-transport","ok","Control connection: Encrypted rendezvous relay","Commands and remote input use the end-to-end encrypted rendezvous relay."):t==="direct-tcp"?Re("control-transport","ok","Control connection: Direct TCP","Commands and remote input use the direct Hub connection."):Re("control-transport","warning","Control connection is not identified","Waiting for Direct TCP or encrypted rendezvous relay status.")}function wT(e,t){const n=kt(e),s=kt(t),a=mw(n);if(a==="encrypted-rendezvous-relay"){const i=ft(s,"state")||(s.connected===!0?"registered":"unknown"),c=Eg(ft(s,"endpoint"))||Eg(ft(n,"relayEndpoint")),u=n.connected!==!0||s.connected===!1||/(connecting|reconnect|failed|error|degraded|unavailable|disabled)/.test(i);return Re("debug-control-transport",u?"warning":"ok",`Encrypted rendezvous relay control · ${i}`,[`endpoint ${c||"-"}`,`state ${i}`,`reconnect ${Math.max(0,Number(s.reconnectCount||0))}`,`handshake ${Math.max(0,Number(s.handshakeCount||0))}`,`peers ${Math.max(0,Number(s.peerCount||0))}`,ft(s,"lastError")].filter(Boolean).join(" · "))}if(a==="direct-tcp"){const i=ft(n,"remoteAddress"),c=Je(n,"remotePort"),u=i?`${i}${c?`:${c}`:""}`:"-";return Re("debug-control-transport",n.connected===!0?"ok":"warning","Direct TCP control",`peer ${u} · protocol ${ft(n,"protocol")||"-"} v${Je(n,"protocolVersion")??"-"} · input ${kt(n.channels).input===!1?"shared control channel":"dedicated channel"}`)}return Re("debug-control-transport","warning","Control transport is not identified","No Direct TCP or encrypted rendezvous relay metadata is available.")}function hw(e,t){const n=Number(e?.browserReceivedEpochMs);return Number.isFinite(n)&&n>0?Math.max(0,t-n):Number.POSITIVE_INFINITY}function fw(e,t,n){const s=kt(t?.frameTransport),a=ft(e,"frameTransportChangedAt"),i=ft(s,"changedAt"),c=sc(a),u=sc(i),d=u!==void 0&&(c===void 0||u>c),p=d?s:e,h=d?e:s,m=ft(e,"transport").toLowerCase(),g=ft(p,d?"active":"frameTransportActive")||ft(h,d?"frameTransportActive":"active"),w=ft(p,d?"protocol":"frameTransportProtocol")||ft(h,d?"frameTransportProtocol":"protocol"),y=(d?ft(s,"videoTransport","activeTransport")||[g,w].filter(Boolean).join("-")||ft(e,"videoTransport"):ft(e,"videoTransport")||ft(s,"videoTransport","activeTransport")||[g,w].filter(Boolean).join("-")).toLowerCase(),k=/(?:^|[-_])ws(?:$|[-_])|websocket/.test(y)||/(?:^|[-_])ws(?:$|[-_])|websocket/.test(m),C=/relay/.test(y)||/relay/.test(m)?"encrypted-relay":/p2p|udp/.test(y)||m==="udp-p2p"?"p2p-udp":/direct|tcp|ws|websocket/.test(y)||m==="binary"||k?k?"direct-ws":"direct-tcp":"",A=(ft(p,d?"state":"frameTransportState")||ft(h,d?"frameTransportState":"state")||(C?"active":"")).toLowerCase(),E=ft(p,d?"reason":"frameTransportReason")||ft(h,d?"frameTransportReason":"reason"),I=d?i||a:a||i,F=sc(I),M=F===void 0?void 0:Math.max(0,n-F),H=M===void 0?"":M<1e3?"changed now":M<6e4?`changed ${Math.round(M/1e3)}s ago`:M<36e5?`changed ${Math.round(M/6e4)}m ago`:`changed ${I}`,V=d?s.switchCount??e?.frameTransportSwitchCount:e?.frameTransportSwitchCount??s.switchCount,P=d?s.tcpFailureCount??e?.frameTransportTcpFailureCount:e?.frameTransportTcpFailureCount??s.tcpFailureCount,D=d?typeof s.p2pReady=="boolean"?s.p2pReady:e?.frameTransportP2pReady===!0:typeof e?.frameTransportP2pReady=="boolean"?e.frameTransportP2pReady:s.p2pReady===!0;return{rawTransport:m,videoTransport:C,state:A,reason:E,changedAt:I,changedLabel:H,switchCount:Math.max(0,Number(V??0)||0),tcpFailureCount:Math.max(0,Number(P??0)||0),p2pReady:D}}function yT(e,t,n){const s=fw(e,t,n),a=/(connecting|recovering|failed|error|degraded|unavailable)/.test(s.state);if(s.videoTransport==="encrypted-relay")return Re("transport",a?"warning":"ok",a?"Encrypted TCP relay fallback needs attention":"Encrypted TCP relay fallback",a?`End-to-end encrypted TCP relay is ${s.state||"not ready"}; open Debug Status for the technical reason${s.changedLabel?` · ${s.changedLabel}`:""}.`:`End-to-end encrypted TCP relay fallback is active${s.changedLabel?` · ${s.changedLabel}`:""}.`);if(s.videoTransport==="p2p-udp")return Re("transport",a?"warning":"ok",a?"P2P video connection needs attention":"P2P video connection",a?`Encrypted UDP P2P is ${s.state||"not ready"}; open Debug Status for the technical reason${s.changedLabel?` · ${s.changedLabel}`:""}.`:`Encrypted UDP P2P fallback is active${s.changedLabel?` · ${s.changedLabel}`:""}.`);if(s.videoTransport==="direct-tcp"||s.videoTransport==="direct-ws"){const i=s.videoTransport==="direct-ws"?"WebSocket":"TCP";return Re("transport",a?"warning":"ok",a?"Direct video connection needs attention":"Direct video connection",a?`Direct ${i} to Hub is ${s.state||"not ready"}; open Debug Status for the technical reason${s.changedLabel?` · ${s.changedLabel}`:""}.`:`Direct ${i} to Hub is active${s.changedLabel?` · ${s.changedLabel}`:""}.`)}return Re("transport","warning","Video transport is not identified",s.reason||"Waiting for Direct TCP, encrypted UDP P2P, or encrypted TCP relay transport data.")}const xT=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 gw(e){const n=String(e?.platformProfile||"").toLowerCase().includes("macos-screencapturekit"),s=Number(e?.nativeCaptureTelemetryVersion)>=5&&xT.every(i=>Je(e,i)!==void 0)&&typeof e?.nativeOutputQueueAwaitingKeyFrame=="boolean"&&e?.nativeCopyTelemetryAvailable===!0,a=e?.nativeCaptureTelemetryAvailable===!0&&e?.nativeCaptureResourceTelemetryAvailable===!0&&s;return{required:n,available:a,pending:Math.max(0,Number(e?.nativeEncodePendingFrameCount||0)),timestampOwners:Math.max(0,Number(e?.nativeEncodeTimestampOwnerCount||0)),timestampOwnerHighWatermark:Math.max(0,Number(e?.nativeEncodeTimestampOwnerHighWatermark||0)),coalesced:Math.max(0,Number(e?.nativeBackpressureCoalescedFrameCount||0)),pendingReplaced:Math.max(0,Number(e?.nativeEncodePendingReplacedFrameCount||0)),vtActive:Math.max(0,Number(e?.nativeVideoToolboxActiveSessionCount||0)),vtHighWatermark:Math.max(0,Number(e?.nativeVideoToolboxSessionHighWatermark||0)),outputOldestAgeMs:Math.max(0,Number(e?.nativeOutputQueueOldestAgeMs||0)),nativeAndPipeResidenceAgeMs:Math.max(0,Number(e?.nativeAndPipeResidenceAgeMs||0)),handoffDropped:Math.max(0,Number(e?.handoffDroppedFrameCount||0)),handoffRecoveryRequests:Math.max(0,Number(e?.handoffRecoveryKeyFrameRequestCount||0)),handoffOldestAgeMs:Math.max(0,Number(e?.handoffOldestFrameAgeMs||0)),annexBAllocations:Math.max(0,Number(e?.nativeAnnexBAccessUnitAllocationCount||0)),annexBPayloadCopies:Math.max(0,Number(e?.nativeAnnexBPayloadCopyCount||0)),annexBPayloadCopiedBytes:Math.max(0,Number(e?.nativeAnnexBPayloadCopiedBytes||0)),pipePayloadAllocations:Math.max(0,Number(e?.pipePayloadAllocationCount||0)),pipePayloadCopies:Math.max(0,Number(e?.pipePayloadCopyCount||0)),pipePayloadCopiedBytes:Math.max(0,Number(e?.pipePayloadCopiedBytes||0))}}function ST(e){const t=String(e?.frameMode||e?.mode||e?.codec||"").toLowerCase(),n=[e?.hardwareEncoder,e?.platformProfile].filter(Boolean).join(" · "),s=uw(e,"nativeEncoderHardwareAccelerated"),a=e?.nativeEncoderHardwareAccelerationKnown===!0||s!==void 0,i=gw(e);return!e||!/h264/.test(t)?Re("encoder","warning","Video encoder unavailable","Waiting for an H.264 frame."):i.required&&!i.available?Re("encoder","warning","H.264 encoder resource status is unavailable",`${n||"Native encoder"} has not provided complete VideoToolbox v5 ownership, queue, and copy telemetry.`):i.required&&(i.vtActive!==1||i.vtHighWatermark>1||i.timestampOwners>2||i.timestampOwnerHighWatermark>2)?Re("encoder","warning","VideoToolbox encoder ownership needs attention",`${i.vtActive} active session(s); high-water ${i.vtHighWatermark}; timestamp owners ${i.timestampOwners}/2 (HWM ${i.timestampOwnerHighWatermark})`):i.required&&i.coalesced>0?Re("encoder","warning","Hardware H.264 encoding is under load",`${i.coalesced} current-window frame(s) were coalesced while the encoder was busy.`):a&&s===!1?Re("encoder","warning","H.264 hardware acceleration is not active",`${n||"Native encoder"} is running without confirmed hardware acceleration.`):a&&s===!0?Re("encoder","ok","Hardware H.264 encoding",`${n||"Native encoder"} · hardware acceleration confirmed`):hT.test(n)?Re("encoder","ok","Hardware H.264 encoding",n):fT.test(n)?Re("encoder","warning","Software H.264 encoding",`${n||"CPU encoder"} may limit frame rate.`):Re("encoder","warning","H.264 encoder not identified",n||"The Client has not reported its active encoder profile.")}function CT({device:e,frame:t,receiveStat:n,paintStat:s,codec:a,selectedMonitorIndex:i=0,control:c=!1,controlInputReady:u=!1,controlBinding:d,hubRelay:p,capturePaused:h=!1,capturePauseConfirmed:m=!0,capturePauseError:g="",clientHeartbeatMs:w=5e3,now:v=Date.now()}={}){const y=kt(e),k=kt(y.status),N=kt(s?.lastInfo),C=[],A=hw(t,v);C.push(vT(y)),C.push(h?m?Re("connection","ok","Video capture is paused","Client screen capture and video encoder shutdown were confirmed by the Client."):Re("connection","warning","Video stop needs attention",String(g||"The Hub is blocking video restart, but the Client did not confirm screen capture and video encoder shutdown.")):y.connected===!0&&A<=ut.frameAgeWarningMs?Re("connection","ok","Video connection is current",`${Math.round(A)}ms since the latest frame.`):Re("connection","warning",y.connected===!0?"Video frame is stale":"Client is offline",y.connected===!0&&Number.isFinite(A)?`${Math.round(A)}ms since the latest frame.`:String(y.lastDisconnectReason||"No current Client session."))),C.push(yT(t,k,v)),C.push(ST(t));const E=dw(k.capture),I=kt(k.capture),F=pw({key:`${String(y.deviceId||y.id||"")}:capture-cleanup`,sampleId:ft(I,"sampledAt"),mismatch:E.helperLedgerMismatch||E.utilityLedgerMismatch});(E.helperQuarantineCount>0||E.utilityQuarantineCount>0||F.confirmed)&&C.push(Re("capture-cleanup","warning","Video capture cleanup needs attention",`capture quarantine ${E.helperQuarantineCount} · utility quarantine ${E.utilityQuarantineCount} · owned I/O ${E.helperOwnedIoTaskCount+E.utilityOwnedIoTaskCount} · exit observers ${E.helperOwnedExitObserverCount} · undisposed processes ${E.helperUndisposedProcessCount+E.utilityUndisposedProcessCount}`));const M=Math.max(0,Number(t?.requestedFps||t?.effectiveFps||0)),H=Math.max(0,Number(n?.framesPerSecond||0));Math.max(0,Number(t?.sourceGapMs||0));const V=Math.max(0,Number(t?.nativeCaptureFps||0)),P=Math.max(0,Number(t?.nativeEncodedFps||0)),D=Math.max(0,Number(t?.nativeCaptureSampleCount||0)),O=Math.max(0,Number(t?.nativeCaptureTelemetryVersion||0)),X=Je(t,"nativeCaptureTelemetryAgeMs"),U=Math.max(0,Number(X||0))+(Number.isFinite(A)?A:0),ie=O<2||X!==void 0&&U<=ut.nativeTelemetryStaleMs,j=Math.max(0,Number(t?.nativeBackpressureSkippedFrameCount||0)),re=Math.max(0,Number(t?.nativeIdleSkippedFrameCount||0)),de=t?.nativeCaptureTelemetryAvailable===!0&&D>0&&ie,Q=Je(t,"captureP95Ms","captureAverageMs","captureStageMs"),ge=Math.max(0,Number(Q||0)),oe=t?.captureTimingAvailable===!0&&M>0&&Number(n?.sampleMs||0)>0&&Q!==void 0,me=oe||de,Ae=Math.max(ut.minimumCaptureBudgetMs,M>0?1e3/M*ut.captureBudgetMultiplier:0),Te=M>0?1e3/M:100,Pe=M>0&&V>=M*ut.receiveRatioWarning,Se=P>0&&P<M*ut.receiveRatioWarning,te=de&&Pe&&Se&&P>=1&&re>=Math.max(10,V*.6)&&j===0,Ce=de&&M>0&&(V<M*ut.receiveRatioWarning||!te&&P>0&&P<M*ut.receiveRatioWarning),Fe=de?Ce:oe&&ge>Ae;C.push(me?Fe?Re("capture","warning","Screen capture cannot keep target speed",de?`${V.toFixed(1)} native capture · ${P.toFixed(1)} encoded · ${M||"?"} requested fps`:`${ge?`capture p95 ${Math.round(ge)}ms`:"capture timing unavailable"} · ${H.toFixed(1)}/${M||"?"} fps`):Re("capture","ok","Screen capture speed is healthy",de?`${V.toFixed(1)} native capture · ${P.toFixed(1)} encoded · ${M||"?"} requested fps${te?" · idle optimized":""}`:`${ge?`capture p95 ${Math.round(ge)}ms`:"no slow capture reported"}${M?` · ${H.toFixed(1)}/${M} fps`:""}`):Re("capture","warning","Screen capture data is still collecting","A current frame-rate and capture-time sample is required."));const Le=Je(t,"hubPacketTransitAgeMs"),Ue=Math.max(0,Number(Le||0)),ne=Math.max(0,Number(t?.agentSendGapMs||0)),ae=Math.max(0,Number(t?.agentSendDurationMs||0)),le=!bT(y.remoteAddress),ce=Dr(k,"network.usageRatio"),J=Je(k,"network.latencyMs"),ye=(ce??0)>=ut.networkUsageWarningRatio||(J??0)>=ut.networkLatencyWarningMs,ue=t?.hubClientQueueTelemetryAvailable===!0||Je(t,"hubClientDropped")!==void 0&&Je(t,"hubClientQueueDepth")!==void 0&&Je(t,"hubClientQueueLimit")!==void 0&&Je(t,"hubClientBufferedBytes")!==void 0,Ee=ue?Math.max(0,Number(t?.hubClientQueueDepth||0)):0,nt=ue?Math.max(0,Number(t?.hubClientQueueLimit||0)):0,T=ue&&nt>0&&Ee>=nt,ve=Le!==void 0&&Number(n?.sampleMs||0)>0,De=!te&&M>0&&Number(n?.sampleMs||0)>0&&H<M*ut.deliveryRatioWarning,qe=!te&&ne>Math.max(ut.networkDelayWarningMs,Te*3),_e=Ue>ut.networkDelayWarningMs||qe||ae>ut.networkDelayWarningMs||De||A>ut.frameAgeWarningMs||ye||T;C.push(ve?_e||le?Re("network","warning",le?"External network route may add delay":ye?"Client network adapter needs attention":T?"Hub browser video queue needs attention":"Video delivery is uneven",[Ue?`${Math.round(Ue)}ms Hub-to-browser`:"",ne?`${Math.round(ne)}ms Client send gap`:"",ae?`${Math.round(ae)}ms Client send time`:"",De?`${H.toFixed(1)} of ${M} requested fps`:"",J!==void 0?`${Math.round(J)}ms Client network latency`:"",ce!==void 0?`${Math.round(ce*100)}% Client link use`:"",ue&&nt>0?`Hub queue ${Ee}/${nt}`:"",le?String(y.remoteAddress||"external route"):""].filter(Boolean).join(" · ")||"Frame delivery is not current."):Re("network","ok","Network delivery is healthy",`${Math.round(Ue)}ms Hub-to-browser · ${te?`idle optimized at ${P.toFixed(1)} fps`:"the current video rate is on target."}`):Re("network","warning","Network delivery data is still collecting","A calibrated Hub-to-browser transit sample is required."));const $e=Dr(k,"cpu.usageRatio","cpu.usedRatio","cpu.percent"),mt=Dr(k,"memory.usedRatio","usedMemRatio"),ct=Dr(k,"gpu.usageRatio"),z=Dr(k,"gpu.memory.usedRatio"),pe=Je(k,"gpu.temperatureC","thermal.gpuC"),Y=$e!==void 0&&mt!==void 0,K=sc(y.lastStatusAt),ee=K===void 0?Number.POSITIVE_INFINITY:Math.max(0,v-K),R=Math.max(ut.minimumClientStatusFreshMs,Math.max(1e3,Number(w||0))*ut.clientStatusFreshMultiplier),se=ee<=R,Ie=($e??0)>=ut.cpuWarningRatio||(mt??0)>=ut.memoryWarningRatio||(ct??0)>=ut.gpuWarningRatio||(z??0)>=ut.gpuMemoryWarningRatio||(pe??0)>=ut.gpuTemperatureWarningC;C.push(Y?se?Ie?Re("computer","warning",(ct??0)>=ut.gpuWarningRatio||(z??0)>=ut.gpuMemoryWarningRatio||(pe??0)>=ut.gpuTemperatureWarningC?"Client GPU is under load":"Client computer is under load",[`CPU ${Math.round($e*100)}%`,`memory ${Math.round(mt*100)}%`,ct!==void 0?`GPU ${Math.round(ct*100)}%`:"",z!==void 0?`GPU memory ${Math.round(z*100)}%`:"",pe!==void 0?`GPU ${Math.round(pe)}C`:""].filter(Boolean).join(" · ")):Re("computer","ok","Client computer has working capacity",[`CPU ${Math.round($e*100)}%`,`memory ${Math.round(mt*100)}%`,ct!==void 0?`GPU ${Math.round(ct*100)}%`:""].filter(Boolean).join(" · ")):Re("computer","warning","Client performance snapshot is stale",Number.isFinite(ee)?`The latest CPU and memory report is ${Math.round(ee/1e3)} seconds old.`:"No current Client performance heartbeat has been received."):Re("computer","warning","Client performance data is unavailable","CPU and memory telemetry have not been reported yet."));const He=Number(t?.monitorIndex),Be=Number.isInteger(He)&&He===Number(i),xe=kt(y.channels),Ge=kt(y.capabilities),rt=xe.input!==!1&&Ge.remoteInput!==!1&&Ge.accessibilityPermission!==!1,Ke=Ge.screenRecordingPermission!==!1,gt=kt(d),_=!c||String(t?.sessionId||"")&&String(t?.sessionId||"")===String(gt.sessionId||"")&&String(t?.commandId||"")&&String(t?.commandId||"")===String(gt.commandId||"")&&Number(t?.captureGeneration||0)>0&&Number(t?.captureGeneration||0)===Number(gt.captureGeneration||0)&&Number(t?.monitorIndex)===Number(gt.monitorIndex),je=!c||u&&_;C.push(Be&&je&&rt&&Ke?Re("display","ok",c?"Display and remote input are bound":"Display and remote input are available",`Display ${Number(i)+1} · generation ${Number(t?.captureGeneration||0)||"current"}.`):Re("display","warning",Ke?rt?c?"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(i)+1}; latest frame ${Number.isInteger(He)?He+1:"not available"}.`));const Qe=kt(a),Ye=Array.isArray(Qe.canvases)?kt(Qe.canvases[0]):{},Gt=Math.max(0,Number(s?.decoderInputFps||0)),en=Math.max(0,Number(s?.decoderOutputFps||0)),qn=Gt>0&&Number(s?.sampleMs||n?.sampleMs||0)>0,Sr=H>0&&Number(n?.sampleMs||0)>0&&Number(s?.sampleMs||0)>0&&Gt<H*ut.decoderInputRatioWarning,Un=Gt>0?en/Gt:0,Fn=ft(Ye,"configuredAcceleration","requestedAcceleration")||ft(N,"h264DecodeAcceleration"),Sn=ft(Ye,"softwareFallbackReason"),rr=!!Sn||Fn==="prefer-software";return C.push(Sr?Re("decoder","warning","Browser decoder input is dropping frames",`${H.toFixed(1)} received / ${Gt.toFixed(1)} decoder input / ${en.toFixed(1)} output fps.`):qn?rr||Un<ut.decoderOutputRatioWarning?Re("decoder","warning",rr?"Browser is using software H.264 fallback":"Browser decoder output is slow",`${Sn||String(N.decoderLabel||Fn||"decoder")} · ${Gt.toFixed(1)} in / ${en.toFixed(1)} out fps.`):Re("decoder","ok",Fn==="prefer-hardware"?"Browser requests hardware H.264":"Browser H.264 path is responsive",`${Gt.toFixed(1)} in / ${en.toFixed(1)} out fps. Chrome does not expose definitive hardware acceptance.`):Re("decoder","warning","Browser decoder data is still collecting","Decoder input and output samples are required before this path can be marked healthy.")),C}function ss(e){const t=String(e||"").trim();return t?t.length<=14?t:`${t.slice(0,6)}…${t.slice(-5)}`:"-"}function Pt(e,t=1){const n=Number(e);return Number.isFinite(n)?n.toFixed(t):"-"}function kT({device:e,frame:t,receiveStat:n,paintStat:s,codec:a,selectedMonitorIndex:i=0,control:c=!1,controlInputReady:u=!1,controlBinding:d,hubRelay:p,now:h=Date.now()}={}){const m=kt(e),g=kt(m.status),w=kt(g.runtimeProcess),v=kt(g.capture),y=dw(v),k=kt(d),N=kt(s?.lastInfo),C=kt(a),A=Array.isArray(C.canvases)?kt(C.canvases[0]):{},E=[],I=Number(i),F=Number(t?.monitorIndex),M=Number.isInteger(F)&&F===I,H=Number(t?.captureGeneration||0),V=Number(k.captureGeneration||0),P=!c||M&&String(t?.sessionId||"")===String(k.sessionId||"")&&String(t?.commandId||"")===String(k.commandId||"")&&H>0&&H===V,D=Math.max(0,Number(t?.requestedFps||t?.effectiveFps||0)),O=Math.max(0,Number(n?.framesPerSecond||0)),X=Math.max(0,Number(s?.framesPerSecond||0)),G=Math.max(0,Number(s?.decoderInputFps||0)),U=Math.max(0,Number(s?.decoderOutputFps||0)),ie=Number(n?.sampleMs||0)>0&&Number(s?.sampleMs||0)>0,j=D>0&&ie&&Math.min(O,X||O,U||O)<D*ut.deliveryRatioWarning,re=Math.max(0,Number(t?.sourceGapMs||0)),de=Math.max(0,Number(t?.agentSendGapMs||0)),Q=Math.max(0,Number(t?.agentSendDurationMs||0)),ge=Math.max(0,Number(t?.agentSendDurationFrameSeq||0)),oe=Math.max(0,Number(t?.agentQueueBeforePaceMs||0)),me=Math.max(0,Number(t?.agentFrameAgeMs||0)),Ae=Je(t,"hubPacketTransitAgeMs"),Te=Math.max(0,Number(t?.droppedByAgent||0)),Pe=Math.max(0,Number(t?.hubIngressDropped||0)),Se=t?.hubClientQueueTelemetryAvailable===!0||Je(t,"hubClientDropped")!==void 0&&Je(t,"hubClientQueueDepth")!==void 0&&Je(t,"hubClientQueueLimit")!==void 0&&Je(t,"hubClientBufferedBytes")!==void 0,te=Se?Math.max(0,Number(t?.hubClientDropped||0)):0,Ce=Se?Math.max(0,Number(t?.hubClientQueueDepth||0)):0,Fe=Se?Math.max(0,Number(t?.hubClientQueueLimit||0)):0,Le=Se?Math.max(0,Number(t?.hubClientBufferedBytes||0)):0,Ue=Math.max(0,Number(t?.udpIncompleteFrames||0)),ne=Te+Pe+te,ae=hw(t,h),le=ft(A,"configuredAcceleration","requestedAcceleration")||ft(N,"h264DecodeAcceleration"),ce=ft(A,"softwareFallbackReason"),J=Math.max(0,Number(C.hardwareReleaseGeneration||0)),ye=Math.max(0,Number(C.hardwareRecoveryProbeCount||0)),ue=Number(C.lastHardwareRecoveryProbeAt),Ee=Number.isFinite(ue)&&ue>0?Math.max(0,h-ue):void 0,nt=`hardware releases ${J} · recovery probes ${ye} · last probe ${Ee===void 0?"-":`${Math.round(Ee)}ms ago`}`,T=ie&&O>0&&G<O*ut.decoderInputRatioWarning,ve=fw(t,g,h),De=ft(m,"deviceId")||ft(t,"deviceId"),qe=ft(t,"sessionId")||ft(m,"sessionId"),_e=ft(m,"productVersion")||ft(g,"productVersion","runtime.productVersion"),$e=ft(m,"agentVersion")||ft(g,"agentVersion","runtime.agentVersion"),mt=Je(m,"pid","runtimePid")??Je(g,"pid","runtimePid","process.pid"),ct=Je(w,"pid"),z=Dr(w,"cpuUsageRatio"),pe=Je(w,"cpuCorePercent"),Y=Je(w,"workingSetBytes"),K=Je(w,"privateMemoryBytes"),ee=Math.max(Y||0,K||0),R=(ct??0)>0&&(Y??0)>0,se=R&&(mt??0)>0&&ct!==mt,Ie=(z??0)>=ut.runtimeProcessCpuWarningRatio||ee>=ut.runtimeProcessMemoryWarningBytes,He=Dr(g,"cpu.usageRatio"),Be=Dr(g,"memory.usedRatio","usedMemRatio"),xe=Math.max(0,Number(Je(v,"videoStreamCount")||0)),Ge=Math.max(0,Number(Je(v,"audioStreamCount")||0)),rt=Je(v,"helperCount"),Ke=Math.max(0,Number(rt||0)),gt=Je(v,"helperAliveCount"),_=gt===void 0?Ke:Math.max(0,Number(gt||0)),je=Je(v,"helperExitedOwnedCount"),Qe=Math.max(0,Number(je||0)),Ye=Je(v,"helperMaxConcurrent"),Gt=Math.max(Ke,Number(Ye||0)),en=Array.isArray(v.helperPids)?v.helperPids.map(Ls=>Number(Ls)).filter(Ls=>Number.isSafeInteger(Ls)&&Ls>0):[],qn=Array.isArray(v.helperProfiles)?v.helperProfiles.map(Ls=>String(Ls||"").trim()).filter(Boolean).slice(0,4):[],on=Dr(v,"helperCpuUsageRatio"),Sr=Je(v,"helperCpuCorePercent"),Un=Je(v,"helperWorkingSetBytes"),Fn=Je(v,"helperPrivateMemoryBytes"),Sn=Math.max(Un||0,Fn||0),rr=Math.max(0,Number(Je(v,"helperStartCount")||0)),bt=Math.max(0,Number(Je(v,"helperStopCount")||0)),Z=rt!==void 0,be=gt!==void 0&&je!==void 0,We=Z&&rr>=bt&&(rr-bt!==Ke||be&&_+Qe!==Ke),lt=Ke>1||_>1||Gt>1||xe>1||We||y.currentProblem,It=Z&&(xe>0&&_===0||xe===0&&_>0),At=pw({key:De&&qe?`${De}:${qe}`:"",sampleId:ft(v,"sampledAt"),mismatch:It}),et=It&&!At.confirmed,Mt=lt||At.confirmed,Cn=(on??0)>=ut.captureHelperCpuWarningRatio||Sn>=ut.captureHelperMemoryWarningBytes,zt=!!(De&&qe&&_e&&$e&&(mt??0)>0),kn=t?.nativeCaptureTelemetryAvailable===!0,Nt=Math.max(0,Number(t?.nativeCaptureTelemetryVersion||0)),cn=Nt>=2,ht=gw(t),we=!ht.required||ht.available,Ot=Je(t,"nativeCaptureTelemetryAgeMs"),tn=Math.max(0,Number(Ot||0))+(Number.isFinite(ae)?ae:0),ps=Ot===void 0?"-":`${Math.round(tn)}ms`,Is=!cn||Ot!==void 0&&tn<=ut.nativeTelemetryStaleMs,Bt=kn&&!Is,ms=uw(t,"nativeEncoderHardwareAccelerated"),bc=t?.nativeEncoderHardwareAccelerationKnown===!0||ms!==void 0,ei=ft(t,"nativeEncoderHardwareQueryStatus"),ia=ei==="0"?"confirmed":ei,vc=Math.max(0,Number(t?.nativeCaptureDisplayId||0)),dr=Math.max(0,Number(t?.nativeCaptureFps||0)),ti=Math.max(0,Number(t?.nativeCompressionOutputCount||0)),Dn=Math.max(0,Number(t?.nativeCompressionFps||0)),pr=Math.max(0,Number(t?.nativeEncodedFps||0)),sr=cn||ti>0?Dn:pr,nn=Math.max(0,Number(t?.nativeCaptureSampleCount||0)),oa=Math.max(0,Number(t?.nativeEncodableFrameCount||0)),qt=Math.max(0,Number(t?.nativeSkippedFrameCount||0)),ca=Math.max(0,Number(t?.nativeEncodedFrameCount||0)),Vn=Math.max(0,Number(t?.nativeEncodeFramesInFlight||0)),la=ht.pending,$r=ht.timestampOwners,hs=ht.timestampOwnerHighWatermark,wc=ht.coalesced,js=Math.max(0,Number(t?.nativeBackpressureSkippedFrameCount||0)),Cr=ht.pendingReplaced,Or=Math.max(0,Number(t?.nativeIdleSkippedFrameCount||0)),yc=ht.vtActive,Br=ht.vtHighWatermark,io=Math.max(0,Number(t?.nativeOutputQueueDepth||0)),ua=Math.max(0,Number(t?.nativeOutputQueueBytes||0)),Hr=ht.outputOldestAgeMs,pm=Math.max(0,Number(t?.nativeOutputQueueHighWatermark||0)),Pu=Math.max(0,Number(t?.nativeOutputQueueDroppedCount||0)),fs=t?.nativeOutputQueueAwaitingKeyFrame===!0,oo=ht.nativeAndPipeResidenceAgeMs,ot=ht.handoffDropped,co=ht.handoffRecoveryRequests,rn=ht.handoffOldestAgeMs,da=Vn>2||la>1||$r>2||hs>2||wc>0||Vn>=2&&js>0,Ct=ht.required&&ht.available&&(yc!==1||Br>1||$r>2||hs>2),ni=io>=3||ua>=6*1024*1024||Hr>120||Pu>0||fs||oo>250||ot>0||co>0||rn>120,lo=`in-flight ${Vn}/2 · backpressure skipped ${js} · idle skipped ${Or} · stdout queue ${io} AU/${Math.round(ua/1024)} KB/${Math.round(Hr)}ms · HWM ${pm} · dropped ${Pu} · awaiting key ${fs?"yes":"no"} · native+pipe ${Math.round(oo)}ms · handoff ${Math.round(rn)}ms/drop ${ot}/recovery ${co}`,Es=`pending ${la}/1; timestamp owners ${$r}/2 (HWM ${hs}); coalesced ${wc}; pending replaced ${Cr}; VideoToolbox ${yc} active/HWM ${Br}`,xc=ht.available&&ht.annexBAllocations>0&&ht.annexBPayloadCopies>=ht.annexBAllocations&&ht.annexBPayloadCopiedBytes>0&&ht.pipePayloadAllocations>0&&ht.pipePayloadCopies>=ht.pipePayloadAllocations&&ht.pipePayloadCopiedBytes>0,vt=`Annex-B allocation/copy ${ht.annexBAllocations}/${ht.annexBPayloadCopies} (${Math.round(ht.annexBPayloadCopiedBytes/1024)} KB) · pipe allocation/read ${ht.pipePayloadAllocations}/${ht.pipePayloadCopies} (${Math.round(ht.pipePayloadCopiedBytes/1024)} KB)`,ln=kn&&nn>0&&Is,ri=D>0?1e3/D:100,uo=D>0&&dr>=D*ut.receiveRatioWarning,po=sr>0&&sr<D*ut.receiveRatioWarning,Wr=ln&&uo&&po&&sr>=1&&pr>=1&&Or>=Math.max(10,dr*.6)&&js===0,si=j&&!Wr,Ln=!Wr&&de>Math.max(ut.networkDelayWarningMs,ri*3),Fs=ln&&D>0&&dr<D*ut.receiveRatioWarning,Ds=ln&&!Wr&&dr>0&&(cn&&sr<=0||sr>0&&sr<dr*ut.receiveRatioWarning),Sc=ln&&ti>0&&sr>0&&pr<sr*ut.receiveRatioWarning,Iu=Bt?"Native capture telemetry is stale":we?Ct?"VideoToolbox encoder ownership needs attention":ln?Fs?"Native screen capture is below request":Ds||da?"VideoToolbox compression is behind capture":Sc||ni?"Native stdout delivery is backpressured":ms===!1?"Native hardware encoder is unavailable":"Native capture or encoder needs attention":"Native capture telemetry is unavailable":"Native encoder resource telemetry is unavailable";E.push(wT(m,p)),E.push(zt?Re("debug-runtime","ok",`LiveDesk ${_e} · Agent ${$e}`,`pid ${mt} · session ${ss(qe)} · device ${ss(De)}`):Re("debug-runtime","warning","Runtime identity is incomplete",`LiveDesk ${_e||"-"} · Agent ${$e||"-"} · pid ${mt??"-"} · session ${ss(qe)} · device ${ss(De)}`)),E.push(R&&!se&&!Ie?Re("debug-process-load","ok","RemoteFast process load is healthy",`pid ${ct} · CPU ${Gs(z)} machine / ${Bl(pe)} core · RSS ${Vs(Y)} · private ${Vs(K)} · system CPU ${Gs(He)} · memory ${Gs(Be)}`):Re("debug-process-load","warning",R?se?"RemoteFast process identity does not match":"RemoteFast process load needs attention":"RemoteFast process telemetry is collecting",`runtime pid ${ct??"-"} · reported pid ${mt??"-"} · CPU ${Gs(z)} machine / ${Bl(pe)} core · RSS ${Vs(Y)} · private ${Vs(K)} · system CPU ${Gs(He)} · memory ${Gs(Be)}`)),E.push(t?Re("debug-frame","ok",`Frame #${Number(t.frameSeq||0)} · ${String(t.streamPurpose||(c?"control":"wall"))}`,`stream ${ss(t.streamId)} · ${t.width||0}x${t.height||0} · ${Math.round(Number(t.byteLength||0)/1024)} KB · age ${Number.isFinite(ae)?Math.round(ae):"-"}ms`):Re("debug-frame","warning","No current frame",`Device ${ss(m.deviceId)} has not produced a frame.`));const ju=/(connecting|recovering|failed|error|degraded|unavailable)/.test(ve.state);E.push(ve.videoTransport&&!ju?Re("debug-transport","ok",`${ve.videoTransport==="encrypted-relay"?"Encrypted TCP relay fallback":ve.videoTransport==="p2p-udp"?"P2P UDP":ve.videoTransport==="direct-ws"?"Direct WebSocket":"Direct TCP"} · ${ve.state||"active"}`,[`raw ${ve.rawTransport||"-"}`,`P2P ${ve.p2pReady?"ready":"standby unavailable"}`,`switch ${ve.switchCount}`,`TCP failure ${ve.tcpFailureCount}`,ve.changedLabel,ve.reason].filter(Boolean).join(" · ")):Re("debug-transport","warning",ve.videoTransport?`Video transport ${ve.state||"needs attention"}`:"Video transport is not identified",[ve.videoTransport||"no active path",`raw ${ve.rawTransport||"-"}`,`P2P ${ve.p2pReady?"ready":"not ready"}`,ve.changedLabel,ve.reason].filter(Boolean).join(" · "))),E.push(M?Re("debug-monitor","ok",`Monitor selected ${I+1} · frame ${F+1}`,`reported ${Number(t?.monitorCount||0)||"?"} displays · generation ${H||"-"}`):Re("debug-monitor","warning",`Monitor mismatch: selected ${I+1} · frame ${Number.isInteger(F)?F+1:"-"}`,`reported ${Number(t?.monitorCount||0)||"?"} displays · generation ${H||"-"}`)),E.push(P&&(!c||u)?Re("debug-binding","ok",c?"Control generation is bound":"Wall capture generation is current",`session ${ss(t?.sessionId)} · command ${ss(t?.commandId)} · generation ${H||"-"}`):Re("debug-binding","warning",c?"Control generation is not bound":"Wall capture generation is unavailable",`frame ${ss(t?.commandId)}/${H||"-"} · expected ${ss(k.commandId)}/${V||"-"} · input ${u?"ready":"waiting"}`)),E.push(ie&&!si?Re("debug-cadence","ok",`Cadence ${Pt(O)} rx · ${Pt(X)} paint · ${Pt(U)} decode`,`requested ${Pt(D)} · decoder input ${Pt(G)} fps · receive p95 ${Pt(n?.p95IntervalMs)}ms${Wr?" · idle optimized":""}`):Re("debug-cadence","warning",ie?"Frame cadence is below request":"Frame cadence sample is collecting",`requested ${Pt(D)} · receive ${Pt(O)} · paint ${Pt(X)} · decode ${Pt(U)} fps`)),E.push(ln&&we&&!Fs&&!Ds&&!Sc&&!da&&!Ct&&!ni&&ms!==!1?Re("debug-native-capture","ok",`Native capture ${Pt(dr)} fps · compress ${Pt(sr)} fps · stdout ${Pt(pr)} fps${Wr?" · idle optimized":""}`,`telemetry v${Nt||1} · age ${ps} · hardware ${bc?ms?"yes":"no":"unknown"}${ia?` (${ia})`:""} · display ${vc||"-"} · capture samples ${nn} · encodable ${oa} · skipped ${qt} · compression outputs ${ti} · stdout written ${ca} · ${lo} · encoded AU output gap ${Math.round(re)}ms`):Re("debug-native-capture","warning",Iu,`telemetry ${kn?`v${Nt||1}`:"no"} · age ${ps} · hardware ${bc?ms?"yes":"no":"unknown"}${ia?` (${ia})`:""} · display ${vc||"-"} · capture ${Pt(dr)} fps · compress ${Pt(sr)} fps · stdout ${Pt(pr)} fps · capture samples ${nn} · encodable ${oa} · skipped ${qt} · compression outputs ${ti} · stdout written ${ca} · ${lo} · encoded AU output gap ${Math.round(re)}ms`)),ht.required&&(E.push(we&&!da&&!Ct?Re("debug-native-resource","ok","VideoToolbox resource ownership is bounded",Es):Re("debug-native-resource","warning",we?Ct?"VideoToolbox session ownership is not exclusive":"VideoToolbox encode lane is coalescing":"VideoToolbox resource telemetry is unavailable",Es)),E.push(we&&xc?Re("debug-native-copy","ok","Capture copy accounting is current",vt):Re("debug-native-copy","warning",we?"Capture copy accounting needs attention":"Capture copy accounting is unavailable",vt))),E.push(Z&&!Mt&&!Cn?Re("debug-capture-ownership","ok",et?"Capture ownership transition is settling":_>0?"Capture helper ownership is exclusive":"Capture helpers are idle",`video ${xe} · audio ${Ge} · helpers ${Ke} owned / ${_} alive / ${Qe} exiting (max ${Gt||"-"}) · pid ${en.join(",")||"-"} · profile ${qn.join(", ")||"-"} · CPU ${Gs(on)} machine / ${Bl(Sr)} core · RSS ${Vs(Un)} · private ${Vs(Fn)} · starts ${rr} / stops ${bt}${et?` · mismatch samples ${At.count}/${Ep}`:""}`):Re("debug-capture-ownership","warning",Z?Ke>1||_>1||Gt>1?"Duplicate capture helpers detected":Mt?"Capture stream and helper ownership do not match":"Capture helper load needs attention":"Capture process telemetry is collecting",`video ${xe} · audio ${Ge} · helpers ${Ke} owned / ${_} alive / ${Qe} exiting (max ${Gt||"-"}) · pid ${en.join(",")||"-"} · profile ${qn.join(", ")||"-"} · CPU ${Gs(on)} machine / ${Bl(Sr)} core · RSS ${Vs(Un)} · private ${Vs(Fn)} · starts ${rr} / stops ${bt}`));const Cc=`helper I/O ${y.helperOwnedIoTaskCount} | exit observers ${y.helperOwnedExitObserverCount} | undisposed ${y.helperUndisposedProcessCount} | quarantine ${y.helperQuarantineCount} | dispose failures ${y.helperDisposeFailureCount} | utility I/O ${y.utilityOwnedIoTaskCount} | undisposed ${y.utilityUndisposedProcessCount} | quarantine ${y.utilityQuarantineCount} | utility pid ${y.utilityQuarantinePids.join(",")||"-"} | profile ${y.utilityQuarantineProfiles.join(", ")||"-"} | utility starts ${y.utilityQuarantineStartCount} / stops ${y.utilityQuarantineStopCount} | dispose failures ${y.utilityDisposeFailureCount}${y.helperLastDisposeFailure?` | helper last ${y.helperLastDisposeFailure}`:""}${y.utilityLastDisposeFailure?` | utility last ${y.utilityLastDisposeFailure}`:""}`;E.push(y.telemetryAvailable&&!y.currentProblem&&!y.historicalCleanupFailure?Re("debug-capture-cleanup","ok",Ke>0?"Capture cleanup ownership is exact":"Capture cleanup is idle",Cc):Re("debug-capture-cleanup","warning",y.telemetryAvailable?y.currentProblem?"Capture cleanup is quarantined or mismatched":"Capture cleanup recorded a disposal failure":"Capture cleanup telemetry is collecting",Cc)),E.push(Se?ne===0&&Ue===0&&(Fe<=0||Ce<Fe)&&!Ln&&Q<=ut.networkDelayWarningMs&&me<=ut.networkDelayWarningMs&&(Ae===void 0||Ae<=ut.networkDelayWarningMs)?Re("debug-delivery","ok","Delivery counters are clear",`encoded AU output gap ${Math.round(re)}ms · Client send gap ${Math.round(de)}ms · Client send time ${Math.round(Q)}ms (frame ${ge||"-"}) · Agent queue ${Math.round(oe)}ms · Agent age ${Math.round(me)}ms · Agent drop ${Te} · Hub transit ${Ae===void 0?"-":Math.round(Ae)}ms · Hub ingress drop ${Pe} · browser queue drop ${te} (${Ce}/${Fe||"-"}) · buffered ${Math.round(Le/1024)} KB · UDP incomplete ${Ue}${Wr?" · idle optimized":""}`):Re("debug-delivery","warning","Delivery counters show loss or delay",`encoded AU output gap ${Math.round(re)}ms · Client send gap ${Math.round(de)}ms · Client send time ${Math.round(Q)}ms (frame ${ge||"-"}) · Agent queue ${Math.round(oe)}ms · Agent age ${Math.round(me)}ms · Agent drop ${Te} · Hub transit ${Ae===void 0?"-":Math.round(Ae)}ms · Hub ingress drop ${Pe} · browser queue drop ${te} (${Ce}/${Fe||"-"}) · buffered ${Math.round(Le/1024)} KB · UDP incomplete ${Ue}`):Re("debug-delivery","warning","Browser queue counters are available in Hub Status",`encoded AU output gap ${Math.round(re)}ms · Client send gap ${Math.round(de)}ms · Agent drop ${Te} · Hub ingress drop ${Pe} · per-browser lane counters are intentionally collected outside video packets.`));const mo=Je(t,"captureP95Ms");return E.push(t?.captureTimingAvailable===!0&&mo!==void 0?Re("debug-capture","ok",`Capture p95 ${Pt(mo)}ms · avg ${Pt(t?.captureAverageMs)}ms`,`stage ${Pt(t?.captureStageMs)}ms · slow ${Number(t?.slowFrameCount||0)} · helper restart ${Number(t?.captureHelperRestarts||0)} · source skip ${Number(t?.captureSourceSkipped||0)}`):ln&&cn?Re("debug-capture","ok","Capture latency is not instrumented; native cadence is current",`ScreenCaptureKit ${Pt(dr)} fps · VideoToolbox ${Pt(sr)} fps · stdout ${Pt(pr)} fps · telemetry age ${ps}`):Re("debug-capture","warning","Capture timing sample is unavailable",`stage ${Pt(t?.captureStageMs)}ms · helper restart ${Number(t?.captureHelperRestarts||0)} · source serial ${Number(t?.captureSourceSerial||0)}`)),E.push(!ce&&le!=="prefer-software"&&!T?Re("debug-decoder","ok",`Decoder ${le||"acceleration unknown"}`,`${String(t?.frameMode||t?.codec||"-")} · ${String(t?.hardwareEncoder||"-")} · ${String(t?.platformProfile||"-")} · ${nt}`):Re("debug-decoder","warning",T?"Decoder input is losing received frames":"Decoder software fallback is active",T?`${Pt(O)} received / ${Pt(G)} decoder input / ${Pt(U)} output fps · ${nt}`:`${ce||le||"software"} · ${Pt(G)} in / ${Pt(U)} out fps · ${nt}`)),E}function MT({status:e,deviceDiagnostics:t=[],codec:n,browser:s,frameStats:a}={}){const i=kt(e),c=kt(i.diagnostics),u=kt(c.system),d=kt(c.network),p=kt(n),h=kt(s),m=Array.isArray(t)?t:[],g=m.reduce((me,Ae)=>me+(Array.isArray(Ae)&&Ae.some(Te=>Te?.state==="warning")?1:0),0),w=Dr(u,"cpuUsageRatio","processCpuRatio"),v=Dr(u,"memoryUsedRatio"),y=Je(u,"totalMemoryBytes"),k=Je(u,"cpuLogicalCores")??Je(h,"hardwareConcurrency"),N=Je(h,"deviceMemory"),C=(k??0)>0&&w!==void 0&&v!==void 0&&(y??0)>0,A=(y??0)>0&&y<ut.hubMinimumTotalMemoryBytes,E=(N??0)>0&&N<ut.hubMinimumBrowserMemoryGb,I=(k??0)>0&&k<4||(w??0)>=ut.cpuWarningRatio||(v??0)>=ut.memoryWarningRatio||A||E,F=Math.max(0,Number(p.activeSoftwareFallbackCount??p.softwareFallbackCount??0)),M=Math.max(0,Number(p.activeDecoderCount||0)),H=Math.max(0,Number(a?.bytesPerSecond||0)*8/1e6),V=Je(d,"externalDeviceCount"),P=ft(d,"route"),D=V!==void 0&&!!P,O=(V??0)>0||P==="external",X=kt(i.frameLanes),G=kt(X.packetFanout),U=["packetBuilds","metadataSerializations","payloadCopyOperations","fanoutEligibleSubscribers"].every(me=>Je(G,me)!==void 0),ie=Array.isArray(X.clients)?X.clients.map(kt):[],j=Je(X,"clientCount")!==void 0&&Array.isArray(X.clients)&&U,re=ie.some(me=>{const Ae=Math.max(0,Number(me.queueDepth||0)),Te=Math.max(0,Number(me.queueLimit||0)),Pe=Math.max(0,Number(me.queuedBytes||0)),Se=Math.max(0,Number(me.queueByteLimit||0));return Math.max(0,Number(me.droppedPackets||0))>0||Te>0&&Ae>=Te||Se>0&&Pe>=Se||Array.isArray(me.backpressuredDeviceIds)&&me.backpressuredDeviceIds.length>0}),de=Math.max(0,Number(G.packetBuilds||0)),Q=Math.max(0,Number(G.metadataSerializations||0)),ge=Math.max(0,Number(G.payloadCopyOperations||0)),oe=Math.max(0,Number(G.fanoutEligibleSubscribers||0));return[i.started&&!i.lastError?Re("hub-runtime","ok","Hub runtime is ready",`${i.connectedDeviceCount||0} Clients connected.`):Re("hub-runtime","warning","Hub runtime needs attention",String(i.lastError||"Hub is not ready.")),C?I?Re("hub-computer","warning",A?"Hub has limited system memory":E?"Browser reports limited memory capacity":"Hub computer may limit remote performance",[`${k||"?"} logical cores`,`${jg(y)} RAM`,N!==void 0?`${N} GB browser memory class`:"",`CPU ${w===void 0?"?":Math.round(w*100)}%`,`memory ${v===void 0?"?":Math.round(v*100)}%`].filter(Boolean).join(" · ")):Re("hub-computer","ok","Hub computer capacity is healthy",`${k||"?"} logical cores · ${jg(y)} RAM · CPU ${w===void 0?"not reported":`${Math.round(w*100)}%`}.`):Re("hub-computer","warning","Hub performance data is unavailable","Logical-core, CPU, used-memory, and total-memory telemetry are required."),M<=0?Re("hub-codec","warning","No active browser H.264 decoder to check","Open Wall or Control and wait for a video frame."):F>0?Re("hub-codec","warning","Some browser decoders use software fallback",`${M} active H.264 decoders · ${F} software fallbacks. Chrome does not expose definitive hardware acceptance.`):Re("hub-codec","ok","All active streams request hardware H.264",`${M} active decoders. Chrome hardware acceptance is inferred from health, not directly exposed.`),j?re?Re("hub-frame-lanes","warning","A Hub browser video lane needs attention",`${ie.length}/${X.clientCount||0} lanes reported · packet builds ${de} · metadata serializations ${Q} · payload copies ${ge} · fanout deliveries ${oe}.`):Re("hub-frame-lanes","ok","Hub browser video lanes are bounded",`${ie.length}/${X.clientCount||0} lanes reported · packet builds ${de} · metadata serializations ${Q} · payload copies ${ge} · fanout deliveries ${oe}.`):Re("hub-frame-lanes","warning","Hub browser queue data is unavailable","Per-browser queue, drop, buffered-byte, and packet-allocation evidence is required."),g>0?Re("hub-clients","warning",`${g} Clients need attention`,"Open the matching Wall slot lines for the exact cause."):Re("hub-clients","ok","Connected Clients report healthy remote paths",`${m.length} Client reports checked.`),Re("hub-network",!D||O||H>120?"warning":"ok",D?O?`${V} Clients use an external network route`:H>120?"Hub receive load is high":"Hub receive load is within range":"Hub network route data is unavailable",D?`${P.toUpperCase()} route · ${H.toFixed(H>=10?0:1)} Mbps received by this browser.`:"The Hub has not reported LAN/external route classification yet.")]}async function AT(e,t={}){const n=e.filter(m=>m.canvas&&m.canvas.width>0&&m.canvas.height>0),s=Math.max(320,t.maxWidth||1920),a=Math.max(180,t.maxHeight||1080),i=n.length<=1?1:n.length<=4?2:n.length<=9?3:4,c=Math.max(1,Math.ceil(Math.max(1,n.length)/i)),u=Math.floor(s/i),d=Math.floor(a/c),p=document.createElement("canvas");p.width=Math.max(320,u*i),p.height=Math.max(180,d*c);const h=p.getContext("2d",{alpha:!1});if(!h)return p;h.fillStyle="#0b1220",h.fillRect(0,0,p.width,p.height),h.font="600 14px system-ui, sans-serif",h.textBaseline="bottom";for(let m=0;m<n.length;m+=1){const g=n[m],w=m%i,v=Math.floor(m/i),y=w*u,k=v*d,N=g.canvas,C=Math.min(u/N.width,d/N.height),A=Math.max(1,Math.floor(N.width*C)),E=Math.max(1,Math.floor(N.height*C)),I=y+Math.floor((u-A)/2),F=k+Math.floor((d-E)/2);h.drawImage(N,I,F,A,E),t.includeLabels!==!1&&(h.fillStyle="rgba(4, 10, 20, .74)",h.fillRect(y,k+d-28,u,28),h.fillStyle="#f8fafc",h.fillText(g.label,y+9,k+d-9))}return p}function NT(e){return e?.signature||"none"}function RT(e){return e?.label||"No capture target"}function Fg(e){return{...e,deviceIds:[...e.deviceIds],sourceCanvas:e.sourceCanvas||null}}function TT(){const e=new Date,t=n=>String(n).padStart(2,"0");return`${e.getFullYear()}${t(e.getMonth()+1)}${t(e.getDate())}_${t(e.getHours())}${t(e.getMinutes())}${t(e.getSeconds())}`}function PT(e){return e.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"Wall"}function IT(e){return`LiveDesk_${e.type==="wall"||e.type==="selection"?"Wall":`${PT(e.label)}_Monitor-${Number(e.monitorIndex||0)+1}`}_${TT()}.png`}async function jT(e,t,n){const s=await new Promise((i,c)=>e.toBlob(u=>u?i(u):c(new Error("Screenshot could not be encoded.")),"image/png")),a=await ow(s,{kind:"screenshot",fileName:IT(t),target:t},n);try{await navigator.clipboard.write([new ClipboardItem({"image/png":s})])}catch{}return a.capture}function bw(){return["video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm"].find(t=>typeof MediaRecorder<"u"&&MediaRecorder.isTypeSupported(t))||""}function ET(e,t){const n=new Date().toISOString().replace(/[-:]/g,"").replace(/\.\d{3}Z$/,"").replace("T","_"),s=t.label.replace(/[^a-zA-Z0-9._-]+/g,"-").slice(0,70)||"Wall";return e==="timelapse"?`LiveDesk_Timelapse_${s}_${n}.webm`:`LiveDesk_Recording_${s}_${n}.webm`}async function vw(e){if(typeof MediaRecorder>"u"||typeof e.canvas.captureStream!="function")throw new Error("This browser does not support video recording.");const t=bw();if(!t)throw new Error("This browser does not support WebM recording.");const n=e.kind||"recording",s=await oT({kind:n,fileName:ET(n,e.target),mimeType:t,target:e.target},e.hubUrl),a=e.canvas.captureStream(e.frameRequests?0:e.fps),i=new MediaRecorder(a,{mimeType:t,videoBitsPerSecond:n==="timelapse"?2e6:4e6}),c=performance.now();let u=0,d=!1,p=null,h=Promise.resolve();return i.ondataavailable=m=>{if(!m.data||m.data.size===0)return;const g=u++;h=h.then(()=>cT(s.sessionId,g,m.data,e.hubUrl).then(()=>{})).catch(w=>{p=p||(w instanceof Error?w:new Error(String(w))),e.onError?.(p)})},i.onerror=()=>{p=new Error("Video recording stopped unexpectedly."),e.onError?.(p)},i.start(1e3),{requestFrame:()=>{a.getVideoTracks()[0]?.requestFrame?.()},stop:async()=>{if(!d){if(d=!0,await new Promise(m=>{i.addEventListener("stop",()=>m(),{once:!0}),i.stop()}),a.getTracks().forEach(m=>m.stop()),await h,p)throw await Ag(s.sessionId,e.hubUrl).catch(()=>{}),p;await lT(s.sessionId,Math.max(0,performance.now()-c),e.hubUrl)}},cancel:async()=>{d||(d=!0,i.stop(),a.getTracks().forEach(m=>m.stop()),await Ag(s.sessionId,e.hubUrl).catch(()=>{}))}}}class FT{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(t,n){if(this.recorder&&this.targetSignature===n.signature)return;if(this.stop(),typeof MediaRecorder>"u"||typeof t.captureStream!="function")throw new Error("This browser does not support Last 30s.");const s=bw();if(!s)throw new Error("This browser does not support WebM recording.");this.targetSignature=n.signature,this.stream=t.captureStream(20),this.recorder=new MediaRecorder(this.stream,{mimeType:s,videoBitsPerSecond:3e6}),this.startedAt=performance.now(),this.recorder.ondataavailable=a=>{if(!a.data.size)return;const i=performance.now();for(this.segments.push({blob:a.data,at:i}),this.totalBytes+=a.data.size;this.segments.length>1&&(i-this.segments[0].at>this.maxDurationMs||this.totalBytes>this.maxBytes);){const c=this.segments.shift();this.totalBytes-=c.blob.size}},this.recorder.start(1e3)}stop(){const t=this.recorder;this.recorder=null,t&&t.state!=="inactive"&&(t.ondataavailable=null,t.stop()),this.stream?.getTracks().forEach(n=>n.stop()),this.stream=null,this.segments=[],this.totalBytes=0,this.startedAt=0}async save(t,n){if(this.segments.length===0)throw new Error("The Last 30s buffer is not ready yet.");const s=new Blob(this.segments.map(c=>c.blob),{type:this.segments[0].blob.type||"video/webm"}),i=`LiveDesk_Last30s_${t.label.replace(/[^a-zA-Z0-9._-]+/g,"-").slice(0,70)||"Wall"}_${new Date().toISOString().replace(/[-:]/g,"").replace(/\.\d{3}Z$/,"").replace("T","_")}.webm`;return await ow(s,{kind:"last-30s",fileName:i,target:t,durationMs:Math.min(3e4,this.segments.length*1e3)},n)}}async function DT(e,t,n,s,a){const i=await vw({canvas:e,target:t,kind:"timelapse",fps:30,frameRequests:!0,hubUrl:s,onError:a});i.requestFrame?.();const c=window.setInterval(()=>i.requestFrame?.(),Math.max(5,n)*1e3);return{stop:async()=>{window.clearInterval(c),await i.stop()},cancel:async()=>{window.clearInterval(c),await i.cancel()}}}const ww="livedesk.captureSettings";function LT(){const e={rollingEnabled:!1,recordingQuality:"standard",timelapseIntervalSeconds:10,includeRemoteCursor:!0};try{const t=JSON.parse(localStorage.getItem(ww)||"null");return{...e,...t&&typeof t=="object"?t:{}}}catch{return e}}function _T(e){const[t,n]=o.useState(LT),[s,a]=o.useState(0),[i,c]=o.useState(0),[u,d]=o.useState(0),[p,h]=o.useState(!1),m=o.useRef(void 0),g=o.useRef(!1),w=o.useRef(""),v=o.useRef(null),y=o.useRef(null),k=o.useRef(null),N=o.useRef(null),C=o.useRef(new FT),A=e.sourceRegistry.resolveCurrentTarget(),E=NT(A),I=RT(A),F=typeof MediaRecorder<"u"&&typeof HTMLCanvasElement<"u"&&"captureStream"in HTMLCanvasElement.prototype;o.useEffect(()=>{if(localStorage.setItem(ww,JSON.stringify(t)),!g.current)return;const re=JSON.stringify(t);re!==w.current&&(w.current=re,Oe("/api/settings",{method:"PATCH",body:JSON.stringify({revision:m.current,filesAudio:{rollingBufferEnabled:t.rollingEnabled,recordingQuality:t.recordingQuality,timelapseIntervalSeconds:t.timelapseIntervalSeconds,includeRemoteCursor:t.includeRemoteCursor}})},e.hubUrl).then(de=>{m.current=Number(de.revision||m.current||0)}).catch(()=>{}))},[e.hubUrl,t]),o.useEffect(()=>{let re=!0;return Oe("/api/settings",void 0,e.hubUrl).then(de=>{if(!re)return;const Q=de.settings?.filesAudio||{},ge=typeof Q.rollingBufferEnabled=="boolean"?Q.rollingBufferEnabled:t.rollingEnabled,oe=Q.recordingQuality==="high"?"high":"standard",me=[5,10,30,60].includes(Number(Q.timelapseIntervalSeconds))?Number(Q.timelapseIntervalSeconds):t.timelapseIntervalSeconds,Ae=typeof Q.includeRemoteCursor=="boolean"?Q.includeRemoteCursor:t.includeRemoteCursor,Te={rollingEnabled:ge,recordingQuality:oe,timelapseIntervalSeconds:me,includeRemoteCursor:Ae};m.current=Number(de.revision||0),w.current=JSON.stringify(Te),g.current=!0,n(Te)}).catch(()=>{g.current=!0}),()=>{re=!1}},[e.hubUrl]);const M=o.useCallback(async re=>{if(re.sourceCanvas&&re.sourceCanvas.width>0&&re.sourceCanvas.height>0)return{target:Fg(re),canvas:re.sourceCanvas,cleanup:()=>{}};const de=await e.sourceRegistry.composeWall(re.deviceIds,{maxWidth:1920,maxHeight:1080,includeLabels:!0});let Q=!1;const ge=window.setInterval(async()=>{if(Q)return;const oe=await e.sourceRegistry.composeWall(re.deviceIds,{maxWidth:1920,maxHeight:1080,includeLabels:!0}).catch(()=>null);!oe||Q||((de.width!==oe.width||de.height!==oe.height)&&(de.width=oe.width,de.height=oe.height),de.getContext("2d")?.drawImage(oe,0,0))},100);return{target:Fg(re),canvas:de,cleanup:()=>{Q=!0,window.clearInterval(ge)}}},[e.sourceRegistry]);o.useEffect(()=>{const re=C.current;if(!t.rollingEnabled||!A||!F){re.stop(),d(0);return}let de=!1,Q=null;return(async()=>{try{if(Q=await M(A),de)return;await re.start(Q.canvas,Q.target);const oe=window.setInterval(()=>d(Math.round(re.seconds)),500),me=()=>{window.clearInterval(oe),Q?.cleanup()};re.__cleanup=me}catch(oe){de||e.onToast(oe instanceof Error?oe.message:String(oe))}})(),()=>{de=!0,re.stop(),re.__cleanup?.(),re.__cleanup=void 0,d(0)}},[M,e.onToast,t.rollingEnabled,E,F]);const H=o.useCallback(re=>n(de=>({...de,rollingEnabled:re})),[]),V=o.useCallback(re=>n(de=>({...de,recordingQuality:re})),[]),P=o.useCallback(re=>n(de=>({...de,timelapseIntervalSeconds:re})),[]),D=o.useCallback(async()=>{const re=e.sourceRegistry.resolveCurrentTarget();if(!re)throw new Error("화면이 준비된 후 다시 시도하세요.");h(!0);let de=null;try{de=await M(re),await jT(de.canvas,de.target,e.hubUrl),e.onToast("Screenshot saved")}finally{de?.cleanup(),h(!1)}},[M,e.hubUrl,e.onToast,e.sourceRegistry]),O=o.useCallback(async()=>{if(k.current)throw new Error("Stop the timelapse before recording.");const re=e.sourceRegistry.resolveCurrentTarget();if(!re)throw new Error("화면이 준비된 후 다시 시도하세요.");const de=await M(re),Q=await vw({canvas:de.canvas,target:de.target,fps:re.type==="control"?30:15,hubUrl:e.hubUrl,onError:ge=>e.onToast(ge.message)});y.current=de.cleanup,v.current=Q,a(Date.now()),e.onToast("Recording started")},[M,e.hubUrl,e.onToast,e.sourceRegistry]),X=o.useCallback(async()=>{const re=v.current;if(re){h(!0);try{await re.stop(),e.onToast("Recording saved")}finally{v.current=null,y.current?.(),y.current=null,a(0),h(!1)}}},[e.onToast]),G=o.useCallback(async()=>{if(v.current||k.current)throw new Error("Last 30s is unavailable during a recording.");const re=e.sourceRegistry.resolveCurrentTarget();if(!re)throw new Error("화면이 준비된 후 다시 시도하세요.");h(!0);try{await C.current.save(re,e.hubUrl),e.onToast("Last 30 seconds saved")}finally{h(!1)}},[e.hubUrl,e.onToast,e.sourceRegistry]),U=o.useCallback(async()=>{if(v.current)throw new Error("Stop the recording before starting a timelapse.");const re=e.sourceRegistry.resolveCurrentTarget();if(!re)throw new Error("화면이 준비된 후 다시 시도하세요.");const de=await M(re),Q=await DT(de.canvas,de.target,t.timelapseIntervalSeconds,e.hubUrl,ge=>e.onToast(ge.message));N.current=de.cleanup,k.current=Q,c(Date.now()),e.onToast("Timelapse started")},[M,e.hubUrl,e.onToast,e.sourceRegistry,t.timelapseIntervalSeconds]),ie=o.useCallback(async()=>{const re=k.current;if(re){h(!0);try{await re.stop(),e.onToast("Timelapse saved")}finally{k.current=null,N.current?.(),N.current=null,c(0),h(!1)}}},[e.onToast]);return o.useEffect(()=>{const re=de=>{!v.current&&!k.current||(de.preventDefault(),de.returnValue="")};return window.addEventListener("beforeunload",re),()=>window.removeEventListener("beforeunload",re)},[]),o.useEffect(()=>()=>{C.current.stop(),v.current?.cancel(),k.current?.cancel(),y.current?.(),N.current?.()},[]),{state:o.useMemo(()=>({recording:!!v.current,recordingStartedAt:s,timelapse:!!k.current,timelapseStartedAt:i,bufferSeconds:u,bufferEnabled:t.rollingEnabled,busy:p,targetLabel:I}),[u,p,s,t.rollingEnabled,I,i]),settings:t,videoSupported:F,targetKey:E,setRollingEnabled:H,setRecordingQuality:V,setTimelapseInterval:P,takeScreenshot:D,startRecording:O,stopRecording:X,saveLast30Seconds:G,startTimelapse:U,stopTimelapse:ie}}function $T(){if(typeof window>"u")return{isIos:!1,isAndroid:!1,isSafari:!1,browserName:"browser"};const e=window.navigator.userAgent,t=window.navigator.standalone,n=ak(e,window.navigator.platform,window.navigator.maxTouchPoints,t),s=/Android/i.test(e),a=n&&/CriOS/i.test(e),i=n&&/Safari/i.test(e)&&!/(CriOS|FxiOS|EdgiOS|OPiOS|DuckDuckGo)/i.test(e);return{isIos:n,isAndroid:s,isSafari:i,browserName:a?"Chrome":i?"Safari":"browser"}}const OT=120,BT=999,yw="livedesk.remoteDirectory",Fp="livedesk.localHubAccessEnabled",HT="livedesk.streamSettings",WT=18,zT="livedesk.controlStreamSettings",qT=10,xw="livedesk.wallCadence",Sw="livedesk.wallViewScale",Cw="livedesk.mobileWallStatsVisible",UT=1e3,kw="livedesk.wallMonitorSelections",Mw=2,Gd=512*1024,VT=250,GT=15e3,KT=!1;function QT(){return typeof navigator>"u"?!1:/Mac|iPhone|iPad|iPod/i.test(`${navigator.platform} ${navigator.userAgent}`)}function YT(e){let t="";for(let n=0;n<e.length;n+=32*1024)t+=String.fromCharCode(...e.subarray(n,Math.min(e.length,n+32*1024)));return window.btoa(t)}function Dg(e){const t=window.atob(String(e||"")),n=new Uint8Array(t.length);for(let s=0;s<t.length;s+=1)n[s]=t.charCodeAt(s);return n}async function Aw(e){const t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t),n=>n.toString(16).padStart(2,"0")).join("")}async function XT(e){const t=navigator.clipboard;let n="text",s="clipboard.txt",a="text/plain",i=null;if(typeof t?.read=="function"){const u=await t.read(),d=u.find(p=>p.types.includes("image/png"));if(d){const p=await d.getType("image/png");n="image",s="clipboard.png",a="image/png",i=new Uint8Array(await p.arrayBuffer())}else{const p=u.find(h=>h.types.includes("text/plain"));if(p){const h=await p.getType("text/plain");i=new TextEncoder().encode(await h.text())}}}if(!i&&typeof t?.readText=="function"&&(i=new TextEncoder().encode(await t.readText())),!i)throw new Error("The browser did not provide text or a PNG image from the clipboard.");return{manifest:yp({operationId:e,contentKind:n,totalBytes:i.byteLength,items:[{itemIndex:0,kind:n,name:s,mimeType:a,size:i.byteLength,lastModified:Date.now(),sha256:await Aw(i),storageName:"item-0.bin"}]},e),payloads:[i]}}async function JT(e){const{manifest:t,payloads:n}=e,s=n[0];if(!s||t.items.length!==1)throw new Error("clipboard-browser-snapshot-invalid");if(t.contentKind==="text"){await navigator.clipboard.writeText(new TextDecoder().decode(s));return}if(t.contentKind==="image"&&typeof ClipboardItem<"u"){await navigator.clipboard.write([new ClipboardItem({"image/png":new Blob([s],{type:"image/png"})})]);return}throw new Error("Multiple files require the LiveDesk desktop app.")}"".trim();"".trim();const ZT=Object.freeze([{code:"ShiftLeft",label:"Shift"},{code:"ControlLeft",label:"Ctrl"},{code:"AltLeft",label:"Alt"},{code:"MetaLeft",label:"Win"}]),eP=1e3/60,Kd=1500,tP=650,nP=1800,rP=650,sP=2500,Qd=1500,Lg=15e3,_g=120,aP=.72,Nw=6,iP=640*360,oP=8;function cP(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t=Math.imul(t^e.charCodeAt(n),16777619);return(t>>>0)%Nw}const $g=100,Og=20,lP=6e4,uP=6e4,Bg=240,dP=1024,pP=640,mP=360,Hg="Connected LiveDesk clients are updating in batches. Hub will restart after every target reconnects on the requested versions.",Hl="LiveDesk is replacing the Hub and verifying the requested version.",Wl=5*6e4,hP=5e3,Wg=2e3,fP=8e3;function zg(e,t){return`${e}:${t.deviceId}:${t.completedAt||t.candidateSessionId||t.commandId||"completed"}`}function Ba({label:e,tooltip:t,disabled:n=!1,active:s=!1,danger:a=!1,pressed:i,onClick:c,children:u}){return r.jsx("span",{className:`manual-action-tooltip ${n?"disabled":""}`.trim(),"data-tooltip":t,children:r.jsx("button",{className:`manual-action ${s?"active":""} ${a?"danger":""}`.trim(),onClick:c,disabled:n,"aria-label":e,"aria-pressed":i,type:"button",children:u})})}function gP(e,t){if(t.deviceId!==e.deviceId)return!1;const n=Number(t.browserReceivedEpochMs);if(!Number.isFinite(n)||n<e.startedAtEpochMs)return!1;const s=Number(t.monitorIndex);if(Number.isFinite(s)&&Math.floor(s)!==e.monitorIndex)return!1;const a=String(t.frameMode||t.mode||"").trim().toLowerCase();return!a||a===e.frameMode}const bP={"mode3-h264-hw":30};function qg(e,t){const n=c=>{const d=String(c||"").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(!d)return null;const p=d[4]?d[4].split(".").map(h=>/^\d+$/.test(h)?h.length>1&&h.startsWith("0")?Number.NaN:Number(h):h):[];return p.some(h=>typeof h=="number"&&!Number.isFinite(h))?null:{core:[Number(d[1]),Number(d[2]),Number(d[3])],prerelease:p}},s=n(e),a=n(t);if(!s||!a)return!1;for(let c=0;c<3;c+=1){if(s.core[c]>a.core[c])return!0;if(s.core[c]<a.core[c])return!1}if(s.prerelease.length===0||a.prerelease.length===0)return s.prerelease.length===0;const i=Math.max(s.prerelease.length,a.prerelease.length);for(let c=0;c<i;c+=1){const u=s.prerelease[c],d=a.prerelease[c];if(u===void 0||d===void 0)return d===void 0;if(u!==d){if(typeof u=="number"&&typeof d=="number")return u>d;if(typeof u=="number")return!1;if(typeof d=="number"||u>d)return!0;if(u<d)return!1}}return!0}const vP=1024;function Ut(e,t){return`${e}:${t}`}function as(e){return[e.deviceId,e.sessionId||"",e.streamId||"",e.commandId||"",Number(e.captureGeneration||0),Number(e.monitorIndex??-1),e.streamPurpose||""].join("|")}const wP={frameMode:"mode3-h264-hw",h264DecodeAcceleration:"prefer-hardware",fps:bP["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},yP={frameMode:"mode3-h264-hw",h264DecodeAcceleration:"prefer-hardware",fps:30,maxWidth:3840,maxHeight:2160,quality:75,showScreenStatus:!1},Ug={maxWidth:3840,maxHeight:2160};function Go(e,t){if(e.length===0)return 0;const n=[...e].sort((a,i)=>a-i),s=Math.max(0,Math.min(n.length-1,Math.ceil(n.length*t)-1));return n[s]}function Rw(e,t){e.push(t),e.length>Bg&&e.splice(0,e.length-Bg)}function zl(e,t){e.sampleFrames=0,e.sampleStartedAt=t,e.intervalCount=0,e.intervalSumMs=0,e.minIntervalMs=Number.POSITIVE_INFINITY,e.maxIntervalMs=0,e.intervalSamplesMs.length=0,e.seqGapCount=0,e.maxSeqGap=0}function Vg(e,t,n){if(e.lastAt!==void 0){const s=Math.max(0,t-e.lastAt);e.intervalCount+=1,e.intervalSumMs+=s,e.minIntervalMs=Math.min(e.minIntervalMs,s),e.maxIntervalMs=Math.max(e.maxIntervalMs,s),Rw(e.intervalSamplesMs,s)}if(e.lastFrameSeq!==void 0){const s=n-e.lastFrameSeq;s!==1&&(e.seqGapCount+=1,e.maxSeqGap=Math.max(e.maxSeqGap,Math.abs(s)))}e.lastAt=t,e.lastFrameSeq=n}function Gg(e){return!e||e.intervalCount<=0?"waiting":`${Math.round(e.averageIntervalMs)}ms avg / p95 ${Math.round(e.p95IntervalMs)}ms / max ${Math.round(e.maxIntervalMs)}ms`}function Kg(e){return!e||e.seqGapCount<=0?"none":`${e.seqGapCount} gaps / max ${e.maxSeqGap}`}function xP(e){return Number.isFinite(e)?String(e):"30+"}const Tw=[1,2,5,8,12,20,30],Qg={large:{maxWidth:1920,maxHeight:1080},medium:{maxWidth:1280,maxHeight:720},list:{maxWidth:960,maxHeight:540}},Fr={visibleRootMargin:"520px 0px 760px 0px",fallbackVisibleCounts:{large:12,medium:18,list:32},maxWallBytesPerSecond:80*1024*1024,maxFrameGapMs:280,downshiftCooldownMs:1800,downshiftStableSampleMs:$t.adaptiveDownshiftStableMs,downshiftConsecutiveSamples:$t.adaptiveDownshiftConsecutiveSamples,recoveryCooldownMs:14e3,minFps:5},Yg=2200,SP=2500,CP=8e3,kP=3500,MP=7e3,AP=2,NP=2500,RP=7e3,TP=2600,PP=4200,IP=750,jP=2,Xg=2500,Jg=4200,Zg=2200;function eb(e,t){return Math.min(3e4,e*2**Math.min(3,Math.max(0,t)))}function Xi(e,t){const n=e.capabilities?.[t];return typeof n=="boolean"?n:/^(1|true|yes|on)$/i.test(String(n||"").trim())}function dn(e){return e.deviceName||e.hostname||e.deviceId}function EP(){return"npx -y --prefer-online livedesk@latest client"}function FP(){return"npx -y --prefer-online livedesk@latest"}function DP(){try{return localStorage.getItem(yw)||""}catch{return""}}function LP(){try{return localStorage.getItem(Fp)==="1"}catch{return!1}}function Ki(e){try{e?localStorage.setItem(Fp,"1"):localStorage.removeItem(Fp)}catch{}}function Lr(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function os(e){const t=Lr(e.status),n=Lr(t.screens),s=Lr(e.capabilities),a=Lr(e.latestLiveFrame),i=Lr(e.activeLiveStream),u=[t.monitorCount,t.screenCount,n.count,s.monitorCount,s.screenCount,a.monitorCount,i.monitorCount,Array.isArray(n.displays)?n.displays.length:0,Array.isArray(t.displays)?t.displays.length:0,Array.isArray(t.monitors)?t.monitors.length:0].map(Number).filter(d=>Number.isFinite(d)&&d>0).map(d=>Math.max(1,Math.min(64,Math.floor(d))));return u.length>0?Math.max(...u):1}function Js(e){const t=Number(e);return Number.isFinite(t)&&t>0?Math.floor(t):0}function Pw(e){const t=Lr(e.status),s=[Lr(t.screens).displays,t.displays,t.monitors];for(const a of s)if(!(!Array.isArray(a)||a.length===0))return a.map(i=>Lr(i));return[]}function dm(e,t){const n=Pw(e),s=n.find(d=>Number(d.index)===t)||n[t]||n[0]||{},a=Js(s.width),i=Js(s.height),c=[s.name,s.displayName,s.deviceName,s.id].find(d=>typeof d=="string"&&d.trim()),u=typeof c=="string"?c.trim():`Display ${t+1}`;return{index:t,name:u,width:a,height:i,primary:s.primary===!0||s.isPrimary===!0}}function _P(e){const t=os(e);return Array.from({length:t},(n,s)=>dm(e,s))}function $P(e){const t=Pw(e);if(t.length===0)return"";const n=t.map((s,a)=>{const i=Number(s.index),c=[s.name,s.displayName,s.deviceName,s.id].find(d=>typeof d=="string"&&d.trim()),u=d=>{const p=Number(d);return Number.isFinite(p)?p:null};return[Number.isFinite(i)?Math.floor(i):a,typeof c=="string"?c.trim().toLowerCase():"",u(s.left),u(s.top),u(s.width),u(s.height),s.primary===!0||s.isPrimary===!0]}).sort((s,a)=>s[0]-a[0]);return JSON.stringify(n)}function OP(e){const t=[e.name||`Display ${e.index+1}`];return e.width>0&&e.height>0&&t.push(`${e.width}x${e.height}`),e.primary&&t.push("Primary"),t.join(" - ")}function Iw(e,t){const n=dm(e,t);if(n.width>0&&n.height>0)return{width:n.width,height:n.height};const s=Lr(e.status),a=Js(s.screenWidth||s.width),i=Js(s.screenHeight||s.height);return a>0&&i>0?{width:a,height:i}:null}function jw(e){if(!e)return null;const t=Js(e.sourceWidth)||Js(e.width),n=Js(e.sourceHeight)||Js(e.height);return t>0&&n>0?{width:t,height:n}:null}function BP(e,t,n){const i=((typeof t?.monitorIndex=="number"?Xo(t.monitorIndex,Math.max(1,t.monitorCount||1)):n)===n?jw(t):null)||Iw(e,n);return i?Math.max(.25,Math.min(4,i.width/i.height)):16/9}const ql=16/9;function Xo(e,t){const n=Math.max(1,Math.min(64,Math.floor(Number(t)||1))),s=Math.floor(Number(e));return Number.isFinite(s)?Math.max(0,Math.min(n-1,s)):0}function lr(e,t){return X0(t,os(e),e.platform)}function HP(){try{const e=localStorage.getItem(kw);if(!e)return{selections:{},topologyFingerprints:{}};const t=JSON.parse(e),n=t&&typeof t=="object"&&!Array.isArray(t)?t.selections:void 0;if(Number(t?.version)!==Mw||!n||typeof n!="object"||Array.isArray(n))return{selections:{},topologyFingerprints:{}};const s={},a={};for(const[i,c]of Object.entries(n)){const u=i.trim(),d=Lr(c),p=d.monitorIndex,h=Math.floor(Number(p));if(!u||!Number.isFinite(h))continue;s[u]=Math.max(0,Math.min(63,h));const m=typeof d.topologyFingerprint=="string"?d.topologyFingerprint.trim():"";m&&(a[u]=m)}return{selections:s,topologyFingerprints:a}}catch{return{selections:{},topologyFingerprints:{}}}}function WP(e,t){try{const n=Object.fromEntries(Object.entries(e).map(([s,a])=>[s,{monitorIndex:a,topologyFingerprint:t[s]||""}]));localStorage.setItem(kw,JSON.stringify({version:Mw,selections:n}))}catch{}}function zP(){return{...wP}}function qP(e){try{localStorage.setItem(HT,JSON.stringify({...e,version:WT}))}catch{}}function UP(){return{...yP}}function VP(e){try{localStorage.setItem(zT,JSON.stringify({...e,version:qT}))}catch{}}function GP(){try{return localStorage.getItem(xw)==="slow"?"slow":"fast"}catch{return"fast"}}function KP(e){try{localStorage.setItem(xw,e)}catch{}}function QP(){try{return localStorage.getItem(Cw)==="true"}catch{return!1}}function YP(e){try{localStorage.setItem(Cw,String(e))}catch{}}function XP(){try{const e=localStorage.getItem(Sw);return e===null?Za:hc(Number(e))}catch{return Za}}function JP(e){try{localStorage.setItem(Sw,String(hc(e)))}catch{}}function Yd(e,t){return e.length!==t.length?!1:e.every((n,s)=>n===t[s])}function Xd(e){return[...new Set(e.filter(Boolean))].sort()}function ZP(e){return Fr.fallbackVisibleCounts[e]||Fr.fallbackVisibleCounts.large}function tb(e,t,n){if(e.frameMode==="mode4-h264-atlas")return e.atlasTileSizeMode==="auto"?t==="large"?{maxWidth:640,maxHeight:360}:{maxWidth:320,maxHeight:180}:{maxWidth:e.atlasTileWidth,maxHeight:e.atlasTileHeight};if(!e.adaptiveSizeByWall)return{maxWidth:e.maxWidth,maxHeight:e.maxHeight};const s=Qg[t]||Qg.large;return{maxWidth:Math.min(e.maxWidth,s.maxWidth),maxHeight:Math.min(e.maxHeight,s.maxHeight)}}function eI(e,t=Fr.minFps){const n=[...Tw].sort((a,i)=>a-i),s=Math.max(t,Math.floor(e/2));return[...n].reverse().find(a=>a<e&&a>=t)||s}function tI(e,t){return[...Tw].sort((s,a)=>s-a).find(s=>s>e&&s<=t)||t}function Jo(e){if(!Number.isFinite(e)||e<=0)return"0 B";const t=["B","KB","MB","GB","TB"];let n=e,s=0;for(;n>=1024&&s<t.length-1;)n/=1024,s+=1;const a=s===0||n>=100?0:1;return`${n.toFixed(a)} ${t[s]}`}function nb(e){if(!Number.isFinite(e)||!e||e<=0)return"0GB";const t=1024**4,n=1024**3;return e>=t?`${Math.max(1,Math.round(e/t))}TB`:`${Math.max(1,Math.round(e/n))}GB`}function Jd(e,t){if(!Number.isFinite(e)||!e||e<=0)return"not reported";const n=Math.max(0,e-Math.max(0,Number(t||0)));return`${nb(n)} / ${nb(e)}`}function nI(e){const t=new Uint8Array(e),n=32768;let s="";for(let a=0;a<t.length;a+=n){const i=t.subarray(a,a+n);s+=String.fromCharCode(...i)}return btoa(s)}function rb(e){return Array.from(e).filter(t=>t.size>=0).map(t=>{const n=t.webkitRelativePath||t.name;return{file:t,relativePath:n,fingerprint:`${t.size}:${t.lastModified}`}})}function rI(e){return e===1?"middle":e===2?"right":"left"}function sb(e,...t){for(const n of t){const s=e?.[n];if(typeof s=="string"&&s.trim())return s.trim()}return""}function ab(e){const t=Number(e);return Number.isInteger(t)&&t>=1&&t<=BT?t:0}const sI={cpu:"CPU",memory:"MEM",disk:"Disk",gpu:"GPU",vram:"VRAM",npu:"NPU",temp:"Temp",network:"Net"};function aI(e,t,n){if(e==="online")return"Online";if(e==="busy")return"Busy";if(e==="stale")return"Stale";if(e==="offline")return"Offline";if(n==="failed")return"Task failed";const s=e==="critical"?"critical":"warn",a=t.find(c=>c.state===s)||t.find(c=>c.state==="critical"||c.state==="warn");if(!a)return e==="critical"?"Issue":"Check";const i=sI[a.id]||a.label;return a.value&&a.value!=="-"?`${i} ${a.value}`:i}function Ew(e,t){const n=t.split(".");let s=e;for(const a of n){if(s==null)return;if(Array.isArray(s)){const i=Number(a);s=Number.isInteger(i)?s[i]:void 0;continue}if(typeof s=="object"){s=s[a];continue}return}return s}function Wt(e,...t){for(const n of t){const s=Ew(e,n),a=Number(s);if(Number.isFinite(a))return a}}function is(e,...t){for(const n of t){const s=Ew(e,n);if(typeof s=="string"&&s.trim())return s.trim();if(typeof s=="number"&&Number.isFinite(s))return String(s)}return""}function As(e){const t=Number(e);if(Number.isFinite(t))return Math.max(0,Math.min(1,t>1?t/100:t))}function Zd(e,t){if(!(typeof e!="number"||typeof t!="number"||!Number.isFinite(e)||!Number.isFinite(t)||e<=0))return As((e-Math.max(0,t))/e)}function Qi(e){return e===void 0?"-":`${Math.round(e*100)}%`}function ep(e){return e===void 0||!Number.isFinite(e)?"":e>=1e3?`${(e/1e3).toFixed(e>=1e4?0:1)}Gb/s`:`${Math.round(e)}Mb/s`}function Ha(e,t=.92,n=.78){return e===void 0?"unknown":e>=t?"critical":e>=n?"warn":"good"}function iI(e){return!Number.isFinite(e)||!e||e<=0?"-":e<3600?`${Math.round(e/60)}m`:e<86400?`${Math.round(e/3600)}h`:`${Math.round(e/86400)}d`}function Fw(e){const t=e.status||{},n=Wt(t,"cpu.cores","cpuCores","processorCount"),s=Wt(t,"loadavg.0","cpu.load1"),a=As(Wt(t,"cpu.usedRatio","cpu.usageRatio","cpu.ratio","cpu.usedPct","cpu.usagePct","cpu.percent")??(n&&s!==void 0?s/Math.max(1,n):void 0)),i=Wt(t,"memory.totalBytes","totalMem"),c=Wt(t,"memory.freeBytes","freeMem"),u=As(Wt(t,"memory.usedRatio","memory.usedPct","usedMemRatio"))??Zd(i,c),d=Wt(t,"disk.totalBytes","rootDisk.totalBytes","storage.totalBytes"),p=Wt(t,"disk.freeBytes","rootDisk.freeBytes","storage.freeBytes"),h=As(Wt(t,"disk.usedRatio","disk.usedPct","rootDisk.usedRatio","storage.usedRatio"))??Zd(d,p),m=Wt(t,"thermal.cpuC","temperatureC","cpu.temperatureC","gpu.temperatureC"),g=As(Wt(t,"gpu.usedRatio","gpu.usageRatio","gpu.usedPct","gpu.usagePct","gpu.percent","accelerators.gpu.usageRatio")),w=is(t,"gpu.name","gpu.model","accelerators.gpu.name"),v=Wt(t,"gpu.memory.totalBytes","gpu.totalMemoryBytes","gpu.vramTotalBytes"),y=Wt(t,"gpu.memory.freeBytes","gpu.freeMemoryBytes","gpu.vramFreeBytes"),k=As(Wt(t,"gpu.memory.usedRatio","gpu.vramUsedRatio"))??Zd(v,y),N=Wt(t,"gpu.temperatureC","thermal.gpuC"),C=As(Wt(t,"npu.usedRatio","npu.usageRatio","npu.usedPct","npu.usagePct","npu.percent","accelerators.npu.usageRatio")),A=is(t,"npu.name","npu.model","accelerators.npu.name"),E=Wt(t,"npu.tops","npu.topsInt8","accelerators.npu.tops"),I=Wt(t,"network.rxMbps","network.receiveMbps","network.downMbps"),F=Wt(t,"network.txMbps","network.transmitMbps","network.upMbps"),M=Wt(t,"network.latencyMs","network.rttMs"),H=As(Wt(t,"network.usedRatio","network.usageRatio","network.saturationRatio")),V=is(t,"network.link","network.interface","network.name"),P=Math.max(m??Number.NEGATIVE_INFINITY,N??Number.NEGATIVE_INFINITY),D=Number.isFinite(P)?P:void 0,O=D===void 0?void 0:As((D-35)/60),X=m!==void 0&&N!==void 0?`CPU ${Math.round(m)}° · GPU ${Math.round(N)}°`:m!==void 0?`CPU ${Math.round(m)}°`:N!==void 0?`GPU ${Math.round(N)}°`:"-",G=is(t,"workload.role","role","lane")||(Xi(e,"taskDispatch")?"Command-ready Client":"Local machine"),U=is(e.latestTask,"status")||is(t,"workload.status")||"idle",ie=is(e.latestTask,"title","instructionPreview")||is(t,"workload.title"),j=is(e.latestTask,"resultSummary","error","instructionPreview")||is(t,"workload.summary"),re=Date.parse(e.lastSeenAt||e.connectedAt||""),de=Number.isFinite(re)?Date.now()-re:0;let Q="online";e.connected?de>5*6e4?Q="stale":(m??0)>=86||(N??0)>=88||(a??0)>=.94||(g??0)>=.96||(k??0)>=.96||(C??0)>=.96||(u??0)>=.94||(h??0)>=.94||(M??0)>=200||U==="failed"?Q="critical":(m??0)>=78||(N??0)>=80||(a??0)>=.82||(g??0)>=.86||(k??0)>=.88||(C??0)>=.86||(u??0)>=.82||(h??0)>=.86||(M??0)>=80?Q="warn":["queued","running","targeted"].includes(U)&&(Q="busy"):Q="offline";const ge=[{id:"cpu",label:"CPU",value:Qi(a),detail:n?`${n} cores`:s!==void 0?`load ${s.toFixed(1)}`:"not reported",ratio:a,state:Ha(a,.92,.78)},{id:"memory",label:"RAM",value:Qi(u),detail:Jd(i,c),ratio:u,state:Ha(u,.92,.78)},{id:"disk",label:"DISK",value:Qi(h),detail:Jd(d,p),ratio:h,state:Ha(h,.92,.82)},{id:"gpu",label:"GPU",value:Qi(g),detail:w||(v&&y!==void 0?`${Jo(y)} VRAM free`:N!==void 0?`${Math.round(N)}C`:"not reported"),ratio:g,state:N!==void 0&&N>=88?"critical":N!==void 0&&N>=80?"warn":Ha(g,.96,.86)},{id:"vram",label:"VRAM",value:Qi(k),detail:Jd(v,y),ratio:k,state:Ha(k,.96,.88)},{id:"npu",label:"NPU",value:C!==void 0?Qi(C):E!==void 0?`${Math.round(E)} TOPS`:"-",detail:A||(E!==void 0?"neural engine":"not reported"),ratio:C,state:Ha(C,.96,.86)},{id:"temp",label:"TEMP",value:X,detail:`uptime ${iI(Wt(t,"uptimeSec"))}`,ratio:O,state:D===void 0?"unknown":D>=86?"critical":D>=78?"warn":"good"},{id:"network",label:"NET",value:ep(I)||(M!==void 0?`${Math.round(M)}ms`:V||"-"),detail:ep(F)?`${ep(F)} up`:V||"not reported",ratio:H,state:M!==void 0&&M>=200?"critical":M!==void 0&&M>=80?"warn":Ha(H,.9,.75)}];return{state:Q,label:aI(Q,ge,U),role:G,taskLabel:ie||(U==="idle"?"idle":U),taskStatus:U,taskSummary:j,metrics:ge}}const oI=[{id:"slow",label:"Slow",fps:Ap("slow")},{id:"fast",label:"Fast",fps:Ap("fast")}],cI=[{id:"list",label:"List"},{id:"medium",label:"Small"},{id:"large",label:"Large"}],lI=[{id:"sync-server",label:"Hub",icon:ls,accent:"blue",tooltip:"hub"},{id:"wall",label:"Wall",icon:Mb,accent:"blue",tooltip:"wall"},{id:"control",label:"Control",icon:Ko,accent:"red",tooltip:"control"},{id:"share-files",label:"Share Files",icon:tc,accent:"green",tooltip:"share-files"},{id:"agents",label:"Agents",icon:Gl,accent:"violet",tooltip:"agents"}],uI=[{id:"doc",label:"Doc",icon:tu,accent:"amber"},{id:"support",label:"Support",icon:Zo,accent:"violet"},{id:"pricing",label:"Pricing",icon:ec,accent:"green"}];function dI(e){return e.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 _t(e){return dI(e).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 Wa(e){return e.map(t=>_t(t))}function In(e){return{languageName:e.languageName,languageLabel:e.languageLabel,eyebrow:e.eyebrow,title:_t(e.title),intro:_t(e.intro),sections:[{title:_t(e.managerTitle),body:_t(e.managerBody),points:Wa(e.managerPoints)},{title:_t(e.clientTitle),body:_t(e.clientBody),points:Wa(e.clientPoints)},{title:_t(e.syncTitle),body:_t(e.syncBody),points:Wa(e.syncPoints)},...e.agentTitle&&e.agentBody&&e.agentPoints?[{title:_t(e.agentTitle),body:_t(e.agentBody),points:Wa(e.agentPoints)}]:[],{title:_t(e.platformTitle),body:_t(e.platformBody),points:Wa(e.platformPoints)}],sync:{title:_t(e.syncTitle),body:_t(e.syncBody),points:Wa(e.syncPoints)},firewall:{title:_t(e.firewallTitle),body:_t(e.firewallBody),points:Wa(e.firewallPoints)},commands:{title:_t(e.commandsTitle),body:_t(e.commandsBody),manager:_t(e.managerCommandLabel),primary:_t(e.clientCommandLabel),slot:_t(e.slotCommandLabel),manual:_t(e.manualCommandLabel)}}}const no={ko:In({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:In({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:In({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":In({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":In({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:In({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:In({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:In({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":In({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:In({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:In({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:In({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:In({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:In({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:In({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:In({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(no).map(([e,t])=>({id:e,label:t.languageName}));function mI(){if(typeof navigator>"u")return"en";const e=navigator.languages?.length?navigator.languages:[navigator.language];for(const t of e){const n=t.toLowerCase();if(no[t])return t;if(n.startsWith("zh-tw")||n.startsWith("zh-hk"))return"zh-TW";if(n.startsWith("pt"))return"pt-BR";const s=n.split("-")[0];if(no[s])return s}return"en"}function ib({index:e}){const t=e+1;return r.jsx("article",{className:"device-tile placeholder-tile","aria-label":`Empty slot ${t}`,children:r.jsxs("div",{className:"tile-screen","aria-hidden":"true",children:[r.jsx("span",{className:"slot-grid","aria-hidden":"true"}),r.jsxs("span",{className:"empty-screen",children:[r.jsx(pn,{size:24}),r.jsxs("strong",{children:["Slot ",String(t).padStart(3,"0")]})]})]})})}const hI=["cpu","gpu","memory","vram","network","disk","temp"];function fI({device:e,slotNumber:t,selected:n,updateIndicator:s,remoteDiagnostics:a,diagnosticsMode:i="remote",onSelect:c,onOpenControl:u}){const d=Fw(e),p=new Map(d.metrics.map(m=>[m.id,m])),h=s?.label||d.label;return r.jsxs("div",{className:`wall-device-list-row state-${d.state} ${n?"selected":""}`,role:"row","aria-selected":n,tabIndex:0,onClick:c,onDoubleClick:m=>{m.preventDefault(),u()},onKeyDown:m=>{(m.key==="Enter"||m.key===" ")&&(m.preventDefault(),c())},children:[r.jsxs("span",{className:"wall-device-name",role:"gridcell",children:[r.jsx("span",{className:"wall-device-icon","aria-hidden":"true",children:r.jsx(pn,{size:17})}),r.jsxs("span",{children:[r.jsx("strong",{children:dn(e)}),r.jsxs("small",{children:["Slot ",String(t).padStart(3,"0"),e.platform?` · ${e.platform}`:"",e.arch?` · ${e.arch}`:""]})]}),n&&r.jsx(Rs,{size:16,strokeWidth:3,"aria-label":"Selected"})]}),r.jsxs("span",{className:`wall-device-list-status state-${d.state} ${s?`update-${s.state}`:""}`,role:"gridcell",title:s?.error||h,children:[r.jsx("i",{"aria-hidden":"true"}),r.jsx("strong",{children:h})]}),hI.map(m=>{const g=p.get(m);return r.jsxs("span",{className:`wall-device-list-metric state-${g?.state||"unknown"}`,role:"gridcell",title:g?`${g.label}: ${g.value} · ${g.detail}`:"Not reported",children:[r.jsx("strong",{children:g?.value||"-"}),r.jsx("small",{children:g?.detail||"not reported"}),g?.ratio!==void 0&&r.jsx("i",{style:{width:`${Math.round(g.ratio*100)}%`},"aria-hidden":"true"})]},m)}),a&&r.jsx("span",{className:"wall-device-list-diagnostics",role:"gridcell",children:r.jsx(lw,{items:a,mode:i})})]})}function gI(e){if(!e)return!1;const t=String(e.platform||"").trim().toLowerCase();return cs(t)&&e.capabilities?.screenRecordingPermission===!1}function cs(e){const t=String(e||"").trim().toLowerCase();return t==="macos"||t==="darwin"||t==="mac"||t==="macosx"}function bI(e){const t=String(e||"").trim().toLowerCase();return t==="linux"||t.startsWith("linux ")}function ob(e){const t=String(e||"").trim().toLowerCase();return["win32","windows","win32nt"].includes(t)?"mode5-lzo-delta":cs(t)?"mode1-jpeg":""}function tp({device:e,frame:t,selected:n,controlEnabled:s,showStatus:a,showDeviceTitle:i=!0,monitorIndex:c,monitorCount:u,onSelect:d,onFocusDevice:p,onOpenControl:h,onCycleMonitor:m,onCanvasReady:g,sendInput:w,remoteModifierState:v,updateIndicator:y,presentationReady:k,showPresentationSpinner:N=!1,remoteDiagnostics:C,diagnosticsMode:A="remote"}){const E=o.useRef(null),I=o.useRef(null),F=o.useRef(null),M=o.useRef(0),H=o.useRef(null),V=o.useRef(null),P=o.useRef(new Map),D=o.useRef(null),O=o.useRef(L0()),X=o.useRef(ou()),G=o.useRef(null),U=o.useRef(null),ie=Fw(e),j=["cpu","gpu","memory","vram"].map(R=>ie.metrics.find(se=>se.id===R)).filter(R=>!!R),re=Kp(c),de=u>1,Q=k??!!t,ge=gI(e)&&!Q,oe=N&&e.connected&&!Q&&!ge,me=BP(e,t,re),Ae=me>=ql?100:me/ql*100,Te=me>=ql?ql/me*100:100,Pe={"--screen-aspect":me.toFixed(5),"--screen-content-width":`${Math.max(1,Math.min(100,Ae)).toFixed(3)}%`,"--screen-content-height":`${Math.max(1,Math.min(100,Te)).toFixed(3)}%`},Se=s?{transformOrigin:"0 0",transform:`translate3d(${X.current.translateX.toFixed(2)}px, ${X.current.translateY.toFixed(2)}px, 0) scale(${X.current.scale.toFixed(4)})`}:void 0,te=o.useCallback(R=>{X.current=R;const se=E.current;se&&(se.style.transformOrigin="0 0",se.style.transform=`translate3d(${R.translateX.toFixed(2)}px, ${R.translateY.toFixed(2)}px, 0) scale(${R.scale.toFixed(4)})`,se.dataset.touchZoom=R.scale.toFixed(2))},[]),Ce=o.useCallback(R=>{if(E.current=R,R&&s){const se=X.current;R.style.transformOrigin="0 0",R.style.transform=`translate3d(${se.translateX.toFixed(2)}px, ${se.translateY.toFixed(2)}px, 0) scale(${se.scale.toFixed(4)})`,R.dataset.touchZoom=se.scale.toFixed(2)}g(e.deviceId,R)},[s,e.deviceId,g]),Fe=(R,se,Ie)=>D0(R,se,Ie.getBoundingClientRect()),Le=R=>Fe(R.clientX,R.clientY,R.currentTarget),Ue=R=>q0(R,v),ne=o.useCallback(()=>{H.current!==null&&(window.cancelAnimationFrame(H.current),H.current=null)},[]),ae=o.useCallback(()=>{const R=G.current;R&&(window.clearTimeout(R.timerId),G.current=null);const se=U.current;se&&window.clearTimeout(se.timerId),U.current=null},[]),le=o.useCallback(()=>{const R=F.current;if(!R)return;F.current=null;const se=Number(R.input.normalizedX),Ie=Number(R.input.normalizedY);if(!Number.isFinite(se)||!Number.isFinite(Ie))return;w(e.deviceId,{...R.input,normalizedX:se,normalizedY:Ie})&&(M.current=performance.now())},[e.deviceId,w]),ce=o.useCallback(()=>{H.current===null&&(H.current=window.requestAnimationFrame(()=>{H.current=null,le()}))},[le]);o.useEffect(()=>{const R=ou();return te(R),()=>{ne(),ae(),F.current=null,V.current=null,P.current.clear(),D.current=null}},[re,te,ae,ne,s,e.deviceId]);const J=(R,se)=>{if(!s)return;const Ie={...R,type:se};if(se==="pointermove"){const He=performance.now();F.current={input:Ie},He-M.current>=eP&&(ne(),le()),ce();return}F.current&&(ne(),le()),w(e.deviceId,Ie)},ye=(R,se)=>{J({monitorIndex:re,...Le(R),button:rI(R.button),...Ue(R)},se)},ue=(R,se)=>{w(e.deviceId,{...R,type:"pointerdown",button:se}),w(e.deviceId,{...R,type:"pointerup",button:se})},Ee=(R,se,Ie)=>({monitorIndex:re,...Fe(R,se,Ie),shiftKey:!!v?.shiftKey,ctrlKey:!!v?.ctrlKey,altKey:!!v?.altKey,metaKey:!!v?.metaKey}),nt=(R,se)=>{const Ie=G.current;Ie&&(window.clearTimeout(Ie.timerId),G.current=null,ue(Ie.input,"left"));const He={tap:R,input:se,timerId:0};He.timerId=window.setTimeout(()=>{G.current===He&&(G.current=null,ue(se,"left"))},xp),G.current=He},T=(R,se,Ie)=>{if(P.current.set(R,{clientX:se,clientY:Ie}),D.current)return;const He=V.current;if(He&&He.pointerId!==R){const rt=P.current.get(He.pointerId),Ke=P.current.get(R),gt=I.current?.getBoundingClientRect();rt&&Ke&&gt&&(ne(),F.current=null,ae(),V.current=null,D.current={gesture:_0(rt,Ke,X.current,gt),pointerIds:[He.pointerId,R]});return}const Be=performance.now(),xe=G.current,Ge={clientX:se,clientY:Ie,at:Be};if(xe&&Cf(xe.tap,Ge)){window.clearTimeout(xe.timerId),G.current=null;const rt={...xe,timerId:0};rt.timerId=window.setTimeout(()=>{U.current===rt&&(U.current=null,ue(rt.input,"left"))},Math.max(0,xe.tap.at+xp-Be)),U.current=rt}else U.current=null,xe&&(window.clearTimeout(xe.timerId),G.current=null,ue(xe.input,"left"));V.current=O0(R,se,Ie),p()},ve=(R,se,Ie,He)=>{P.current.set(R,{clientX:se,clientY:Ie});const Be=D.current;if(Be){const rt=P.current.get(Be.pointerIds[0]),Ke=P.current.get(Be.pointerIds[1]);rt&&Ke&&te($0(Be.gesture,rt,Ke));return}const xe=V.current;if(!xe||xe.pointerId!==R)return;const Ge=gv(xe,R,se,Ie);if(V.current=Ge,Ge?.dragged&&U.current){const rt=U.current;window.clearTimeout(rt.timerId),U.current=null,ue(rt.input,"left")}Ge?.dragged&&J(Ee(se,Ie,He),"pointermove")},De=(R,se,Ie,He)=>{if(P.current.set(R,{clientX:se,clientY:Ie}),D.current){P.current.delete(R),P.current.size===0&&(D.current=null);return}const Be=B0(V.current,R,se,Ie,performance.now());if(P.current.delete(R),Be.kind==="ignore")return;Be.kind==="drag"&&(J(Ee(se,Ie,He),"pointermove"),ne(),le()),V.current=null;const xe=U.current;if(xe&&window.clearTimeout(xe.timerId),U.current=null,Be.kind==="tap"&&Be.tap){const Ge=Ee(se,Ie,He);xe&&Cf(xe.tap,Be.tap)?ue(Ge,"right"):(xe&&ue(xe.input,"left"),nt(Be.tap,Ge))}else xe&&ue(xe.input,"left")},qe=R=>{if(P.current.delete(R),D.current){P.current.size===0&&(D.current=null);return}if(V.current?.pointerId===R){ne(),F.current=null,V.current=null;const se=U.current;se&&(window.clearTimeout(se.timerId),ue(se.input,"left")),U.current=null}},_e=R=>{if(R.pointerType!=="touch")return!1;if(R.preventDefault(),R.stopPropagation(),O.current.shouldHandlePointerEvent()){T(R.pointerId,R.clientX,R.clientY);try{R.currentTarget.setPointerCapture(R.pointerId)}catch{}}return!0},$e=R=>R.pointerType!=="touch"?!1:(R.preventDefault(),O.current.shouldHandlePointerEvent()&&ve(R.pointerId,R.clientX,R.clientY,R.currentTarget),!0),mt=R=>R.pointerType!=="touch"?!1:(R.preventDefault(),R.stopPropagation(),O.current.shouldHandlePointerEvent()&&De(R.pointerId,R.clientX,R.clientY,R.currentTarget),R.currentTarget.hasPointerCapture(R.pointerId)&&R.currentTarget.releasePointerCapture(R.pointerId),!0),ct=R=>R.pointerType!=="touch"?!1:(R.preventDefault(),R.stopPropagation(),O.current.shouldHandlePointerEvent()&&qe(R.pointerId),R.currentTarget.hasPointerCapture(R.pointerId)&&R.currentTarget.releasePointerCapture(R.pointerId),!0),z=R=>{if(s){R.preventDefault(),R.stopPropagation(),O.current.shouldHandlePointerEvent()&&(O.current.claimNativeTouchEvents(),V.current=null,P.current.clear(),D.current=null);for(const se of Array.from(R.changedTouches))T(se.identifier,se.clientX,se.clientY)}},pe=R=>{if(!s)return;R.preventDefault(),R.stopPropagation();for(const He of Array.from(R.touches))P.current.set(He.identifier,{clientX:He.clientX,clientY:He.clientY});const se=V.current?.pointerId,Ie=Array.from(R.touches).find(He=>He.identifier===se)||R.touches.item(0);Ie&&ve(Ie.identifier,Ie.clientX,Ie.clientY,R.currentTarget)},Y=R=>{if(s){R.preventDefault(),R.stopPropagation();for(const se of Array.from(R.changedTouches))De(se.identifier,se.clientX,se.clientY,R.currentTarget)}},K=R=>{if(s){R.preventDefault(),R.stopPropagation();for(const se of Array.from(R.changedTouches))qe(se.identifier)}},ee=o.useCallback(R=>{const se=document.activeElement;se instanceof HTMLElement&&R.contains(se)&&se.classList.contains("monitor-cycle-button")&&se.blur()},[]);return r.jsx("article",{className:`device-tile ${n?"selected":""} ${e.connected?"online":"offline"}`,"data-live-device-id":e.deviceId,style:Pe,children:r.jsxs("div",{className:`tile-screen ${Q?"has-frame":"is-empty"}`,role:"button",tabIndex:s?-1:0,"aria-pressed":n,onClick:R=>{R.target instanceof Element&&R.target.closest(".monitor-cycle")||s||d()},onKeyDown:R=>{R.target instanceof Element&&R.target.closest(".monitor-cycle")||s||(R.key==="Enter"||R.key===" ")&&(R.preventDefault(),d())},onDoubleClick:R=>{if(!(R.target instanceof Element&&R.target.closest(".monitor-cycle"))){if(R.preventDefault(),s){R.stopPropagation();return}h()}},onPointerLeave:R=>ee(R.currentTarget),children:[r.jsx("span",{ref:I,className:`screen-content ${Q?"has-frame":"is-empty"}`,children:r.jsx("canvas",{ref:Ce,className:`remote-canvas ${Q?"has-frame":"is-empty"} ${s?"control-input-enabled":""}`,"data-monitor-index":re,"data-touch-zoom":X.current.scale.toFixed(2),style:Se,tabIndex:s?0:-1,onPointerDown:R=>{s&&(_e(R)||(R.preventDefault(),R.stopPropagation(),p(),R.currentTarget.focus(),R.currentTarget.setPointerCapture(R.pointerId),ye(R,"pointerdown")))},onPointerMove:R=>{s&&R.preventDefault(),!$e(R)&&ye(R,"pointermove")},onPointerLeave:R=>{s&&R.pointerType!=="touch"&&(ye(R,"pointermove"),ne(),le())},onPointerUp:R=>{s&&(mt(R)||(R.preventDefault(),R.stopPropagation(),ye(R,"pointerup"),R.currentTarget.hasPointerCapture(R.pointerId)&&R.currentTarget.releasePointerCapture(R.pointerId)))},onPointerCancel:R=>{ct(R)||(s&&(R.preventDefault(),R.stopPropagation(),ye(R,"pointerup")),R.currentTarget.hasPointerCapture(R.pointerId)&&R.currentTarget.releasePointerCapture(R.pointerId))},onTouchStart:z,onTouchMove:pe,onTouchEnd:Y,onTouchCancel:K,onWheel:R=>{s&&(R.preventDefault(),w(e.deviceId,{type:"wheel",monitorIndex:re,...Le(R),deltaX:R.deltaX,deltaY:R.deltaY,...Ue(R)}))},onContextMenu:R=>s&&R.preventDefault(),onDoubleClick:R=>{s&&(R.preventDefault(),R.stopPropagation())}},`${e.deviceId}:monitor:${re}`)}),!Q&&r.jsx("span",{className:"empty-screen",children:r.jsx(pn,{size:26})}),i&&r.jsx("span",{className:"wall-device-title",title:dn(e),children:dn(e)}),oe&&r.jsxs("span",{className:"wall-presentation-loading",role:"status","aria-live":"polite",children:[r.jsx("span",{className:"wall-presentation-spinner","aria-hidden":"true"}),r.jsx("strong",{children:"Preparing video"})]}),ge&&r.jsxs("span",{className:"wall-presentation-loading permission-required",role:"status","aria-live":"polite",children:[r.jsx(Zt,{size:24,"aria-hidden":"true"}),r.jsx("strong",{children:"Screen Recording permission required"}),r.jsx("small",{children:"Allow the terminal app on this Mac, then restart LiveDesk."})]}),y&&r.jsxs("span",{className:`wall-update-status state-${y.state}`,role:"status","aria-live":"polite",title:y.error||y.label,children:[y.state==="updated"?r.jsx(En,{size:20,"aria-hidden":"true"}):y.state==="failed"?r.jsx(xn,{size:22,"aria-hidden":"true"}):y.state==="offline"?r.jsx(bu,{size:22,"aria-hidden":"true"}):r.jsx("span",{className:"wall-update-spinner","aria-hidden":"true"}),r.jsx("strong",{children:y.label}),y.error?r.jsx("small",{children:y.error}):null]}),a&&r.jsxs(r.Fragment,{children:[r.jsx("span",{className:`tile-health-pill state-${ie.state}`,children:ie.label}),r.jsx("span",{className:"tile-metrics","aria-label":`${dn(e)} status`,children:j.map(R=>r.jsxs("span",{className:`tile-metric state-${R.state}`,children:[r.jsx("b",{children:R.label}),r.jsx("em",{children:R.value}),R.ratio!==void 0&&r.jsx("i",{style:{width:`${Math.round(R.ratio*100)}%`}})]},R.id))})]}),C&&r.jsx(lw,{items:C,mode:A}),de&&r.jsxs("span",{className:"monitor-cycle","aria-label":`${dn(e)} display ${re+1} of ${u}`,onPointerDown:R=>R.stopPropagation(),onClick:R=>R.stopPropagation(),onDoubleClick:R=>R.stopPropagation(),children:[r.jsx("button",{className:"monitor-cycle-button previous",onClick:R=>{R.preventDefault(),R.stopPropagation(),m(-1),R.currentTarget.blur()},title:"Previous display",type:"button",children:r.jsx(Ab,{size:18})}),r.jsxs("span",{className:"monitor-cycle-count",children:["Screen ",re+1,"/",u]}),r.jsx("button",{className:"monitor-cycle-button next",onClick:R=>{R.preventDefault(),R.stopPropagation(),m(1),R.currentTarget.blur()},title:"Next display",type:"button",children:r.jsx(_p,{size:18})})]})]})})}function vI({visible:e}){const t=KT;return o.useEffect(()=>{},[t]),null}function wI({runtimeBaseUrl:e=""}){const t=typeof window<"u"&&!!window.liveDesk,{session:n,loading:s}=c0();By(n?{accessToken:n.access_token,refreshToken:n.refresh_token,expiresAt:n.expires_at,user:{id:n.user.id,email:n.user.email}}:null);const{target:a,error:i,refresh:c}=u0(n),u=o.useMemo(()=>{if(!a?.active)return null;const l=a.expires_at?Date.parse(a.expires_at):Number.POSITIVE_INFINITY;return Number.isFinite(l)&&l<=Date.now()?null:a},[a]),d=o.useMemo(()=>Fh(u),[u]),p=eu(),h=e.trim().replace(/\/+$/,""),m=o.useMemo(()=>[...new Set((p?d:[h,...d,an]).filter(Boolean))],[p,d,h]),[g,w]=o.useState(null),[v]=o.useState($T),[y,k]=o.useState(!1),[N,C]=o.useState(()=>typeof window>"u"?!1:!!window.navigator.standalone||window.matchMedia("(display-mode: standalone), (display-mode: fullscreen)").matches),[A,E]=o.useState(()=>typeof window<"u"&&jf(window.matchMedia(Pf).matches,N,window.matchMedia("(pointer: coarse)").matches));o.useEffect(()=>{if(!p){w(null);return}const l=window.matchMedia("(display-mode: standalone), (display-mode: fullscreen)"),f=()=>C(l.matches||!!window.navigator.standalone),b=S=>{S.preventDefault(),w(S)},x=()=>{w(null),C(!0)};return f(),l.addEventListener("change",f),window.addEventListener("beforeinstallprompt",b),window.addEventListener("appinstalled",x),()=>{l.removeEventListener("change",f),window.removeEventListener("beforeinstallprompt",b),window.removeEventListener("appinstalled",x)}},[p]);const I=o.useCallback(async()=>{const l=g;if(!l){v.isIos&&k(!0);return}w(null);try{await l.prompt(),(await l.userChoice).outcome==="accepted"&&C(!0)}catch(f){w(l),console.warn("[LiveDesk] PWA install prompt failed.",f)}},[v.isIos,g]);o.useEffect(()=>{const l=window.matchMedia(Pf),f=window.matchMedia("(pointer: coarse)"),b=()=>E(jf(l.matches,N,f.matches));return b(),l.addEventListener("change",b),f.addEventListener("change",b),()=>{l.removeEventListener("change",b),f.removeEventListener("change",b)}},[N]),o.useLayoutEffect(()=>{const l=document.documentElement,f=()=>{l.classList.remove("livedesk-mobile-console-active"),l.style.removeProperty("--livedesk-mobile-viewport-height"),l.style.removeProperty("--livedesk-mobile-viewport-top"),l.style.removeProperty("--livedesk-mobile-viewport-width"),l.style.removeProperty("--livedesk-mobile-viewport-left"),l.style.removeProperty("--livedesk-mobile-ios-top-guard")};if(!A){f();return}l.classList.add("livedesk-mobile-console-active");const b=window.visualViewport,x=document.createElement("div");x.setAttribute("aria-hidden","true"),x.style.cssText="position:fixed;visibility:hidden;pointer-events:none;padding-top:env(safe-area-inset-top);",document.body.appendChild(x);let S=0;const $=()=>{S=0;const B=Math.max(window.innerHeight,document.documentElement.clientHeight),q=lk(b,B,window.innerWidth,N||v.isIos,N||v.isIos||v.isAndroid),W=Number.parseFloat(window.getComputedStyle(x).paddingTop),ke=ck({isIos:v.isIos,standalone:N,safeAreaTop:W,screenHeight:window.screen.height,layoutViewportHeight:B});l.style.setProperty("--livedesk-mobile-viewport-height",`${q.height}px`),l.style.setProperty("--livedesk-mobile-viewport-top",`${q.offsetTop}px`),l.style.setProperty("--livedesk-mobile-viewport-width",`${q.width}px`),l.style.setProperty("--livedesk-mobile-viewport-left",`${q.offsetLeft}px`),l.style.setProperty("--livedesk-mobile-ios-top-guard",`${ke}px`)},L=()=>{S||(S=window.requestAnimationFrame($))};return $(),b?.addEventListener("resize",L),b?.addEventListener("scroll",L),window.addEventListener("resize",L),window.addEventListener("orientationchange",L),window.addEventListener("pageshow",L),()=>{S&&window.cancelAnimationFrame(S),b?.removeEventListener("resize",L),b?.removeEventListener("scroll",L),window.removeEventListener("resize",L),window.removeEventListener("orientationchange",L),window.removeEventListener("pageshow",L),x.remove(),f()}},[v.isAndroid,v.isIos,A,N]);const[F,M]=o.useState(LP),H=o.useMemo(()=>m.some(l=>!!Ul(l)),[m]),V=p?!!n:!H||F,{status:P,devices:D,error:O,refresh:X,hubBaseUrl:G}=l0(m,V,n?.access_token||""),[U,ie]=o.useState(!1);o.useEffect(()=>{if(!P?.started){ie(!1);return}const l=new AbortController;return Oe("/api/settings",{signal:l.signal},G).then(f=>{ie(f.settings?.connection?.showThisComputer===!0)}).catch(f=>{l.signal.aborted||(ie(!1),console.warn("[LiveDesk] Computer visibility setting could not be loaded.",f))}),()=>l.abort()},[G,P?.started]);const{entitlement:j,licensed:re,loading:de,error:Q,refresh:ge}=d0(n),[oe,me]=o.useState([]),[Ae,Te]=o.useState(""),[Pe,Se]=o.useState(""),[te,Ce]=o.useState(""),[Fe,Le]=o.useState(""),[Ue,ne]=o.useState(""),[ae,le]=o.useState("idle"),[ce,J]=o.useState(!1),[ye,ue]=o.useState(""),[Ee,nt]=o.useState(null),T=o.useRef(null),[ve,De]=o.useState(""),qe=o.useRef("");qe.current=Fe;const[_e,$e]=o.useState(!1),[mt,ct]=o.useState([]),z=o.useRef(null),pe=o.useRef(null),Y=o.useRef(null),K=o.useRef(!1),ee=o.useRef({key:"",source:"",at:0}),[R,se]=o.useState(!1),[Ie,He]=o.useState(!1),Be=o.useRef(""),xe=o.useRef(new Map),Ge=o.useRef(0),rt=o.useRef(!1),Ke=o.useRef(""),gt=o.useRef(null);gt.current||(gt.current=dk());const _=o.useRef(document.visibilityState==="visible"),[je,Qe]=o.useState({}),Ye=o.useRef({}),Gt=o.useRef(new Set),en=o.useRef(new Map),qn=o.useRef(new Map),[on,Sr]=o.useState({}),Un=o.useMemo(()=>new Set(Object.keys(je)),[je]),Fn=o.useCallback((l,f)=>{if(!l)return;const b={...Ye.current};f?b[l]=f:delete b[l],Ye.current=b,Qe(b)},[]),Sn=o.useCallback((l,f)=>{l&&Sr(b=>{if(!!b[l]===f)return b;const x={...b};return f?x[l]=!0:delete x[l],x})},[]),rr=o.useCallback((l,f)=>{l&&qn.current.set(l,{paused:f,expiresAt:Date.now()+fP})},[]),[bt,Z]=o.useState(""),[be,We]=o.useState(""),[lt,It]=o.useState(!1),At=o.useRef(null),et=o.useRef(null);o.useEffect(()=>{bt==="auth"&&n?.access_token&&Z("")},[bt,n?.access_token]);const[Mt,Cn]=o.useState(""),[zt,kn]=o.useState(null),Nt=o.useRef(null),cn=o.useRef(0),ht=o.useCallback((l,f,b)=>{const x=String(l||"").trim();if(Cn(x),Nt.current!==null&&(window.clearTimeout(Nt.current),Nt.current=null),!x){kn(null);return}const S=++cn.current;if(kn({id:S,message:x,tone:f}),!b)return;const $=window.setTimeout(()=>{kn(L=>L?.id===S?null:L),Nt.current===$&&(Nt.current=null)},5e3);Nt.current=$},[]),we=o.useCallback((l,f="info")=>{ht(l,f,!0)},[ht]),Ot=o.useCallback(l=>{ht(l,"progress",!1)},[ht]);o.useEffect(()=>()=>{Nt.current!==null&&window.clearTimeout(Nt.current)},[]);const[jt,tn]=o.useState(()=>typeof window>"u"?"wall":window.location.pathname.startsWith("/support")?"support":new URLSearchParams(window.location.search).get("view")==="pricing"?"pricing":"wall");o.useEffect(()=>{const l=()=>{tn(window.location.pathname.startsWith("/support")?"support":f=>f==="support"?"wall":f)};return window.addEventListener("popstate",l),()=>window.removeEventListener("popstate",l)},[]);const[ps,Is]=o.useState(XP),Bt=Rk(ps),ms=o.useCallback(l=>{const f=hc(l);Is(f),JP(f)},[]),bc=o.useCallback(l=>{ms(l==="list"?lu:l==="medium"?Mk:Za)},[ms]),ei=Tk(ps),ia=o.useMemo(()=>({"--wall-tile-min-width":`${ei}px`}),[ei]),vc=Bt==="list"?"List view":`${Bt==="medium"?"Small":"Large"} tiles, ${ei} pixel minimum width`,[dr,ti]=o.useState(GP),Dn=Ap(dr),[pr,sr]=o.useState(QP),[nn,oa]=o.useState(!1),[qt,ca]=o.useState(!1),[Vn,la]=o.useState(!1),[$r,hs]=o.useState(!1),[wc,js]=o.useState(Date.now),Cr=o.useRef(null);o.useEffect(()=>()=>{Cr.current!==null&&window.clearTimeout(Cr.current)},[]);const[Or,yc]=o.useState(mI),[Br,io]=o.useState(!1),[ua,Hr]=o.useState(!1),[pm,Pu]=o.useState(!1),[fs,oo]=o.useState(DP),[ot]=o.useState(zP),co=A?pr:ot.showScreenStatus,[rn]=o.useState(UP),[da]=o.useState(HP),[Ct,ni]=o.useState(da.selections),lo=o.useRef({...da.topologyFingerprints}),Es=o.useRef({}),xc=o.useRef({...da.selections}),[vt,ln]=o.useState(null),[ri,uo]=o.useState({}),po=o.useRef(new Set),[Wr,si]=o.useState([]),[Ln,Fs]=o.useState(Dn),[Ds,Sc]=o.useState(""),[Iu,ju]=o.useState(0),[Cc,mo]=o.useState(0),[Ls,Dw]=o.useState(0),[Eu,ho]=o.useState(()=>new Set),Tt=o.useRef(new Map),_n=o.useRef(new Map),gs=o.useRef(new Map),Ht=o.useRef(new Map),pa=o.useRef(null),ma=o.useRef(new Map),bs=o.useRef(new Set),_s=o.useRef(new Map),ai=o.useRef(new Map),ha=o.useRef(new Map),zr=o.useRef(new Map),kc=o.useRef(new WeakMap),Mc=o.useRef(new WeakMap),$s=o.useRef(""),Gn=o.useRef(null),mm=o.useRef(Promise.resolve()),Ac=o.useRef(0),ii=o.useRef(null),ar=o.useRef(null),fo=o.useRef(""),gn=o.useRef(new Map),oi=o.useRef(null),go=o.useRef(0),vs=o.useRef(new Map),Nc=o.useRef(typeof window<"u"&&new URLSearchParams(window.location.search).get("livedeskTransmissionProbe")==="1"),Rc=o.useRef(new Map),Fu=o.useRef([]),hm=o.useRef(0),[Tc,Du]=o.useState({}),Os=o.useRef(new Map),[Pc,Ic]=o.useState({}),jc=o.useRef(null),[Lu,$n]=o.useState(!1),Ec=o.useRef(null),Lw=o.useRef(0),ws=o.useRef(null),fm=o.useRef(new Map),kr=o.useRef(null),mr=o.useRef(null),ir=o.useRef(null),bo=o.useRef(!1),gm=o.useRef(0),Kt=o.useRef(0),Mn=o.useRef(""),bm=o.useRef(Promise.resolve()),ci=o.useRef(""),it=o.useRef(null),hr=o.useRef(""),fa=o.useRef(null),li=o.useRef(0),vo=o.useRef(""),Bs=o.useRef(new Map),ga=o.useRef(new Map),Fc=o.useRef(performance.now()),ui=o.useRef(new Map),qr=o.useRef(new Map),ba=o.useRef(new Map),va=o.useRef(new Map),di=o.useRef(new Map),wa=o.useRef(new Map),Mr=o.useRef(document.visibilityState==="visible"),Ur=o.useRef(1),_u=o.useRef([]),[On,_w]=o.useState(document.visibilityState==="visible"),[pi,$w]=o.useState(0),wo=o.useRef(0),Dc=o.useRef(0),Lc=o.useRef(0),_c=o.useRef(0),$u=o.useRef(0),Ou=o.useRef(new Map),yo=o.useRef([]),vm=o.useRef(new Map),wm=o.useRef(new Map),ys=o.useRef(new Map),$c=o.useRef(new Set),mi=o.useCallback(l=>wC(kc.current,l),[]),hi=o.useCallback(l=>Wp(Mc.current,l),[]),ya=o.useCallback((l,f)=>af(Mc.current,l,f),[]),sn=o.useCallback(l=>{const f=sf(kc.current,l);return sf(Mc.current,l),f},[]),fi=o.useCallback((l,f)=>af(kc.current,l,f),[]),ym=o.useCallback(l=>ar.current===l||pa.current===l?!0:[Tt.current,_n.current,gs.current,Ht.current,gn.current].some(b=>Array.from(b.values()).some(x=>x===l)),[]),Bn=o.useCallback(l=>{l&&(sn(l),$c.current.add(l),SC(l,{isCurrent:ym,dispose:zi,schedule:f=>queueMicrotask(()=>{try{f()}finally{$c.current.delete(l)}})}))},[ym,sn]),Hn=o.useCallback(l=>(sn(l),Cu(l,zi)),[sn]),xm=o.useCallback(()=>{const l=ar.current,f=pa.current,b=[...$c.current];ar.current=null,pa.current=null,$c.current.clear(),kc.current=new WeakMap,Mc.current=new WeakMap,zr.current.clear(),fo.current="",xC([Tt.current,_n.current,gs.current,Ht.current,gn.current],[l,f,...b],zi),oi.current=null,go.current=0,ma.current.clear(),bs.current.clear(),_s.current.clear(),ai.current.clear(),ha.current.clear(),vs.current.clear(),Rc.current.clear(),Fu.current.length=0,Os.current.clear(),Gt.current.clear()},[]);o.useEffect(()=>()=>{xm()},[xm]);const bn=o.useCallback((l,f)=>{const b=Ut(l,f),x=performance.now();Bs.current.delete(b),ga.current.delete(b),ui.current.delete(b),qr.current.delete(b),wa.current.delete(b),ys.current.delete(b),Os.current.delete(b),vs.current.delete(b),Ic(S=>{if(!Object.prototype.hasOwnProperty.call(S,b))return S;const $={...S};return delete $[b],$}),Du(S=>{if(!Object.prototype.hasOwnProperty.call(S,b))return S;const $={...S};return delete $[b],$}),l==="control"?(ba.current.delete(b),va.current.set(b,x)):di.current.set(b,x)},[]),[xa,Hs]=o.useState(null),[Ow,Bu]=o.useState(!1),[kI,Bw]=o.useState([]),[gi,Hw]=o.useState("all"),[bi,Hu]=o.useState([]),[MI,AI]=o.useState(!1),[NI,Ww]=o.useState(!0),Sm=o.useRef(null),Cm=o.useRef(null),zw=o.useRef(null),qw=o.useRef(null),Uw=o.useRef(!1),Wu=o.useRef(!1),xo=o.useRef(0),Vr=o.useRef(0),Gr=o.useRef(0),Ar=o.useRef(0),So=o.useRef(0),Co=o.useRef(""),zu=o.useRef({}),ko=jt==="settings",km=jt==="pricing",Mm=jt==="doc",Am=jt==="support",Sa=jt==="share-files",Oc=jt==="agents",Ca=!ko&&!km&&!Mm&&!Am&&!Sa&&!Oc,Xe=jt==="control",Nm=hk(jt),Nr=On&&jt==="wall",Rm=o.useRef(Nr);Rm.current=Nr;const Vw=Nm&&yo.current.length>0,ka=On&&(jt==="wall"||Xe||Vw),vi=o.useRef(ka);vi.current=ka;const Bc=On&&(Xe||Nr),wi=On&&(Bc||Nm&&(ae==="connecting"||ae==="active")),qu=o.useRef({active:ka,epoch:Ur.current});qu.current.active!==ka&&(Ur.current+=1,qu.current={active:ka,epoch:Ur.current}),o.useEffect(()=>{Ca||(oa(!1),ca(!1),la(!1))},[Ca]);const St=ot.frameMode==="mode4-h264-atlas",fr=Ue||rn.frameMode,Mo=fr!=="mode3-h264-hw"?Math.min(30,rn.fps):rn.fps,yi=D.find(l=>l.deviceId===Pe),Gw=yi?.platform,Kw=yi?lr(yi,Ct[yi.deviceId]):0,Hc=yi?dm(yi,Kw):null,Tm=bI(Gw)?{maxWidth:1280,maxHeight:720}:Ug,Pm=fr!=="mode3-h264-hw"?{maxWidth:1920,maxHeight:1080}:Ug,Wc={maxWidth:Math.min(Pm.maxWidth,Tm.maxWidth,rn.maxWidth),maxHeight:Math.min(Pm.maxHeight,Tm.maxHeight,rn.maxHeight)},Kr={maxWidth:Hc?.width?Math.min(Wc.maxWidth,Hc.width):Wc.maxWidth,maxHeight:Hc?.height?Math.min(Wc.maxHeight,Hc.height):Wc.maxHeight};o.useEffect(()=>{if(P?.started){if(!n?.access_token){Oe("/api/remote/license",{method:"DELETE"},G).catch(()=>{});return}Oe("/api/remote/license/sync",{method:"POST",headers:{Authorization:`Bearer ${n.access_token}`}},G).catch(l=>{console.warn("[LiveDesk] Hub license sync failed",l)})}},[j?.updated_at,G,n?.access_token,P?.started]),o.useEffect(()=>{!n?.access_token||!P?.started||P.runtimeRole!=="hub"||!P.deviceId||(async()=>{try{const{data:l,error:f}=await pt.rpc("register_livedesk_device",{p_device_id:P.deviceId,p_device_name:P.deviceName||P.deviceId,p_role:"hub",p_assigned_hub_id:null,p_platform:navigator.platform||navigator.userAgent,p_os_version:navigator.userAgent,p_app_version:P.managerVersion||P.managerPackage||""}),b=Array.isArray(l)?l[0]:l;(f||b?.ok===!1)&&console.warn("[LiveDesk] Hub device role registration failed",f||b?.reason||"unknown-error")}catch(l){console.warn("[LiveDesk] Hub device role registration failed",l)}})()},[n?.access_token,P?.deviceId,P?.deviceName,P?.managerPackage,P?.managerVersion,P?.runtimeRole,P?.started]);const Uu=P?.runtimeRole==="hub"?String(P.deviceId||"").trim():"",Ze=o.useMemo(()=>D.filter(l=>l.connected&&(A||U||!Uu||l.deviceId!==Uu)),[D,Uu,A,U]);o.useEffect(()=>{const l={...Ye.current},f=Date.now();let b=!1;Sr(x=>{const S={...x};let $=!1;for(const L of D){const B=String(L.liveCapturePause?.token||"").trim(),q=qn.current.get(L.deviceId);if(q)if((q.paused?!!B:!B)||q.expiresAt<=f)qn.current.delete(L.deviceId);else continue;const W=!!B&&(L.liveCapturePause?.captureStopConfirmed!==!0||L.liveCapturePause?.phase==="stop-unconfirmed");!!S[L.deviceId]!==W&&($=!0,W?S[L.deviceId]=!0:delete S[L.deviceId])}return $?S:x});for(const x of D){const S=String(x.liveCapturePause?.token||"").trim(),$=String(l[x.deviceId]||""),L=qn.current.get(x.deviceId);if(L)if((L.paused?!!S:!S)||L.expiresAt<=f)qn.current.delete(x.deviceId);else continue;S&&S!==$?(l[x.deviceId]=S,b=!0):!S&&$&&(delete l[x.deviceId],en.current.delete(x.deviceId),b=!0)}b&&(Ye.current=l,Qe(l))},[D]);const Im=gi==="all"?Ze.length:bi.filter(l=>Ze.some(f=>f.deviceId===l)).length,Qw=o.useMemo(()=>Ze.reduce((l,f)=>Math.max(l,ab(f.slotNumber)),0),[Ze]),Vu=Math.max(OT,Ze.length,Qw),Ma=o.useMemo(()=>{const l=Array(Vu).fill(null),f=[];for(const b of Ze){const x=ab(b.slotNumber);x>0&&x<=Vu&&!l[x-1]?l[x-1]=b:f.push(b)}for(const b of f){const x=l.findIndex(S=>!S);x<0?l.push(b):l[x]=b}return l},[Ze]),jm=o.useMemo(()=>Ma.flatMap((l,f)=>l?[{device:l,slotNumber:f+1}]:[]),[Ma]),zc=o.useMemo(()=>Ze.map(l=>l.deviceId),[Ze]),Aa=o.useMemo(()=>new Set(oe),[oe]),An=o.useMemo(()=>Ze.filter(l=>Aa.has(l.deviceId)),[Ze,Aa]),xi=o.useMemo(()=>D.find(l=>l.deviceId===Ae)||An[0]||null,[D,Ae,An]),vn=o.useMemo(()=>D.find(l=>l.deviceId===Pe)||null,[Pe,D]),Rr=vn?lr(vn,Ct[vn.deviceId]):0,fe=Xe?vn:xi,Em=o.useMemo(()=>new Set(bi),[bi]),Yw=o.useMemo(()=>gi==="all"?Ze.map(l=>l.deviceId):Ze.filter(l=>Em.has(l.deviceId)).map(l=>l.deviceId),[Ze,Em,gi]),Xw=fe?Xi(fe,"control"):!1,Gu=cs(fe?.platform)&&(fe?.capabilities?.controlPermission===!1||fe?.capabilities?.accessibilityPermission===!1),Tr=fe?Xi(fe,"audio")||Xi(fe,"remoteAudio"):!1,Na=(Array.isArray(fe?.capabilities?.agentTools)?fe.capabilities.agentTools.map(String):[]).includes("system.power"),Qt=re?j?.plan==="pro"?"pro":"ltd":"free",Fm=Ms[Qt],Ku=Fm.limit,Qr=o.useMemo(()=>new Set(vk(Ze,Ku)),[Ku,Ze]),Jw=!fe||Qr.has(fe.deviceId),Zw=Qt==="free",Rt=Jw,Si=Qt==="ltd"?`Plus includes up to ${Ho} Clients. Upgrade to Pro for commercial use and larger walls.`:`Free includes up to ${yl} Clients. Upgrade to Plus for ${Ho} devices and no ads.`,ey=Qt==="free",Pr=Rt&&!!fe&&Xw,Qu=Rt&&!!fe&&Tr,Ao=o.useMemo(()=>Xe?fe?[fe]:[]:An.length>0?An:fe?[fe]:[],[fe,An,Xe]),Kn=o.useMemo(()=>Ao.filter(l=>Qr.has(l.deviceId)),[Qr,Ao]),qc=Kn.some(l=>String(je[l.deviceId]||"").startsWith("pending:")||on[l.deviceId]===!0),xs=!(Kn.length>0&&Kn.every(l=>{const f=String(je[l.deviceId]||"");return!!f&&!f.startsWith("pending:")&&on[l.deviceId]!==!0}))||qc,Uc=o.useMemo(()=>Ma.filter(l=>!!l?.connected).slice(0,ZP(Bt)).map(l=>l.deviceId),[Ma,Bt]),Vc=o.useMemo(()=>ka?Nr?St||Bt==="list"?zc:ot.visibleOnlyLive?Wr.length>0?Wr:Uc:zc:yo.current.length>0?yo.current:zc:[],[Uc,St,Wr,ot.visibleOnlyLive,zc,ka,Nr,Bt]),gr=o.useMemo(()=>Xd(Vc.filter(l=>Qr.has(l))),[Qr,Vc]);yo.current=gr;const Yr=o.useMemo(()=>gr.filter(l=>l!==Ds&&!Un.has(l)),[Un,gr,Ds]),Gc=o.useMemo(()=>new Map(Ze.map(l=>[l.deviceId,l.platform])),[Ze]),Ss=o.useMemo(()=>Object.fromEntries(Ze.map(l=>[l.deviceId,String(l.sessionId||"").trim()])),[Ze]),ty=Ef(zu.current,Ss)?Dn:Ln;o.useLayoutEffect(()=>{const l=zu.current,f=Ef(l,Ss);zu.current={...Ss},f&&(Fs(Dn),xo.current=Date.now(),Vr.current=0,Gr.current=0,Ar.current=0,So.current=0,Co.current="")},[Ss,Dn]);const Xr=wk(St,gr.length),Qn=o.useMemo(()=>St?Yr.filter(l=>zo({mode4Enabled:St,directMode4WallEnabled:Xr,isMac:cs(Gc.get(l))})==="atlas"):[],[Xr,St,Gc,Yr]),or=o.useMemo(()=>Yr.filter(l=>zo({mode4Enabled:St,directMode4WallEnabled:Xr,isMac:cs(Gc.get(l))})==="direct"),[Xr,St,Gc,Yr]),Dm=o.useMemo(()=>{const l=ot.autoStartLive?Yr.map(f=>Ut("wall",f)):[];return wi&&Rt&&te&&Qr.has(te)&&(ae==="connecting"||ae==="active"||ae==="warm")&&l.push(Ut("control",te)),[...new Set(l)].sort()},[wi,te,ae,Rt,Qr,ot.autoStartLive,Yr]);o.useEffect(()=>{const l=new Set(gr);ho(f=>{let b=!1;const x=new Set;for(const S of f)l.has(S)?x.add(S):b=!0;return b?x:f})},[gr]);const ny=o.useMemo(()=>{const l=S=>Ze.find($=>$.deviceId===S)||null,f=S=>{const $=l(S);return $?lr($,Ct[S]):0},b=(S,$=f(S))=>S===te&&(ae==="connecting"||ae==="active"||ae==="warm")?Ht.current.get(S)||_n.current.get(S)||null:St?gn.current.get(S)||Tt.current.get(S)||null:Tt.current.get(S)||null,x=(S,$=f(S))=>{const L=l(S);return`${L?dn(L):S} · Monitor ${$+1}`};return{resolveCurrentTarget(){if(Xe&&vn){const q=Rr;return{type:"control",deviceIds:[vn.deviceId],monitorIndex:q,label:`${dn(vn)} · Monitor ${q+1}`,sourceCanvas:b(vn.deviceId,q),signature:`control:${vn.deviceId}:${q}:${rn.frameMode}`}}const S=An.map(q=>q.deviceId).filter(q=>Yr.includes(q)),$=xi&&Yr.includes(xi.deviceId)?xi.deviceId:"",L=S.length>0?S:$?[$]:Yr,B=S.length===0&&!$;if(L.length===0)return null;if(L.length===1){const q=L[0],W=f(q);return{type:B?"wall":S.length>1?"selection":"device",deviceIds:L,monitorIndex:W,label:B?"Wall":x(q,W),sourceCanvas:B?null:b(q,W),signature:`${B?"wall":"device"}:${q}:${W}:${St?"atlas":"direct"}`}}return{type:S.length>1?"selection":"wall",deviceIds:L,label:S.length>1?`${L.length} selected Clients`:"Wall",sourceCanvas:null,signature:`${S.length>1?"selection":"wall"}:${L.join(",")}:${Bt}`}},getDeviceCanvas:b,composeWall(S,$={}){return AT(S.map(L=>{const B=f(L);return{deviceId:L,label:x(L,B),canvas:b(L,B)}}),$)}}},[Ze,vn,te,ae,rn.frameMode,Tt,St,Ct,Rr,An,Xe,Yr,xi,Bt]),Lm=_T({hubUrl:G,sourceRegistry:ny,onToast:we}),Ci=o.useMemo(()=>fk({captureOwnershipActive:wi,localFeatureAccess:Rt,controlSessionDeviceId:te,planAllowed:Qr.has(te),sessionState:ae,controlFocusVisible:Xe,presentationCanvasMounted:ye===te,wallPresentationVisible:Nr,wallPresentationCanvasMounted:Tt.current.has(te)||gn.current.has(te),decoderOwnerExists:Ht.current.has(te)})?[te]:[],[wi,te,ae,Rt,ye,Qr,Xe,Nr]),Yu=o.useMemo(()=>Xd([...gr,...Ci]),[Ci,gr]),Kc=o.useMemo(()=>tb(ot,Bt),[ot,Bt]),ki=o.useMemo(()=>tb(ot,"large"),[ot]),Qc=yk({mode4Enabled:St,directMode4WallEnabled:Xr,adaptiveFps:ty,directDeviceCount:or.length,adaptive:ot.adaptiveLoadShedding}),Nn=ik({fps:Qc,maxWidth:ki.maxWidth,maxHeight:ki.maxHeight,quality:ot.quality},A),Xu=Ck({deviceCount:Qn.length,targetFps:Ln,adaptive:ot.adaptiveLoadShedding});St&&Qn.length>0;const Cs=o.useCallback((l,f,b,x=1)=>{if(l.width<=0||l.height<=0)return!1;if(l===f)return!0;const S=b?Math.min(1,b.maxWidth/l.width,b.maxHeight/l.height):1,$=Math.max(1,Math.round(l.width*S)),L=Math.max(1,Math.round(l.height*S)),B=f.width!==$||f.height!==L;B&&(f.width=$,f.height=L);const q=f.getContext("2d",{alpha:!1});if(!q)return!1;q.imageSmoothingEnabled=!0,q.imageSmoothingQuality="low";const W=q.globalAlpha;q.globalAlpha=B?1:Math.max(.05,Math.min(1,x));try{q.drawImage(l,0,0,l.width,l.height,0,0,f.width,f.height)}finally{q.globalAlpha=W}return!0},[]),Yc=o.useCallback((l,f)=>{const b=Math.max(0,Number(f.clientWidth||0)),x=Math.max(0,Number(f.clientHeight||0)),S=Math.max(1,Number(window.devicePixelRatio||1)),$=b>0&&x>0?{maxWidth:Math.ceil(b*S),maxHeight:Math.ceil(x*S)}:void 0;return Cs(l,f,$)},[Cs]),Xc=o.useCallback((l,f,b)=>{const x=Math.max(0,Math.floor(Number(l?.frameSeq||0))),S=f||(l?Tt.current.get(l.deviceId):null),$=b||S,L=Math.max(0,Number($?.width||0))*Math.max(0,Number($?.height||0)),B=Math.max(Tt.current.size,gn.current.size);return t&&x>0&&(x+cP(l?.deviceId||""))%Nw===0&&B<=oP&&CS(S)&&L>0&&L<=iP?aP:1},[t]),Mi=o.useCallback((l,f,b)=>{if(!Nc.current)return;const x=`${l}:${f.deviceId}`,S=Rc.current.get(x)||{bindingKey:"",totalPaints:0,lastPaintAt:0,lastFrameSeq:0};S.bindingKey=as(f),S.totalPaints+=1,S.lastPaintAt=performance.now(),S.lastFrameSeq=Number(f.frameSeq||0),Rc.current.set(x,S);const $=++hm.current,L={sequence:$,scope:l,deviceId:f.deviceId,bindingKey:S.bindingKey,frameSeq:S.lastFrameSeq,paintedAt:S.lastPaintAt,sourceGapMs:Number(f.sourceGapMs||0),agentSendGapMs:Number(f.agentSendGapMs||0),agentSendDurationMs:Number(f.agentSendDurationMs||0),agentSendDurationFrameSeq:Number(f.agentSendDurationFrameSeq||0),agentFrameAgeMs:Number(f.agentFrameAgeMs||0),timestampUs:Number(f.timestampUs||0),queuedForMs:Number(b?.queuedForMs||0),decodedForMs:Number(b?.decodedForMs||0),scheduledForMs:Number(b?.scheduledForMs||0),interactiveBurstOutputWindowMs:Number(b?.interactiveBurstOutputWindowMs||0),interactiveBurstTailHoldCount:Number(b?.interactiveBurstTailHoldCount||0)};Fu.current[($-1)%vP]=L},[]),Jr=o.useCallback(l=>{l&&ho(f=>{if(f.has(l))return f;const b=new Set(f);return b.add(l),b})},[]),Zr=o.useCallback(l=>{l&&ho(f=>{if(!f.has(l))return f;const b=new Set(f);return b.delete(l),b})},[]),Ra=o.useCallback((l,f)=>{if(!f||f.width<=0||f.height<=0)return!1;const b=document.createElement("canvas");if(b.width=f.width,b.height=f.height,!Cs(f,b))return Bn(b),!1;const x=gs.current.get(l);return gs.current.set(l,b),x&&x!==b&&Hn(x),Jr(l),!0},[Jr,Cs,Hn,Bn]),un=o.useCallback(l=>{yC(gs.current,l,zi)},[]),Jc=o.useCallback((l,f)=>{const b=gs.current.get(l),x=Tt.current.get(l)===f||gn.current.get(l)===f;return Ye.current[l]?(un(l),!1):!b||!x||b.width<=0||b.height<=0?!1:Cs(b,f)?!0:(un(l),!1)},[Cs,un]),ks=o.useCallback((l,f=!1,b)=>{if(Ye.current[l]||!bs.current.has(l))return!1;const x=Math.max(1,Math.min(Dn,$t.controlWallReuseMaxFps,Mo)),S=performance.now(),$=ai.current.get(l)||0,L=Ht.current.get(l)||_n.current.get(l),B=Tt.current.get(l)||gn.current.get(l);if(!L||!B||!B.isConnected)return!1;const q=bk({cadenceCredit:_s.current.get(l)||0,targetFps:x,sourceFps:Mo,elapsedSincePaintMs:$>0?S-$:0,nowMs:S,scheduledPaintAtMs:ha.current.get(l)||0,force:f});if(!q.shouldPaint)return _s.current.set(l,q.nextCadenceCredit),!1;const W=Math.max(0,Number(B.clientWidth||0)),ke=Math.max(0,Number(B.clientHeight||0)),Me=Math.max(1,Number(window.devicePixelRatio||1)),he=W>0&&ke>0?{maxWidth:Math.min(Kc.maxWidth,Math.ceil(W*Me)),maxHeight:Math.min(Kc.maxHeight,Math.ceil(ke*Me))}:Kc;return Cs(L,B,he,b?Xc(b,L,B):1)?(_s.current.set(l,q.nextCadenceCredit),q.nextScheduledPaintAtMs>0&&ha.current.set(l,q.nextScheduledPaintAtMs),ai.current.set(l,performance.now()),q.sourceCadencePassthrough&&(_s.current.delete(l),ha.current.delete(l)),b&&Mi("wall-reuse-visible",b),Jr(l),un(l),!0):!1},[Mo,Kc,Jr,Cs,Mi,un,Xc,Dn]);o.useEffect(()=>{$s.current=Ds},[Ds]);const Zc=o.useCallback((l,f)=>{const b=ws.current;if(!b||b.deviceId!==l)return;const x=Date.now();fm.current.set(l,{...b,source:f,completedAtEpochMs:x,durationMs:Math.max(0,performance.now()-b.startedAt)}),ws.current=null},[]),_m=o.useCallback((l,f)=>{const b=Tt.current.get(l);if(f&&b&&b!==f&&Ra(l,b),f){if(Tt.current.set(l,f),b&&b!==f&&Bn(b),Ye.current[l]){un(l),Hn(f),Zr(l);return}gs.current.get(l)&&Jc(l,f)&&Jr(l),ks(l,!0);return}if(b&&vi.current&&yo.current.includes(l)){Ra(l,b),Tt.current.delete(l),Bn(b);return}Tt.current.delete(l),un(l),Bn(b),Zr(l)},[Zr,Jr,ks,Jc,Ra,Hn,un,Bn]),ry=o.useCallback((l,f)=>{const b=_n.current.get(l);if(f){_n.current.set(l,f),ue(l),b&&b!==f&&Bn(b);const x=te===l&&ce?Ht.current.get(l):null;x&&Yc(x,f)&&l===Pe&&(Zc(l,"warm-reuse"),$n(!0)),x&&x!==f&&gk({decodeWidth:x.width,decodeHeight:x.height,presentationCssWidth:f.getBoundingClientRect().width,presentationCssHeight:f.getBoundingClientRect().height,devicePixelRatio:window.devicePixelRatio,sourceWidth:Kr.maxWidth,sourceHeight:Kr.maxHeight})&&(Ht.current.set(l,f),Bn(x));return}_n.current.delete(l),ue(x=>x===l?"":x),Bn(b)},[Zc,Pe,te,ce,Kr.maxHeight,Kr.maxWidth,Yc,Bn]),el=o.useCallback((l,f,b)=>{const x=performance.now(),S=Ut(l,b.deviceId);let $=b;if(l==="control"&&b.visualChanged){const q=String(f.inputFeedbackEventId||""),W=Number(f.inputFeedbackInputSeq||0),ke=Number(f.inputFeedbackIssuedAtEpochMs||0),Me=Number(f.browserReceivedEpochMs||0),he=vm.current.get(b.deviceId)||"",tt=ke>0?Math.max(0,Date.now()-ke):Number.POSITIVE_INFINITY;if(q.length>0&&W>0&&q!==he&&tt<=Qd){const at=wm.current.get(b.deviceId)||[];at.push(tt),at.length>_g&&at.splice(0,at.length-_g),wm.current.set(b.deviceId,at),$={...b,inputFeedbackSeq:W,inputFeedbackMs:tt,inputFeedbackAt:x,inputFeedbackExact:!0,inputFeedbackEventId:q,inputFeedbackInputType:f.inputFeedbackInputType,inputFeedbackInputToFrameMs:Me>0?Math.max(0,Me-ke):void 0,inputFeedbackFrameToPaintMs:Me>0?Math.max(0,Date.now()-Me):void 0,inputFeedbackAgentApplyMs:f.inputFeedbackAgentApplyMs,inputFeedbackApplyToCaptureMs:f.inputFeedbackApplyToCaptureMs,inputFeedbackSampleCount:at.length,inputFeedbackP50Ms:Go(at,.5),inputFeedbackP95Ms:Go(at,.95)},vm.current.set(b.deviceId,q),Ou.current.set(b.deviceId,W)}else if(!q){const at=v0(b.deviceId),wt=Ou.current.get(b.deviceId)||0,Et=at?x-at.sentAt:Number.POSITIVE_INFINITY;at&&at.inputSeq>wt&&Et<=Qd&&($={...b,inputFeedbackSeq:at.inputSeq,inputFeedbackMs:Math.max(0,Et),inputFeedbackAt:x,inputFeedbackExact:!1},Ou.current.set(b.deviceId,at.inputSeq))}}ga.current.set(S,x),wa.current.delete(S),ys.current.delete(S);const L=vs.current.get(S)||{totalFrames:0,totalChangedFrames:0,sampleFrames:0,sampleChangedFrames:0,sampleStartedAt:x,intervalCount:0,intervalSumMs:0,minIntervalMs:Number.POSITIVE_INFINITY,maxIntervalMs:0,intervalSamplesMs:[],seqGapCount:0,maxSeqGap:0,sampleDecoderInputBase:0,sampleDecoderOutputBase:0},B=as(f);L.bindingKey!==B&&(L.bindingKey=B,L.lastAt=void 0,L.lastFrameSeq=void 0,L.sampleChangedFrames=0,L.sampleDecoderInputBase=Number(b.decoderInputCount||0),L.sampleDecoderOutputBase=Number(b.decoderOutputCount||0),zl(L,x)),l==="control"&&$.inputFeedbackMs===void 0&&L.lastInfo?.inputFeedbackMs!==void 0&&L.lastInfo.inputFeedbackAt!==void 0&&x-L.lastInfo.inputFeedbackAt<=Qd&&($={...$,inputFeedbackSeq:L.lastInfo.inputFeedbackSeq,inputFeedbackMs:L.lastInfo.inputFeedbackMs,inputFeedbackAt:L.lastInfo.inputFeedbackAt,inputFeedbackExact:L.lastInfo.inputFeedbackExact,inputFeedbackEventId:L.lastInfo.inputFeedbackEventId,inputFeedbackInputType:L.lastInfo.inputFeedbackInputType,inputFeedbackInputToFrameMs:L.lastInfo.inputFeedbackInputToFrameMs,inputFeedbackFrameToPaintMs:L.lastInfo.inputFeedbackFrameToPaintMs,inputFeedbackAgentApplyMs:L.lastInfo.inputFeedbackAgentApplyMs,inputFeedbackApplyToCaptureMs:L.lastInfo.inputFeedbackApplyToCaptureMs,inputFeedbackSampleCount:L.lastInfo.inputFeedbackSampleCount,inputFeedbackP50Ms:L.lastInfo.inputFeedbackP50Ms,inputFeedbackP95Ms:L.lastInfo.inputFeedbackP95Ms}),L.totalFrames+=1,L.sampleFrames+=1,Vg(L,x,$.frameSeq),$.visualChanged&&(L.totalChangedFrames+=1,L.sampleChangedFrames+=1),L.lastInfo=$,vs.current.set(S,L)},[]),tl=o.useCallback((l,f)=>{if(Ye.current[l.deviceId]||$s.current===l.deviceId)return;el("wall",l,f);const b=ce&&te===l.deviceId,x=Tt.current.get(l.deviceId)||gn.current.get(l.deviceId);Nc.current&&!Xe&&!b&&x?.isConnected&&Mi("wall-visible",l,f),l.kind==="live"&&(Jr(l.deviceId),un(l.deviceId)),$s.current!==l.deviceId&&!b&&(bs.current.delete(l.deviceId),_s.current.delete(l.deviceId),ai.current.delete(l.deviceId),ha.current.delete(l.deviceId))},[te,ce,Jr,el,Mi,un,Xe]),$m=o.useCallback((l,f)=>{if(Ye.current[l.deviceId]||Dt(ir.current,it.current)||!Fd(l,it.current))return;el("control",l,f),De(L=>L&&"");const b=Ht.current.get(l.deviceId),x=_n.current.get(l.deviceId);let S=!1;b&&b.width>0&&b.height>0&&(x&&Xe&&l.deviceId===Pe&&(S=Yc(b,x),S&&Mi("control-visible",l,f)),ma.current.set(l.deviceId,qa(l)),bs.current.add(l.deviceId),l.deviceId===te&&(J(!0),le(L=>L==="connecting"?"active":L)),ks(l.deviceId,!1,l));const $=Ec.current;!$||!gP($,l)||!S||(Zc(l.deviceId,"fresh-frame"),$n(!0))},[Zc,Pe,te,ks,Yc,el,Mi,Xe]),Ta=o.useCallback((l,f)=>{const b=performance.now(),x=Ut(l,f.deviceId);Bs.current.set(x,b),qr.current.delete(x),l==="control"?ba.current.delete(x):di.current.delete(x);const S=Os.current.get(x)||{totalFrames:0,sampleFrames:0,sampleStartedAt:b,intervalCount:0,intervalSumMs:0,minIntervalMs:Number.POSITIVE_INFINITY,maxIntervalMs:0,intervalSamplesMs:[],seqGapCount:0,maxSeqGap:0,sampleBytes:0,sampleH264Frames:0,sampleTinyFrames:0,sampleRepeatedFrames:0,sourceSendIntervalsMs:[]},$=as(f);if(S.bindingKey!==$&&(S.bindingKey=$,S.lastAt=void 0,S.lastFrameSeq=void 0,S.lastContentHash=void 0,S.sampleBytes=0,S.sampleH264Frames=0,S.sampleTinyFrames=0,S.sampleRepeatedFrames=0,S.sourceSendIntervalsMs.length=0,zl(S,b)),S.totalFrames+=1,S.sampleFrames+=1,S.sampleBytes+=Math.max(0,Number(f.byteLength||0)),String(f.frameMode||f.mode||f.codec||f.mimeType||"").toLowerCase().includes("h264")){S.sampleH264Frames+=1,Number(f.byteLength||0)<=dP&&(S.sampleTinyFrames+=1);const W=String(f.contentHash||"");W&&S.lastContentHash===W&&(S.sampleRepeatedFrames+=1),S.lastContentHash=W}const q=Number(f.agentSendGapMs||0);q>0&&q<1e3&&Rw(S.sourceSendIntervalsMs,q),S.lastFrame=qa(f),Vg(S,b,f.frameSeq),Os.current.set(x,S)},[]);o.useEffect(()=>{const l=new Set(Dm);for(const x of vs.current.keys())l.has(x)||vs.current.delete(x);for(const x of Os.current.keys())l.has(x)||Os.current.delete(x);const f=x=>{const S=Object.entries(x).filter(([$])=>l.has($));return S.length===Object.keys(x).length?x:Object.fromEntries(S)};if(Du(f),Ic(f),l.size===0)return;const b=window.setInterval(()=>{const x=performance.now(),S={},$={};for(const L of l){const B=vs.current.get(L);if(B){const Me=Math.max(1,x-B.sampleStartedAt);S[L]={bindingKey:B.bindingKey||"",totalFrames:B.totalFrames,totalChangedFrames:B.totalChangedFrames,framesPerSecond:B.sampleFrames*1e3/Me,changedFramesPerSecond:B.sampleChangedFrames*1e3/Me,averageIntervalMs:B.intervalCount>0?B.intervalSumMs/B.intervalCount:0,minIntervalMs:Number.isFinite(B.minIntervalMs)?B.minIntervalMs:0,maxIntervalMs:B.maxIntervalMs,p95IntervalMs:Go(B.intervalSamplesMs,.95),intervalCount:B.intervalCount,seqGapCount:B.seqGapCount,maxSeqGap:B.maxSeqGap,decoderInputFps:Math.max(0,(Number(B.lastInfo?.decoderInputCount||0)-B.sampleDecoderInputBase)*1e3/Me),decoderOutputFps:Math.max(0,(Number(B.lastInfo?.decoderOutputCount||0)-B.sampleDecoderOutputBase)*1e3/Me),sampleMs:Me,lastInfo:B.lastInfo},B.sampleDecoderInputBase=Number(B.lastInfo?.decoderInputCount||0),B.sampleDecoderOutputBase=Number(B.lastInfo?.decoderOutputCount||0),B.sampleChangedFrames=0,zl(B,x)}const q=Os.current.get(L);if(!q)continue;const W=Math.max(1,x-q.sampleStartedAt),ke=q.lastFrame?qa(q.lastFrame):void 0;q.lastFrame=ke,$[L]={totalFrames:q.totalFrames,framesPerSecond:q.sampleFrames*1e3/W,averageIntervalMs:q.intervalCount>0?q.intervalSumMs/q.intervalCount:0,minIntervalMs:Number.isFinite(q.minIntervalMs)?q.minIntervalMs:0,maxIntervalMs:q.maxIntervalMs,p95IntervalMs:Go(q.intervalSamplesMs,.95),intervalCount:q.intervalCount,seqGapCount:q.seqGapCount,maxSeqGap:q.maxSeqGap,averageFrameBytes:q.sampleFrames>0?q.sampleBytes/q.sampleFrames:0,tinyFrameRatio:q.sampleH264Frames>0?q.sampleTinyFrames/q.sampleH264Frames:0,repeatedFrameRatio:q.sampleH264Frames>0?q.sampleRepeatedFrames/q.sampleH264Frames:0,sourceSendAverageMs:q.sourceSendIntervalsMs.length>0?q.sourceSendIntervalsMs.reduce((Me,he)=>Me+he,0)/q.sourceSendIntervalsMs.length:0,sourceSendP95Ms:Go(q.sourceSendIntervalsMs,.95),sourceSendSampleCount:q.sourceSendIntervalsMs.length,sampleMs:W,lastFrame:ke},q.sampleBytes=0,q.sampleH264Frames=0,q.sampleTinyFrames=0,q.sampleRepeatedFrames=0,q.sourceSendIntervalsMs.length=0,zl(q,x)}Du(S),Ic($)},1e3);return jc.current=b,()=>{window.clearInterval(b),jc.current===b&&(jc.current=null)}},[Dm]);const Om=o.useCallback(l=>{const f=l.deviceId,b=as(l);if(Ye.current[f]||$s.current===f||l.currentGenerationVerified!==!0||zr.current.get(f)!==b)return;Ta("wall",l);const x=Tt.current.get(f);if(!x)return;const S=mi(x),$=hi(x),L=()=>Tt.current.get(f)!==x||!fi(x,S)||!!Ye.current[f]||$s.current===f||zr.current.get(f)!==b,B=()=>L()||!ya(x,$),q=kk(St,ot.h264DecodeAcceleration);Td(x,l,B,tl,q.acceleration,q.latencyMode,L,Xc).catch(()=>{})},[mi,ya,fi,hi,tl,St,Ta,Xc,ot.h264DecodeAcceleration]),Bm=o.useCallback(l=>{const f=l.deviceId;if(Ye.current[f]||Dt(ir.current,it.current)||!Fd(l,it.current))return;let b=Ht.current.get(f);if(!b){const he=_n.current.get(f),tt=pa.current;b=he||tt||document.createElement("canvas"),he&&tt&&tt!==he&&Hn(tt),pa.current=null,b!==he&&b.setAttribute("aria-hidden","true"),Ht.current.set(f,b)}const x=b,S=l,$=mi(x),L=hi(x),B=()=>Ht.current.get(f)!==x||!fi(x,$)||!!Ye.current[f]||!Fd(S,it.current),q=()=>B()||!ya(x,L),W=qe.current,ke=String(l.frameMode||l.mode||l.codec||l.mimeType||"").toLowerCase().includes("h264");ke||Ta("control",l);const Me=Td(x,l,q,$m,rn.h264DecodeAcceleration,"interactive",B);ke&&Ta("control",l),Me.catch(he=>{qe.current!==W||Ht.current.get(f)!==x||!ya(x,L)||B()||te!==f||De(he instanceof Error?he.message:String(he||"Control H.264 decode failed"))})},[mi,ya,fi,hi,te,rn.h264DecodeAcceleration,$m,Ta,Hn]),sy=o.useCallback(l=>{const f=ar.current;ar.current=l,f&&f!==l&&Bn(f),wo.current=0,Dc.current=0,Lc.current=0,_c.current=0,$u.current=0,go.current=0},[Bn]),Ai=o.useCallback(()=>{const l=new Set,f=ar.current,b=oi.current;if(!f||!b||f.width<=0||f.height<=0||go.current!==b.layoutVersion)return l;for(const x of b.tiles){if(Ye.current[x.deviceId])continue;const S=gn.current.get(x.deviceId);if(!S||x.width<=0||x.height<=0)continue;const $=Math.max(1,Math.round(x.width)),L=Math.max(1,Math.round(x.height)),B=pP,q=mP;(S.width!==B||S.height!==q)&&(S.width=B,S.height=q);const W=S.getContext("2d",{alpha:!1});if(W){W.imageSmoothingEnabled=!0,W.imageSmoothingQuality="high";try{W.drawImage(f,Math.round(x.x),Math.round(x.y),$,L,0,0,B,q),l.add(x.deviceId)}catch{}}}return l},[]),ay=o.useCallback((l,f)=>{const b=gn.current.get(l);if(f&&b&&b!==f&&Ra(l,b),f){if(gn.current.set(l,f),b&&b!==f&&Bn(b),Ye.current[l]){un(l),Hn(f),Zr(l);return}gs.current.get(l)&&Jc(l,f)&&Jr(l),window.requestAnimationFrame(()=>{Ai().has(l)&&un(l)}),window.requestAnimationFrame(()=>ks(l,!0));return}gn.current.delete(l),un(l),Bn(b),Zr(l)},[Zr,Jr,Ai,ks,Jc,Ra,Hn,un,Bn]),Hm=o.useCallback((l,f)=>{Lc.current=performance.now(),go.current=Number(l.layoutVersion||0),Ai();const b=oi.current?.tiles||[],x=b.length>0?Math.round(l.byteLength/b.length):l.byteLength;for(const S of b){if(Ye.current[S.deviceId])continue;const $={...l,deviceId:S.deviceId,width:S.width,height:S.height,sourceWidth:S.width,sourceHeight:S.height,byteLength:x};tl($,{...f,deviceId:S.deviceId,width:S.width,height:S.height,byteLength:x}),$s.current===S.deviceId&&ks(S.deviceId,!0)}},[tl,Ai,ks]),iy=o.useCallback(l=>{const f=performance.now();wo.current<=0&&(wo.current=f),Dc.current=f;const b=ar.current;if(!b)return;const x=as(l);fo.current!==x&&(fo.current=x,sn(b));const S=mi(b),$=hi(b),L=()=>ar.current!==b||fo.current!==x||!fi(b,S),B=()=>L()||!ya(b,$),q=oi.current?.tiles||[],W=q.length>0?Math.round(l.byteLength/q.length):l.byteLength;for(const ke of q)Ye.current[ke.deviceId]||Ta("wall",{...l,deviceId:ke.deviceId,width:ke.width,height:ke.height,sourceWidth:ke.width,sourceHeight:ke.height,byteLength:W});Td(b,l,B,Hm,void 0,"smooth",L).catch(()=>{})},[mi,ya,fi,hi,Hm,Ta,sn]),Wm=o.useCallback(l=>{if(l.streamPurpose!=="wall"||Ye.current[l.deviceId])return;const f=as(l);zr.current.get(l.deviceId)!==f&&(zr.current.set(l.deviceId,f),sn(Tt.current.get(l.deviceId)))},[sn]),oy=o.useMemo(()=>({fps:Nn.fps,maxWidth:Nn.maxWidth,maxHeight:Nn.maxHeight,quality:Nn.quality,mode:St?"mode3-h264-hw":ot.frameMode,frameMode:St?"mode3-h264-hw":ot.frameMode,streamPurpose:"wall",configurationRefreshMs:UT,forceRestart:pi>0,forceRestartToken:pi>0?`document-presentation-resume-${pi}`:"",restartReason:pi>0?"document-presentation-resume":"",connectionSessionIds:Ss,monitorSelections:Ct,onFrame:Om,onStreamReady:Wm}),[Ss,pi,Om,Wm,St,Ct,ot.frameMode,Nn.fps,Nn.maxHeight,Nn.maxWidth,Nn.quality]),zm=o.useCallback(l=>{const f=it.current;if(Ye.current[l.deviceId]||!f||Dt(ir.current,f)||f.deviceId!==l.deviceId||l.deviceId!==te||l.streamPurpose!=="control"||l.monitorIndex!==Rr)return;const b=Ze.find(S=>S.deviceId===l.deviceId);if(!b?.sessionId||b.sessionId!==l.sessionId)return;const x=T.current;(!x||as(x)!==as(l))&&sn(Ht.current.get(l.deviceId)),it.current=Ed(f.deviceId,f.transitionGeneration,l),T.current=l,nt(l),le(S=>S==="connecting"?"active":S)},[Ze,te,sn,Rr]);o.useEffect(()=>{sn(Ht.current.get(te)),T.current=null,nt(null)},[te,Fe,fr,sn,Rr]);const nl=Fe?`${Fe}-monitor-${Rr}`:"",cy=o.useMemo(()=>({fps:Mo,maxWidth:Kr.maxWidth,maxHeight:Kr.maxHeight,quality:rn.quality,mode:fr,frameMode:fr,streamPurpose:"control",forceRestart:nl!=="",forceRestartToken:nl,restartReason:nl?"control-session-or-monitor-change":"",connectionSessionIds:Ss,monitorSelections:Ct,onFrame:Bm,onStreamReady:zm}),[Ss,nl,rn.quality,Bm,Mo,fr,Kr.maxHeight,Kr.maxWidth,zm,Ct]),{frames:qm,state:No,error:Um,stats:Pa,restartLive:rl,reconnectLive:Vm}=ff(or,ot.autoStartLive&&or.length>0,G,oy);o.useEffect(()=>{const l=new Set(or);for(const f of zr.current.keys())l.has(f)||(zr.current.delete(f),sn(Tt.current.get(f)))},[or,sn]);const{frame:Ni,layout:Ia,state:Ju,stats:ly,refreshInputs:Gm}=C0(Qn,St&&ot.autoStartLive&&Qn.length>0,G,{fps:$t.atlasOutputFps,inputFps:Xu,width:1920,height:1080,tileWidth:ki.maxWidth,tileHeight:ki.maxHeight,captureDeviceIds:Qn,connectionSessionIds:Ss,monitorSelections:Ct,onFrame:iy});o.useEffect(()=>{oi.current=Ia,Ia&&window.requestAnimationFrame(Ai)},[Ia,Ai]),o.useEffect(()=>{if(!St||Ju!=="open"){wo.current=0,Dc.current=0,Lc.current=0;return}const l=window.setInterval(()=>{const f=ar.current,b=performance.now();if(!f||document.visibilityState!=="visible"||b-Fc.current<Kd)return;const x=Dc.current,S=wo.current;if(x<=0||S<=0||b-x>500)return;const $=Lc.current||S,L=b-$;if(L>=nP&&b-$u.current>=sP){qi(f)&&($u.current=b,_c.current=b);return}L>=tP&&b-_c.current>=rP&&mC(f)&&(_c.current=b)},250);return()=>window.clearInterval(l)},[Ju,St]);const{frames:Ro,state:Zu,error:To,stats:uy,restartLive:sl,reconnectLive:Po}=ff(Ci,Ci.length>0,G,cy);o.useEffect(()=>{const l=xc.current,f=new Set([...Object.keys(l),...Object.keys(Ct)]);for(const b of f){const x=Math.max(0,Math.floor(Number(l[b])||0)),S=Math.max(0,Math.floor(Number(Ct[b])||0));x!==S&&(zr.current.delete(b),sn(Tt.current.get(b)),sn(Ht.current.get(b)),sn(gn.current.get(b)),bn("wall",b),bn("control",b),qi(Tt.current.get(b)||null),qi(Ht.current.get(b)||null))}f.size>0&&(sn(ar.current),qi(ar.current)),xc.current={...Ct}},[Ct,bn,sn]);const Ri=o.useMemo(()=>{const l=(b,x)=>{const S=Ze.find(L=>L.deviceId===b),$=S?lr(S,Ct[b]):0;return!Number.isFinite(Number(x.monitorIndex))||Number(x.monitorIndex)===$},f=new Map;for(const[b,x]of qm.entries())l(b,x)&&f.set(b,x);if(St&&Ni&&Qn.length>0){const b=new Map((Ia?.tiles||[]).map(S=>[S.deviceId,S])),x=Math.max(1,b.size);for(const S of Qn){const $=b.get(S);$&&f.set(S,{...Ni,deviceId:S,width:$.width,height:$.height,sourceWidth:$.width,sourceHeight:$.height,byteLength:Math.round(Ni.byteLength/x)})}}for(const[b,x]of Ro.entries())l(b,x)&&f.set(b,x);for(const b of Vc){if(!bs.current.has(b)||f.has(b))continue;const x=ma.current.get(b);x&&l(b,x)&&f.set(b,x)}return f},[Ni,Ia,Ze,Ro,Qn,St,Ct,qm,Vc,Ls]),ed=Xe&&Ci.length>0?Zu:Qn.length>0?Ju:No,al=Xe&&Ci.length>0?uy:Qn.length>0?ly:Pa;o.useCallback((l,f="browser-stale")=>{const b=rl(l,f),x=sl(l,f);return b||x},[sl,rl]),o.useEffect(()=>{St&&Qn.length>0&&!Xe&&Gm()},[Qn.length,St,Gm,Xe]);const Ti=o.useCallback((l,f,b)=>{const x=f==="control"?Ht.current.get(l)||null:Tt.current.get(l)||null;if(!x)return!1;qi(x);const S=performance.now();return wa.current.set(Ut(f,l),S),!0},[]),Io=o.useCallback(l=>{if(fr!=="mode3-h264-hw"||!te||Ue)return!1;const f=Ze.find(B=>B.deviceId===te)||vn,b=ob(f?.platform);if(!b)return!1;const x=Ut("control",te),S=performance.now();va.current.set(x,S),Bs.current.delete(x),ga.current.delete(x),ui.current.delete(x),ba.current.delete(x),ys.current.delete(x),qi(Ht.current.get(te)||null),Po([te],"control-decode-fallback"),ne(b),Le(`control-${b}-fallback-${te}-${Date.now()}`),J(!1),$n(!1);const $=l==="no first frame"||l==="control-first-frame-timeout",L=b==="mode1-jpeg"?"Mode 1 JPEG":"Mode 5";return De(B=>B||($?`Control frame transport timeout; retrying Control with ${L} (${l})`:`H.264 decode failed; retrying Control with ${L} (${l})`)),le("connecting"),!0},[Ze,vn,te,Ue,fr,Po]);o.useEffect(()=>{const l=Xe?vn:null;if(l){Ec.current={deviceId:l.deviceId,monitorIndex:Rr,frameMode:fr,startedAtEpochMs:Date.now()},$n(te===l.deviceId&&ce);return}Ec.current=null,$n(!1)},[vn?.sessionId,Pe,te,ce,fr,Rr,Xe]);const Km=o.useCallback(async(l,f)=>{const b=String(f.streamId||"").trim(),x=String(f.streamPurpose||"").trim(),S=String(f.sessionId||"").trim(),$=String(f.commandId||"").trim(),L=Number(f.captureGeneration||0),B=Number(f.monitorIndex??-1);if(!b||!["wall","atlas"].includes(x)||!S||!$||!Number.isSafeInteger(L)||L<=0||!Number.isSafeInteger(B)||B<0)throw new Error("wall-start-owner-incomplete");const q=performance.now()+3e3;for(;;){const W=await Oe(`/api/remote/devices/${encodeURIComponent(l)}/live/stop`,{method:"POST",body:JSON.stringify({streamId:b,streamPurpose:x,expectedSessionId:S,expectedCommandId:$,expectedCaptureGeneration:L,expectedMonitorIndex:B,requireNoPresentationOwner:!0,reason:"wall-start-presentation-revoked"})},G);if(W?.ok===!1)throw new Error(W.error||"revoked-wall-start-stop-failed");if(W?.captureStopConfirmed===!0||W?.alreadyStopped===!0||W?.staleOwner===!0)return W;if(W?.presentationOwnerActive===!0||W?.retainedForPresentation===!0){if(Mr.current&&vi.current)return W;if(performance.now()<q){await new Promise(ke=>window.setTimeout(ke,50));continue}throw new Error("revoked-wall-start-presentation-owner-did-not-release")}throw new Error("revoked-wall-start-stop-unconfirmed")}},[G]),ja=o.useCallback(async l=>{if(Ye.current[l])throw new Error("LIVE_CAPTURE_PAUSED");if(!Mr.current||!vi.current)return{ok:!0,skipped:!0,reason:"wall-capture-owner-hidden"};const f=Ur.current,b=D.find(L=>L.deviceId===l);zo({mode4Enabled:St,directMode4WallEnabled:Xr,isMac:cs(b?.platform)});const x=b?lr(b,Ct[l]):0,S={fps:Nn.fps,maxWidth:Nn.maxWidth,maxHeight:Nn.maxHeight,quality:Nn.quality,mode:St?"mode3-h264-hw":ot.frameMode,frameMode:St?"mode3-h264-hw":ot.frameMode,streamPurpose:"wall",monitorIndex:x},$=await Oe(`/api/remote/devices/${encodeURIComponent(l)}/live/start`,{method:"POST",body:JSON.stringify(S)},G);if($?.ok===!1)throw new Error($.error||"wall-stream-start-failed");return f!==Ur.current||!Mr.current||!vi.current?(await Km(l,$),{...$,skipped:!0,reason:"wall-presentation-owner-revoked",compensated:!0}):$},[Xu,D,Xr,G,St,Ct,Km,ot.frameMode,ki.maxHeight,ki.maxWidth,Nn.fps,Nn.maxHeight,Nn.maxWidth,Nn.quality]),Qm=o.useCallback(async l=>{const f=D.find(x=>x.deviceId===l);zo({mode4Enabled:St,directMode4WallEnabled:Xr,isMac:cs(f?.platform)});const b=await Oe(`/api/remote/devices/${encodeURIComponent(l)}/live/stop`,{method:"POST",body:JSON.stringify({streamPurpose:"wall",reason:"control-active"})},G);if(b?.ok===!1)throw new Error(b.error||"wall-stream-stop-failed");return b},[D,Xr,G,St]),Ym=o.useCallback(async(l,f="control-session-stop")=>{const b=await Oe(`/api/remote/devices/${encodeURIComponent(l)}/live/stop`,{method:"POST",body:JSON.stringify({streamPurpose:"control",reason:f})},G);if(b?.ok===!1)throw new Error(b.error||"control-stream-stop-failed");return b},[G]),Yn=o.useCallback((l,f={})=>{ir.current?.deviceId===l&&(ir.current=null);const b=Ht.current.get(l);if(b){const S=gs.current.has(l)||Tt.current.has(l)||gn.current.has(l);f.preservePresentation!==!1&&!S&&Ra(l,b),Ht.current.delete(l),Hn(b),!(_n.current.get(l)||Tt.current.get(l)||gn.current.get(l))&&!pa.current&&(pa.current=b)}const x=_n.current.get(l);x&&zi(x),ma.current.delete(l),bs.current.delete(l),_s.current.delete(l),ai.current.delete(l),ha.current.delete(l)},[Ra,Hn]),il=o.useCallback(l=>{const f=[Ut("wall",l),Ut("control",l)];for(const b of f){const x=Os.current.get(b);x?.lastFrame&&(x.lastFrame=qa(x.lastFrame))}Ic(b=>{let x=!1;const S={...b};for(const $ of f){const L=b[$];!L?.lastFrame||L.lastFrame.payload.byteLength===0||(S[$]={...L,lastFrame:qa(L.lastFrame)},x=!0)}return x?S:b})},[]),td=o.useCallback(l=>{zr.current.delete(l),un(l),Yn(l,{preservePresentation:!1});const f=new Set;for(const b of[_n.current.get(l),Tt.current.get(l),gn.current.get(l)])b&&f.add(b);for(const b of f)Hn(b);Zr(l),te===l&&(Ec.current=null,$n(!1),J(!1)),Gt.current.add(l),il(l)},[Zr,te,Hn,Yn,il,un]);o.useEffect(()=>{const l=new Set(Object.keys(je));for(const f of l)Gt.current.has(f)||td(f);for(const f of Gt.current)l.has(f)||Gt.current.delete(f)},[td,je]);const Pi=o.useCallback(l=>{const f=Tf(mm.current,l);return mm.current=f.tail,f.result},[]),br=o.useCallback(l=>{const f=Tf(bm.current,l);return bm.current=f.tail,f.result},[]),vr=o.useCallback(l=>{Gn.current=l,Ac.current=0;const f=l?.deviceId||"";$s.current=f,Sc(f),f&&bs.current.add(f)},[]),Ii=o.useCallback(l=>Pi(async()=>{if(Ye.current[l.deviceId])return!1;const f=Gn.current;return!Dt(f,l)||!Tl(l.deviceId,l,it.current)?!1:(await ja(l.deviceId),Dt(Gn.current,l)&&vr(null),!0)}),[vr,Pi,ja]),Xm=o.useCallback((l,f,b)=>Pi(async()=>{const x=Gn.current;if(Dt(x,l))return b.stoppedWallDeviceId=l.deviceId,!0;if(x)if(Ye.current[x.deviceId])Dt(Gn.current,x)&&vr(null);else{if(!Tl(x.deviceId,x,it.current))return!1;await ja(x.deviceId),Dt(Gn.current,x)&&vr(null)}if(!f())return!1;if(await Qm(l.deviceId),b.stoppedWallDeviceId=l.deviceId,!f()){if(Tl(b.stoppedWallDeviceId,l,it.current))try{await ja(b.stoppedWallDeviceId)}catch(S){throw vr(l),S}finally{b.stoppedWallDeviceId=""}return!1}return zi(Tt.current.get(l.deviceId)||null),vr(l),!0}),[vr,Pi,ja,Qm]),ol=o.useCallback(async(l,f)=>{if(f.stoppedWallDeviceId){if(Dt(Gn.current,l)){try{await Ii(l)}catch(b){we(b instanceof Error?b.message:String(b))}finally{f.stoppedWallDeviceId=""}return}await Pi(async()=>{if(!f.stoppedWallDeviceId||!Tl(f.stoppedWallDeviceId,l,it.current))return;const b=f.stoppedWallDeviceId;try{await ja(b)}catch(x){vr(l),we(x instanceof Error?x.message:String(x))}finally{f.stoppedWallDeviceId=""}})}},[vr,Pi,Ii,we,ja]),wr=o.useCallback(async(l,f,b={})=>{const x=b.allowStopFailure===!0,S=b.resumeWall!==!1;try{await Ym(l.deviceId,f)}catch($){if(!x)throw $}if(!Dt(it.current,l))return!1;if(it.current=null,T.current=null,nt(null),Yn(l.deviceId),J(!1),Le(""),ne(""),De(""),Ce($=>$===l.deviceId?"":$),!S)return Dt(Gn.current,l)&&vr(null),!0;try{await Ii(l)}catch($){we($ instanceof Error?$.message:String($))}return!0},[vr,Yn,Ii,we,Ym]),Jm=(On&&Xe&&Rt&&Pe&&!Un.has(Pe)&&Ze.find(l=>l.deviceId===Pe)||null)?.deviceId||"";o.useEffect(()=>{ci.current=Jm},[Jm]),o.useEffect(()=>{const l=Pe&&Ze.find($=>$.deviceId===Pe)||null;if(!On||!Xe||!Rt||!l){Mn.current&&(++Kt.current,Mn.current="");return}if(Ye.current[l.deviceId]){Mn.current&&(++Kt.current,Mn.current=""),te===l.deviceId&&le("paused");return}if(hr.current){if(hr.current===l.deviceId)return;hr.current=""}if(te===l.deviceId&&(ae==="active"||ae==="warm"||ae==="connecting")){le($=>$==="warm"?"active":$);return}if(Mn.current===l.deviceId)return;const f=++Kt.current,b=Ed(l.deviceId,f,{sessionId:l.sessionId,monitorIndex:Rr});Mn.current=l.deviceId;const x={stoppedWallDeviceId:""},S=()=>f===Kt.current&&ci.current===b.deviceId;br(async()=>{if(!S())return;const $=it.current;if($){le("stopping");try{await wr($,"control-session-switch")}catch(q){S()&&(le("error"),we(q instanceof Error?q.message:String(q)));return}if(!S()){it.current||le("idle");return}}try{if(!await Xm(b,S,x)||!S()){await ol(b,x),it.current||le("idle");return}}catch(q){await ol(b,x),S()&&(le("error"),we(q instanceof Error?q.message:String(q)));return}if(!S()){await ol(b,x);return}it.current=b,ir.current=null,hr.current="",fa.current=null,li.current=0,vo.current="",x.stoppedWallDeviceId="";const L=Ut("control",b.deviceId),B=`control-session-${f}-${b.deviceId}`;va.current.set(L,performance.now()),Bs.current.delete(L),ga.current.delete(L),ys.current.delete(L),ba.current.delete(L),ne(""),De(""),Le(B),Ce(b.deviceId),J(!1),le("connecting")}).catch($=>{S()&&(le("error"),we($ instanceof Error?$.message:String($)))}).finally(()=>{Kt.current===f&&Mn.current===b.deviceId&&(Mn.current="")})},[Ze,Pe,te,ae,On,br,Rt,Xm,ol,Rr,we,Xe,wr,je]),o.useEffect(()=>{if(!te||Ze.some(b=>b.deviceId===te))return;const l=te;++Kt.current,Mn.current="";const f=it.current;le("stopping"),br(async()=>{f&&f.deviceId===l?await wr(f,"control-device-disconnected",{allowStopFailure:!0}):(Yn(l),Ce(b=>b===l?"":b)),it.current||le("idle")})},[Ze,te,br,Yn,wr]),o.useEffect(()=>{if(mr.current!==null&&(window.clearTimeout(mr.current),mr.current=null),!Nr||Xe||!te||Ye.current[te]||ae!=="connecting"&&ae!=="active"&&ae!=="warm")return;const l=te,f=it.current;if(!f||f.deviceId!==l)return;const b=window.setTimeout(()=>{mr.current===b&&(mr.current=null);const x=it.current;if(ci.current||Ye.current[l]||!Dt(x,f))return;ir.current=f;const S=++Kt.current;Mn.current="",le("stopping"),br(async()=>{if(S!==Kt.current||ci.current||!Dt(it.current,f)){Dt(ir.current,f)&&(ir.current=null),Dt(it.current,f)&&ci.current===l&&le("active");return}try{await wr(f,"control-session-wall-downshift")}catch($){Dt(ir.current,f)&&(ir.current=null),S===Kt.current&&!ci.current&&Dt(it.current,f)&&(le("active"),we($ instanceof Error?$.message:String($)));return}ir.current=null,S===Kt.current&&!it.current&&le("idle")})},uP);return mr.current=b,()=>{mr.current===b&&(window.clearTimeout(b),mr.current=null)}},[te,ae,br,we,Xe,wr,je,Nr]);const cl=o.useCallback(l=>{if(gm.current===l)return;gm.current=l;const f=it.current,b=f?.deviceId||te,x=++Kt.current;Mn.current="",T.current=null,bo.current=!0,nt(null),J(!1),$n(!1),b&&(bn("control",b),Yn(b,{preservePresentation:!1}),le("stopping"),br(async()=>{if(f&&f.deviceId===b)try{await wr(f,"control-session-document-hidden",{resumeWall:!1})}catch(S){!Mr.current&&Ur.current===l&&(le("error"),we(S instanceof Error?S.message:String(S)));return}else Yn(b,{preservePresentation:!1}),Ce(S=>S===b?"":S);!it.current&&Kt.current===x&&le("idle")}))},[te,br,Yn,bn,we,wr]);o.useEffect(()=>{if(kr.current!==null&&(window.clearTimeout(kr.current),kr.current=null),!te||ae==="idle"||ae==="paused"||ae==="error")return;if(!On){cl(Ur.current);return}if(ae==="stopping"||wi){te&&Bc&&ae==="connecting"&&(bo.current=!1),te&&Bc&&bo.current&&(ae==="warm"||ae==="active")&&(bo.current=!1,T.current=null,nt(null),J(!1),$n(!1),bn("control",te),Le(`control-presentation-resume-${Date.now()}-${te}`),le("connecting"));return}T.current=null,bo.current=!0,nt(null),J(!1),$n(!1),le(f=>f==="idle"||f==="stopping"?f:"warm");const l=te;return Yn(l,{preservePresentation:!1}),kr.current=window.setTimeout(()=>{kr.current=null,++Kt.current,Mn.current="";const f=it.current;le("stopping"),br(async()=>{if(f&&f.deviceId===l)try{await wr(f,"control-session-warm-timeout")}catch(b){le("error"),we(b instanceof Error?b.message:String(b));return}else Yn(l),Ce(b=>b===l?"":b);it.current||le("idle")})},lP),()=>{kr.current!==null&&(window.clearTimeout(kr.current),kr.current=null)}},[wi,Bc,te,ae,On,br,Yn,cl,bn,we,wr]),o.useEffect(()=>()=>{kr.current!==null&&window.clearTimeout(kr.current),mr.current!==null&&(window.clearTimeout(mr.current),mr.current=null),ir.current=null},[]);const ll=o.useCallback(()=>{const l=new Set(_u.current),f=it.current?.deviceId||"";te&&l.add(te),f&&l.add(f),_u.current=[];for(const x of l){zr.current.delete(x),un(x),Yn(x,{preservePresentation:!1});for(const S of[Tt.current.get(x),_n.current.get(x),gn.current.get(x)])S&&Hn(S);Zr(x),bn("wall",x),bn("control",x),il(x)}const b=ar.current;b&&Hn(b),fo.current="",oi.current=null,go.current=0},[Zr,te,Hn,Yn,il,un,bn]);o.useEffect(()=>{if(On){_u.current=[...Yu];return}ll()},[On,Yu,ll]),o.useEffect(()=>{const l=Gn.current,f=it.current;if(!Nr||!l||Ye.current[l.deviceId]||f&&f.deviceId===l.deviceId){Ac.current=0;return}const b=Ac.current,x=Math.min(5e3,500*2**Math.min(b,4)),S=window.setTimeout(()=>{ii.current===S&&(ii.current=null);const $=Gn.current;!Rm.current||!$||Ye.current[$.deviceId]||!Dt($,l)||(Ac.current=b+1,Ii($).catch(L=>{we(L instanceof Error?L.message:String(L)),Dt(Gn.current,$)&&!it.current&&ju(B=>B+1)}))},x);return ii.current=S,()=>{window.clearTimeout(S),ii.current===S&&(ii.current=null)}},[ae,Ii,we,Nr,Iu,Ds]);const Ws=te&&Ze.find(l=>l.deviceId===te)||null,ji=!!(Xe&&_e&&ae==="active"&&ce&&Ws?.sessionId&&Ee?.deviceId===Ws.deviceId&&Ee.sessionId===Ws.sessionId&&Ee.streamPurpose==="control"&&Ee.commandId&&Ee.captureGeneration>0&&Ee.monitorIndex===Rr),Zm=Ws?.capabilities?.clipboardProtocol==="livedesk.clipboard.v1",eh=Zm&&Xi(Ws,"clipboardCopy"),th=Zm&&Xi(Ws,"clipboardPaste"),{state:jo,connectionId:Ea,sendInput:nh,stats:es,error:rh}=k0(On&&Pr&&ji,G),Ei=Ws?.deviceId||"",Fi=Ws?.sessionId||"",Di=Ee?.commandId||"",Li=Number(Ee?.captureGeneration||0),Eo=Number(Ee?.monitorIndex||0),Fo=o.useCallback((l,f)=>!Mr.current||!ji||!Ei||!Fi||!Di||Li<=0||l!==Ei?!1:nh(l,{...f,monitorIndex:Eo,controlSessionId:Fi,controlCommandId:Di,captureGeneration:Li}),[ji,Li,Di,Ei,Eo,Fi,nh]),ul=[Ei,Fi,Di,Li,Eo,Ea].join("|"),nd=o.useRef(ul);nd.current=ul;const dl=o.useRef(null),Wn=o.useCallback(async(l,f,b,x,S=15e3)=>{if(!Ea||nd.current!==x)throw new Error("Remote Control changed before the clipboard transfer completed.");const $=await Oe(`/api/remote/devices/${encodeURIComponent(Ei)}/clipboard`,{method:"POST",timeoutMs:S,body:JSON.stringify({action:l,hubConnectionId:Ea,operationId:f,binding:{sessionId:Fi,commandId:Di,captureGeneration:Li,monitorIndex:Eo},payload:b})},G);if(nd.current!==x)throw new Error("Remote Control changed before the clipboard transfer completed.");if($?.ok===!1)throw new Error($.error||"Remote clipboard transfer failed.");return $},[Li,Di,Ei,Eo,Fi,Ea,G]),sh=o.useCallback(async(l,f)=>{const b=window.liveDesk?.clipboard;let x=!1,S=!1;try{await Wn("clipboard.prepare",l,{clipboardDirection:"copy"},f),await Wn("clipboard.copy",l,{clipboardDirection:"copy"},f),S=!0;const $=await Wn("clipboard.copy.begin",l,{},f),L=yp($.manifest,l);if(b?.beginWrite&&b.writeChunk&&b.commitWrite){await b.beginWrite(L),x=!0;for(const B of L.items)for(const q of Id(B.size)){const W=await Wn("clipboard.copy.chunk",l,{itemIndex:B.itemIndex,offset:q.offset,maxBytes:Ql},f),ke=Dg(String(W.dataBase64||""));if(Number(W.itemIndex)!==B.itemIndex||Number(W.offset)!==q.offset||Number(W.bytes)!==q.byteLength||ke.byteLength!==q.byteLength||W.final===!0!==q.final)throw new Error("Remote clipboard chunk did not match the requested file range.");await b.writeChunk({operationId:l,itemIndex:B.itemIndex,offset:q.offset,dataBase64:String(W.dataBase64||""),final:q.final})}await b.commitWrite(l),x=!1}else{if(L.contentKind==="files")throw new Error("Multiple files require the LiveDesk desktop app.");const B=[];for(const q of L.items){const W=new Uint8Array(q.size);for(const ke of Id(q.size)){const Me=await Wn("clipboard.copy.chunk",l,{itemIndex:q.itemIndex,offset:ke.offset,maxBytes:Ql},f),he=Dg(String(Me.dataBase64||""));if(he.byteLength!==ke.byteLength)throw new Error("Remote clipboard chunk was incomplete.");W.set(he,ke.offset)}if(await Aw(W)!==q.sha256)throw new Error("Remote clipboard content check failed.");B.push(W)}await JT({manifest:L,payloads:B})}await Wn("clipboard.copy.end",l,{},f),S=!1,we(L.contentKind==="files"?`${L.items.length} remote file${L.items.length===1?"":"s"} copied.`:L.contentKind==="image"?"Remote image copied.":"Remote text copied.","success")}catch($){throw x&&await b?.cancelWrite?.(l).catch(()=>{}),S&&await Wn("clipboard.copy.end",l,{},f).catch(()=>{}),$}},[Wn,we]),ah=o.useCallback(async(l,f)=>{const b=window.liveDesk?.clipboard;let x=null,S,$=!1;try{b?.readSnapshot&&b.readChunk?S=yp(await b.readSnapshot(l),l):(x=await XT(l),S=x.manifest),await Wn("clipboard.prepare",l,{clipboardDirection:"paste",manifest:S},f),$=!0,await Wn("clipboard.paste.begin",l,{manifest:S},f);for(const q of S.items)for(const W of Id(q.size)){const ke=b?.readChunk?await b.readChunk({operationId:l,itemIndex:q.itemIndex,offset:W.offset,maxBytes:W.byteLength||Ql}):{operationId:l,itemIndex:q.itemIndex,offset:W.offset,byteLength:W.byteLength,dataBase64:YT(x.payloads[q.itemIndex].subarray(W.offset,W.offset+W.byteLength)),final:W.final};if(ke.offset!==W.offset||ke.byteLength!==W.byteLength||ke.final!==W.final)throw new Error("Local clipboard changed during transfer.");const Me=await Wn("clipboard.paste.chunk",l,{itemIndex:q.itemIndex,offset:W.offset,dataBase64:ke.dataBase64,final:W.final},f);if(Number(Me.itemIndex)!==q.itemIndex||Number(Me.offset)!==W.offset||Number(Me.bytes)!==W.byteLength||Me.final===!0!==W.final)throw new Error("Remote clipboard did not confirm the requested file range.")}await Wn("clipboard.paste",l,{clipboardDirection:"paste"},f);const L=Date.now()+GT;let B=!1;for(;Date.now()<L;){const q=await Wn("clipboard.operation.status",l,{},f,Math.max(250,L-Date.now())),W=String(q.status||"").toLowerCase();if(["completed","complete","applied","pasted"].includes(W)){B=!0;break}if(["failed","cancelled","expired"].includes(W))throw new Error(`Remote clipboard paste ${W}.`);await new Promise(ke=>window.setTimeout(ke,VT))}if(!B)throw new Error("Remote clipboard paste confirmation timed out.");$=!1,we(S.contentKind==="files"?`${S.items.length} file${S.items.length===1?"":"s"} pasted on the remote computer.`:S.contentKind==="image"?"Image pasted on the remote computer.":"Text pasted on the remote computer.","success")}catch(L){throw $&&await Wn("clipboard.paste.cancel",l,{},f).catch(()=>{}),L}finally{await b?.releaseRead?.(l).catch(()=>{})}},[Wn,we]),ih=o.useCallback(async l=>{if(!ji||jo!=="open"||!Ea){we("Remote input is not ready for clipboard transfer.","error");return}if(dl.current){we("Another clipboard transfer is still running.");return}const f=E0(l),b=ul;dl.current={operationId:f,direction:l,bindingKey:b};try{Ot(l==="copy"?"Copying from the remote computer…":"Pasting on the remote computer…"),l==="copy"?await sh(f,b):await ah(f,b)}catch(x){we(x instanceof Error?x.message:String(x),"error")}finally{dl.current?.operationId===f&&(dl.current=null)}},[ul,ji,sh,Ea,jo,ah,we,Ot]),ts=On&&Mr.current&&ji&&jo==="open"&&!!Ea,rd={shiftKey:mt.includes("ShiftLeft"),ctrlKey:mt.includes("ControlLeft"),altKey:mt.includes("AltLeft"),metaKey:mt.includes("MetaLeft")},Ir=o.useCallback(l=>gt.current.enqueueStop(l),[]),Fa=o.useCallback(l=>gt.current.enqueueStart(l),[]),Rn=o.useCallback((l,f=Ke.current)=>(rt.current=l,Ke.current=l?String(f||""):"",Ge.current+=1,Ge.current),[]),jr=o.useCallback((l,f,b)=>pk({generation:l,currentGeneration:Ge.current,enabled:rt.current,deviceId:f,currentDeviceId:Ke.current,documentVisible:Mr.current,presentationVisible:_.current,streamId:b,currentStreamId:xe.current.get(f)||""}),[]),yr=o.useCallback(async(l,f,b)=>{if(!f)return{ok:!0,alreadyStopped:!0,captureStopConfirmed:!0,noExactOwner:!0};const S=await(L=>Oe(`/api/remote/devices/${encodeURIComponent(l)}/audio/stop`,{method:"POST",body:JSON.stringify({...L?{streamId:L}:{},reason:b})},G))(f),$=mk(S);if($.staleOwner)return S;if(!$.confirmed)throw new Error(S?.error||"Remote audio capture stop was not confirmed.");return S},[G]),sd=o.useCallback(async(l,f)=>{const b=await Oe(`/api/remote/devices/${encodeURIComponent(l)}/audio/stop`,{method:"POST",body:JSON.stringify({reason:f})},G);if(b?.ok===!1||b?.captureStopConfirmed!==!0&&b?.alreadyStopped!==!0)throw new Error(b?.error||"Remote audio stop-all was not confirmed.");return b},[G]),dy=o.useCallback(l=>{const f=Ge.current,b=xe.current.get(l)||"";return Ir(()=>yr(l,b,"remote-audio-automatic-restart")).then(()=>Fa(async()=>{if(f!==Ge.current||!rt.current||Ke.current!==l||!Mr.current||!_.current||!Rt||!Tr||(Be.current||fe?.deviceId||"")!==l)return"";const x=`audio-restart-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;if(xe.current.set(l,x),!jr(f,l,x))return xe.current.delete(l),"";const S=await Oe(`/api/remote/devices/${encodeURIComponent(l)}/audio/start`,{method:"POST",body:JSON.stringify({streamId:x,mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},G);if(S?.ok===!1)throw xe.current.get(l)===x&&xe.current.delete(l),new Error(S.error||"Remote audio restart failed.");return jr(f,l,x)?x:(await yr(l,x,"remote-audio-stale-restart-compensation"),xe.current.get(l)===x&&xe.current.delete(l),"")}))},[Fa,Ir,Rt,G,jr,Tr,fe?.deviceId,yr]),oh=fe?.deviceId&&xe.current.get(fe.deviceId)||"",py=o.useCallback(async(l,f,b)=>{Rn(!1),He(!1),await Ir(()=>yr(l,f,b)),xe.current.get(l)===f&&xe.current.delete(l)},[Ir,Rn,yr]),{state:ad,lastFrame:id,stats:Ft,error:od}=N0(fe?.deviceId||"",On&&Qu&&Ie,G,pi,nn||qt||Nc.current,oh,dy,py),Do=o.useRef(new Map);o.useEffect(()=>{const l=[["hub",O],["registry",i],["license",Q],["wall-stream",Um],["control-stream",To],["control-decode",ve],["remote-input",rh],["remote-audio",od]];for(const[f,b]of l){const x=String(b||"").trim(),S=it.current;if(f==="wall-stream"&&x==="CONTROL_CAPTURE_OWNS_DEVICE"&&!!S&&$s.current===S.deviceId){Do.current.delete(f);continue}if(f==="hub"&&vt?.requiresHubRestart&&vt.stage==="updating"){Do.current.delete(f);continue}if(!x){Do.current.delete(f);continue}Do.current.get(f)!==x&&(Do.current.set(f,x),we(x))}},[od,ve,To,O,rh,Q,i,we,Um,vt]);const pl=fe?.deviceId||"",ch=fe?lr(fe,Ct[pl]):0;o.useEffect(()=>{if(!_e||!Pr||!ts||!pl)return;const l=G0(),f=pl,b=ch,x=he=>{if(!he)return!1;const tt=Fo(f,{...he,monitorIndex:b});return!tt&&he.type!=="keyboard.reset"&&(l.reset("browser-input-send-rejected"),ct([])),tt},S=(he,tt)=>{const yt=he.target,at=yt?.tagName?.toLowerCase(),wt=yt?.isContentEditable||at==="input"||at==="textarea"||at==="select",Et=l.isPressed(he);if(wt&&(tt==="keydown"||!Et))return;const Xn=tt==="keydown"?j0(he,QT()):"";if(Xn&&(Xn==="copy"?eh:Xn==="paste"?th:!1)){he.preventDefault(),he.stopPropagation();const Wi=l.reset("remote-clipboard-shortcut",!0);Wi&&x(Wi),ct([]),ih(Xn);return}const zs=l.event(he,tt);zs&&(he.preventDefault(),he.stopPropagation(),x(zs))},$=he=>S(he,"keydown"),L=he=>S(he,"keyup"),B=(he,tt=!1)=>{const yt=l.reset(he,tt);yt&&(x(yt),ct([]))};z.current=he=>{const tt=l.snapshot().latchedCodes.includes(he),yt=l.modifier(he,!tt);yt&&(x(yt),ct(at=>tt?at.filter(wt=>wt!==he):[...at.filter(wt=>wt!==he),he]))};const q=he=>{const tt=Rl(he);if(!tt)return!1;const yt=l.snapshot(),at={...tt,shiftKey:yt.shiftKey,ctrlKey:yt.ctrlKey,altKey:yt.altKey,metaKey:yt.metaKey},wt=l.event(at,"keydown");if(!wt||!x(wt))return!1;const Et=l.event(at,"keyup");return!!Et&&x(Et)};pe.current={sendKey:q,sendText:he=>{let tt=!1;const yt=String(he??"").split(/(\r\n|\r|\n)/);for(const at of yt)if(at){if(at==="\r"||at===`
177
177
  `||at===`\r
178
- `){if(!q("Enter"))return!1;tt=!0;continue}for(const wt of W0(at)){const Et=l.snapshot();if(!x({type:"text",text:wt,repeat:!1,pressedCodes:Et.pressedCodes,shiftKey:Et.shiftKey,ctrlKey:Et.ctrlKey,altKey:Et.altKey,metaKey:Et.metaKey}))return!1;tt=!0}}return tt}};const W=()=>B("browser-window-blur"),ke=()=>B("browser-page-hidden"),Me=()=>{document.visibilityState==="hidden"&&B("browser-document-hidden")};return window.addEventListener("keydown",$,!0),window.addEventListener("keyup",L,!0),window.addEventListener("blur",W),window.addEventListener("pagehide",ke),document.addEventListener("visibilitychange",Me),()=>{window.removeEventListener("keydown",$,!0),window.removeEventListener("keyup",L,!0),window.removeEventListener("blur",W),window.removeEventListener("pagehide",ke),document.removeEventListener("visibilitychange",Me),z.current=null,pe.current=null,B("control-keyboard-owner-changed",!0)}},[Tr,Zr,pl,oh,_e,Zm,eh,ah,Io]);const ch=(l,f)=>{const b=Rl(l);if(!b)return!1;const x=performance.now(),S=ee.current;return S.key===b.key&&S.source!==f&&x-S.at<80?!0:(ee.current={key:b.key,source:f,at:x},pe.current?.sendKey(b.key)??!1)},lh=o.useCallback(l=>{_.current=l;const f=Be.current||fe?.deviceId||"";if(!Ie||!f)return;const b=Rn(rt.current,f);if(!l){const S=xe.current.get(f)||"";Pr(async()=>{await yr(f,S,"remote-audio-document-hidden")}).catch($=>{(Be.current||fe?.deviceId||"")===f&&(Rn(!1),xe.current.delete(f),He(!1),we($ instanceof Error?$.message:String($)))});return}const x=`audio-presentation-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;xe.current.set(f,x),Ea(async()=>{if(!Ir(b,f,x)||!Rt||!Rr||(Be.current||fe?.deviceId||"")!==f)return;const S=await Oe(`/api/remote/devices/${encodeURIComponent(f)}/audio/start`,{method:"POST",body:JSON.stringify({streamId:x,mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},G);if(S?.ok===!1)throw new Error(S.error||"Remote audio presentation resume failed.");Ir(b,f,x)||(await yr(f,x,"remote-audio-stale-presentation-compensation"),xe.current.get(f)===x&&xe.current.delete(f))}).catch(S=>{Mr.current&&b===Ge.current&&(Rn(!1),xe.current.delete(f),He(!1),we(S instanceof Error?S.message:String(S)))})},[Ie,Ea,Pr,Rn,Rt,G,Ir,Rr,fe?.deviceId,we,yr]);o.useEffect(()=>{const l=S=>{const $=Mr.current;S!==$&&(Mr.current=S,qr.current+=1,zu.current={active:S&&bi.current,epoch:qr.current},S||(ll(),cl(qr.current)),lh(S),Dw(S),S&&!$&&(Lw(L=>L+1),Ic.current=performance.now()))},f=()=>{l(document.visibilityState==="visible")},b=()=>l(!1),x=()=>f();return document.addEventListener("visibilitychange",f),window.addEventListener("pagehide",b),window.addEventListener("pageshow",x),()=>{document.removeEventListener("visibilitychange",f),window.removeEventListener("pagehide",b),window.removeEventListener("pageshow",x)}},[ll,cl,lh]),o.useEffect(()=>{if(!te||ae!=="connecting"&&ae!=="active"&&ae!=="warm"||Ju!=="open")return;const l=te,f=Ut("control",l),b=window.setInterval(()=>{const x=performance.now();if(document.visibilityState!=="visible"||x-Ic.current<Gd)return;const S=$s.current.get(f)||0,$=fa.current.get(f)||0,L=li.current.get(f)||0,B=ba.current.get(f)||x;ba.current.has(f)||ba.current.set(f,B);const q=S<=0,W=q?x-B>yP:x-S>Kg,ke=Ef({lastReceivedAt:S,lastPaintedAt:$,now:x,staleAfterMs:Kg}),Me=jf({paintStale:ke,lastRecoveryAt:va.current.get(f)||0,now:x,recoveryCooldownMs:Yg,transportRecoveryAfterMs:Xg});if(!W&&Me==="reset-decoder"&&Ri(l,"control","decoder-paint-stale")||!W&&Me==="wait")return;if(!(W||Me==="recover-transport")){ke&&Ri(l,"control","decoder-paint-stale"),q&&x-B>wP&&!zr.current.has(f)&&No([l],"control-frame-socket-recovery")&&zr.current.set(f,x);return}const tt=zr.current.get(f)||0;if(tt<=0){No([l],"control-frame-socket-recovery")&&zr.current.set(f,x);return}if(x-tt<Qg)return;const yt=ga.current.get(f)||0;if(yt>0){if(x-yt<SP)return;ga.current.delete(f)}const at=vs.current.get(f)||0,wt=Ze.find(Bi=>Bi.deviceId===l)||vn,Et=ab(wt?.platform);if(!W&&Me==="recover-transport"&&Et==="mode1-jpeg"&&Ro("mac-control-paint-timeout"))return;if(at>=CP){if(Ro(q?"no first frame":"stale stream"))return;J(!1),_n(!1),hr.current=l,le("error");return}if(x-L<Jg(xP,at))return;sl([l],q?"control-first-frame-timeout":Me==="recover-transport"?"control-paint-timeout":"control-receive-stale")&&(zr.current.delete(f),va.current.delete(f),li.current.set(f,x),ga.current.set(f,x),ba.current.set(f,x),vs.current.set(f,at+1))},650);return()=>window.clearInterval(b)},[Ze,vn,Ju,te,ae,Ro,No,Ri,sl]),o.useEffect(()=>{!ve||te&&Ye.current[te]||fr!=="mode3-h264-hw"||Ro(ve)||(J(!1),_n(!1),hr.current=it.current?.deviceId||"",le("error"))},[ve,te,fr,Ro]),o.useEffect(()=>{!Xe||!te||Ye.current[te]||!Ao||(hr.current=te,le(l=>l==="error"?l:"error"))},[Ao,te,Xe]),o.useEffect(()=>{if(ae!=="error")return;const l=it.current;if(!l)return;hr.current=l.deviceId,Dt(ha.current,l)||(ha.current=l,ci.current=0);const f=ci.current,b=f===0?0:Math.min(5e3,500*2**Math.min(f-1,4)),x=window.setTimeout(()=>{Dt(it.current,l)&&(++Kt.current,Mn.current="",le("stopping"),br(async()=>{if(Dt(it.current,l))try{if(!await wr(l,"control-session-terminal-error"))return;ha.current=null,ci.current=0,bo.current===l.deviceId?(bo.current="",hr.current="",le("idle")):le("error")}catch(S){if(!Dt(it.current,l))return;ci.current+=1,we(S instanceof Error?S.message:String(S)),le("error"),po($=>$+1)}}))},b);return()=>window.clearTimeout(x)},[ae,yc,br,we,wr]);const Eo=o.useCallback(l=>{if(!l||hr.current!==l)return!1;const f=it.current;return++Kt.current,Mn.current="",ci.current=0,f&&f.deviceId===l?(bo.current=l,ha.current=null,le("error"),po(b=>b+1),!0):(bo.current="",hr.current="",ha.current=null,le("idle"),!0)},[]);o.useEffect(()=>{if(ko!=="open"||!ot.autoStartLive||ir.length===0)return;const l=window.setInterval(()=>{const f=performance.now();if(document.visibilityState!=="visible"||f-Ic.current<Gd)return;const b=1e3/Math.max(1,Qc||dr||1),x=Math.max(AP,Math.ceil(b*4)),S=[],$=[];for(const L of ir){if($.length+S.length>=TP)break;const B=Ut("wall",L),q=$s.current.get(B)||0,W=q<=0,ke=ui.current.get(B)||f;ui.current.has(B)||ui.current.set(B,ke);const Me=li.current.get(B)||0,he=fa.current.get(B)||0,tt=W||f-q>x,yt=Ef({lastReceivedAt:q,lastPaintedAt:he,now:f,staleAfterMs:x}),at=jf({paintStale:yt,lastRecoveryAt:va.current.get(B)||0,now:f,recoveryCooldownMs:Yg,transportRecoveryAfterMs:Xg});if(!tt&&at==="reset-decoder"&&Ri(L,"wall","decoder-paint-stale")||!tt&&at==="wait")continue;if(!(tt||at==="recover-transport")){yt&&Ri(L,"wall","decoder-paint-stale");continue}const Et=zr.current.get(B)||0;if(Et<=0&&(!W||f-ke>kP)){S.push(L);continue}if(W&&f-ke<=MP||Et>0&&f-Et<Qg)continue;const Yn=vs.current.get(B)||0;f-Me>=Jg(NP,Yn)&&$.push(L)}if(S.length>0&&Um(S,"wall-frame-socket-recovery"))for(const L of S)zr.current.set(Ut("wall",L),f);if($.length>0&&rl($,$.some(L=>($s.current.get(Ut("wall",L))||0)<=0)?"wall-first-frame-timeout":"wall-frame-stale"))for(const L of $){const B=Ut("wall",L);zr.current.delete(B),va.current.delete(B),li.current.set(B,f),ui.current.set(B,f),$s.current.delete(B),fa.current.delete(B),vs.current.set(B,(vs.current.get(B)||0)+1)}},RP);return()=>window.clearInterval(l)},[Qc,ir,Um,Ri,rl,ot.autoStartLive,dr,ko]),o.useEffect(()=>{ua(dr),Lc.current=Date.now(),ws.current=0,ys.current=0,Ur.current=0,_c.current=0,$c.current=""},[dr,ot.frameMode,ot.adaptiveLoadShedding]),o.useEffect(()=>{VS({h264DecodeAcceleration:ot.h264DecodeAcceleration})},[ot.h264DecodeAcceleration]),o.useEffect(()=>{if(!Rt||Xe||Bt==="list"||!ot.visibleOnlyLive){ri([]);return}const l=xm.current;if(!l||typeof IntersectionObserver>"u"){ri(Uc);return}const f=Array.from(l.querySelectorAll("[data-live-device-id]"));if(f.length===0){ri([]);return}const b=new Map,x=sk(l,A),S=()=>{const L=Yd(f.map(B=>String(B.dataset.liveDeviceId||"")).filter(B=>(b.get(B)||0)>0));ri(B=>Qd(B,L)?B:L)},$=new IntersectionObserver(L=>{for(const B of L){const q=String(B.target.dataset.liveDeviceId||"");q&&b.set(q,B.isIntersecting?B.intersectionRatio||.01:0)}S()},{root:x,rootMargin:A?X0:Er.visibleRootMargin,threshold:[0,.01,.2,.6,1]});return f.forEach(L=>$.observe(L)),S(),()=>$.disconnect()},[Uc,Rt,A,Xe,ka,ot.visibleOnlyLive,Bt]),o.useEffect(()=>{if(!ot.adaptiveLoadShedding||!ot.autoStartLive||ir.length===0){ys.current=0,Ur.current=0,_c.current=0,$c.current="";return}const l=dr;if(ko!=="open"||Ta.sampleMs<500||Ta.lastUpdatedAt<=0||_c.current===Ta.lastUpdatedAt)return;_c.current=Ta.lastUpdatedAt;const f=Date.now(),b=ir.map(Me=>({deviceId:Me,receive:Nc[Ut("wall",Me)],paint:Ac[Ut("wall",Me)]}));if(!b.every(({receive:Me,paint:he})=>{const tt=Me?.lastFrame,yt=Math.max(0,Number(tt?.requestedFps||0)),at=tt?rs(tt):"";return wk({receiveSampleMs:Number(Me?.sampleMs||0),paintSampleMs:Number(he?.sampleMs||0),currentGenerationVerified:tt?.currentGenerationVerified===!0,frameRequestedFps:yt,adaptiveFps:Dn})&&he?.bindingKey===at})){ys.current=0,Ur.current=0,ws.current=0;return}const S=[Dn,...b.map(({deviceId:Me,receive:he})=>`${Me}:${rs(he.lastFrame)}`).sort()].join("|");if($c.current!==S){$c.current=S,ys.current=f,Ur.current=0,ws.current=0;return}if(!ys.current){ys.current=f,Ur.current=0;return}if(f-ys.current<Er.downshiftStableSampleMs)return;const $=b.reduce((Me,{receive:he})=>Me+Math.max(0,Number(he?.framesPerSecond||0)),0),L=b.reduce((Me,{receive:he})=>Me+Math.max(0,Number(he?.framesPerSecond||0))*Math.max(0,Number(he?.averageFrameBytes||0)),0),B=b.reduce((Me,{paint:he})=>Me+Math.max(0,Number(he?.framesPerSecond||0)),0),q=Math.max(0,...b.map(({receive:Me})=>Number(Me?.maxIntervalMs||0))),W=Math.max(0,...b.map(({paint:Me})=>Number(Me?.p95IntervalMs||0))),ke=vk({directDeviceCount:ir.length,requestedFps:Dn,measuredFramesPerSecond:$,measuredPaintFramesPerSecond:B,measuredBytesPerSecond:L,maxBytesPerSecond:Er.maxWallBytesPerSecond,worstReceiveGapMs:q,worstPaintP95Ms:W,maxFrameGapMs:Er.maxFrameGapMs});if(ke.overloaded){if(ws.current=0,Ur.current+=1,Ur.current<Er.downshiftConsecutiveSamples)return;const Me=Er.minFps;if(f-Lc.current>=Er.downshiftCooldownMs&&Dn>Me){const he=Math.max(Me,XP(Dn,Me));he<Dn&&(ua(he),Lc.current=f,ys.current=0,Ur.current=0)}return}if(Ur.current=0,!ke.healthyForRecovery||Dn>=l){ke.healthyForRecovery||(ws.current=0);return}if(!ws.current){ws.current=f;return}if(f-ws.current>=Er.recoveryCooldownMs){const Me=Math.min(l,JP(Dn,l));Me>Dn&&(ua(Me),Lc.current=f,ws.current=0,ys.current=0,Ur.current=0)}},[Dn,ir.length,ir,Ac,Nc,ko,Ta.lastUpdatedAt,Ta.sampleMs,ot.adaptiveLoadShedding,ot.autoStartLive,ot.frameMode,dr]),o.useEffect(()=>{const l=new URLSearchParams(window.location.search).get("checkout");if(l==="success"){we("Checkout returned. Waiting for Dodo confirmation."),ge();const f=window.setInterval(()=>{ge()},4e3),b=window.setTimeout(()=>{window.clearInterval(f)},45e3);return()=>{window.clearInterval(f),window.clearTimeout(b)}}l==="cancelled"&&we("Checkout cancelled.")},[ge]),o.useEffect(()=>{!Rt&&_e&&$e(!1),!Rt&&Ie&&(Rn(!1),He(!1))},[Ie,_e,Rn,Rt]),o.useEffect(()=>{Ie&&(!fe||!Rr)&&(Rn(!1),He(!1))},[Ie,Rn,Rr,fe]),o.useEffect(()=>{const l=fe?.deviceId||"",f=Be.current;if(Be.current=l,!f||f===l)return;const b=Rn(Ie,l),x=l?`audio-${Date.now()}-${Math.random().toString(36).slice(2,8)}`:"";l&&Ie&&xe.current.set(l,x);let S=!0;const $=xe.current.get(f)||"";return(async()=>{try{await Pr(async()=>{await yr(f,$,"remote-audio-device-switch"),xe.current.delete(f)}),await Ea(async()=>{if(!S||!Ir(b,l,x)||!l||!Rt||!Rr)return;const L=await Oe(`/api/remote/devices/${encodeURIComponent(l)}/audio/start`,{method:"POST",body:JSON.stringify({streamId:x,mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},G);if(L.ok===!1)throw new Error(L.error||"Remote audio start failed.");Ir(b,l,x)||(await yr(l,x,"remote-audio-stale-device-switch-compensation"),xe.current.get(l)===x&&xe.current.delete(l))})}catch(L){S&&(Rn(!1),xe.current.delete(l),He(!1),we(L instanceof Error?L.message:String(L)))}})(),()=>{S=!1}},[Ie,Ea,Pr,Rn,Rt,G,Ir,Rr,fe?.deviceId,yr]),o.useEffect(()=>{const l=Ze.map(S=>S.deviceId),f=new Set(l),b=new Map(Ze.map(S=>[S.deviceId,S])),x=new Map;for(const S of Ze){const $=DP(S);if(!$)continue;const L=Dr(S.status),B=[S.lastStatusAt,L.capturedAt,L.collectedAt,L.timestamp,L.updatedAt].find(W=>typeof W=="string"&&W.trim()),q=V0(js.current[S.deviceId],$,B);q&&(js.current[S.deviceId]=q,x.set(S.deviceId,q),wv({platform:S.platform,topologyFingerprint:$,consecutiveTopologySamples:q.consecutiveSamples})&&(co.current[S.deviceId]=$))}for(const S of Object.keys(js.current))f.has(S)||delete js.current[S];me(S=>{const $=S.filter(L=>f.has(L));return Qd(S,$)?S:$}),Te(S=>S&&f.has(S)?S:""),Se(S=>S&&f.has(S)?S:""),ti(S=>{let $=!1;const L={};for(const[B,q]of Object.entries(S)){const W=b.get(B);if(!W){L[B]=q;continue}const ke=x.get(B)||js.current[B],Me=G0({requestedIndex:q,monitorCount:as(W),platform:W.platform,topologyFingerprint:ke?.fingerprint||"",consecutiveTopologySamples:ke?.consecutiveSamples||0});L[B]=Me,Me!==q&&($=!0)}return $?L:S}),Hu(S=>{const $=S.filter(L=>f.has(L));return Qd(S,$)?S:$})},[Ze,Uu]),o.useEffect(()=>{$w([]),Bw(!1)},[Cs]),o.useEffect(()=>{!xa||fi!=="selected"||gi.length>0||An.length===0||Hu(An.map(l=>l.deviceId))},[An,gi.length,fi,xa]),o.useEffect(()=>{try{localStorage.setItem(vw,ms)}catch{}},[ms]),o.useEffect(()=>{HP(ot)},[ot]),o.useEffect(()=>{zP(rn)},[rn]),o.useEffect(()=>{OP(Ct,co.current)},[Ze,Ct]);const ml=o.useCallback(async()=>{const l=new Set(m);l.add(an);try{const $=await Oe("/api/remote/status",void 0,an);Eh({endpoint:$.agentEndpoint,endpoint_candidates:[...$.agentEndpointCandidates||[],...$.hostTargetEndpointCandidates||[]]}).forEach(L=>l.add(L))}catch{}const f=[...l].sort(($,L)=>{const B=q=>{const W=Ul(q);return W==="local"?0:W==="loopback"?1:2};return B($)-B(L)||$.localeCompare(L)});let b=!1,x="",S=!1;try{for(const $ of f){const L=Ul($);try{if(await Oe("/api/health",void 0,$),L==="local")return M(!0),Gi(!0),$;L==="loopback"&&(b=!0,x=$)}catch{L==="local"&&(S=!0)}}return b?(S&&we("LiveDesk Hub is reachable on this PC, but not through the LAN address yet. Restart LiveDesk Hub to bind 5179 on the network."),M(!0),Gi(!0),x||an):(M(!1),Gi(!1),"")}catch{return M(!1),Gi(!1),""}},[m]),Li=async()=>{if(Z("auth"),Br(!1),window.liveDesk?.auth?.signInWithGoogle){const x=window.liveDesk.auth.signInWithGoogle();ml();const S=await x;S?.ok===!1&&(we(S.error||"LiveDesk could not open the system browser for Google sign-in."),Z(""));return}const l=pt.auth.signInWithOAuth({provider:"google",options:{redirectTo:`${window.location.origin}/callback`}});ml();const{data:f,error:b}=await l;b&&(we(b.message),Z(""))},uy=async()=>{Z("auth"),Br(!1),window.liveDesk?.auth?.signOut||await Oe("/api/auth/session",{method:"DELETE"},G||an).catch(()=>{}),await pt.auth.signOut(),(await window.liveDesk?.auth?.signOut?.())?.runtimeCleared===!1&&we("Signed out locally. The LiveDesk runtime could not be reached to clear its session."),Z("")};o.useEffect(()=>{if(!ca)return;const l=b=>{b.target instanceof Element&&(b.target.closest(".account-popover, .rail-account")||Br(!1))},f=b=>{b.key==="Escape"&&Br(!1)};return window.addEventListener("pointerdown",l),window.addEventListener("keydown",f),()=>{window.removeEventListener("pointerdown",l),window.removeEventListener("keydown",f)}},[ca]);const uh=o.useCallback(async(l={})=>{const f=l.silent===!0,b=l.takeover===!0,x=l.requestLocalAccess===!0;if(!n?.user){f||we("Sign in before publishing this host.","error");return}if(!Wu.current){Wu.current=!0,f||(Z("host"),Ot("Hub · 1/4 · Checking the local runtime…"));try{const $=(x?await ml():"")||G||an;if(!(P||await Oe("/api/remote/status",void 0,$)).started)throw new Error("Start LiveDesk on this computer before syncing the server.");f||Ot("Hub · 2/4 · Sending the signed-in session to the Hub…");const B=await Oe("/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}})},$);if(!B.ok||!B.authenticated)throw new Error(B.error||"hub-session-sync-failed");f||Ot("Hub · 3/4 · Claiming the Hub role and publishing its endpoint…");const q=await Oe("/api/hub/sync",{method:"POST",body:JSON.stringify({takeover:b})},$);if(!q.ok)throw new Error(q.error||"host-target-failed");if(!f){Ot("Hub · 4/4 · Verifying the endpoint and lease renewal…");const W=await Oe("/api/hub/status",void 0,$);if(!W.hostTargetActive)throw new Error(W.hostTargetLease?.lastError||"host-target-not-active-after-sync");const ke=W.hostTargetEndpoint||W.agentEndpoint||"endpoint ready",Me=Number(W.connectedDeviceCount||0),he=Me>0?`${Me} client${Me===1?"":"s"} connected.`:"No clients connected yet; reconnect the laptop Client.";we(`Hub ready · ${ke} · lease auto-renewal active. ${he}`,"success"),(x||H)&&(M(!0),Gi(!0)),X()}c()}catch(S){if(!f){const $=S instanceof Error?S.message:String(S);$.includes("local network access")&&(M(!1),Gi(!1)),we(`Hub setup failed · ${$}`,"error")}}finally{Wu.current=!1,f||Z("")}}},[G,H,X,c,ml,n,we,Ot,P]),Fo=o.useCallback((l=!0)=>{bt!=="host"&&(It(!1),l&&window.requestAnimationFrame(()=>et.current?.focus()))},[bt]),dy=o.useCallback(()=>{bt!=="host"&&(et.current=document.activeElement instanceof HTMLElement?document.activeElement:null,Br(!1),It(!0))},[bt]),py=o.useCallback(()=>{It(!1),uh({takeover:!0,requestLocalAccess:!0})},[uh]);o.useEffect(()=>{if(!lt)return;const l=window.requestAnimationFrame(()=>At.current?.focus()),f=x=>{x.target instanceof Element&&x.target.closest(".client-hub-switch-popover, .hub-sync-trigger")||Fo(!1)},b=x=>{x.key==="Escape"&&Fo()};return window.addEventListener("pointerdown",f),window.addEventListener("keydown",b),()=>{window.cancelAnimationFrame(l),window.removeEventListener("pointerdown",f),window.removeEventListener("keydown",b)}},[Fo,lt]);const dh=o.useCallback(async()=>{if(!(!P?.update?.canApply||bt==="update")){Z("update");try{const l=await Oe("/api/update/apply",{method:"POST",body:JSON.stringify({})},G||an);if(!l.ok)throw new Error(l.error||"LiveDesk update could not be started.");const f=[...new Set((l.targets||[]).map(S=>String(S.deviceId||"").trim()).filter(Boolean))],b=!!(l.managerUpdateAvailable||l.clientPackageUpdateAvailable),x=l.state==="hub-restart-requested"?Date.now():void 0;(f.length>0||b)&&ln({operationId:String(l.operationId||`wall-update-${Date.now()}`),targetIds:f,stage:l.state==="clients-updated"?"updated":"updating",requiresHubRestart:b,initialHostInstanceId:String(P.hostInstanceId||""),targetManagerVersion:String(l.latestVersion||P.update?.latestVersion||""),targetClientVersion:String(l.latestClientVersion||P.update?.latestClientVersion||""),restartRequestedAt:x,restartDeadlineAt:x?x+Wl:void 0}),Ot(l.state==="hub-restart-requested"?Hl:Og),X()}catch(l){we(l instanceof Error?l.message:String(l),"error")}finally{Z("")}}},[bt,G,X,we,Ot,P]);o.useEffect(()=>{const l=vt,f=P?.update;if(!l||l.stage!=="updating"||!f)return;const b=f.restartResult?.operationId===l.operationId?f.restartResult:null;if(b?.outcome==="restored"){const q=b.error||`The requested Hub ${b.targetVersion||l.targetManagerVersion||"version"} failed verification.`;ln(W=>W?.operationId===l.operationId?{...W,stage:"restored",error:q}:W),we(`LiveDesk update did not complete. Hub ${b.fallbackVersion||b.appVersion||"the previous version"} was restored. ${q}`,"error");return}if(b?.outcome==="failed"){const q=b.error||"No verified LiveDesk Hub replacement could be started.";ln(W=>W?.operationId===l.operationId?{...W,stage:"failed",error:q}:W),we(`LiveDesk Hub update failed. ${q}`,"error");return}if(f.operationId===l.operationId&&f.state==="failed"){const q=f.error||"LiveDesk update failed before the Hub replacement completed.";ln(W=>W?.operationId===l.operationId?{...W,stage:"failed",error:q}:W),we(q,"error");return}if(f.operationId===l.operationId){if(f.state==="hub-restart-requested"&&!l.restartDeadlineAt){const q=Date.now();ln(W=>W?.operationId===l.operationId?{...W,restartRequestedAt:q,restartDeadlineAt:q+Wl}:W),Ot(Hl)}!l.requiresHubRestart&&f.state==="clients-updated"&&(ln(q=>q?.operationId===l.operationId?{...q,stage:"updated"}:q),we("LiveDesk clients updated and reconnected successfully.","success"));return}if(!l.requiresHubRestart)return;const x=P.started===!0&&(!l.initialHostInstanceId||P.hostInstanceId&&P.hostInstanceId!==l.initialHostInstanceId),S=!!f.checkedAt,$=Wg(f.currentVersion,l.targetManagerVersion),L=!l.targetClientVersion||Wg(f.currentClientVersion,l.targetClientVersion),B=S&&f.state==="idle"&&f.updateAvailable===!1&&$&&L;x&&B&&(ln(q=>q?.operationId===l.operationId?{...q,stage:"updated"}:q),we(`LiveDesk Hub ${f.currentVersion||b?.appVersion||l.targetManagerVersion} restarted and passed version verification.`,"success"))},[we,Ot,P,vt]),o.useEffect(()=>{const l=vt;if(!l||l.stage!=="updating"||!l.requiresHubRestart||l.restartDeadlineAt)return;const f=()=>{const x=Date.now();ln(S=>S?.operationId===l.operationId&&S.stage==="updating"&&!S.restartDeadlineAt?{...S,restartRequestedAt:x,restartDeadlineAt:x+Wl}:S),Ot(Hl)};if(P?.update?.state==="hub-restart-requested"){f();return}if(!O)return;const b=window.setTimeout(f,dP);return()=>window.clearTimeout(b)},[O,Ot,P?.update?.state,vt]),o.useEffect(()=>{const l=vt;if(!l||l.stage!=="updating"||!l.requiresHubRestart||!l.restartDeadlineAt)return;const f=Math.max(0,l.restartDeadlineAt-Date.now()),b=l.operationId,x=window.setTimeout(()=>{const S=`LiveDesk Hub did not return and verify ${l.targetManagerVersion||"the requested version"} within ${Math.round(Wl/6e4)} minutes. Check the Hub terminal or restart log, then run livedesk@latest manually if the Hub is still offline.`;ln($=>$?.operationId===b&&$.stage==="updating"?{...$,stage:"failed",error:S}:$),we(S,"error")},f);return()=>window.clearTimeout(x)},[we,vt]),o.useEffect(()=>{if(!vt||vt.stage!=="updated")return;const l=vt.operationId,f=window.setTimeout(()=>{ln(b=>b?.operationId===l?null:b)},Bg);return()=>window.clearTimeout(f)},[vt]),o.useEffect(()=>{uo.current.clear(),lo({})},[vt?.operationId]),o.useEffect(()=>{if(!vt||P?.update?.operationId!==vt.operationId)return;const l=(P.update.targets||[]).filter(b=>b.state==="completed").map(b=>Hg(vt.operationId,b)).filter(b=>!uo.current.has(b));if(l.length===0)return;const f=Date.now()+Bg;for(const b of l)uo.current.add(b);lo(b=>({...b,...Object.fromEntries(l.map(x=>[x,f]))}))},[P?.update,vt]),o.useEffect(()=>{const l=Math.min(...Object.values(ni));if(!Number.isFinite(l))return;const f=window.setTimeout(()=>{const b=Date.now();lo(x=>Object.fromEntries(Object.entries(x).filter(([,S])=>S>b)))},Math.max(0,l-Date.now()));return()=>window.clearTimeout(f)},[ni]),o.useEffect(()=>{if(Mt!==Og&&Mt!==Hl)return;const l=P?.update;if(String(l?.state||"")==="failed"){we(l?.error||"LiveDesk update failed.","error");return}vt?.stage==="updated"&&we("")},[Mt,we,P?.update?.error,P?.update?.state,vt?.stage]);const my=o.useCallback(async()=>{if(!bt){Z("pin");try{const f=await Oe("/api/remote/pairing-pin",{method:"POST"},G||an);if(!f.ok)throw new Error(f.error||"pin-rotation-failed");await X(),we("New PIN published.")}catch(l){we(l instanceof Error?l.message:String(l))}finally{Z("")}}},[bt,G,X]),od=o.useCallback(l=>{l&&(Te(l),me(f=>f.includes(l)?f:[...f,l]))},[]),cd=o.useCallback(l=>{if(!l)return;const f=Ma.has(l);Te(b=>f?b===l?"":b:l),me(b=>f?b.filter(x=>x!==l):b.includes(l)?b:[...b,l])},[Ma]),Do=o.useCallback(()=>{me([]),Te("")},[Ss]),ph=o.useCallback(()=>{me(Ze.map(l=>l.deviceId)),Te("")},[Ze]),ld=o.useCallback((l,f)=>{const b=Ze.find(S=>S.deviceId===l);if(!b)return;const x=as(b);if(!(x<=1)&&(ti(S=>{const $=Ko(S[l],x),L=($+f+x)%x;return L===$?S:{...S,[l]:L}}),bn("wall",l),bn("control",l),mo(S=>{if(!S.has(l))return S;const $=new Set(S);return $.delete(l),$}),pa.current.delete(l),fs.current.delete(l),Xe)){const S=Eo(l);J(!1),S||le("connecting"),_n(!1),Se(l)}},[Ze,bn,Eo,Xe]);o.useEffect(()=>{const l=f=>{if(_e&&Tr&&Zr)return;const b=f.target,x=b?.tagName?.toLowerCase();b?.isContentEditable||x==="input"||x==="textarea"||x==="select"||((f.ctrlKey||f.metaKey)&&f.key.toLowerCase()==="a"&&(f.preventDefault(),ph()),f.key==="Escape"&&Do())};return window.addEventListener("keydown",l),()=>window.removeEventListener("keydown",l)},[Tr,Do,Zr,_e,ph]);const hy=(l,f)=>{const b=Ze.find(L=>L.deviceId===l),x=b?as(b):1,S=Ko(Ct[l],x),$=Ko(f,x);if(S!==$&&(ti(L=>({...L,[l]:$})),mo(L=>{if(!L.has(l))return L;const B=new Set(L);return B.delete(l),B}),pa.current.delete(l),fs.current.delete(l),Ds.current.delete(l),si.current.delete(l),ma.current.delete(l),bn("wall",l),bn("control",l)),Xe){const L=Eo(l);S!==$&&(J(!1),L||le("connecting")),_n(!1),Se(l)}else od(l)},fy=l=>{const f=Be.current||fe?.deviceId||"",b=[...new Set([f,l].filter(Boolean))],x=Ie||b.some(S=>xe.current.has(S));Rn(!1),He(!1);for(const S of b)xe.current.delete(S);b.length!==0&&(async()=>{for(const S of b)await Pr(()=>rd(S,"remote-audio-control-entry"))})().catch(S=>{x&&we("Remote audio was muted locally, but Client capture stop was not confirmed: "+(S instanceof Error?S.message:String(S)),"error")})},Fa=async l=>{const f={requestId:++Fw.current,deviceId:l,startedAt:performance.now(),startedAtEpochMs:Date.now()};if(bs.current=f,!Gr.has(l)){bs.current?.requestId===f.requestId&&(bs.current=null),$e(!1),we(xi);return}const b=Ze.find(S=>S.deviceId===l);if(is(b?.platform)&&(b?.capabilities?.controlPermission===!1||b?.capabilities?.accessibilityPermission===!1)){bs.current?.requestId===f.requestId&&(bs.current=null),$e(!1),we("Mac remote control needs Accessibility permission. Allow it for the terminal app that starts LiveDesk, then restart the Mac client.","error");return}fy(l),Eo(l),_n(!1),Se(l),tn("control"),$e(!0),we(`Opening remote control${b?` for ${dn(b)}`:""}.`,"success")},mh=async()=>{if(!fe){we("Select a Client before playing audio.");return}if(!Rt){we(xi);return}if(!Rr){we("Selected Client does not report remote audio support yet.");return}if(be)return;const l=!Ie,f=l?`audio-${Date.now()}-${Math.random().toString(36).slice(2,8)}`:xe.current.get(fe.deviceId),b=Rn(l,fe.deviceId);l&&f?xe.current.set(fe.deviceId,f):l||xe.current.delete(fe.deviceId),We("audio"),He(l);try{l?(await Pr(()=>rd(fe.deviceId,"remote-audio-user-enable-reconcile")),await Ea(async()=>{if(!f||!Ir(b,fe.deviceId,f))return;const x=await Oe(`/api/remote/devices/${encodeURIComponent(fe.deviceId)}/audio/start`,{method:"POST",body:JSON.stringify({streamId:f,mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},G);if(x?.ok===!1)throw new Error(x.error||"Remote audio start failed.");Ir(b,fe.deviceId,f)||await yr(fe.deviceId,f,"remote-audio-stale-user-start-compensation")})):await Pr(()=>rd(fe.deviceId,"remote-audio-user-disabled")),we(`${l?"Audio started":"Audio stopped"} for ${dn(fe)}.`,"success")}catch(x){Rn(!1),l&&xe.current.delete(fe.deviceId),He(!1),we(x instanceof Error?x.message:String(x),"error")}finally{We("")}},gy=async(l,f)=>{const b=l.deviceId,x=dn(l),S=String(Ye.current[b]||""),$=!!S&&on[b]===!0;if(f&&S&&!$)return{ok:!0,skipped:!0,action:"pause",deviceId:b,title:x};if(!f&&!S)return{ok:!0,skipped:!0,action:"resume",deviceId:b,title:x};if(!f&&S.startsWith("pending:"))return{ok:!1,action:"resume",deviceId:b,title:x,error:"Pause is still pending confirmation."};if(f){const ke=S||`pending:${Date.now()}:${b}`,Me=it.current?.deviceId===b?it.current:null,he=!!Me||te===b,tt=he?++Kt.current:0,yt=()=>Nf({deviceId:b,requestTransitionGeneration:tt,currentTransitionGeneration:Kt.current,actualControlOwner:it.current}),at=en.current.get(b);en.current.set(b,{deviceId:b,monitorIndex:cr(l,Ct[b]??at?.monitorIndex),previousControlOwner:Me||at?.previousControlOwner||null}),nr(b,!0),Sn(b,!1),Fn(b,ke),ed(b),he&&(Mn.current="",le("paused"));try{const wt=await Oe(`/api/remote/devices/${encodeURIComponent(b)}/live/pause`,{method:"POST",body:JSON.stringify({reason:"user-video-pause"})},G);if(!wt?.pauseToken)return zn.current.delete(b),Fn(b,""),Sn(b,!1),en.current.delete(b),yt()&&(T.current=null,nt(null),J(!1),Le(`control-pause-rollback-${Date.now()}-${b}`),le("connecting")),{ok:!1,action:"pause",deviceId:b,title:x,error:wt?.error||"video-capture-pause-failed"};const Et=String(Ye.current[b]||"");if(Et!==ke&&Et!==wt.pauseToken)return{ok:!1,action:"pause",deviceId:b,title:x,error:"Pause ownership changed before confirmation."};const Yn=yt(),Bi=Yn&&it.current?.deviceId===b?it.current:Me,Hs=en.current.get(b);return Hs&&(Hs.previousControlOwner=Bi),Yn&&it.current?.deviceId===b&&(it.current=null),Yn&&(T.current=null,nt(null)),Fn(b,wt.pauseToken),Yn&&le("paused"),wt.ok===!1||wt.captureStopConfirmed!==!0?(Sn(b,!0),{ok:!1,unconfirmed:!0,action:"pause",deviceId:b,title:x,error:wt.stopError||wt.error||"Client capture shutdown was not confirmed."}):(Sn(b,!1),{ok:!0,action:"pause",deviceId:b,title:x})}catch(wt){return Sn(b,!0),{ok:!1,unconfirmed:!0,action:"pause",deviceId:b,title:x,error:wt instanceof Error?wt.message:String(wt)}}}const L=en.current.get(b),B=L?.previousControlOwner||null,q=te===b&&(B!==null||Vn.current?.deviceId===b||ae==="paused"),W=q?Kt.current:0;try{nr(b,!1);const ke=await Oe(`/api/remote/devices/${encodeURIComponent(b)}/live/resume`,{method:"POST",body:JSON.stringify({pauseToken:S})},G);if(ke?.ok===!1)throw new Error(ke.error||"video-capture-resume-failed");if(String(Ye.current[b]||"")!==S)return{ok:!1,action:"resume",deviceId:b,title:x,error:"Resume ownership changed before confirmation."};const Me=en.current.get(b)||L,he=Me?.previousControlOwner||B,tt=q&&Nf({deviceId:b,requestTransitionGeneration:W,currentTransitionGeneration:Kt.current,actualControlOwner:it.current});if(Fn(b,""),Sn(b,!1),en.current.delete(b),tt){const yt=++Kt.current;Mn.current="";const at=jd(b,yt,{sessionId:l.sessionId||he?.sessionId,monitorIndex:cr(l,Ct[b]??Me?.monitorIndex)});it.current=at,vr(at),hr.current="",ha.current=null,T.current=null,nt(null),ne(""),De(""),J(!1),bn("control",b);const wt=`control-video-resume-${yt}-${b}`;Le(wt),Ce(b),le("connecting")}else bn("wall",b);return{ok:!0,action:"resume",deviceId:b,title:x}}catch(ke){return zn.current.delete(b),{ok:!1,action:"resume",deviceId:b,title:x,error:ke instanceof Error?ke.message:String(ke)}}},hh=async()=>{if(So.length===0){we("Select one or more Clients before pausing video.");return}if(Gn.length===0){we(xi);return}if(be)return;const l=Gn.some(b=>{const x=String(Ye.current[b.deviceId]||"");return!x||x.startsWith("pending:")||on[b.deviceId]===!0}),f=Gn.filter(b=>{const x=String(Ye.current[b.deviceId]||"");return l?!x||x.startsWith("pending:")||on[b.deviceId]===!0:!!x});if(f.length===0){we(l?"Selected Clients are already paused.":"Selected Clients are already playing.");return}We("video");try{const b=await Promise.all(f.map(W=>gy(W,l)));X();const x=b.filter(W=>W.ok&&!W.skipped),S=b.filter(W=>!W.ok&&W.unconfirmed),$=b.filter(W=>!W.ok&&!W.unconfirmed),L=Gn.length-f.length+b.filter(W=>W.skipped).length,B=So.length-Gn.length,q=l?"pause":"resume";if($.length>0||S.length>0){const W=$.slice(0,2).map(ke=>`${ke.title}: ${ke.error||"unknown error"}`).join(" · ");we([`Video ${q} completed for ${x.length}/${f.length} Clients.`,S.length>0?`${S.length} Client capture stop${S.length===1?"":"s"} remain unconfirmed.`:"",W,B>0?`${B} selected Client${B===1?"":"s"} were outside the current plan limit.`:""].filter(Boolean).join(" "),"error");return}we([`Video ${l?"paused":"resumed"} for ${x.length} Client${x.length===1?"":"s"}.`,L>0?`${L} already ${l?"paused":"playing"}.`:"",B>0?`${B} outside the current plan limit.`:""].filter(Boolean).join(" "),"success")}finally{We("")}},by=l=>{const f=l instanceof Error?l.message:String(l);return/remote-actions-disabled|remote-access-blocked-by-settings/i.test(f)?"Remote access is blocked. Change Settings > Remote Access > Access mode first.":/power-actions-disabled|allowPowerActions-blocked-by-settings/i.test(f)?"Power actions are off. Turn on Settings > Remote Access > Power actions first.":/agent-tool-capability-unavailable|unsupported-agent-operation/i.test(f)?"This Client needs a newer LiveDesk Client for power actions.":/device-not-connected|404 device-not-found/i.test(f)?"The Client disconnected before the action could be sent.":f},hl=async l=>{if(!fe||be)return;const f=fe,x={sleep:"Sleep",restart:"Restart",shutdown:"Shut down"}[l];if(window.confirm(`${x} ${dn(f)}? Unsaved work on that computer may be lost.`)){We(l),we(`Sending ${x.toLowerCase()} request to ${dn(f)}...`);try{const S=await Oe(`/api/remote/devices/${encodeURIComponent(f.deviceId)}/quick-actions`,{method:"POST",body:JSON.stringify({action:l})},G);if(!S.ok)throw new Error(S.error||"The remote action could not be sent.");we(`${x} request sent to ${dn(f)}.`,"success"),X()}catch(S){we(by(S),"error")}finally{We("")}}},fh=async(l,f,b="files")=>{const x=l.filter(B=>B.file.size>=0);if(x.length===0)return{files:0,bytes:0};if(!Rt)throw new Error(xi);if(f.length===0)throw new Error("Select at least one connected Client.");const S=crypto.randomUUID(),$=x.reduce((B,q)=>B+q.file.size,0);let L=0;Os({id:S,status:"reading",progress:1,message:`Preparing ${x.length} ${b}`});try{for(let B=0;B<x.length;B+=1){const q=x[B],W=q.file,ke=Math.max(1,Math.ceil(W.size/Vd));for(let Me=0;Me<ke;Me+=1){const he=Me*Vd,tt=Math.min(W.size,he+Vd),yt=W.size===0?new ArrayBuffer(0):await W.slice(he,tt).arrayBuffer(),at=Me===ke-1;Os({id:S,status:"sending",progress:Math.max(2,Math.min(98,Math.round(L/Math.max(1,$)*96))),message:`${B+1}/${x.length} ${q.relativePath}`});const wt=await Oe("/api/remote/files/chunk",{method:"POST",body:JSON.stringify({transferId:S,deviceIds:f,remoteDirectory:ms.trim(),name:W.name,relativePath:q.relativePath,size:W.size,type:W.type,lastModified:W.lastModified,offset:he,totalBytes:W.size,final:at,dataBase64:ZP(yt)})},G);if(!wt.ok||wt.queued!==f.length)throw new Error(wt.error||`file-chunk-not-queued-${wt.queued}/${f.length}`);L+=yt.byteLength,await new Promise(Et=>window.setTimeout(Et,0))}}return Os({id:S,status:"queued",progress:100,message:`Sent ${x.length} file${x.length===1?"":"s"} to ${f.length} Client${f.length===1?"":"s"}`}),window.setTimeout(()=>{Os(B=>B?.id===S&&B.status==="queued"?null:B)},4500),{files:x.length,bytes:$}}catch(B){throw Os({id:S,status:"failed",progress:100,message:B instanceof Error?B.message:String(B)}),B}},gh=async l=>{const f=An.length>0?An.map(b=>b.deviceId):fe?[fe.deviceId]:[];try{await fh(tb(l),f)}catch(b){we(b instanceof Error?b.message:String(b))}},bh=async l=>{try{await fh(tb(l),Kw)}catch(f){we(f instanceof Error?f.message:String(f))}};o.useEffect(()=>{zw.current=!1},[]);const vy=l=>{l.preventDefault(),l.stopPropagation(),Bu(!1),gh(l.dataTransfer.files)},ud=async(l="ltd")=>{if(!n){we("Sign in with Google before checkout.");return}if(re&&l===Qt){we("LiveDesk license is already active.");return}if(re&&Qt==="pro"){we("LiveDesk Pro is already active.");return}Z("checkout");try{const{data:f,error:b}=await pt.functions.invoke("dodo-checkout",{body:{plan:l}});if(b)throw b;if(!f?.checkout_url)throw new Error("Checkout function did not return a checkout URL.");window.location.assign(f.checkout_url)}catch(f){we(f instanceof Error?f.message:String(f)),Z("")}},fl=PP(),vh=IP(),dd=Qu.filter(l=>Ni.has(l)).length,pd=Zu==="open"&&al.sampleMs>0?`${al.framesPerSecond.toFixed(1)} fps`:Zu,Ne=fe?Xe?Mo.get(fe.deviceId):Ni.get(fe.deviceId):void 0,gl=fe?cr(fe,Ct[fe.deviceId]):0,wy=fe?FP(fe):[],yy=typeof Ne?.monitorIndex=="number"?Ko(Ne.monitorIndex,Math.max(1,Ne.monitorCount||1)):gl,md=(Ne&&yy===gl?Pw(Ne):null)||(fe?Tw(fe,gl):null);md&&`${md.width}${md.height}`;const bl=fe?Ut(Xe?"control":"wall",fe.deviceId):"",wn=bl?Nc[bl]:void 0,or=bl?Ac[bl]:void 0,st=or?.lastInfo,xy=wn&&wn.sampleMs>0?`${wn.framesPerSecond.toFixed(1)} fps`:"waiting";wn&&`${wn.totalFrames}${xy}`,or&&or.sampleMs>0&&`${or.framesPerSecond.toFixed(1)}`,or&&or.sampleMs>0&&`${or.changedFramesPerSecond.toFixed(1)}`,st&&(`${st.frameSeq}${st.decoderLabel}${st.queueSize}${st.renderQueueSize}${st.droppedForLatency}${st.decoderFlushCount}${st.decoderTimestampFallbacks}${st.decoderInputCount}${st.decoderOutputCount}`,st.visualChanged),st&&`${Math.round(st.queuedForMs)}${Math.round(st.decodedForMs)}${Math.round(st.scheduledForMs)}${st.drawMs.toFixed(1)}`,st?.targetPaintIntervalMs&&`${st.targetPaintIntervalMs.toFixed(1)}${(1e3/st.targetPaintIntervalMs).toFixed(1)}`,or&&`${or.decoderInputFps.toFixed(1)}${or.decoderOutputFps.toFixed(1)}`,st?.canvasPresentation,st&&`${st.interactiveBufferWaitCount}${Math.round(st.interactiveBufferWaitMs)}${st.interactiveQueueDrainCount}`,wn&&(Ne?.frameMode==="mode5-lzo-delta"?`${Qo(wn.averageFrameBytes)}${Ne.deltaVisualTileCount||0}${Ne.deltaRefreshTileCount||0}${Ne.deltaTotalTiles||0}`:`${Qo(wn.averageFrameBytes)}${Math.round(wn.tinyFrameRatio*100)}${Math.round(wn.repeatedFrameRatio*100)}`),wn&&wn.sourceSendSampleCount>0&&`${wn.sourceSendAverageMs.toFixed(1)}${wn.sourceSendP95Ms.toFixed(1)}`,Ug(wn),Ug(or),wn&&or&&`${Vg(wn)}${Vg(or)}`,Ne?Ne.frameMode||Ne.mode||Ne.codec||Ne.mimeType:Xe?rn.frameMode:ot.frameMode,Xe?rn.frameMode:ot.frameMode,Ne?`${Ne.width}${Ne.height}${Qo(Ne.byteLength)}`:Xe?`${Vr.maxWidth}${Vr.maxHeight}`:`${ot.maxWidth}${ot.maxHeight}`,Ne&&`${Ne.isKeyFrame?"key":String(Ne.chunkType||"delta")}`,Ne&&Ne.monitorCount&&((Ne.monitorIndex??0)+1,`${Ne.monitorCount}`),Ne&&[`src ${Math.round(Ne.sourceGapMs||0)}ms`,`gap ${Math.round(Ne.agentSendGapMs||0)}ms`,`tx ${Math.round(Ne.agentSendDurationMs||0)}ms`,`pace ${Math.round(Ne.agentPaceMs||0)}ms`,`queue ${Math.round(Ne.agentQueueBeforePaceMs||0)}ms`,`age ${Math.round(Ne.agentFrameAgeMs||0)}ms`,Ne.hubPacketTransitAgeMs!==void 0?`sock ${Math.max(0,Math.round(Ne.hubPacketTransitAgeMs))}ms`:"",Ne.droppedByAgent?`drop ${Ne.droppedByAgent}`:"",Ne.hubIngressDropped?`ingress-drop ${Ne.hubIngressDropped}`:"",Ne.hubClientDropped?`ws-drop ${Ne.hubClientDropped}`:"",Ne.captureStageMs?`capture ${Math.round(Ne.captureStageMs)}ms`:"",Ne.requestedFps?`req ${Math.round(Ne.requestedFps)}fps`:"",Ne.effectiveFps?`eff ${Math.round(Ne.effectiveFps)}fps`:"",Ne.captureAverageMs?`avg ${Math.round(Ne.captureAverageMs)}ms`:"",Ne.captureP95Ms?`p95 ${Math.round(Ne.captureP95Ms)}ms`:"",Ne.slowFrameCount?`slow ${Math.round(Ne.slowFrameCount)}`:"",Ne.captureHelperRestarts?`helper ${Math.round(Ne.captureHelperRestarts)}`:"",Ne.convertMs?`rgb565 ${Math.round(Ne.convertMs)}ms`:"",Ne.compressMs?`lzo ${Math.round(Ne.compressMs)}ms`:"",Ne.captureSourceSerial?`cap #${Ne.captureSourceSerial}`:"",Ne.captureSourceSkipped?`cap skip ${Ne.captureSourceSkipped}`:"",Ne.frameMode==="mode5-lzo-delta"?`tiles ${Ne.deltaVisualTileCount||0}+${Ne.deltaRefreshTileCount||0}/${Ne.deltaTotalTiles||0}@${Ne.deltaTileSize||0}`:"",Ne.platformProfile||Ne.hardwareEncoder||"-",Ne.atlasComposeMs?`atlas ${Ne.atlasComposeMs.toFixed(1)}ms`:"",Ne.atlasPoolStarved?`pool ${Ne.atlasPoolStarved}`:"",Ne.atlasTileCount?`tiles ${Ne.atlasReadyTiles||0}/${Ne.atlasTileCount}`:"",Ne.atlasInputRevision?`input #${Ne.atlasInputRevision}`:"",Ne.atlasSourceMaxAgeMs!==void 0?`input-age ${Math.round(Ne.atlasSourceMaxAgeMs)}ms`:"",st?.inputFeedbackMs!==void 0&&st.inputFeedbackAt!==void 0&&performance.now()-st.inputFeedbackAt<=Fg?`feedback ${Math.round(st.inputFeedbackMs)}ms`:"",Ne.contentHash?`enc ${Ne.contentHash.slice(0,6)}`:"",st?.visualHash?`pix ${st.visualHash.slice(0,6)}`:""].filter(Boolean).join(" / "),To==="open"&&[`${Jr.sentPerSecond.toFixed(1)} hz`,Jr.lastInputSeq>0?`rtt ${Math.round(Jr.lastRoundTripMs)}ms`:"",Jr.lastInputSeq>0?`apply ${Jr.lastAgentApplyMs.toFixed(1)}ms`:"",Jr.droppedPerSecond>0?`drop ${Jr.droppedPerSecond.toFixed(1)}/s`:"",Jr.bufferedAmount>0?`buf ${Qo(Jr.bufferedAmount)}`:"",Jr.lastInputType||"ready"].filter(Boolean).join(" / "),st?.inputFeedbackMs!==void 0&&st.inputFeedbackAt!==void 0&&performance.now()-st.inputFeedbackAt<=Fg&&[st.inputFeedbackExact?"exact":"estimated",st.inputFeedbackInputType||"",`total ${Math.round(st.inputFeedbackMs)}ms`,st.inputFeedbackAgentApplyMs!==void 0?`apply ${st.inputFeedbackAgentApplyMs.toFixed(1)}ms`:"",st.inputFeedbackApplyToCaptureMs!==void 0?`apply→frame ${Math.round(st.inputFeedbackApplyToCaptureMs)}ms`:"",st.inputFeedbackInputToFrameMs!==void 0?`input→browser ${Math.round(st.inputFeedbackInputToFrameMs)}ms`:"",st.inputFeedbackFrameToPaintMs!==void 0?`browser→paint ${Math.round(st.inputFeedbackFrameToPaintMs)}ms`:"",st.inputFeedbackSampleCount?`p50 ${Math.round(st.inputFeedbackP50Ms||0)}ms`:"",st.inputFeedbackSampleCount?`p95 ${Math.round(st.inputFeedbackP95Ms||0)}ms`:"",st.inputFeedbackSampleCount?`n=${st.inputFeedbackSampleCount}`:"",`input #${st.inputFeedbackSeq||0}`].filter(Boolean).join(" / "),Ne&&`${Ne.frameSeq}${lb(Ne.receivedAt||Ne.capturedAt)}`;const _i=Math.max(0,al.bytesPerSecond*8/1e6),wh={activeTool:jt,audioError:id,audioMode:Ie,audioState:sd,audioStats:Ft,lastAudioFrame:ad,selectedAudioCaptureStreamId:ih,controlFrames:Mo,controlInputReady:Zr,controlMode:_e,controlPresentationReady:Lu,controlSessionDeviceId:te,controlSessionFrameReady:ce,controlSessionState:ae,controlStreamBinding:Ee,devices:D,documentPresentationVisible:$n,focusedDeviceId:Ae,frames:Ni,localFeatureAccess:Rt,quickActionBusy:be,selectedDeviceId:fe?.deviceId||"",selectedIds:oe,showControlFocus:Xe,videoCaptureStopUnconfirmedByDeviceId:on,videoCapturePausedDeviceIds:qn,wallPresentationReadyDeviceIds:Eu},yh=o.useRef(wh);yh.current=wh,o.useEffect(()=>{if(!kc.current)return;const l=window,f=B=>{if(!B)return null;const q=B.sourceGapMs,W=q==null||q===""?null:Number.isFinite(Number(q))?Number(q):null,ke=B;return{deviceId:B.deviceId,sessionId:B.sessionId||"",streamId:B.streamId||"",commandId:B.commandId||"",captureGeneration:Number(B.captureGeneration||0),monitorIndex:Number(B.monitorIndex||0),streamPurpose:B.streamPurpose||"",frameSeq:Number(B.frameSeq||0),frameMode:B.frameMode||"",mimeType:B.mimeType||"",currentGenerationVerified:ke.currentGenerationVerified===!0,receivedAt:ke.receivedAt||"",capturedAt:ke.capturedAt||"",sourceGapMs:W,inputFeedbackEventId:String(B.inputFeedbackEventId||""),inputFeedbackInputSeq:Number(B.inputFeedbackInputSeq||0),inputFeedbackIssuedAtEpochMs:Number(B.inputFeedbackIssuedAtEpochMs||0),inputFeedbackAgentApplyMs:Number(B.inputFeedbackAgentApplyMs||0),inputFeedbackApplyToCaptureMs:Number(B.inputFeedbackApplyToCaptureMs||0)}},b=B=>{if(!B)return null;const q=window.getComputedStyle(B),W=B.getBoundingClientRect(),ke=Math.max(0,Math.min(W.right,window.innerWidth)-Math.max(W.left,0)),Me=Math.max(0,Math.min(W.bottom,window.innerHeight)-Math.max(W.top,0)),he=Number(q.opacity),tt=B.isConnected&&q.display!=="none"&&q.visibility!=="hidden"&&q.visibility!=="collapse"&&Number.isFinite(he)&&he>0&&W.width>0&&W.height>0&&ke>0&&Me>0;return{connected:B.isConnected,userVisible:tt,width:Math.max(0,Number(B.width||0)),height:Math.max(0,Number(B.height||0)),css:{display:q.display,visibility:q.visibility,opacity:Number.isFinite(he)?he:0},rect:{left:W.left,top:W.top,right:W.right,bottom:W.bottom,width:W.width,height:W.height,viewportIntersectionWidth:ke,viewportIntersectionHeight:Me},codec:Ml(B)}},x=(B,q)=>{const W=gs.current.get(Ut(B,q));return W?{bindingKey:W.bindingKey||"",totalFrames:W.totalFrames,totalChangedFrames:W.totalChangedFrames,lastFrameSeq:Number(W.lastFrameSeq||0),lastPaintAgeMs:W.lastAt===void 0?-1:Math.max(0,performance.now()-W.lastAt),lastInfo:W.lastInfo?{frameSeq:Number(W.lastInfo.frameSeq||0),decoderInputCount:Number(W.lastInfo.decoderInputCount||0),decoderOutputCount:Number(W.lastInfo.decoderOutputCount||0),targetPaintIntervalMs:Number(W.lastInfo.targetPaintIntervalMs||0),droppedForLatency:Number(W.lastInfo.droppedForLatency||0),visualChanged:W.lastInfo.visualChanged===!0,inputFeedbackExact:W.lastInfo.inputFeedbackExact===!0,inputFeedbackMs:Number(W.lastInfo.inputFeedbackMs||0),inputFeedbackSampleCount:Number(W.lastInfo.inputFeedbackSampleCount||0),inputFeedbackP50Ms:Number(W.lastInfo.inputFeedbackP50Ms||0),inputFeedbackP95Ms:Number(W.lastInfo.inputFeedbackP95Ms||0),inputFeedbackTargetMs:Lg,inputFeedbackTargetMinSamples:_g,inputFeedbackOnTarget:W.lastInfo.inputFeedbackExact===!0&&Number(W.lastInfo.inputFeedbackSampleCount||0)>=_g&&Number(W.lastInfo.inputFeedbackP95Ms)<Lg}:null}:null},S=(B,q)=>{if(!B)return null;if(q==="wall-visible"){const ke=gs.current.get(Ut("wall",B));return ke?{bindingKey:ke.bindingKey||"",total:ke.totalFrames,lastFrameSeq:Number(ke.lastFrameSeq||0),lastPaintAgeMs:ke.lastAt===void 0?-1:Math.max(0,performance.now()-ke.lastAt)}:null}if(q!=="control-visible"&&q!=="wall-reuse-visible")return null;const W=Mc.current.get(`${q}:${B}`);return W?{bindingKey:W.bindingKey,total:W.totalPaints,lastFrameSeq:W.lastFrameSeq,lastPaintAgeMs:Math.max(0,performance.now()-W.lastPaintAt)}:null},$=(B,q)=>{const W=S(B,q);return W?{bindingKey:W.bindingKey,totalPaints:W.total,lastPaintAgeMs:W.lastPaintAgeMs,lastFrameSeq:W.lastFrameSeq}:null},L={readPresentationCounter(B,q){return S(String(B||""),q)},snapshot(B,q={}){const W=String(B||""),ke=q.includeHistory===!0,Me=Math.max(0,Number(q.presentationAfterSequence||0)),he=yh.current,tt=he.devices.find(ts=>ts.deviceId===W)?.liveCapturePause,yt=String(Ye.current[W]||""),at=Tt.current.get(W)||null,wt=Ht.current.get(W)||null,Et=Ln.current.get(W)||null,Yn=n0(),Bi=r0(),Hs={frameStats:Tc.current===null?0:1,wallRecovery:ai.current===null?0:1,controlWarm:kr.current===null?0:1,controlWallDownshift:mr.current===null?0:1},Hi=bs.current?.deviceId===W?bs.current:null,jh=hm.current.get(W)||null;return{capturedAt:Date.now(),deviceId:W,activeTool:he.activeTool,documentPresentationVisible:he.documentPresentationVisible,showControlFocus:he.showControlFocus,selectedDeviceId:he.selectedDeviceId,focusedDeviceId:he.focusedDeviceId,selectedDeviceIds:[...he.selectedIds],localFeatureAccess:he.localFeatureAccess,quickActionBusy:he.quickActionBusy,audioMode:he.audioMode,audioState:he.audioState,audioError:he.audioError,audioCaptureStreamId:he.selectedAudioCaptureStreamId,audioFrame:he.lastAudioFrame?{deviceId:he.lastAudioFrame.deviceId,streamId:he.lastAudioFrame.streamId,frameSeq:Number(he.lastAudioFrame.frameSeq||0),mimeType:he.lastAudioFrame.mimeType,sampleRate:Number(he.lastAudioFrame.sampleRate||0),channels:Number(he.lastAudioFrame.channels||0),byteLength:Number(he.lastAudioFrame.byteLength||0)}:null,audioStats:{...he.audioStats},videoCapturePausePhase:yt?yt.startsWith("pending:")?"pending":"confirmed":"none",videoCaptureStopUnconfirmed:he.videoCaptureStopUnconfirmedByDeviceId[W]===!0,authoritativeLiveCapturePause:tt?{phase:tt.phase||"",captureStopConfirmed:tt.captureStopConfirmed===!0,stopAttemptCount:Math.max(0,Number(tt.stopAttemptCount||0)),stopError:tt.stopError||""}:null,controlMode:he.controlMode,controlSessionDeviceId:he.controlSessionDeviceId,controlSessionState:he.controlSessionState,controlSessionFrameReady:he.controlSessionFrameReady,controlPresentationReady:he.controlPresentationReady,controlInputReady:he.controlInputReady,controlConnection:jh?{...jh}:null,pendingControlConnection:Hi?{...Hi,elapsedMs:Math.max(0,performance.now()-Hi.startedAt)}:null,videoCapturePaused:he.videoCapturePausedDeviceIds.has(W),wallPresentationReady:he.wallPresentationReadyDeviceIds.has(W),controlBinding:he.controlStreamBinding?.deviceId===W?{...he.controlStreamBinding}:null,actualControlOwner:it.current?.deviceId===W?{...it.current}:null,wallCapturePauseOwner:Vn.current?.deviceId===W?{...Vn.current}:null,frameSubscriptions:Yn,audioSubscriptions:Bi,presentationTimers:{...Hs,total:Object.values(Hs).reduce((ts,vd)=>ts+vd,0)},wallFrame:f(he.frames.get(W)),controlFrame:f(pa.current.get(W)||he.controlFrames.get(W)),wallPaint:x("wall",W),controlPaint:x("control",W),controlVisiblePaint:$(W,"control-visible"),wallReuseVisiblePaint:$(W,"wall-reuse-visible"),presentationPaintSequence:mm.current,presentationPaintEvents:ke?Fu.current.filter(ts=>ts.deviceId===W&&ts.sequence>Me).sort((ts,vd)=>ts.sequence-vd.sequence).map(ts=>({...ts})):[],wallCanvas:b(at),controlDecodeCanvas:b(wt),controlPresentationCanvas:b(Et),globalCodec:Ml(void 0,{includeLifecycleEvents:ke})}}};return l.__liveDeskTransmissionProbe=L,()=>{l.__liveDeskTransmissionProbe===L&&delete l.__liveDeskTransmissionProbe}},[]);const $i=o.useCallback(()=>{ps(!0),Is(Date.now()),X(),Cr.current!==null&&window.clearTimeout(Cr.current),Cr.current=window.setTimeout(()=>{Cr.current=null,Is(Date.now()),ps(!1)},650)},[X]),xh=o.useCallback(()=>{if(nn){aa(!1);return}ia(!1),aa(!0),$i()},[$i,nn]),Sh=o.useCallback(()=>{if(qt){ia(!1);return}aa(!1),ia(!0),$i()},[qt,$i]),Ch=o.useCallback(()=>{if(Un){oa(!1);return}oa(!0),$i()},[Un,$i]),kh=nn||qt,Mh=JSON.stringify(Ze.filter(l=>l.connected).map(l=>l.deviceId).sort());o.useEffect(()=>{if(!kh)return;const l=JSON.parse(Mh);if(l.length===0){ps(!1);return}const f=new AbortController,b=[];let x=!1;return Cr.current!==null&&(window.clearTimeout(Cr.current),Cr.current=null),ps(!0),Is(Date.now()),Promise.allSettled(l.map(S=>Oe(`/api/remote/devices/${encodeURIComponent(S)}/status-diagnostic`,{method:"POST",body:JSON.stringify({purpose:"remote-status-current-snapshot"}),signal:f.signal,timeoutMs:1500},G))).then(()=>{x||[500,1800,4500].forEach((S,$,L)=>{const B=window.setTimeout(()=>{x||(X(),Is(Date.now()),$===L.length-1&&ps(!1))},S);b.push(B)})}),()=>{x=!0,f.abort();for(const S of b)window.clearTimeout(S)}},[G,X,Mh,kh]);const Oi=new Map,Lo=new Map;if(nn||qt||Un)for(const l of Ze){const f=l.deviceId,b=Xe&&te===f,S=Ut(b?"control":"wall",f),$=b?Mo.get(f):Ni.get(f),L=b?Ht.current.get(f)||Ln.current.get(f)||null:Tt.current.get(f)||(St?sr.current:null),B={device:l,frame:$,receiveStat:Nc[S],paintStat:Ac[S],codec:L?Ml(L):{},selectedMonitorIndex:cr(l,Ct[f]),control:b,controlInputReady:b&&Zr,controlBinding:b&&Ee?.deviceId===f?Ee:void 0,hubRelay:P?.relay,capturePaused:qn.has(f),capturePauseConfirmed:l.liveCapturePause?.captureStopConfirmed===!0,capturePauseError:l.liveCapturePause?.stopError||"",clientHeartbeatMs:Number(P?.heartbeatMs||5e3),now:Date.now()},q=["open","playing","silent"].includes(sd),W=Ft.nativeCallbackDiagnosticsAvailable&&(Ft.nativeRejectedCallbackCount>0||Ft.nativeCurrentnessDropCount>0),ke=q&&!W,Me=f===fe?.deviceId&&Ie?{id:"browser-remote-audio",state:ke?"ok":"warning",label:ke?"Remote audio is healthy":"Remote audio needs attention",detail:Ft.lastUpdatedAt>0?[sd,`context ${Ft.audioContextState}`,`queue ${Math.round(Ft.queuedMs)}ms`,`packet ${Math.round(Ft.lastPacketAgeMs)}ms`,`capture ${Ft.captureHealthy?"healthy":Ft.captureAwaitingCurrentPcm?"awaiting PCM":"down"}`,Ft.backendKind?`backend ${Ft.backendKind}`:"backend unknown",Ft.helperRequired?`helper ${Ft.helperAlive&&Ft.helperPid>0?`pid ${Ft.helperPid}`:"missing"}`:"helper N/A",`drop ${Ft.drops}`,`restart ${Ft.automaticRestarts}`,Ft.nativeCallbackDiagnosticsAvailable?`native reject ${Ft.nativeRejectedCallbackCount}`:"native callback diagnostics unknown",Ft.nativeCallbackDiagnosticsAvailable?`native stale ${Ft.nativeCurrentnessDropCount}`:"",Ft.nativeLastDropReason?`native reason ${Ft.nativeLastDropReason}`:"",ad?`frame #${ad.frameSeq}`:"waiting for frame"].filter(Boolean).join(" · "):"Browser audio diagnostics are collecting while Remote or Debug status is open."}:null;if(nn||Un){const he=yT(B);nn&&Me&&he.push(Me),Oi.set(f,he)}if(qt){const he=xT(B);Me&&he.push(Me),Lo.set(f,he)}}const Sy=Un?ST({status:P||{},deviceDiagnostics:[...Oi.values()],codec:Ml(),browser:{hardwareConcurrency:navigator.hardwareConcurrency,deviceMemory:Number(navigator.deviceMemory||0)},frameStats:al}):[],Ah=Ai?.atlasReadyTiles??dd,hd=Ai?.atlasTileCount??dd,Cy=Ah===hd?`${hd} tiles`:`${Ah}/${hd} tiles`,ky=Kn.length>0;Xe?`${pd}${_i.toFixed(_i>=10?0:1)}`:ky?`${Cy}${pd}${_i.toFixed(_i>=10?0:1)}`:`${dd}${pd}${_i.toFixed(_i>=10?0:1)}`;const fd=An.length,Nh=Xe?fe?dn(fe):"No Client":fd===0?"No Client":fd>1?`${fd} selected`:fe?dn(fe):"No Client",My=Xe?[fe?.deviceId].filter(l=>!!l):An.map(l=>l.deviceId),Wn=to[$r]||to.en,vl=Wn.sync||to.en.sync,Ay=s||de?"checking":re?Qt==="pro"?"Pro LTD active":`Plus LTD ${Ze.length}/${$o}`:Xw?`Free ${Ze.length}/${yl}`:`Upgrade ${Ze.length}/${yl}`,Ny=re?Qt==="pro"?"Pro active":"Upgrade to Pro LTD":n?bt==="checkout"?"Opening checkout":Qt==="ltd"?"Buy Pro LTD":"Buy Plus LTD":bt==="auth"?"Opening Google":"Sign in to buy",Ry=Qt==="pro"||bt==="checkout"||bt==="auth"||s||de,Rh=n?.user?.user_metadata,wl=nb(Rh,"avatar_url","picture"),_o=nb(Rh,"full_name","name")||n?.user?.email||"Google",Th=_o.slice(0,1).toUpperCase(),Ty=P?.started?"Local app ready":"Start LiveDesk",Py=a?.active?"Published":n?"Not published":"Sign in required",Iy=/^\d{6}$/.test(P?.pairingPin||"")?P?.pairingPin:"------",Da=l=>{if(typeof window<"u"&&(l==="support"?window.history.pushState({},"","/support"):jt==="support"&&window.history.pushState({},"",p?"/app":"/")),l==="control"){const f=vn||yi;if(f&&(Eo(f.deviceId),_n(!1),Se(f.deviceId)),tn(l),!Rt){$e(!1),we(xi);return}$e(!0);return}l==="wall"&&Ew(f=>f+1),tn(l),$e(!1)},es=bt==="update"||vt?.stage==="updating"||["dispatching","waiting-for-clients","hub-restart-requested"].includes(P?.update?.state||""),Ph=!!(P?.update?.updateAvailable&&P.update.canApply||es||vt?.error||!P&&vt),La=nS($r),gd=o.useCallback(l=>{if(!vt?.targetIds.includes(l))return;const f=P?.update?.operationId===vt.operationId?P.update.targets?.find(b=>b.deviceId===l):void 0;switch(f?.state){case"completed":return ni[Hg(vt.operationId,f)]?{state:"updated",label:"Updated"}:void 0;case"failed":return{state:"failed",label:"Update failed",error:f.error};case"pending-offline":return{state:"offline",label:"Waiting for reconnect"};case"queued":return vt.stage==="updating"?{state:"queued",label:"Queued"}:void 0;case"waiting":return vt.stage==="updating"?f.candidateSince?{state:"updating",label:"Verifying restart..."}:{state:"updating",label:"Restarting..."}:void 0;default:return vt.stage==="updated"?{state:"updated",label:"Updated"}:vt.stage==="updating"?{state:"updating",label:"Verifying..."}:void 0}},[P?.update,ni,vt]),bd=A&&!!n&&V&&!P?.started,jy=s?"checking":P?.started?"online":bd?O?"retrying":"connecting":"offline",Ey=s?"Checking Hub":P?.started?`${Ze.length} online`:bd?O?"Hub offline":"Connecting Hub":n?"Hub offline":"Sign in required",Fy=P?.deviceName||(bd?O?"Retrying automatically…":"Trying saved Hub routes…":O?"Desktop Hub unavailable":"Remote management"),Ih=A&&p&&!s&&!n;return r.jsxs("main",{className:`app-shell ${Sa||Xe?"stream-surface-active":""} ${A?"mobile-console-shell":""} ${A&&Xe?"mobile-console-control-active":""}`,"data-mobile-auth-required":Ih?"true":void 0,"data-mobile-standalone":A&&N?"true":void 0,"data-mobile-ios":A&&v.isIos?"true":void 0,"data-mobile-android":A&&v.isAndroid?"true":void 0,children:[r.jsxs("aside",{className:"tool-rail","aria-label":"LiveDesk tools",children:[r.jsx("div",{className:"rail-brand",title:"LiveDesk",children:r.jsx(ib,{size:25})}),r.jsx("nav",{className:"rail-tools",children:iI.map(l=>{const f=l.icon,b=ru(l.tooltip,$r);return r.jsxs("button",{className:`rail-tool ${l.id==="sync-server"?"sync-server hub-sync-trigger":""} ${jt===l.id?"active":""} accent-${l.accent}`,onClick:()=>l.id==="sync-server"?dy():Da(l.id),"data-tooltip":l.id==="sync-server"&&lt?void 0:op(l.label,l.tooltip,$r),"aria-label":`${l.label}. ${b}`,type:"button",disabled:l.id==="sync-server"&&bt==="host","aria-busy":l.id==="sync-server"&&bt==="host","aria-expanded":l.id==="sync-server"?lt:void 0,"aria-haspopup":l.id==="sync-server"?"dialog":void 0,"aria-controls":l.id==="sync-server"&&lt?"hub-sync-popover":void 0,children:[l.id==="sync-server"&&bt==="host"?r.jsx("span",{className:"sync-server-spinner","aria-hidden":"true"}):r.jsx(f,{size:19}),r.jsx("span",{children:l.id==="sync-server"&&bt==="host"?"Syncing…":l.label})]},l.id)})}),r.jsxs("div",{className:"rail-footer",children:[oI.map(l=>{const f=l.icon;return r.jsxs("button",{className:`rail-tool compact ${jt===l.id?"active":""} accent-${l.accent}`,onClick:()=>Da(l.id),title:l.label,type:"button",children:[r.jsx(f,{size:18}),r.jsx("span",{children:l.label})]},l.id)}),r.jsxs("button",{className:`rail-tool compact local-settings ${yo?"active":""}`,onClick:()=>{tn("settings"),typeof window<"u"&&window.history.pushState({},"","/"),Br(!1),$e(!1),ao(!1)},title:"Settings",type:"button",children:[r.jsx(nu,{size:18}),r.jsx("span",{children:"Settings"})]}),r.jsxs("button",{className:`rail-account ${n?"signed-in":""}`,onClick:()=>{Br(l=>!l)},disabled:s||bt==="auth","aria-expanded":ca,title:n?`Account: ${n.user?.email||_o}`:"Sign in with Google",type:"button",children:[n?wl?r.jsx("img",{src:wl,alt:_o,referrerPolicy:"no-referrer"}):r.jsx("span",{className:"avatar-fallback",children:Th}):r.jsx(Gs,{size:18}),r.jsx("span",{children:n?"Account":"Google"})]}),ca&&r.jsxs("section",{className:"account-popover",role:"dialog","aria-label":"LiveDesk account",children:[r.jsxs("div",{className:"account-popover-head",children:[r.jsx("div",{className:"account-popover-avatar",children:n&&wl?r.jsx("img",{src:wl,alt:_o,referrerPolicy:"no-referrer"}):n?r.jsx("span",{children:Th}):r.jsx(Gs,{size:18})}),r.jsxs("div",{children:[r.jsx("strong",{children:n?_o:"Account"}),r.jsx("p",{children:n?.user?.email||"Not signed in"})]})]}),r.jsxs("dl",{className:"account-popover-facts",children:[r.jsx("dt",{children:"User"}),r.jsx("dd",{children:n?.user?.email||"Not signed in"}),r.jsx("dt",{children:"Network"}),r.jsx("dd",{children:Ty}),r.jsx("dt",{children:"Access"}),r.jsx("dd",{children:Py}),r.jsx("dt",{children:"Plan"}),r.jsx("dd",{children:Ay}),r.jsx("dt",{children:"Ads"}),r.jsx("dd",{children:Qt==="free"?"Standard banner":"Removed"})]}),n?r.jsxs("button",{className:"account-popover-action",onClick:uy,disabled:bt==="auth",type:"button",children:[r.jsx(mb,{size:16}),"Logout"]}):r.jsxs("button",{className:"account-popover-action primary",onClick:Li,disabled:bt==="auth",type:"button",children:[r.jsx(Gs,{size:16}),"Sign in with Google"]})]})]})]}),A&&y&&r.jsx("div",{className:"mobile-pwa-guide-backdrop",role:"presentation",onClick:()=>k(!1),children:r.jsxs("section",{className:"mobile-pwa-guide",role:"dialog","aria-modal":"true","aria-labelledby":"mobile-pwa-guide-title",onClick:l=>l.stopPropagation(),children:[r.jsxs("header",{children:[r.jsx("span",{className:"mobile-pwa-guide-mark","aria-hidden":"true",children:r.jsx(Sb,{size:20})}),r.jsxs("span",{children:[r.jsx("strong",{id:"mobile-pwa-guide-title",children:"Install LiveDesk on iPhone"}),r.jsx("small",{children:"Open without browser bars and tabs"})]}),r.jsx("button",{type:"button",onClick:()=>k(!1),"aria-label":"Close install guide",children:r.jsx(xn,{size:18,"aria-hidden":"true"})})]}),r.jsxs("ol",{children:[r.jsxs("li",{children:["Tap ",v.browserName==="browser"?"the browser":v.browserName,"'s ",r.jsx("strong",{children:"Share"})," button."]}),r.jsxs("li",{children:["Tap ",r.jsx("strong",{children:"Add to Home Screen"}),"."]}),r.jsx("li",{children:v.isSafari?r.jsxs(r.Fragment,{children:["Turn on ",r.jsx("strong",{children:"Open as Web App"}),", then tap ",r.jsx("strong",{children:"Add"}),"."]}):r.jsxs(r.Fragment,{children:["Confirm the app name, then tap ",r.jsx("strong",{children:"Add"}),"."]})})]}),r.jsx("button",{className:"mobile-pwa-guide-done",type:"button",onClick:()=>k(!1),children:"Got it"})]})}),Ih&&r.jsxs("section",{className:"mobile-console-auth","aria-labelledby":"mobile-console-auth-title",children:[r.jsx("span",{className:"mobile-console-auth-mark","aria-hidden":"true",children:r.jsx(Zt,{size:26})}),r.jsx("h1",{id:"mobile-console-auth-title",children:s?"Checking your account":"Sign in to LiveDesk"}),r.jsx("p",{children:"Use the same Google account as your LiveDesk Hub."}),r.jsxs("button",{type:"button",onClick:()=>{Li()},disabled:s||bt==="auth","aria-busy":s||bt==="auth",children:[s||bt==="auth"?r.jsx(Zn,{className:"spin",size:19,"aria-hidden":"true"}):r.jsx(Gs,{size:19,"aria-hidden":"true"}),bt==="auth"?"Opening Google…":s?"Checking sign-in…":"Sign in with Google"]}),r.jsx("small",{children:"After sign-in, LiveDesk returns to this installed app."})]}),lt&&r.jsxs("section",{id:"hub-sync-popover",className:"client-hub-switch-popover hub-sync-popover",role:"dialog","aria-modal":"false","aria-labelledby":"hub-sync-title","aria-describedby":"hub-sync-description hub-sync-notice",children:[r.jsxs("header",{className:"client-hub-switch-head",children:[r.jsx("span",{className:"client-hub-switch-mark","aria-hidden":"true",children:r.jsx(os,{size:19})}),r.jsx("span",{className:"client-hub-switch-eyebrow",children:La.eyebrow}),r.jsx("button",{className:"client-hub-switch-close",type:"button",onClick:()=>Fo(),"aria-label":La.closeLabel,children:r.jsx(xn,{size:17})})]}),r.jsx("h2",{id:"hub-sync-title",children:La.title}),r.jsx("p",{id:"hub-sync-description",children:La.description}),r.jsxs("p",{id:"hub-sync-notice",className:"client-hub-switch-notice",children:[r.jsx(Zt,{size:16,"aria-hidden":"true"}),r.jsx("span",{children:La.restartNotice})]}),r.jsxs("div",{className:"client-hub-switch-actions",children:[r.jsx("button",{type:"button",onClick:()=>Fo(),children:La.cancel}),r.jsxs("button",{ref:At,className:"primary",type:"button",onClick:py,disabled:bt==="host",children:[r.jsx(os,{size:16}),La.confirm]})]})]}),r.jsxs("section",{className:`desk-stage ${Sa&&!Or?"dock-open":""} ${Xe?"control-stage":""} ${Oc?"agents-stage":""} ${xa?"file-share-stage":""}`,children:[A&&r.jsxs("header",{className:"mobile-console-header",children:[r.jsxs("span",{className:"mobile-console-brand","aria-label":"LiveDesk mobile Console",children:[r.jsx("span",{className:"mobile-console-brand-mark",children:r.jsx(Ji,{size:18})}),r.jsxs("span",{children:[r.jsx("strong",{children:"LiveDesk"}),r.jsx("small",{children:"Mobile Console"})]})]}),r.jsxs("span",{className:`mobile-console-hub state-${jy}`,role:"status","aria-live":"polite",children:[r.jsx("i",{"aria-hidden":"true"}),r.jsxs("span",{children:[r.jsx("strong",{children:Ey}),r.jsx("small",{children:Fy})]})]}),r.jsxs("span",{className:"mobile-console-header-actions",children:[p&&!N&&(g||v.isIos)&&r.jsx("button",{className:"mobile-console-install",onClick:()=>{I()},"aria-label":"Install LiveDesk app",title:"Install LiveDesk app",type:"button",children:r.jsx(tp,{size:19,"aria-hidden":"true"})}),Ph&&r.jsx("button",{className:"mobile-console-update",onClick:()=>{dh()},disabled:es||!P?.update?.canApply,"aria-label":es?"LiveDesk update in progress":"Update LiveDesk","aria-busy":es,type:"button",children:es?r.jsx("span",{className:"topbar-update-spinner","aria-hidden":"true"}):r.jsx(rc,{size:18,"aria-hidden":"true"})})]})]}),r.jsxs("header",{className:"topbar",children:[r.jsx("div",{className:"topbar-leading",children:Ph?r.jsxs("button",{className:"topbar-update-button",onClick:()=>{dh()},title:vt?.error?`LiveDesk Hub update failed: ${vt.error}`:`Update LiveDesk to ${P?.update?.latestVersion||vt?.targetManagerVersion||"latest"}`,"aria-label":vt?.error?`LiveDesk Hub update failed: ${vt.error}`:es?"LiveDesk update in progress":`Update LiveDesk to ${P?.update?.latestVersion||vt?.targetManagerVersion||"latest"}`,type:"button",disabled:es||!P?.update?.canApply,"aria-busy":es,children:[es?r.jsx("span",{className:"topbar-update-spinner","aria-hidden":"true"}):r.jsx(rc,{size:19,"aria-hidden":"true"}),es&&P?.update?.targetCount?r.jsxs("span",{className:"topbar-update-count","aria-hidden":"true",children:[P.update.completedCount||0,"/",P.update.targetCount]}):null]}):null}),r.jsxs("div",{className:"topbar-tray",children:[xa&&!Xe&&r.jsxs("div",{className:"file-share-top-route","aria-label":"File distribution route",children:[r.jsxs("div",{children:[r.jsx(qa,{size:17}),r.jsxs("span",{children:[r.jsx("small",{children:"Source"}),r.jsx("strong",{children:"LiveDesk Hub"})]})]}),r.jsx(Dp,{size:15}),r.jsx(mx,{size:16}),r.jsxs("div",{children:[r.jsx("span",{className:"file-share-top-route-laptops",children:"▣ ▣ ▣"}),r.jsxs("span",{children:[r.jsx("small",{children:"Destination"}),r.jsxs("strong",{children:[Pm," Client",Pm===1?"":"s"]}),r.jsx("em",{children:ms.trim()||"Desktop/LiveDeskFiles"})]})]})]}),Sa&&!Xe&&r.jsxs("div",{className:"top-actions",children:[r.jsx(Tg,{active:Un,refreshing:Un&&_r,onClick:Ch}),r.jsx(Ng,{active:nn,refreshing:nn&&_r,onClick:xh}),r.jsx(Rg,{active:qt,refreshing:qt&&_r,onClick:Sh}),r.jsx("span",{className:"top-actions-divider","aria-hidden":"true"}),r.jsx(Ag,{controller:Dm,onError:we}),r.jsx("span",{className:"top-actions-divider","aria-hidden":"true"}),r.jsx("div",{className:"segmented-control wall-cadence-control","aria-label":"Wall frame speed",children:sI.map(l=>r.jsx("button",{className:ur===l.id?"active":"",onClick:()=>{ei(l.id),ua(l.fps),UP(l.id)},title:l.label+" Wall streaming ("+l.fps+" fps)","aria-pressed":ur===l.id,type:"button",children:l.label},l.id))}),r.jsx("span",{className:"top-actions-divider","aria-hidden":"true"}),r.jsxs("div",{className:"wall-view-control",children:[r.jsx("div",{className:"segmented-control","aria-label":"Wall view",children:aI.map(l=>r.jsx("button",{className:Bt===l.id?"active":"",onClick:()=>hc(l.id),"aria-pressed":Bt===l.id,type:"button",children:l.label},l.id))}),r.jsx("label",{className:"wall-view-slider",htmlFor:"wall-view-scale",children:r.jsx("input",{id:"wall-view-scale",type:"range",min:lu,max:Ja,step:1,value:us,onChange:l=>ds(Number(l.currentTarget.value)),"aria-label":"Wall tile size","aria-valuetext":fc})})]})]}),Xe&&r.jsxs("div",{className:"top-actions",children:[r.jsx(Tg,{active:Un,refreshing:Un&&_r,onClick:Ch}),r.jsx(Ng,{active:nn,refreshing:nn&&_r,onClick:xh}),r.jsx(Rg,{active:qt,refreshing:qt&&_r,onClick:Sh}),r.jsx("span",{className:"top-actions-divider","aria-hidden":"true"}),r.jsx(Ag,{controller:Dm,onError:we})]})]})]}),Un&&Sa&&r.jsx(uT,{items:Sy,collectedAt:gc,onClose:()=>oa(!1)}),km?r.jsxs("section",{className:"doc-page",lang:$r,dir:$r==="ar"?"rtl":"ltr",children:[r.jsxs("section",{className:"doc-hero",children:[r.jsxs("div",{className:"doc-hero-copy",children:[r.jsxs("span",{className:"pricing-eyebrow",children:[r.jsx(tu,{size:16}),Wn.eyebrow]}),r.jsx("h2",{children:Wn.title}),r.jsx("p",{children:Wn.intro})]}),r.jsxs("label",{className:"doc-language-picker",children:[r.jsxs("span",{children:[r.jsx(hx,{size:17}),Wn.languageLabel]}),r.jsx("select",{value:$r,onChange:l=>bc(l.target.value),children:lI.map(l=>r.jsx("option",{value:l.id,children:l.label},l.id))})]})]}),r.jsx("section",{className:"doc-grid",children:Wn.sections.map((l,f)=>{const x=[os,Gl,Bh,Zt,bu][f]||tu;return r.jsxs("article",{className:"doc-card",children:[r.jsx("div",{className:"doc-card-icon",children:r.jsx(x,{size:19})}),r.jsxs("div",{children:[r.jsx("h3",{children:l.title}),r.jsx("p",{children:l.body}),r.jsx("ul",{children:l.points.map(S=>r.jsx("li",{children:S},S))})]})]},l.title)})}),vl&&r.jsxs("section",{className:"doc-sync",children:[r.jsxs("div",{className:"doc-sync-head",children:[r.jsx(Bh,{size:20}),r.jsxs("div",{children:[r.jsx("h3",{children:vl.title}),r.jsx("p",{children:vl.body})]})]}),r.jsx("ul",{children:vl.points.map(l=>r.jsx("li",{children:l},l))})]}),r.jsxs("section",{className:"doc-firewall",children:[r.jsxs("div",{className:"doc-firewall-head",children:[r.jsx(Zt,{size:20}),r.jsxs("div",{children:[r.jsx("h3",{children:Wn.firewall.title}),r.jsx("p",{children:Wn.firewall.body})]})]}),r.jsx("ul",{children:Wn.firewall.points.map(l=>r.jsx("li",{children:l},l))})]}),r.jsxs("section",{className:"doc-command-panel",children:[r.jsxs("div",{className:"doc-command-head",children:[r.jsx(Gl,{size:20}),r.jsxs("div",{children:[r.jsx("h3",{children:Wn.commands.title}),r.jsx("p",{children:Wn.commands.body})]})]}),r.jsxs("div",{className:"doc-command-list",children:[Wn.commands.manager&&r.jsxs("div",{className:"doc-command-row",children:[r.jsx("span",{children:Wn.commands.manager}),r.jsx("code",{children:vh}),r.jsx("button",{className:"icon-button",onClick:()=>Vl(vh),title:"Copy command",type:"button",children:r.jsx(wd,{size:16})})]}),r.jsxs("div",{className:"doc-command-row",children:[r.jsx("span",{children:Wn.commands.primary}),r.jsx("code",{children:fl}),r.jsx("button",{className:"icon-button",onClick:()=>Vl(fl),title:"Copy command",type:"button",children:r.jsx(wd,{size:16})})]}),r.jsxs("div",{className:"doc-command-row",children:[r.jsx("span",{children:Wn.commands.slot}),r.jsx("code",{children:`${fl} 3`}),r.jsx("button",{className:"icon-button",onClick:()=>Vl(`${fl} 3`),title:"Copy command",type:"button",children:r.jsx(wd,{size:16})})]})]})]})]}):Oc?r.jsx(Cg,{hubUrl:G,devices:D}):xa?r.jsx(uR,{hubUrl:G,devices:Ze,localFeatureAccess:Rt,upgradeNotice:xi,remoteDirectory:ms,onRemoteDirectoryChange:io,targetMode:fi,selectedTargetIds:gi,onTargetModeChange:Ow,onTargetToggle:l=>Hu(f=>f.includes(l)?f.filter(b=>b!==l):[...f,l]),filePickerRef:Hw,folderPickerRef:Ww,onBrowserFileImport:l=>{bh(l)},onBrowserFolderImport:l=>{bh(l)},onNotice:we,onTransferChange:l=>{if(!l){Os(null);return}const f=l.state==="failed"||l.state==="partially-failed"||l.state==="cancelled"?"failed":l.state==="completed"?"queued":l.state==="sending"?"sending":"reading";Os({id:l.id,status:f,progress:l.progress,message:l.message}),["completed","partially-failed","failed","cancelled"].includes(l.state)&&window.setTimeout(()=>Os(b=>b?.id===l.id?null:b),4500)}}):Mm?r.jsx(Mb,{session:n,currentProductKey:"livedesk",appVersion:"",onSignIn:Li}):yo?r.jsx(Nk,{hubUrl:G,mobileLayout:A,runtimeRole:P?.runtimeRole||"hub",runtimeDeviceId:P?.deviceId||"",sessionAccessToken:n?.access_token||"",showThisComputerSetting:!A&&P?.runtimeRole==="hub",onShowThisComputerChange:ie,pin:r.jsxs(Rk,{children:[r.jsx("div",{className:"settings-section-grid",children:r.jsxs("section",{className:"settings-section-card settings-pairing-card",children:[r.jsxs("div",{className:"settings-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Pair a Client"}),r.jsx("h3",{children:"Connect another local PC"})]}),r.jsx(pn,{size:20})]}),r.jsxs("div",{className:"settings-pin-display",children:[r.jsx("span",{children:"Hub PIN"}),r.jsx("strong",{children:Iy}),r.jsxs("button",{className:"text-button ghost compact",onClick:my,disabled:!P?.started||bt==="pin",type:"button",children:[r.jsx(As,{size:15}),bt==="pin"?"Creating":"New PIN"]})]})]})}),r.jsxs("section",{className:"settings-section-card",children:[r.jsxs("div",{className:"settings-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"File transfer"}),r.jsx("h3",{children:"Client destination folder"})]}),r.jsx(Xi,{size:20})]}),r.jsxs("label",{className:"settings-field",children:[r.jsx("span",{children:"Remote folder"}),r.jsx("input",{value:ms,onChange:l=>io(l.target.value),placeholder:"Desktop/LiveDeskFiles"})]}),r.jsx("p",{className:"settings-help",children:"Blank uses Desktop/LiveDeskFiles on each Client."})]})]}),desktopUpdate:r.jsx(Ab,{}),agent:r.jsx(Pk,{hubUrl:G,showToast:we}),captureGallery:r.jsx(lT,{hubUrl:G,onToast:we})}):Cm?r.jsxs("section",{className:"pricing-page",children:[r.jsxs("header",{className:"pricing-header",children:[r.jsxs("div",{children:[r.jsxs("span",{className:"pricing-eyebrow",children:[r.jsx(sp,{size:15})," LiveDesk plans"]}),r.jsx("h2",{children:"Choose the plan that fits your wall"}),r.jsx("p",{children:"Free supports up to 5 personal devices with a standard banner. Upgrade for an ad-free wall, more Clients, or commercial use."})]}),r.jsx("button",{className:"pricing-close",onClick:()=>Da("wall"),title:"Close pricing",type:"button",children:r.jsx(xn,{size:18})})]}),r.jsxs("div",{className:"pricing-status","aria-live":"polite",children:[r.jsx("span",{children:"Current plan"}),r.jsx("strong",{children:Em.name}),r.jsxs("small",{children:[Ze.length,"/",vP(Gu)," connected devices"]})]}),r.jsxs("div",{className:"pricing-cards","aria-label":"LiveDesk plans",children:[r.jsxs("article",{className:`pricing-plan-card ${Qt==="free"?"current":""}`,children:[r.jsxs("div",{className:"pricing-plan-topline",children:[r.jsx("span",{className:"pricing-plan-badge free",children:"Free"}),r.jsx("strong",{children:"$0"})]}),r.jsx("p",{className:"pricing-plan-audience",children:ks.free.audience}),r.jsx("h3",{children:"Free personal screen wall"}),r.jsx("p",{children:ks.free.note}),r.jsxs("ul",{children:[r.jsxs("li",{children:[r.jsx(En,{size:16})," Up to ",yl," devices"]}),r.jsxs("li",{children:[r.jsx(En,{size:16})," Live view and local control"]}),r.jsxs("li",{children:[r.jsx(En,{size:16})," Standard banner helps keep Free available"]})]}),r.jsx("span",{className:"pricing-current-label",children:Qt==="free"?"Current plan":"Included for everyone"})]}),r.jsxs("article",{className:`pricing-plan-card featured ${Qt==="ltd"?"current":""}`,children:[r.jsxs("div",{className:"pricing-plan-topline",children:[r.jsxs("span",{className:"pricing-plan-badge plus",children:[r.jsx(fx,{size:14})," Plus"]}),r.jsxs("span",{className:"pricing-plan-price",children:[r.jsx("strong",{children:ks.ltd.price}),r.jsx("small",{children:"/ month"})]})]}),r.jsx("p",{className:"pricing-plan-audience",children:ks.ltd.audience}),r.jsx("h3",{children:"Ad-free personal wall"}),r.jsx("p",{children:"Monitor up to 30 personal computers without the standard banner."}),r.jsxs("ul",{children:[r.jsxs("li",{children:[r.jsx(En,{size:16})," Up to ",$o," devices"]}),r.jsxs("li",{children:[r.jsx(En,{size:16})," No standard ad banner"]})]}),r.jsxs("div",{className:"pricing-ltd-offer",children:[r.jsx("span",{children:"Plus LTD"}),r.jsx("strong",{children:ks.ltd.ltd}),r.jsx("small",{children:"One-time · available now"})]}),r.jsxs("button",{className:"pricing-plan-button",onClick:n?()=>ud("ltd"):Li,disabled:Qt!=="free"||bt==="checkout"||bt==="auth"||s||de,type:"button",children:[r.jsx(Xo,{size:16}),Qt==="free"?n?"Buy Plus LTD · $79":"Sign in for Plus LTD":"Plus active"]})]}),r.jsxs("article",{className:`pricing-plan-card pro ${Qt==="pro"?"current":""}`,children:[r.jsxs("div",{className:"pricing-plan-topline",children:[r.jsxs("span",{className:"pricing-plan-badge pro",children:[r.jsx(Zt,{size:14})," Pro"]}),r.jsxs("span",{className:"pricing-plan-price",children:[r.jsx("strong",{children:ks.pro.price}),r.jsx("small",{children:"/ month"})]})]}),r.jsx("p",{className:"pricing-plan-audience",children:ks.pro.audience}),r.jsx("h3",{children:"Commercial monitoring"}),r.jsx("p",{children:"For studios, offices, teams, and any other business use."}),r.jsxs("ul",{children:[r.jsxs("li",{children:[r.jsx(En,{size:16})," More than ",$o," connected Clients"]}),r.jsxs("li",{children:[r.jsx(En,{size:16})," Ad-free commercial use"]})]}),r.jsxs("div",{className:"pricing-ltd-offer pro",children:[r.jsx("span",{children:"Pro LTD"}),r.jsx("strong",{children:ks.pro.ltd}),r.jsx("small",{children:"One-time · available now"})]}),r.jsxs("button",{className:"pricing-plan-button",onClick:n?()=>ud("pro"):Li,disabled:Qt==="pro"||bt==="checkout"||bt==="auth"||s||de,type:"button",children:[r.jsx(Xo,{size:16}),Qt==="pro"?"Pro active":n?"Buy Pro LTD · $199":"Sign in for Pro LTD"]})]})]}),r.jsxs("section",{className:"pricing-includes",children:[r.jsxs("div",{children:[r.jsx(pn,{size:17}),r.jsx("span",{children:"Screen wall"}),r.jsx("strong",{children:"120+ layout slots"})]}),r.jsxs("div",{children:[r.jsx(Uo,{size:17}),r.jsx("span",{children:"Focused control"}),r.jsx("strong",{children:"Local-first"})]}),r.jsxs("div",{children:[r.jsx(yd,{size:17}),r.jsx("span",{children:"Remote audio"}),r.jsx("strong",{children:"Available"})]}),r.jsxs("div",{children:[r.jsx(Xi,{size:17}),r.jsx("span",{children:"File transfer"}),r.jsx("strong",{children:"Included"})]})]}),r.jsxs("p",{className:"pricing-note",children:[r.jsx(En,{size:15})," Free includes a standard banner for personal use. Plus removes the banner for personal, creator, and homelab use. Commercial use requires Pro."]}),r.jsxs("button",{className:"pricing-primary-cta",onClick:n?()=>ud(Qt==="ltd"?"pro":"ltd"):Li,disabled:Ry,type:"button",children:[r.jsx(Xo,{size:18}),Ny]})]}):r.jsx(r.Fragment,{children:r.jsxs("section",{className:`monitor-layout ${Or?"dock-collapsed":""}`,children:[r.jsxs("section",{ref:xm,className:`screen-wall-panel ${_w?"drop-active":""}`,onClick:l=>{l.currentTarget===l.target&&Do()},onDragEnter:l=>{l.preventDefault(),Bu(!0)},onDragOver:l=>{l.preventDefault(),l.dataTransfer.dropEffect="copy"},onDragLeave:l=>{l.currentTarget===l.target&&Bu(!1)},onDrop:vy,children:[Kn.length>0&&r.jsx("canvas",{ref:ty,className:"atlas-source-canvas",width:Pa?.width||1920,height:Pa?.height||1080,"aria-hidden":"true"}),A&&Sa&&!Xe&&r.jsxs("section",{className:"mobile-console-selection","aria-label":"Selected computer actions",children:[r.jsxs("div",{className:"mobile-console-selection-copy",children:[r.jsx("span",{children:"Selected computer"}),r.jsx("strong",{children:Nh}),r.jsx("small",{children:fe?`${fe.platform||"Client"} · ${as(fe)} display${as(fe)===1?"":"s"}`:"Tap a computer below, then choose an action."})]}),r.jsxs("div",{className:"mobile-console-actions",role:"toolbar","aria-label":"Selected computer quick actions",children:[r.jsxs("button",{onClick:()=>fe&&void Fa(fe.deviceId),disabled:!Tr||!!be,type:"button",children:[r.jsx(Uo,{size:17}),r.jsx("span",{children:"Control"})]}),r.jsxs("button",{className:Ie?"active":"",onClick:()=>{mh()},disabled:!Ku||!!be,"aria-pressed":Ie,type:"button",children:[be==="audio"?r.jsx(Zn,{className:"spin",size:17}):r.jsx(yd,{size:17}),r.jsx("span",{children:"Audio"})]}),r.jsxs("button",{className:xs?"":"active",onClick:()=>{hh()},disabled:Gn.length===0||!!be,"aria-pressed":!xs,type:"button",children:[be==="video"?r.jsx(Zn,{className:"spin",size:17}):xs?r.jsx(Hh,{size:17}):r.jsx(Wh,{size:17}),r.jsx("span",{children:xs?"Pause":"Resume"})]}),r.jsxs("button",{onClick:()=>{hl("restart")},disabled:!fe||!Rt||!!be||!Aa,type:"button",children:[be==="restart"?r.jsx(Zn,{className:"spin",size:17}):r.jsx(rp,{size:17}),r.jsx("span",{children:"Restart"})]})]})]}),Xe?r.jsx("section",{className:"control-focus",children:r.jsxs("div",{className:"control-wall",children:[fe&&r.jsxs("div",{className:"control-monitor-tabs","aria-label":`Select monitor for ${dn(fe)}`,children:[r.jsx("strong",{className:"control-computer-name",title:dn(fe),children:dn(fe)}),wy.map(l=>r.jsxs("button",{className:l.index===gl?"active":"",onClick:()=>hy(fe.deviceId,l.index),title:LP(l),type:"button",children:[r.jsx("span",{children:l.name||`Display ${l.index+1}`}),l.width>0&&l.height>0&&r.jsxs("small",{children:[l.width,"x",l.height]})]},l.index))]}),fe&&Zr&&r.jsxs("div",{className:"control-modifier-bar","aria-label":"Hold remote modifier keys",children:[A&&r.jsxs(r.Fragment,{children:[r.jsx("button",{className:`remote-keyboard-button ${R?"active":""}`,type:"button","aria-pressed":R,"aria-label":"Open remote keyboard",title:"Open the phone keyboard for the remote computer",onClick:()=>{const l=Y.current;l&&(l.focus({preventScroll:!0}),l.setSelectionRange(l.value.length,l.value.length))},children:r.jsx(gx,{size:15,"aria-hidden":"true"})}),r.jsx("textarea",{ref:Y,className:"remote-keyboard-input","aria-label":"Type on the remote computer",autoComplete:"off",autoCorrect:"off",autoCapitalize:"sentences",enterKeyHint:"enter",spellCheck:!1,rows:1,onFocus:()=>se(!0),onBlur:()=>{K.current=!1,se(!1)},onCompositionStart:()=>{K.current=!0},onCompositionEnd:l=>{K.current=!1;const f=l.currentTarget.value;l.currentTarget.value="",pe.current?.sendText(f)},onInput:l=>{if(K.current)return;const f=l.currentTarget.value;l.currentTarget.value="",pe.current?.sendText(f)},onKeyDown:l=>{l.nativeEvent.isComposing||!Rl(l.key)||(l.preventDefault(),l.stopPropagation(),ch(l.key,"keydown"))},onBeforeInput:l=>{const f=l.nativeEvent.inputType||"";Rl(f)&&(l.preventDefault(),l.stopPropagation(),ch(f,"beforeinput"))}})]}),YT.map(l=>{const f=l.code==="MetaLeft"&&is(fe.platform)?"Cmd":l.label,b=mt.includes(l.code);return r.jsx("button",{className:b?"active":"",type:"button","aria-pressed":b,title:`Hold ${f} on the remote computer`,onClick:()=>z.current?.(l.code),children:f},l.code)})]}),fe?r.jsx(ep,{device:fe,frame:Ne,selected:!1,controlEnabled:Tr&&_e&&Zr,showStatus:rn.showScreenStatus,showDeviceTitle:!1,monitorIndex:cr(fe,Ct[fe.deviceId]),monitorCount:as(fe),onSelect:()=>{},onFocusDevice:()=>Se(fe.deviceId),onOpenControl:()=>Fa(fe.deviceId),onCycleMonitor:l=>ld(fe.deviceId,l),onCanvasReady:ey,sendInput:Io,remoteModifierState:nd,presentationReady:Lu,remoteDiagnostics:qt?Lo.get(fe.deviceId):nn?Oi.get(fe.deviceId):void 0,diagnosticsMode:qt?"debug":"remote"},fe.deviceId):r.jsxs("div",{className:"control-empty",children:[r.jsx(pn,{size:30}),r.jsx("strong",{children:"No Client"}),r.jsx("span",{children:"Open a Client from the Wall."})]}),fe&&Vu&&r.jsxs("div",{className:"control-connection-overlay",role:"alert",children:[r.jsx(Zt,{size:22,"aria-hidden":"true"}),r.jsx("strong",{children:"Accessibility permission required"}),r.jsx("small",{children:"On the Mac, allow Accessibility for the terminal app that starts LiveDesk, then restart the Mac client."})]}),fe&&!Vu&&!Lu&&r.jsxs("div",{className:"control-connection-overlay",role:"status","aria-live":"polite",children:[ae!=="error"&&r.jsx("span",{className:"control-connection-spinner","aria-hidden":"true"}),r.jsx("strong",{children:ae==="error"?"Connection failed":"Connecting"}),r.jsx("small",{children:ae==="error"?"See the notification for details. Reopen Control to retry.":Ao||ve?"Control stream is recovering. See the notification for details.":Zu==="open"?"Preparing the first control frame":"Opening the Control stream"})]})]})}):Bt==="list"?r.jsxs("div",{className:"wall-device-list",role:"grid","aria-label":"Computer status list",children:[r.jsxs("div",{className:"wall-device-list-head",role:"row",children:[r.jsx("span",{role:"columnheader",children:"Computer"}),r.jsx("span",{role:"columnheader",children:"Status"}),r.jsx("span",{role:"columnheader",children:"CPU"}),r.jsx("span",{role:"columnheader",children:"GPU"}),r.jsx("span",{role:"columnheader",children:"RAM"}),r.jsx("span",{role:"columnheader",children:"VRAM"}),r.jsx("span",{role:"columnheader",children:"Network"}),r.jsx("span",{role:"columnheader",children:"HDD"}),r.jsx("span",{role:"columnheader",children:"Temp"})]}),Im.length>0?Im.map(({device:l,slotNumber:f})=>r.jsx(pI,{device:l,slotNumber:f,selected:Ma.has(l.deviceId),updateIndicator:gd(l.deviceId),remoteDiagnostics:qt?Lo.get(l.deviceId):nn?Oi.get(l.deviceId):void 0,diagnosticsMode:qt?"debug":"remote",onSelect:()=>cd(l.deviceId),onOpenControl:()=>Fa(l.deviceId)},l.deviceId)):r.jsxs("div",{className:"wall-device-list-empty",children:[r.jsx(pn,{size:24,"aria-hidden":"true"}),r.jsx("strong",{children:"No connected computers"})]})]}):St?r.jsx("div",{className:`screen-wall atlas-slot-wall size-${Bt}`,style:sa,onClick:l=>{l.currentTarget===l.target&&Do()},children:ka.map((l,f)=>l?r.jsx(ep,{device:l,frame:Ni.get(l.deviceId),selected:Ma.has(l.deviceId),controlEnabled:!1,showStatus:oo,monitorIndex:cr(l,Ct[l.deviceId]),monitorCount:as(l),onSelect:()=>cd(l.deviceId),onFocusDevice:()=>od(l.deviceId),onOpenControl:()=>Fa(l.deviceId),onCycleMonitor:b=>ld(l.deviceId,b),onCanvasReady:Bo({mode4Enabled:St,directMode4WallEnabled:Qr,isMac:is(l.platform)})==="direct"?Lm:ny,sendInput:Io,remoteModifierState:nd,updateIndicator:gd(l.deviceId),presentationReady:ot.autoStartLive&&gr.includes(l.deviceId)?Eu.has(l.deviceId):void 0,showPresentationSpinner:ot.autoStartLive&&gr.includes(l.deviceId),remoteDiagnostics:qt?Lo.get(l.deviceId):nn?Oi.get(l.deviceId):void 0,diagnosticsMode:qt?"debug":"remote"},l.deviceId):r.jsx(sb,{index:f},`slot-${f}`))}):r.jsx("div",{className:`screen-wall size-${Bt}`,style:sa,onClick:l=>{l.currentTarget===l.target&&Do()},children:ka.map((l,f)=>l?r.jsx(ep,{device:l,frame:Ni.get(l.deviceId),selected:Ma.has(l.deviceId),controlEnabled:Tr&&_e&&Zr&&fe?.deviceId===l.deviceId,showStatus:oo,monitorIndex:cr(l,Ct[l.deviceId]),monitorCount:as(l),onSelect:()=>cd(l.deviceId),onFocusDevice:()=>od(l.deviceId),onOpenControl:()=>Fa(l.deviceId),onCycleMonitor:b=>ld(l.deviceId,b),onCanvasReady:Lm,sendInput:Io,remoteModifierState:nd,updateIndicator:gd(l.deviceId),presentationReady:ot.autoStartLive&&gr.includes(l.deviceId)?Eu.has(l.deviceId):void 0,showPresentationSpinner:ot.autoStartLive&&gr.includes(l.deviceId),remoteDiagnostics:qt?Lo.get(l.deviceId):nn?Oi.get(l.deviceId):void 0,diagnosticsMode:qt?"debug":"remote"},l.deviceId):r.jsx(sb,{index:f},`slot-${f}`))}),r.jsx(fI,{visible:Jw&&!Xe})]}),!yo&&r.jsxs("aside",{className:`right-dock actions-mode ${Or?"collapsed":""}`,"aria-label":"LiveDesk tools",children:[r.jsx("button",{className:"dock-toggle",onClick:()=>ao(l=>!l),"aria-label":Or?"Show control panel":"Hide control panel",title:Or?"Show control panel":"Hide control panel",type:"button",children:Or?r.jsx(kb,{size:18}):r.jsx(Lp,{size:18})}),!Or&&r.jsxs(r.Fragment,{children:[r.jsxs("section",{className:"action-dock",children:[r.jsx("input",{ref:Sm,className:"hidden-file-input",type:"file",multiple:!0,onChange:l=>{l.currentTarget.files&&gh(l.currentTarget.files),l.currentTarget.value=""}}),r.jsxs("div",{className:"manual-action-bar",role:"toolbar","aria-label":"Manual Client controls",children:[r.jsx(Oa,{label:"Control",tooltip:fe?Vu?"Allow Accessibility for the terminal app that starts LiveDesk, then restart the Mac client.":Tr?Zr?"Keyboard and mouse control is ready":"Waiting for the current Control capture session":"Remote control is not available on this Client":"Select a Client to use Control",onClick:()=>{if(fe){if(Xe&&_e){$e(!1),we("Remote control paused. Screen viewing stays on.");return}Fa(fe.deviceId)}},disabled:!Tr||!!be,active:_e,pressed:Xe&&_e,children:r.jsx(Uo,{size:17})}),r.jsx(Oa,{label:"Audio",tooltip:fe?Rr?Ie?"Stop hearing this Client":"Hear this Client":"Audio is not available on this Client":"Select a Client to use Audio",onClick:()=>{mh()},disabled:!Ku||!!be,active:Ie,pressed:Ie,children:be==="audio"?r.jsx(Zn,{className:"spin",size:17}):r.jsx(yd,{size:17})}),r.jsx(Oa,{label:qc?"Retry pause":xs?"Pause video":"Resume video",tooltip:So.length===0?"Select one or more Clients to pause video":qc?"Retry every selected Client whose capture shutdown is unconfirmed":xs?`Pause video for ${Gn.length} selected Client${Gn.length===1?"":"s"}`:`Resume video for ${Gn.length} selected Client${Gn.length===1?"":"s"}`,onClick:()=>{hh()},disabled:Gn.length===0||!!be,active:!xs,pressed:!xs,children:be==="video"?r.jsx(Zn,{className:"spin",size:17}):!xs&&!qc?r.jsx(Wh,{size:17}):r.jsx(Hh,{size:17})}),r.jsx(Oa,{label:"Send files",tooltip:An.length===0&&!Xe?"Select one or more Clients to send files":fe?"Choose files and send them to the selected Client":"Select a Client to send files",onClick:()=>{we(`Choose files to send to ${Nh}.`),Sm.current?.click()},disabled:!!be||!Rt||(Xe?!fe:An.length===0),children:r.jsx(Xi,{size:17})}),r.jsx(Oa,{label:"Restart",tooltip:fe?Aa?"Restart Client":"Restart is not available on this Client":"Select a Client to restart",onClick:()=>{hl("restart")},disabled:!fe||!Rt||!!be||!Aa,children:be==="restart"?r.jsx(Zn,{className:"spin",size:17}):r.jsx(rp,{size:17})}),r.jsx(Oa,{label:"Sleep",tooltip:fe?Aa?"Put Client to sleep":"Sleep is not available on this Client":"Select a Client to put to sleep",onClick:()=>{hl("sleep")},disabled:!fe||!Rt||!!be||!Aa,children:be==="sleep"?r.jsx(Zn,{className:"spin",size:17}):r.jsx(bx,{size:17})}),r.jsx(Oa,{label:"Shut down",tooltip:fe?Aa?"Shut down Client":"Shut down is not available on this Client":"Select a Client to shut down",onClick:()=>{hl("shutdown")},disabled:!fe||!Rt||!!be||!Aa,danger:!0,children:be==="shutdown"?r.jsx(Zn,{className:"spin",size:17}):r.jsx(gb,{size:17})})]})]}),r.jsx(Cg,{hubUrl:G,devices:D,variant:"dock",selectedDeviceIds:My})]})]})]})})]}),A&&r.jsxs("nav",{className:"mobile-console-nav","aria-label":"Mobile Console pages",children:[r.jsxs("button",{className:pr?"active":"",onClick:()=>rr(l=>{const f=!l;return GP(f),f}),type:"button","aria-label":pr?"Hide computer stats":"Show computer stats","aria-pressed":pr,title:pr?"Hide CPU, GPU, RAM, and online status":"Show CPU, GPU, RAM, and online status",children:[r.jsx(vx,{size:19}),r.jsx("span",{children:"Stats"})]}),r.jsxs("button",{className:jt==="wall"?"active":"",onClick:()=>Da("wall"),type:"button",children:[r.jsx(Cb,{size:19}),r.jsx("span",{children:"Wall"})]}),r.jsxs("button",{className:Xe?"active":"",onClick:()=>fe&&void Fa(fe.deviceId),disabled:!fe||!Tr,type:"button",children:[r.jsx(Uo,{size:19}),r.jsx("span",{children:"Control"})]}),r.jsxs("button",{className:xa?"active":"",onClick:()=>Da("share-files"),type:"button",children:[r.jsx(Jo,{size:19}),r.jsx("span",{children:"Files"})]}),r.jsxs("button",{className:Oc?"active":"",onClick:()=>Da("agents"),type:"button",children:[r.jsx(Gl,{size:19}),r.jsx("span",{children:"Agents"})]}),r.jsxs("button",{className:yo?"active":"",onClick:()=>Da("settings"),type:"button",children:[r.jsx(nu,{size:19}),r.jsx("span",{children:"Settings"})]})]}),ya&&r.jsxs("aside",{className:`transfer-bar state-${ya.status}`,"aria-live":"polite",children:[r.jsx("span",{className:"transfer-bar-icon","aria-hidden":"true",children:ya.status==="queued"?r.jsx(En,{size:18}):ya.status==="failed"?r.jsx(xn,{size:18}):r.jsx(bb,{size:18})}),r.jsxs("div",{className:"transfer-bar-copy",children:[r.jsx("p",{children:ya.message}),r.jsx("div",{className:"transfer-bar-track",children:r.jsx("span",{style:{width:`${Math.max(0,Math.min(100,ya.progress))}%`}})})]}),r.jsxs("strong",{children:[Math.max(0,Math.min(100,ya.progress)),"%"]})]}),zt&&r.jsxs("aside",{className:`livedesk-toast tone-${zt.tone}`,role:zt.tone==="error"?"alert":"status","aria-live":zt.tone==="error"?"assertive":"polite","aria-busy":zt.tone==="progress",children:[zt.tone==="progress"&&r.jsx("span",{className:"livedesk-toast-spinner","aria-hidden":"true"}),r.jsx("span",{children:zt.message}),r.jsx("button",{className:"livedesk-toast-close",onClick:()=>we(""),type:"button","aria-label":"Dismiss notification",title:"Dismiss notification",children:r.jsx(xn,{size:15})})]})]})}const bI=1e3,vI=5e3;function wI(){return typeof window>"u"?!1:(!!window.navigator.standalone||window.matchMedia("(display-mode: standalone), (display-mode: fullscreen)").matches)&&window.matchMedia("(pointer: coarse)").matches}function yI(){return typeof window>"u"?[]:[...new Set([window.location.origin,an].filter(Boolean))]}function WI(){const t=eu(),n=wI(),s=t||n,a=t||typeof window>"u"?an:window.location.origin,i=s?{role:"hub",baseUrl:a}:null,[c,u]=o.useState(i),d=o.useRef(null);return o.useEffect(()=>{if(s){u(k=>k?.role==="hub"&&k.baseUrl===a?k:{role:"hub",baseUrl:a});return}let p=!1,h=!1,m=null;const g=new AbortController,w=async()=>{for(const k of yI()){if(g.signal.aborted)return;try{const C=(await Oe("/api/runtime/status",{signal:g.signal,timeoutMs:900},k)).role==="hub"?"hub":"client";h=!0,p||u(A=>A?.role===C&&A.baseUrl===k?A:{role:C,baseUrl:k});return}catch{if(g.signal.aborted)return}}},v=()=>{Qa(d,w).finally(()=>{!p&&!g.signal.aborted&&(m=window.setTimeout(v,h?vI:bI))}).catch(()=>{})};v();const y=window.setTimeout(()=>{!p&&!h&&u(k=>k?.role==="client"&&k.baseUrl===an?k:{role:"client",baseUrl:an})},2500);return()=>{p=!0,g.abort(new Error("LiveDesk runtime role probe stopped.")),m!==null&&window.clearTimeout(m),window.clearTimeout(y)}},[null,s,a]),c?c.role==="client"?r.jsx(fS,{runtimeBaseUrl:c.baseUrl}):r.jsx(gI,{runtimeBaseUrl:c.baseUrl}):r.jsxs("main",{className:"runtime-role-boot","aria-busy":"true","aria-label":"Starting LiveDesk",children:[r.jsx("span",{className:"runtime-role-boot-mark","aria-hidden":"true"}),r.jsx("strong",{children:"Starting LiveDesk"}),r.jsx("p",{children:"Loading this computer's assigned role..."})]})}export{WI as LiveDeskApp};
178
+ `){if(!q("Enter"))return!1;tt=!0;continue}for(const wt of U0(at)){const Et=l.snapshot();if(!x({type:"text",text:wt,repeat:!1,pressedCodes:Et.pressedCodes,shiftKey:Et.shiftKey,ctrlKey:Et.ctrlKey,altKey:Et.altKey,metaKey:Et.metaKey}))return!1;tt=!0}}return tt}};const W=()=>B("browser-window-blur"),ke=()=>B("browser-page-hidden"),Me=()=>{document.visibilityState==="hidden"&&B("browser-document-hidden")};return window.addEventListener("keydown",$,!0),window.addEventListener("keyup",L,!0),window.addEventListener("blur",W),window.addEventListener("pagehide",ke),document.addEventListener("visibilitychange",Me),()=>{window.removeEventListener("keydown",$,!0),window.removeEventListener("keyup",L,!0),window.removeEventListener("blur",W),window.removeEventListener("pagehide",ke),document.removeEventListener("visibilitychange",Me),z.current=null,pe.current=null,B("control-keyboard-owner-changed",!0)}},[Pr,ts,pl,ch,_e,eh,th,ih,Fo]);const lh=(l,f)=>{const b=Rl(l);if(!b)return!1;const x=performance.now(),S=ee.current;return S.key===b.key&&S.source!==f&&x-S.at<80?!0:(ee.current={key:b.key,source:f,at:x},pe.current?.sendKey(b.key)??!1)},uh=o.useCallback(l=>{_.current=l;const f=Be.current||fe?.deviceId||"";if(!Ie||!f)return;const b=Rn(rt.current,f);if(!l){const S=xe.current.get(f)||"";Ir(async()=>{await yr(f,S,"remote-audio-document-hidden")}).catch($=>{(Be.current||fe?.deviceId||"")===f&&(Rn(!1),xe.current.delete(f),He(!1),we($ instanceof Error?$.message:String($)))});return}const x=`audio-presentation-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;xe.current.set(f,x),Fa(async()=>{if(!jr(b,f,x)||!Rt||!Tr||(Be.current||fe?.deviceId||"")!==f)return;const S=await Oe(`/api/remote/devices/${encodeURIComponent(f)}/audio/start`,{method:"POST",body:JSON.stringify({streamId:x,mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},G);if(S?.ok===!1)throw new Error(S.error||"Remote audio presentation resume failed.");jr(b,f,x)||(await yr(f,x,"remote-audio-stale-presentation-compensation"),xe.current.get(f)===x&&xe.current.delete(f))}).catch(S=>{Mr.current&&b===Ge.current&&(Rn(!1),xe.current.delete(f),He(!1),we(S instanceof Error?S.message:String(S)))})},[Ie,Fa,Ir,Rn,Rt,G,jr,Tr,fe?.deviceId,we,yr]);o.useEffect(()=>{const l=S=>{const $=Mr.current;S!==$&&(Mr.current=S,Ur.current+=1,qu.current={active:S&&vi.current,epoch:Ur.current},S||(ll(),cl(Ur.current)),uh(S),_w(S),S&&!$&&($w(L=>L+1),Fc.current=performance.now()))},f=()=>{l(document.visibilityState==="visible")},b=()=>l(!1),x=()=>f();return document.addEventListener("visibilitychange",f),window.addEventListener("pagehide",b),window.addEventListener("pageshow",x),()=>{document.removeEventListener("visibilitychange",f),window.removeEventListener("pagehide",b),window.removeEventListener("pageshow",x)}},[ll,cl,uh]),o.useEffect(()=>{if(!te||ae!=="connecting"&&ae!=="active"&&ae!=="warm"||Zu!=="open")return;const l=te,f=Ut("control",l),b=window.setInterval(()=>{const x=performance.now();if(document.visibilityState!=="visible"||x-Fc.current<Kd)return;const S=Bs.current.get(f)||0,$=ga.current.get(f)||0,L=ui.current.get(f)||0,B=va.current.get(f)||x;va.current.has(f)||va.current.set(f,B);const q=S<=0,W=q?x-B>CP:x-S>Yg,ke=Df({lastReceivedAt:S,lastPaintedAt:$,now:x,staleAfterMs:Yg}),Me=Ff({paintStale:ke,lastRecoveryAt:wa.current.get(f)||0,now:x,recoveryCooldownMs:Jg,transportRecoveryAfterMs:Zg});if(!W&&Me==="reset-decoder"&&Ti(l,"control","decoder-paint-stale")||!W&&Me==="wait")return;if(!(W||Me==="recover-transport")){ke&&Ti(l,"control","decoder-paint-stale"),q&&x-B>SP&&!qr.current.has(f)&&Po([l],"control-frame-socket-recovery")&&qr.current.set(f,x);return}const tt=qr.current.get(f)||0;if(tt<=0){Po([l],"control-frame-socket-recovery")&&qr.current.set(f,x);return}if(x-tt<Xg)return;const yt=ba.current.get(f)||0;if(yt>0){if(x-yt<MP)return;ba.current.delete(f)}const at=ys.current.get(f)||0,wt=Ze.find(Hi=>Hi.deviceId===l)||vn,Et=ob(wt?.platform);if(!W&&Me==="recover-transport"&&Et==="mode1-jpeg"&&Io("mac-control-paint-timeout"))return;if(at>=AP){if(Io(q?"no first frame":"stale stream"))return;J(!1),$n(!1),hr.current=l,le("error");return}if(x-L<eb(kP,at))return;sl([l],q?"control-first-frame-timeout":Me==="recover-transport"?"control-paint-timeout":"control-receive-stale")&&(qr.current.delete(f),wa.current.delete(f),ui.current.set(f,x),ba.current.set(f,x),va.current.set(f,x),ys.current.set(f,at+1))},650);return()=>window.clearInterval(b)},[Ze,vn,Zu,te,ae,Io,Po,Ti,sl]),o.useEffect(()=>{!ve||te&&Ye.current[te]||fr!=="mode3-h264-hw"||Io(ve)||(J(!1),$n(!1),hr.current=it.current?.deviceId||"",le("error"))},[ve,te,fr,Io]),o.useEffect(()=>{!Xe||!te||Ye.current[te]||!To||(hr.current=te,le(l=>l==="error"?l:"error"))},[To,te,Xe]),o.useEffect(()=>{if(ae!=="error")return;const l=it.current;if(!l)return;hr.current=l.deviceId,Dt(fa.current,l)||(fa.current=l,li.current=0);const f=li.current,b=f===0?0:Math.min(5e3,500*2**Math.min(f-1,4)),x=window.setTimeout(()=>{Dt(it.current,l)&&(++Kt.current,Mn.current="",le("stopping"),br(async()=>{if(Dt(it.current,l))try{if(!await wr(l,"control-session-terminal-error"))return;fa.current=null,li.current=0,vo.current===l.deviceId?(vo.current="",hr.current="",le("idle")):le("error")}catch(S){if(!Dt(it.current,l))return;li.current+=1,we(S instanceof Error?S.message:String(S)),le("error"),mo($=>$+1)}}))},b);return()=>window.clearTimeout(x)},[ae,Cc,br,we,wr]);const Lo=o.useCallback(l=>{if(!l||hr.current!==l)return!1;const f=it.current;return++Kt.current,Mn.current="",li.current=0,f&&f.deviceId===l?(vo.current=l,fa.current=null,le("error"),mo(b=>b+1),!0):(vo.current="",hr.current="",fa.current=null,le("idle"),!0)},[]);o.useEffect(()=>{if(No!=="open"||!ot.autoStartLive||or.length===0)return;const l=window.setInterval(()=>{const f=performance.now();if(document.visibilityState!=="visible"||f-Fc.current<Kd)return;const b=1e3/Math.max(1,Qc||Dn||1),x=Math.max(TP,Math.ceil(b*4)),S=[],$=[];for(const L of or){if($.length+S.length>=jP)break;const B=Ut("wall",L),q=Bs.current.get(B)||0,W=q<=0,ke=di.current.get(B)||f;di.current.has(B)||di.current.set(B,ke);const Me=ui.current.get(B)||0,he=ga.current.get(B)||0,tt=W||f-q>x,yt=Df({lastReceivedAt:q,lastPaintedAt:he,now:f,staleAfterMs:x}),at=Ff({paintStale:yt,lastRecoveryAt:wa.current.get(B)||0,now:f,recoveryCooldownMs:Jg,transportRecoveryAfterMs:Zg});if(!tt&&at==="reset-decoder"&&Ti(L,"wall","decoder-paint-stale")||!tt&&at==="wait")continue;if(!(tt||at==="recover-transport")){yt&&Ti(L,"wall","decoder-paint-stale");continue}const Et=qr.current.get(B)||0;if(Et<=0&&(!W||f-ke>NP)){S.push(L);continue}if(W&&f-ke<=RP||Et>0&&f-Et<Xg)continue;const Xn=ys.current.get(B)||0;f-Me>=eb(PP,Xn)&&$.push(L)}if(S.length>0&&Vm(S,"wall-frame-socket-recovery"))for(const L of S)qr.current.set(Ut("wall",L),f);if($.length>0&&rl($,$.some(L=>(Bs.current.get(Ut("wall",L))||0)<=0)?"wall-first-frame-timeout":"wall-frame-stale"))for(const L of $){const B=Ut("wall",L);qr.current.delete(B),wa.current.delete(B),ui.current.set(B,f),di.current.set(B,f),Bs.current.delete(B),ga.current.delete(B),ys.current.set(B,(ys.current.get(B)||0)+1)}},IP);return()=>window.clearInterval(l)},[Qc,or,Vm,Ti,rl,ot.autoStartLive,Dn,No]),o.useEffect(()=>{Fs(Dn),xo.current=Date.now(),Vr.current=0,Gr.current=0,Ar.current=0,So.current=0,Co.current=""},[Dn,ot.frameMode,ot.adaptiveLoadShedding]),o.useEffect(()=>{QS({h264DecodeAcceleration:ot.h264DecodeAcceleration})},[ot.h264DecodeAcceleration]),o.useEffect(()=>{if(!Rt||Xe||Bt==="list"||!ot.visibleOnlyLive){si([]);return}const l=Sm.current;if(!l||typeof IntersectionObserver>"u"){si(Uc);return}const f=Array.from(l.querySelectorAll("[data-live-device-id]"));if(f.length===0){si([]);return}const b=new Map,x=ok(l,A),S=()=>{const L=Xd(f.map(B=>String(B.dataset.liveDeviceId||"")).filter(B=>(b.get(B)||0)>0));si(B=>Yd(B,L)?B:L)},$=new IntersectionObserver(L=>{for(const B of L){const q=String(B.target.dataset.liveDeviceId||"");q&&b.set(q,B.isIntersecting?B.intersectionRatio||.01:0)}S()},{root:x,rootMargin:A?ek:Fr.visibleRootMargin,threshold:[0,.01,.2,.6,1]});return f.forEach(L=>$.observe(L)),S(),()=>$.disconnect()},[Uc,Rt,A,Xe,Ma,ot.visibleOnlyLive,Bt]),o.useEffect(()=>{if(!ot.adaptiveLoadShedding||!ot.autoStartLive||or.length===0){Gr.current=0,Ar.current=0,So.current=0,Co.current="";return}const l=Dn;if(No!=="open"||Pa.sampleMs<500||Pa.lastUpdatedAt<=0||So.current===Pa.lastUpdatedAt)return;So.current=Pa.lastUpdatedAt;const f=Date.now(),b=or.map(Me=>({deviceId:Me,receive:Pc[Ut("wall",Me)],paint:Tc[Ut("wall",Me)]}));if(!b.every(({receive:Me,paint:he})=>{const tt=Me?.lastFrame,yt=Math.max(0,Number(tt?.requestedFps||0)),at=tt?as(tt):"";return Sk({receiveSampleMs:Number(Me?.sampleMs||0),paintSampleMs:Number(he?.sampleMs||0),currentGenerationVerified:tt?.currentGenerationVerified===!0,frameRequestedFps:yt,adaptiveFps:Ln})&&he?.bindingKey===at})){Gr.current=0,Ar.current=0,Vr.current=0;return}const S=[Ln,...b.map(({deviceId:Me,receive:he})=>`${Me}:${as(he.lastFrame)}`).sort()].join("|");if(Co.current!==S){Co.current=S,Gr.current=f,Ar.current=0,Vr.current=0;return}if(!Gr.current){Gr.current=f,Ar.current=0;return}if(f-Gr.current<Fr.downshiftStableSampleMs)return;const $=b.reduce((Me,{receive:he})=>Me+Math.max(0,Number(he?.framesPerSecond||0)),0),L=b.reduce((Me,{receive:he})=>Me+Math.max(0,Number(he?.framesPerSecond||0))*Math.max(0,Number(he?.averageFrameBytes||0)),0),B=b.reduce((Me,{paint:he})=>Me+Math.max(0,Number(he?.framesPerSecond||0)),0),q=Math.max(0,...b.map(({receive:Me})=>Number(Me?.maxIntervalMs||0))),W=Math.max(0,...b.map(({paint:Me})=>Number(Me?.p95IntervalMs||0))),ke=xk({directDeviceCount:or.length,requestedFps:Ln,measuredFramesPerSecond:$,measuredPaintFramesPerSecond:B,measuredBytesPerSecond:L,maxBytesPerSecond:Fr.maxWallBytesPerSecond,worstReceiveGapMs:q,worstPaintP95Ms:W,maxFrameGapMs:Fr.maxFrameGapMs});if(ke.overloaded){if(Vr.current=0,Ar.current+=1,Ar.current<Fr.downshiftConsecutiveSamples)return;const Me=Fr.minFps;if(f-xo.current>=Fr.downshiftCooldownMs&&Ln>Me){const he=Math.max(Me,eI(Ln,Me));he<Ln&&(Fs(he),xo.current=f,Gr.current=0,Ar.current=0)}return}if(Ar.current=0,!ke.healthyForRecovery||Ln>=l){ke.healthyForRecovery||(Vr.current=0);return}if(!Vr.current){Vr.current=f;return}if(f-Vr.current>=Fr.recoveryCooldownMs){const Me=Math.min(l,tI(Ln,l));Me>Ln&&(Fs(Me),xo.current=f,Vr.current=0,Gr.current=0,Ar.current=0)}},[Ln,or.length,or,Tc,Pc,No,Pa.lastUpdatedAt,Pa.sampleMs,ot.adaptiveLoadShedding,ot.autoStartLive,ot.frameMode,Dn]),o.useEffect(()=>{const l=new URLSearchParams(window.location.search).get("checkout");if(l==="success"){we("Checkout returned. Waiting for Dodo confirmation."),ge();const f=window.setInterval(()=>{ge()},4e3),b=window.setTimeout(()=>{window.clearInterval(f)},45e3);return()=>{window.clearInterval(f),window.clearTimeout(b)}}l==="cancelled"&&we("Checkout cancelled.")},[ge]),o.useEffect(()=>{!Rt&&_e&&$e(!1),!Rt&&Ie&&(Rn(!1),He(!1))},[Ie,_e,Rn,Rt]),o.useEffect(()=>{Ie&&(!fe||!Tr)&&(Rn(!1),He(!1))},[Ie,Rn,Tr,fe]),o.useEffect(()=>{const l=fe?.deviceId||"",f=Be.current;if(Be.current=l,!f||f===l)return;const b=Rn(Ie,l),x=l?`audio-${Date.now()}-${Math.random().toString(36).slice(2,8)}`:"";l&&Ie&&xe.current.set(l,x);let S=!0;const $=xe.current.get(f)||"";return(async()=>{try{await Ir(async()=>{await yr(f,$,"remote-audio-device-switch"),xe.current.delete(f)}),await Fa(async()=>{if(!S||!jr(b,l,x)||!l||!Rt||!Tr)return;const L=await Oe(`/api/remote/devices/${encodeURIComponent(l)}/audio/start`,{method:"POST",body:JSON.stringify({streamId:x,mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},G);if(L.ok===!1)throw new Error(L.error||"Remote audio start failed.");jr(b,l,x)||(await yr(l,x,"remote-audio-stale-device-switch-compensation"),xe.current.get(l)===x&&xe.current.delete(l))})}catch(L){S&&(Rn(!1),xe.current.delete(l),He(!1),we(L instanceof Error?L.message:String(L)))}})(),()=>{S=!1}},[Ie,Fa,Ir,Rn,Rt,G,jr,Tr,fe?.deviceId,yr]),o.useEffect(()=>{const l=Ze.map(S=>S.deviceId),f=new Set(l),b=new Map(Ze.map(S=>[S.deviceId,S])),x=new Map;for(const S of Ze){const $=$P(S);if(!$)continue;const L=Lr(S.status),B=[S.lastStatusAt,L.capturedAt,L.collectedAt,L.timestamp,L.updatedAt].find(W=>typeof W=="string"&&W.trim()),q=Q0(Es.current[S.deviceId],$,B);q&&(Es.current[S.deviceId]=q,x.set(S.deviceId,q),xv({platform:S.platform,topologyFingerprint:$,consecutiveTopologySamples:q.consecutiveSamples})&&(lo.current[S.deviceId]=$))}for(const S of Object.keys(Es.current))f.has(S)||delete Es.current[S];me(S=>{const $=S.filter(L=>f.has(L));return Yd(S,$)?S:$}),Te(S=>S&&f.has(S)?S:""),Se(S=>S&&f.has(S)?S:""),ni(S=>{let $=!1;const L={};for(const[B,q]of Object.entries(S)){const W=b.get(B);if(!W){L[B]=q;continue}const ke=x.get(B)||Es.current[B],Me=Y0({requestedIndex:q,monitorCount:os(W),platform:W.platform,topologyFingerprint:ke?.fingerprint||"",consecutiveTopologySamples:ke?.consecutiveSamples||0});L[B]=Me,Me!==q&&($=!0)}return $?L:S}),Hu(S=>{const $=S.filter(L=>f.has(L));return Yd(S,$)?S:$})},[Ze,Vu]),o.useEffect(()=>{Bw([]),Ww(!1)},[ks]),o.useEffect(()=>{!Sa||gi!=="selected"||bi.length>0||An.length===0||Hu(An.map(l=>l.deviceId))},[An,bi.length,gi,Sa]),o.useEffect(()=>{try{localStorage.setItem(yw,fs)}catch{}},[fs]),o.useEffect(()=>{qP(ot)},[ot]),o.useEffect(()=>{VP(rn)},[rn]),o.useEffect(()=>{WP(Ct,lo.current)},[Ze,Ct]);const ml=o.useCallback(async()=>{const l=new Set(m);l.add(an);try{const $=await Oe("/api/remote/status",void 0,an);Fh({endpoint:$.agentEndpoint,endpoint_candidates:[...$.agentEndpointCandidates||[],...$.hostTargetEndpointCandidates||[]]}).forEach(L=>l.add(L))}catch{}const f=[...l].sort(($,L)=>{const B=q=>{const W=Ul(q);return W==="local"?0:W==="loopback"?1:2};return B($)-B(L)||$.localeCompare(L)});let b=!1,x="",S=!1;try{for(const $ of f){const L=Ul($);try{if(await Oe("/api/health",void 0,$),L==="local")return M(!0),Ki(!0),$;L==="loopback"&&(b=!0,x=$)}catch{L==="local"&&(S=!0)}}return b?(S&&we("LiveDesk Hub is reachable on this PC, but not through the LAN address yet. Restart LiveDesk Hub to bind 5179 on the network."),M(!0),Ki(!0),x||an):(M(!1),Ki(!1),"")}catch{return M(!1),Ki(!1),""}},[m]),_i=async()=>{if(Z("auth"),Hr(!1),window.liveDesk?.auth?.signInWithGoogle){const x=window.liveDesk.auth.signInWithGoogle();ml();const S=await x;S?.ok===!1&&(we(S.error||"LiveDesk could not open the system browser for Google sign-in."),Z(""));return}const l=pt.auth.signInWithOAuth({provider:"google",options:{redirectTo:`${window.location.origin}/callback`}});ml();const{data:f,error:b}=await l;b&&(we(b.message),Z(""))},my=async()=>{Z("auth"),Hr(!1),window.liveDesk?.auth?.signOut||await Oe("/api/auth/session",{method:"DELETE"},G||an).catch(()=>{}),await pt.auth.signOut(),(await window.liveDesk?.auth?.signOut?.())?.runtimeCleared===!1&&we("Signed out locally. The LiveDesk runtime could not be reached to clear its session."),Z("")};o.useEffect(()=>{if(!ua)return;const l=b=>{b.target instanceof Element&&(b.target.closest(".account-popover, .rail-account")||Hr(!1))},f=b=>{b.key==="Escape"&&Hr(!1)};return window.addEventListener("pointerdown",l),window.addEventListener("keydown",f),()=>{window.removeEventListener("pointerdown",l),window.removeEventListener("keydown",f)}},[ua]);const dh=o.useCallback(async(l={})=>{const f=l.silent===!0,b=l.takeover===!0,x=l.requestLocalAccess===!0;if(!n?.user){f||we("Sign in before publishing this host.","error");return}if(!Wu.current){Wu.current=!0,f||(Z("host"),Ot("Hub · 1/4 · Checking the local runtime…"));try{const $=(x?await ml():"")||G||an;if(!(P||await Oe("/api/remote/status",void 0,$)).started)throw new Error("Start LiveDesk on this computer before syncing the server.");f||Ot("Hub · 2/4 · Sending the signed-in session to the Hub…");const B=await Oe("/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}})},$);if(!B.ok||!B.authenticated)throw new Error(B.error||"hub-session-sync-failed");f||Ot("Hub · 3/4 · Claiming the Hub role and publishing its endpoint…");const q=await Oe("/api/hub/sync",{method:"POST",body:JSON.stringify({takeover:b})},$);if(!q.ok)throw new Error(q.error||"host-target-failed");if(!f){Ot("Hub · 4/4 · Verifying the endpoint and lease renewal…");const W=await Oe("/api/hub/status",void 0,$);if(!W.hostTargetActive)throw new Error(W.hostTargetLease?.lastError||"host-target-not-active-after-sync");const ke=W.hostTargetEndpoint||W.agentEndpoint||"endpoint ready",Me=Number(W.connectedDeviceCount||0),he=Me>0?`${Me} client${Me===1?"":"s"} connected.`:"No clients connected yet; reconnect the laptop Client.";we(`Hub ready · ${ke} · lease auto-renewal active. ${he}`,"success"),(x||H)&&(M(!0),Ki(!0)),X()}c()}catch(S){if(!f){const $=S instanceof Error?S.message:String(S);$.includes("local network access")&&(M(!1),Ki(!1)),we(`Hub setup failed · ${$}`,"error")}}finally{Wu.current=!1,f||Z("")}}},[G,H,X,c,ml,n,we,Ot,P]),_o=o.useCallback((l=!0)=>{bt!=="host"&&(It(!1),l&&window.requestAnimationFrame(()=>et.current?.focus()))},[bt]),hy=o.useCallback(()=>{bt!=="host"&&(et.current=document.activeElement instanceof HTMLElement?document.activeElement:null,Hr(!1),It(!0))},[bt]),fy=o.useCallback(()=>{It(!1),dh({takeover:!0,requestLocalAccess:!0})},[dh]);o.useEffect(()=>{if(!lt)return;const l=window.requestAnimationFrame(()=>At.current?.focus()),f=x=>{x.target instanceof Element&&x.target.closest(".client-hub-switch-popover, .hub-sync-trigger")||_o(!1)},b=x=>{x.key==="Escape"&&_o()};return window.addEventListener("pointerdown",f),window.addEventListener("keydown",b),()=>{window.cancelAnimationFrame(l),window.removeEventListener("pointerdown",f),window.removeEventListener("keydown",b)}},[_o,lt]);const ph=o.useCallback(async()=>{if(!(!P?.update?.canApply||bt==="update")){Z("update");try{const l=await Oe("/api/update/apply",{method:"POST",body:JSON.stringify({})},G||an);if(!l.ok)throw new Error(l.error||"LiveDesk update could not be started.");const f=[...new Set((l.targets||[]).map(S=>String(S.deviceId||"").trim()).filter(Boolean))],b=!!(l.managerUpdateAvailable||l.clientPackageUpdateAvailable),x=l.state==="hub-restart-requested"?Date.now():void 0;(f.length>0||b)&&ln({operationId:String(l.operationId||`wall-update-${Date.now()}`),targetIds:f,stage:l.state==="clients-updated"?"updated":"updating",requiresHubRestart:b,initialHostInstanceId:String(P.hostInstanceId||""),targetManagerVersion:String(l.latestVersion||P.update?.latestVersion||""),targetClientVersion:String(l.latestClientVersion||P.update?.latestClientVersion||""),restartRequestedAt:x,restartDeadlineAt:x?x+Wl:void 0}),Ot(l.state==="hub-restart-requested"?Hl:Hg),X()}catch(l){we(l instanceof Error?l.message:String(l),"error")}finally{Z("")}}},[bt,G,X,we,Ot,P]);o.useEffect(()=>{const l=vt,f=P?.update;if(!l||l.stage!=="updating"||!f)return;const b=f.restartResult?.operationId===l.operationId?f.restartResult:null;if(b?.outcome==="restored"){const q=b.error||`The requested Hub ${b.targetVersion||l.targetManagerVersion||"version"} failed verification.`;ln(W=>W?.operationId===l.operationId?{...W,stage:"restored",error:q}:W),we(`LiveDesk update did not complete. Hub ${b.fallbackVersion||b.appVersion||"the previous version"} was restored. ${q}`,"error");return}if(b?.outcome==="failed"){const q=b.error||"No verified LiveDesk Hub replacement could be started.";ln(W=>W?.operationId===l.operationId?{...W,stage:"failed",error:q}:W),we(`LiveDesk Hub update failed. ${q}`,"error");return}if(f.operationId===l.operationId&&f.state==="failed"){const q=f.error||"LiveDesk update failed before the Hub replacement completed.";ln(W=>W?.operationId===l.operationId?{...W,stage:"failed",error:q}:W),we(q,"error");return}if(f.operationId===l.operationId){if(f.state==="hub-restart-requested"&&!l.restartDeadlineAt){const q=Date.now();ln(W=>W?.operationId===l.operationId?{...W,restartRequestedAt:q,restartDeadlineAt:q+Wl}:W),Ot(Hl)}!l.requiresHubRestart&&f.state==="clients-updated"&&(ln(q=>q?.operationId===l.operationId?{...q,stage:"updated"}:q),we("LiveDesk clients updated and reconnected successfully.","success"));return}if(!l.requiresHubRestart)return;const x=P.started===!0&&(!l.initialHostInstanceId||P.hostInstanceId&&P.hostInstanceId!==l.initialHostInstanceId),S=!!f.checkedAt,$=qg(f.currentVersion,l.targetManagerVersion),L=!l.targetClientVersion||qg(f.currentClientVersion,l.targetClientVersion),B=S&&f.state==="idle"&&f.updateAvailable===!1&&$&&L;x&&B&&(ln(q=>q?.operationId===l.operationId?{...q,stage:"updated"}:q),we(`LiveDesk Hub ${f.currentVersion||b?.appVersion||l.targetManagerVersion} restarted and passed version verification.`,"success"))},[we,Ot,P,vt]),o.useEffect(()=>{const l=vt;if(!l||l.stage!=="updating"||!l.requiresHubRestart||l.restartDeadlineAt)return;const f=()=>{const x=Date.now();ln(S=>S?.operationId===l.operationId&&S.stage==="updating"&&!S.restartDeadlineAt?{...S,restartRequestedAt:x,restartDeadlineAt:x+Wl}:S),Ot(Hl)};if(P?.update?.state==="hub-restart-requested"){f();return}if(!O)return;const b=window.setTimeout(f,hP);return()=>window.clearTimeout(b)},[O,Ot,P?.update?.state,vt]),o.useEffect(()=>{const l=vt;if(!l||l.stage!=="updating"||!l.requiresHubRestart||!l.restartDeadlineAt)return;const f=Math.max(0,l.restartDeadlineAt-Date.now()),b=l.operationId,x=window.setTimeout(()=>{const S=`LiveDesk Hub did not return and verify ${l.targetManagerVersion||"the requested version"} within ${Math.round(Wl/6e4)} minutes. Check the Hub terminal or restart log, then run livedesk@latest manually if the Hub is still offline.`;ln($=>$?.operationId===b&&$.stage==="updating"?{...$,stage:"failed",error:S}:$),we(S,"error")},f);return()=>window.clearTimeout(x)},[we,vt]),o.useEffect(()=>{if(!vt||vt.stage!=="updated")return;const l=vt.operationId,f=window.setTimeout(()=>{ln(b=>b?.operationId===l?null:b)},Wg);return()=>window.clearTimeout(f)},[vt]),o.useEffect(()=>{po.current.clear(),uo({})},[vt?.operationId]),o.useEffect(()=>{if(!vt||P?.update?.operationId!==vt.operationId)return;const l=(P.update.targets||[]).filter(b=>b.state==="completed").map(b=>zg(vt.operationId,b)).filter(b=>!po.current.has(b));if(l.length===0)return;const f=Date.now()+Wg;for(const b of l)po.current.add(b);uo(b=>({...b,...Object.fromEntries(l.map(x=>[x,f]))}))},[P?.update,vt]),o.useEffect(()=>{const l=Math.min(...Object.values(ri));if(!Number.isFinite(l))return;const f=window.setTimeout(()=>{const b=Date.now();uo(x=>Object.fromEntries(Object.entries(x).filter(([,S])=>S>b)))},Math.max(0,l-Date.now()));return()=>window.clearTimeout(f)},[ri]),o.useEffect(()=>{if(Mt!==Hg&&Mt!==Hl)return;const l=P?.update;if(String(l?.state||"")==="failed"){we(l?.error||"LiveDesk update failed.","error");return}vt?.stage==="updated"&&we("")},[Mt,we,P?.update?.error,P?.update?.state,vt?.stage]);const gy=o.useCallback(async()=>{if(!bt){Z("pin");try{const f=await Oe("/api/remote/pairing-pin",{method:"POST"},G||an);if(!f.ok)throw new Error(f.error||"pin-rotation-failed");await X(),we("New PIN published.")}catch(l){we(l instanceof Error?l.message:String(l))}finally{Z("")}}},[bt,G,X]),cd=o.useCallback(l=>{l&&(Te(l),me(f=>f.includes(l)?f:[...f,l]))},[]),ld=o.useCallback(l=>{if(!l)return;const f=Aa.has(l);Te(b=>f?b===l?"":b:l),me(b=>f?b.filter(x=>x!==l):b.includes(l)?b:[...b,l])},[Aa]),$o=o.useCallback(()=>{me([]),Te("")},[Cs]),mh=o.useCallback(()=>{me(Ze.map(l=>l.deviceId)),Te("")},[Ze]),ud=o.useCallback((l,f)=>{const b=Ze.find(S=>S.deviceId===l);if(!b)return;const x=os(b);if(!(x<=1)&&(ni(S=>{const $=Xo(S[l],x),L=($+f+x)%x;return L===$?S:{...S,[l]:L}}),bn("wall",l),bn("control",l),ho(S=>{if(!S.has(l))return S;const $=new Set(S);return $.delete(l),$}),ma.current.delete(l),bs.current.delete(l),Xe)){const S=Lo(l);J(!1),S||le("connecting"),$n(!1),Se(l)}},[Ze,bn,Lo,Xe]);o.useEffect(()=>{const l=f=>{if(_e&&Pr&&ts)return;const b=f.target,x=b?.tagName?.toLowerCase();b?.isContentEditable||x==="input"||x==="textarea"||x==="select"||((f.ctrlKey||f.metaKey)&&f.key.toLowerCase()==="a"&&(f.preventDefault(),mh()),f.key==="Escape"&&$o())};return window.addEventListener("keydown",l),()=>window.removeEventListener("keydown",l)},[Pr,$o,ts,_e,mh]);const by=(l,f)=>{const b=Ze.find(L=>L.deviceId===l),x=b?os(b):1,S=Xo(Ct[l],x),$=Xo(f,x);if(S!==$&&(ni(L=>({...L,[l]:$})),ho(L=>{if(!L.has(l))return L;const B=new Set(L);return B.delete(l),B}),ma.current.delete(l),bs.current.delete(l),_s.current.delete(l),ai.current.delete(l),ha.current.delete(l),bn("wall",l),bn("control",l)),Xe){const L=Lo(l);S!==$&&(J(!1),L||le("connecting")),$n(!1),Se(l)}else cd(l)},vy=l=>{const f=Be.current||fe?.deviceId||"",b=[...new Set([f,l].filter(Boolean))],x=Ie||b.some(S=>xe.current.has(S));Rn(!1),He(!1);for(const S of b)xe.current.delete(S);b.length!==0&&(async()=>{for(const S of b)await Ir(()=>sd(S,"remote-audio-control-entry"))})().catch(S=>{x&&we("Remote audio was muted locally, but Client capture stop was not confirmed: "+(S instanceof Error?S.message:String(S)),"error")})},Da=async l=>{const f={requestId:++Lw.current,deviceId:l,startedAt:performance.now(),startedAtEpochMs:Date.now()};if(ws.current=f,!Qr.has(l)){ws.current?.requestId===f.requestId&&(ws.current=null),$e(!1),we(Si);return}const b=Ze.find(S=>S.deviceId===l);if(cs(b?.platform)&&(b?.capabilities?.controlPermission===!1||b?.capabilities?.accessibilityPermission===!1)){ws.current?.requestId===f.requestId&&(ws.current=null),$e(!1),we("Mac remote control needs Accessibility permission. Allow it for the terminal app that starts LiveDesk, then restart the Mac client.","error");return}vy(l),Lo(l),$n(!1),Se(l),tn("control"),$e(!0),we(`Opening remote control${b?` for ${dn(b)}`:""}.`,"success")},hh=async()=>{if(!fe){we("Select a Client before playing audio.");return}if(!Rt){we(Si);return}if(!Tr){we("Selected Client does not report remote audio support yet.");return}if(be)return;const l=!Ie,f=l?`audio-${Date.now()}-${Math.random().toString(36).slice(2,8)}`:xe.current.get(fe.deviceId),b=Rn(l,fe.deviceId);l&&f?xe.current.set(fe.deviceId,f):l||xe.current.delete(fe.deviceId),We("audio"),He(l);try{l?(await Ir(()=>sd(fe.deviceId,"remote-audio-user-enable-reconcile")),await Fa(async()=>{if(!f||!jr(b,fe.deviceId,f))return;const x=await Oe(`/api/remote/devices/${encodeURIComponent(fe.deviceId)}/audio/start`,{method:"POST",body:JSON.stringify({streamId:f,mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},G);if(x?.ok===!1)throw new Error(x.error||"Remote audio start failed.");jr(b,fe.deviceId,f)||await yr(fe.deviceId,f,"remote-audio-stale-user-start-compensation")})):await Ir(()=>sd(fe.deviceId,"remote-audio-user-disabled")),we(`${l?"Audio started":"Audio stopped"} for ${dn(fe)}.`,"success")}catch(x){Rn(!1),l&&xe.current.delete(fe.deviceId),He(!1),we(x instanceof Error?x.message:String(x),"error")}finally{We("")}},wy=async(l,f)=>{const b=l.deviceId,x=dn(l),S=String(Ye.current[b]||""),$=!!S&&on[b]===!0;if(f&&S&&!$)return{ok:!0,skipped:!0,action:"pause",deviceId:b,title:x};if(!f&&!S)return{ok:!0,skipped:!0,action:"resume",deviceId:b,title:x};if(!f&&S.startsWith("pending:"))return{ok:!1,action:"resume",deviceId:b,title:x,error:"Pause is still pending confirmation."};if(f){const ke=S||`pending:${Date.now()}:${b}`,Me=it.current?.deviceId===b?it.current:null,he=!!Me||te===b,tt=he?++Kt.current:0,yt=()=>Rf({deviceId:b,requestTransitionGeneration:tt,currentTransitionGeneration:Kt.current,actualControlOwner:it.current}),at=en.current.get(b);en.current.set(b,{deviceId:b,monitorIndex:lr(l,Ct[b]??at?.monitorIndex),previousControlOwner:Me||at?.previousControlOwner||null}),rr(b,!0),Sn(b,!1),Fn(b,ke),td(b),he&&(Mn.current="",le("paused"));try{const wt=await Oe(`/api/remote/devices/${encodeURIComponent(b)}/live/pause`,{method:"POST",body:JSON.stringify({reason:"user-video-pause"})},G);if(!wt?.pauseToken)return qn.current.delete(b),Fn(b,""),Sn(b,!1),en.current.delete(b),yt()&&(T.current=null,nt(null),J(!1),Le(`control-pause-rollback-${Date.now()}-${b}`),le("connecting")),{ok:!1,action:"pause",deviceId:b,title:x,error:wt?.error||"video-capture-pause-failed"};const Et=String(Ye.current[b]||"");if(Et!==ke&&Et!==wt.pauseToken)return{ok:!1,action:"pause",deviceId:b,title:x,error:"Pause ownership changed before confirmation."};const Xn=yt(),Hi=Xn&&it.current?.deviceId===b?it.current:Me,zs=en.current.get(b);return zs&&(zs.previousControlOwner=Hi),Xn&&it.current?.deviceId===b&&(it.current=null),Xn&&(T.current=null,nt(null)),Fn(b,wt.pauseToken),Xn&&le("paused"),wt.ok===!1||wt.captureStopConfirmed!==!0?(Sn(b,!0),{ok:!1,unconfirmed:!0,action:"pause",deviceId:b,title:x,error:wt.stopError||wt.error||"Client capture shutdown was not confirmed."}):(Sn(b,!1),{ok:!0,action:"pause",deviceId:b,title:x})}catch(wt){return Sn(b,!0),{ok:!1,unconfirmed:!0,action:"pause",deviceId:b,title:x,error:wt instanceof Error?wt.message:String(wt)}}}const L=en.current.get(b),B=L?.previousControlOwner||null,q=te===b&&(B!==null||Gn.current?.deviceId===b||ae==="paused"),W=q?Kt.current:0;try{rr(b,!1);const ke=await Oe(`/api/remote/devices/${encodeURIComponent(b)}/live/resume`,{method:"POST",body:JSON.stringify({pauseToken:S})},G);if(ke?.ok===!1)throw new Error(ke.error||"video-capture-resume-failed");if(String(Ye.current[b]||"")!==S)return{ok:!1,action:"resume",deviceId:b,title:x,error:"Resume ownership changed before confirmation."};const Me=en.current.get(b)||L,he=Me?.previousControlOwner||B,tt=q&&Rf({deviceId:b,requestTransitionGeneration:W,currentTransitionGeneration:Kt.current,actualControlOwner:it.current});if(Fn(b,""),Sn(b,!1),en.current.delete(b),tt){const yt=++Kt.current;Mn.current="";const at=Ed(b,yt,{sessionId:l.sessionId||he?.sessionId,monitorIndex:lr(l,Ct[b]??Me?.monitorIndex)});it.current=at,vr(at),hr.current="",fa.current=null,T.current=null,nt(null),ne(""),De(""),J(!1),bn("control",b);const wt=`control-video-resume-${yt}-${b}`;Le(wt),Ce(b),le("connecting")}else bn("wall",b);return{ok:!0,action:"resume",deviceId:b,title:x}}catch(ke){return qn.current.delete(b),{ok:!1,action:"resume",deviceId:b,title:x,error:ke instanceof Error?ke.message:String(ke)}}},fh=async()=>{if(Ao.length===0){we("Select one or more Clients before pausing video.");return}if(Kn.length===0){we(Si);return}if(be)return;const l=Kn.some(b=>{const x=String(Ye.current[b.deviceId]||"");return!x||x.startsWith("pending:")||on[b.deviceId]===!0}),f=Kn.filter(b=>{const x=String(Ye.current[b.deviceId]||"");return l?!x||x.startsWith("pending:")||on[b.deviceId]===!0:!!x});if(f.length===0){we(l?"Selected Clients are already paused.":"Selected Clients are already playing.");return}We("video");try{const b=await Promise.all(f.map(W=>wy(W,l)));X();const x=b.filter(W=>W.ok&&!W.skipped),S=b.filter(W=>!W.ok&&W.unconfirmed),$=b.filter(W=>!W.ok&&!W.unconfirmed),L=Kn.length-f.length+b.filter(W=>W.skipped).length,B=Ao.length-Kn.length,q=l?"pause":"resume";if($.length>0||S.length>0){const W=$.slice(0,2).map(ke=>`${ke.title}: ${ke.error||"unknown error"}`).join(" · ");we([`Video ${q} completed for ${x.length}/${f.length} Clients.`,S.length>0?`${S.length} Client capture stop${S.length===1?"":"s"} remain unconfirmed.`:"",W,B>0?`${B} selected Client${B===1?"":"s"} were outside the current plan limit.`:""].filter(Boolean).join(" "),"error");return}we([`Video ${l?"paused":"resumed"} for ${x.length} Client${x.length===1?"":"s"}.`,L>0?`${L} already ${l?"paused":"playing"}.`:"",B>0?`${B} outside the current plan limit.`:""].filter(Boolean).join(" "),"success")}finally{We("")}},yy=l=>{const f=l instanceof Error?l.message:String(l);return/remote-actions-disabled|remote-access-blocked-by-settings/i.test(f)?"Remote access is blocked. Change Settings > Remote Access > Access mode first.":/power-actions-disabled|allowPowerActions-blocked-by-settings/i.test(f)?"Power actions are off. Turn on Settings > Remote Access > Power actions first.":/agent-tool-capability-unavailable|unsupported-agent-operation/i.test(f)?"This Client needs a newer LiveDesk Client for power actions.":/device-not-connected|404 device-not-found/i.test(f)?"The Client disconnected before the action could be sent.":f},hl=async l=>{if(!fe||be)return;const f=fe,x={sleep:"Sleep",restart:"Restart",shutdown:"Shut down"}[l];if(window.confirm(`${x} ${dn(f)}? Unsaved work on that computer may be lost.`)){We(l),we(`Sending ${x.toLowerCase()} request to ${dn(f)}...`);try{const S=await Oe(`/api/remote/devices/${encodeURIComponent(f.deviceId)}/quick-actions`,{method:"POST",body:JSON.stringify({action:l})},G);if(!S.ok)throw new Error(S.error||"The remote action could not be sent.");we(`${x} request sent to ${dn(f)}.`,"success"),X()}catch(S){we(yy(S),"error")}finally{We("")}}},gh=async(l,f,b="files")=>{const x=l.filter(B=>B.file.size>=0);if(x.length===0)return{files:0,bytes:0};if(!Rt)throw new Error(Si);if(f.length===0)throw new Error("Select at least one connected Client.");const S=crypto.randomUUID(),$=x.reduce((B,q)=>B+q.file.size,0);let L=0;Hs({id:S,status:"reading",progress:1,message:`Preparing ${x.length} ${b}`});try{for(let B=0;B<x.length;B+=1){const q=x[B],W=q.file,ke=Math.max(1,Math.ceil(W.size/Gd));for(let Me=0;Me<ke;Me+=1){const he=Me*Gd,tt=Math.min(W.size,he+Gd),yt=W.size===0?new ArrayBuffer(0):await W.slice(he,tt).arrayBuffer(),at=Me===ke-1;Hs({id:S,status:"sending",progress:Math.max(2,Math.min(98,Math.round(L/Math.max(1,$)*96))),message:`${B+1}/${x.length} ${q.relativePath}`});const wt=await Oe("/api/remote/files/chunk",{method:"POST",body:JSON.stringify({transferId:S,deviceIds:f,remoteDirectory:fs.trim(),name:W.name,relativePath:q.relativePath,size:W.size,type:W.type,lastModified:W.lastModified,offset:he,totalBytes:W.size,final:at,dataBase64:nI(yt)})},G);if(!wt.ok||wt.queued!==f.length)throw new Error(wt.error||`file-chunk-not-queued-${wt.queued}/${f.length}`);L+=yt.byteLength,await new Promise(Et=>window.setTimeout(Et,0))}}return Hs({id:S,status:"queued",progress:100,message:`Sent ${x.length} file${x.length===1?"":"s"} to ${f.length} Client${f.length===1?"":"s"}`}),window.setTimeout(()=>{Hs(B=>B?.id===S&&B.status==="queued"?null:B)},4500),{files:x.length,bytes:$}}catch(B){throw Hs({id:S,status:"failed",progress:100,message:B instanceof Error?B.message:String(B)}),B}},bh=async l=>{const f=An.length>0?An.map(b=>b.deviceId):fe?[fe.deviceId]:[];try{await gh(rb(l),f)}catch(b){we(b instanceof Error?b.message:String(b))}},vh=async l=>{try{await gh(rb(l),Yw)}catch(f){we(f instanceof Error?f.message:String(f))}};o.useEffect(()=>{Uw.current=!1},[]);const xy=l=>{l.preventDefault(),l.stopPropagation(),Bu(!1),bh(l.dataTransfer.files)},dd=async(l="ltd")=>{if(!n){we("Sign in with Google before checkout.");return}if(re&&l===Qt){we("LiveDesk license is already active.");return}if(re&&Qt==="pro"){we("LiveDesk Pro is already active.");return}Z("checkout");try{const{data:f,error:b}=await pt.functions.invoke("dodo-checkout",{body:{plan:l}});if(b)throw b;if(!f?.checkout_url)throw new Error("Checkout function did not return a checkout URL.");window.location.assign(f.checkout_url)}catch(f){we(f instanceof Error?f.message:String(f)),Z("")}},fl=EP(),wh=FP(),pd=Yu.filter(l=>Ri.has(l)).length,md=ed==="open"&&al.sampleMs>0?`${al.framesPerSecond.toFixed(1)} fps`:ed,Ne=fe?Xe?Ro.get(fe.deviceId):Ri.get(fe.deviceId):void 0,gl=fe?lr(fe,Ct[fe.deviceId]):0,Sy=fe?_P(fe):[],Cy=typeof Ne?.monitorIndex=="number"?Xo(Ne.monitorIndex,Math.max(1,Ne.monitorCount||1)):gl,hd=(Ne&&Cy===gl?jw(Ne):null)||(fe?Iw(fe,gl):null);hd&&`${hd.width}${hd.height}`;const bl=fe?Ut(Xe?"control":"wall",fe.deviceId):"",wn=bl?Pc[bl]:void 0,cr=bl?Tc[bl]:void 0,st=cr?.lastInfo,ky=wn&&wn.sampleMs>0?`${wn.framesPerSecond.toFixed(1)} fps`:"waiting";wn&&`${wn.totalFrames}${ky}`,cr&&cr.sampleMs>0&&`${cr.framesPerSecond.toFixed(1)}`,cr&&cr.sampleMs>0&&`${cr.changedFramesPerSecond.toFixed(1)}`,st&&(`${st.frameSeq}${st.decoderLabel}${st.queueSize}${st.renderQueueSize}${st.droppedForLatency}${st.decoderFlushCount}${st.decoderTimestampFallbacks}${st.decoderInputCount}${st.decoderOutputCount}`,st.visualChanged),st&&`${Math.round(st.queuedForMs)}${Math.round(st.decodedForMs)}${Math.round(st.scheduledForMs)}${st.drawMs.toFixed(1)}`,st?.targetPaintIntervalMs&&`${st.targetPaintIntervalMs.toFixed(1)}${(1e3/st.targetPaintIntervalMs).toFixed(1)}`,cr&&`${cr.decoderInputFps.toFixed(1)}${cr.decoderOutputFps.toFixed(1)}`,st?.canvasPresentation,st&&`${st.interactiveBufferWaitCount}${Math.round(st.interactiveBufferWaitMs)}${st.interactiveQueueDrainCount}`,wn&&(Ne?.frameMode==="mode5-lzo-delta"?`${Jo(wn.averageFrameBytes)}${Ne.deltaVisualTileCount||0}${Ne.deltaRefreshTileCount||0}${Ne.deltaTotalTiles||0}`:`${Jo(wn.averageFrameBytes)}${Math.round(wn.tinyFrameRatio*100)}${Math.round(wn.repeatedFrameRatio*100)}`),wn&&wn.sourceSendSampleCount>0&&`${wn.sourceSendAverageMs.toFixed(1)}${wn.sourceSendP95Ms.toFixed(1)}`,Gg(wn),Gg(cr),wn&&cr&&`${Kg(wn)}${Kg(cr)}`,Ne?Ne.frameMode||Ne.mode||Ne.codec||Ne.mimeType:Xe?rn.frameMode:ot.frameMode,Xe?rn.frameMode:ot.frameMode,Ne?`${Ne.width}${Ne.height}${Jo(Ne.byteLength)}`:Xe?`${Kr.maxWidth}${Kr.maxHeight}`:`${ot.maxWidth}${ot.maxHeight}`,Ne&&`${Ne.isKeyFrame?"key":String(Ne.chunkType||"delta")}`,Ne&&Ne.monitorCount&&((Ne.monitorIndex??0)+1,`${Ne.monitorCount}`),Ne&&[`src ${Math.round(Ne.sourceGapMs||0)}ms`,`gap ${Math.round(Ne.agentSendGapMs||0)}ms`,`tx ${Math.round(Ne.agentSendDurationMs||0)}ms`,`pace ${Math.round(Ne.agentPaceMs||0)}ms`,`queue ${Math.round(Ne.agentQueueBeforePaceMs||0)}ms`,`age ${Math.round(Ne.agentFrameAgeMs||0)}ms`,Ne.hubPacketTransitAgeMs!==void 0?`sock ${Math.max(0,Math.round(Ne.hubPacketTransitAgeMs))}ms`:"",Ne.droppedByAgent?`drop ${Ne.droppedByAgent}`:"",Ne.hubIngressDropped?`ingress-drop ${Ne.hubIngressDropped}`:"",Ne.hubClientDropped?`ws-drop ${Ne.hubClientDropped}`:"",Ne.captureStageMs?`capture ${Math.round(Ne.captureStageMs)}ms`:"",Ne.requestedFps?`req ${Math.round(Ne.requestedFps)}fps`:"",Ne.effectiveFps?`eff ${Math.round(Ne.effectiveFps)}fps`:"",Ne.captureAverageMs?`avg ${Math.round(Ne.captureAverageMs)}ms`:"",Ne.captureP95Ms?`p95 ${Math.round(Ne.captureP95Ms)}ms`:"",Ne.slowFrameCount?`slow ${Math.round(Ne.slowFrameCount)}`:"",Ne.captureHelperRestarts?`helper ${Math.round(Ne.captureHelperRestarts)}`:"",Ne.convertMs?`rgb565 ${Math.round(Ne.convertMs)}ms`:"",Ne.compressMs?`lzo ${Math.round(Ne.compressMs)}ms`:"",Ne.captureSourceSerial?`cap #${Ne.captureSourceSerial}`:"",Ne.captureSourceSkipped?`cap skip ${Ne.captureSourceSkipped}`:"",Ne.frameMode==="mode5-lzo-delta"?`tiles ${Ne.deltaVisualTileCount||0}+${Ne.deltaRefreshTileCount||0}/${Ne.deltaTotalTiles||0}@${Ne.deltaTileSize||0}`:"",Ne.platformProfile||Ne.hardwareEncoder||"-",Ne.atlasComposeMs?`atlas ${Ne.atlasComposeMs.toFixed(1)}ms`:"",Ne.atlasPoolStarved?`pool ${Ne.atlasPoolStarved}`:"",Ne.atlasTileCount?`tiles ${Ne.atlasReadyTiles||0}/${Ne.atlasTileCount}`:"",Ne.atlasInputRevision?`input #${Ne.atlasInputRevision}`:"",Ne.atlasSourceMaxAgeMs!==void 0?`input-age ${Math.round(Ne.atlasSourceMaxAgeMs)}ms`:"",st?.inputFeedbackMs!==void 0&&st.inputFeedbackAt!==void 0&&performance.now()-st.inputFeedbackAt<=Lg?`feedback ${Math.round(st.inputFeedbackMs)}ms`:"",Ne.contentHash?`enc ${Ne.contentHash.slice(0,6)}`:"",st?.visualHash?`pix ${st.visualHash.slice(0,6)}`:""].filter(Boolean).join(" / "),jo==="open"&&[`${es.sentPerSecond.toFixed(1)} hz`,es.lastInputSeq>0?`rtt ${Math.round(es.lastRoundTripMs)}ms`:"",es.lastInputSeq>0?`apply ${es.lastAgentApplyMs.toFixed(1)}ms`:"",es.droppedPerSecond>0?`drop ${es.droppedPerSecond.toFixed(1)}/s`:"",es.bufferedAmount>0?`buf ${Jo(es.bufferedAmount)}`:"",es.lastInputType||"ready"].filter(Boolean).join(" / "),st?.inputFeedbackMs!==void 0&&st.inputFeedbackAt!==void 0&&performance.now()-st.inputFeedbackAt<=Lg&&[st.inputFeedbackExact?"exact":"estimated",st.inputFeedbackInputType||"",`total ${Math.round(st.inputFeedbackMs)}ms`,st.inputFeedbackAgentApplyMs!==void 0?`apply ${st.inputFeedbackAgentApplyMs.toFixed(1)}ms`:"",st.inputFeedbackApplyToCaptureMs!==void 0?`apply→frame ${Math.round(st.inputFeedbackApplyToCaptureMs)}ms`:"",st.inputFeedbackInputToFrameMs!==void 0?`input→browser ${Math.round(st.inputFeedbackInputToFrameMs)}ms`:"",st.inputFeedbackFrameToPaintMs!==void 0?`browser→paint ${Math.round(st.inputFeedbackFrameToPaintMs)}ms`:"",st.inputFeedbackSampleCount?`p50 ${Math.round(st.inputFeedbackP50Ms||0)}ms`:"",st.inputFeedbackSampleCount?`p95 ${Math.round(st.inputFeedbackP95Ms||0)}ms`:"",st.inputFeedbackSampleCount?`n=${st.inputFeedbackSampleCount}`:"",`input #${st.inputFeedbackSeq||0}`].filter(Boolean).join(" / "),Ne&&`${Ne.frameSeq}${db(Ne.receivedAt||Ne.capturedAt)}`;const $i=Math.max(0,al.bytesPerSecond*8/1e6),yh={activeTool:jt,audioError:od,audioMode:Ie,audioState:ad,audioStats:Ft,lastAudioFrame:id,selectedAudioCaptureStreamId:oh,controlFrames:Ro,controlInputReady:ts,controlMode:_e,controlPresentationReady:Lu,controlSessionDeviceId:te,controlSessionFrameReady:ce,controlSessionState:ae,controlStreamBinding:Ee,devices:D,documentPresentationVisible:On,focusedDeviceId:Ae,frames:Ri,localFeatureAccess:Rt,quickActionBusy:be,selectedDeviceId:fe?.deviceId||"",selectedIds:oe,showControlFocus:Xe,videoCaptureStopUnconfirmedByDeviceId:on,videoCapturePausedDeviceIds:Un,wallPresentationReadyDeviceIds:Eu},xh=o.useRef(yh);xh.current=yh,o.useEffect(()=>{if(!Nc.current)return;const l=window,f=B=>{if(!B)return null;const q=B.sourceGapMs,W=q==null||q===""?null:Number.isFinite(Number(q))?Number(q):null,ke=B;return{deviceId:B.deviceId,sessionId:B.sessionId||"",streamId:B.streamId||"",commandId:B.commandId||"",captureGeneration:Number(B.captureGeneration||0),monitorIndex:Number(B.monitorIndex||0),streamPurpose:B.streamPurpose||"",frameSeq:Number(B.frameSeq||0),frameMode:B.frameMode||"",mimeType:B.mimeType||"",currentGenerationVerified:ke.currentGenerationVerified===!0,receivedAt:ke.receivedAt||"",capturedAt:ke.capturedAt||"",sourceGapMs:W,inputFeedbackEventId:String(B.inputFeedbackEventId||""),inputFeedbackInputSeq:Number(B.inputFeedbackInputSeq||0),inputFeedbackIssuedAtEpochMs:Number(B.inputFeedbackIssuedAtEpochMs||0),inputFeedbackAgentApplyMs:Number(B.inputFeedbackAgentApplyMs||0),inputFeedbackApplyToCaptureMs:Number(B.inputFeedbackApplyToCaptureMs||0)}},b=B=>{if(!B)return null;const q=window.getComputedStyle(B),W=B.getBoundingClientRect(),ke=Math.max(0,Math.min(W.right,window.innerWidth)-Math.max(W.left,0)),Me=Math.max(0,Math.min(W.bottom,window.innerHeight)-Math.max(W.top,0)),he=Number(q.opacity),tt=B.isConnected&&q.display!=="none"&&q.visibility!=="hidden"&&q.visibility!=="collapse"&&Number.isFinite(he)&&he>0&&W.width>0&&W.height>0&&ke>0&&Me>0;return{connected:B.isConnected,userVisible:tt,width:Math.max(0,Number(B.width||0)),height:Math.max(0,Number(B.height||0)),css:{display:q.display,visibility:q.visibility,opacity:Number.isFinite(he)?he:0},rect:{left:W.left,top:W.top,right:W.right,bottom:W.bottom,width:W.width,height:W.height,viewportIntersectionWidth:ke,viewportIntersectionHeight:Me},codec:Ml(B)}},x=(B,q)=>{const W=vs.current.get(Ut(B,q));return W?{bindingKey:W.bindingKey||"",totalFrames:W.totalFrames,totalChangedFrames:W.totalChangedFrames,lastFrameSeq:Number(W.lastFrameSeq||0),lastPaintAgeMs:W.lastAt===void 0?-1:Math.max(0,performance.now()-W.lastAt),lastInfo:W.lastInfo?{frameSeq:Number(W.lastInfo.frameSeq||0),decoderInputCount:Number(W.lastInfo.decoderInputCount||0),decoderOutputCount:Number(W.lastInfo.decoderOutputCount||0),targetPaintIntervalMs:Number(W.lastInfo.targetPaintIntervalMs||0),droppedForLatency:Number(W.lastInfo.droppedForLatency||0),visualChanged:W.lastInfo.visualChanged===!0,inputFeedbackExact:W.lastInfo.inputFeedbackExact===!0,inputFeedbackMs:Number(W.lastInfo.inputFeedbackMs||0),inputFeedbackSampleCount:Number(W.lastInfo.inputFeedbackSampleCount||0),inputFeedbackP50Ms:Number(W.lastInfo.inputFeedbackP50Ms||0),inputFeedbackP95Ms:Number(W.lastInfo.inputFeedbackP95Ms||0),inputFeedbackTargetMs:$g,inputFeedbackTargetMinSamples:Og,inputFeedbackOnTarget:W.lastInfo.inputFeedbackExact===!0&&Number(W.lastInfo.inputFeedbackSampleCount||0)>=Og&&Number(W.lastInfo.inputFeedbackP95Ms)<$g}:null}:null},S=(B,q)=>{if(!B)return null;if(q==="wall-visible"){const ke=vs.current.get(Ut("wall",B));return ke?{bindingKey:ke.bindingKey||"",total:ke.totalFrames,lastFrameSeq:Number(ke.lastFrameSeq||0),lastPaintAgeMs:ke.lastAt===void 0?-1:Math.max(0,performance.now()-ke.lastAt)}:null}if(q!=="control-visible"&&q!=="wall-reuse-visible")return null;const W=Rc.current.get(`${q}:${B}`);return W?{bindingKey:W.bindingKey,total:W.totalPaints,lastFrameSeq:W.lastFrameSeq,lastPaintAgeMs:Math.max(0,performance.now()-W.lastPaintAt)}:null},$=(B,q)=>{const W=S(B,q);return W?{bindingKey:W.bindingKey,totalPaints:W.total,lastPaintAgeMs:W.lastPaintAgeMs,lastFrameSeq:W.lastFrameSeq}:null},L={readPresentationCounter(B,q){return S(String(B||""),q)},snapshot(B,q={}){const W=String(B||""),ke=q.includeHistory===!0,Me=Math.max(0,Number(q.presentationAfterSequence||0)),he=xh.current,tt=he.devices.find(rs=>rs.deviceId===W)?.liveCapturePause,yt=String(Ye.current[W]||""),at=Tt.current.get(W)||null,wt=Ht.current.get(W)||null,Et=_n.current.get(W)||null,Xn=a0(),Hi=i0(),zs={frameStats:jc.current===null?0:1,wallRecovery:ii.current===null?0:1,controlWarm:kr.current===null?0:1,controlWallDownshift:mr.current===null?0:1},Wi=ws.current?.deviceId===W?ws.current:null,Eh=fm.current.get(W)||null;return{capturedAt:Date.now(),deviceId:W,activeTool:he.activeTool,documentPresentationVisible:he.documentPresentationVisible,showControlFocus:he.showControlFocus,selectedDeviceId:he.selectedDeviceId,focusedDeviceId:he.focusedDeviceId,selectedDeviceIds:[...he.selectedIds],localFeatureAccess:he.localFeatureAccess,quickActionBusy:he.quickActionBusy,audioMode:he.audioMode,audioState:he.audioState,audioError:he.audioError,audioCaptureStreamId:he.selectedAudioCaptureStreamId,audioFrame:he.lastAudioFrame?{deviceId:he.lastAudioFrame.deviceId,streamId:he.lastAudioFrame.streamId,frameSeq:Number(he.lastAudioFrame.frameSeq||0),mimeType:he.lastAudioFrame.mimeType,sampleRate:Number(he.lastAudioFrame.sampleRate||0),channels:Number(he.lastAudioFrame.channels||0),byteLength:Number(he.lastAudioFrame.byteLength||0)}:null,audioStats:{...he.audioStats},videoCapturePausePhase:yt?yt.startsWith("pending:")?"pending":"confirmed":"none",videoCaptureStopUnconfirmed:he.videoCaptureStopUnconfirmedByDeviceId[W]===!0,authoritativeLiveCapturePause:tt?{phase:tt.phase||"",captureStopConfirmed:tt.captureStopConfirmed===!0,stopAttemptCount:Math.max(0,Number(tt.stopAttemptCount||0)),stopError:tt.stopError||""}:null,controlMode:he.controlMode,controlSessionDeviceId:he.controlSessionDeviceId,controlSessionState:he.controlSessionState,controlSessionFrameReady:he.controlSessionFrameReady,controlPresentationReady:he.controlPresentationReady,controlInputReady:he.controlInputReady,controlConnection:Eh?{...Eh}:null,pendingControlConnection:Wi?{...Wi,elapsedMs:Math.max(0,performance.now()-Wi.startedAt)}:null,videoCapturePaused:he.videoCapturePausedDeviceIds.has(W),wallPresentationReady:he.wallPresentationReadyDeviceIds.has(W),controlBinding:he.controlStreamBinding?.deviceId===W?{...he.controlStreamBinding}:null,actualControlOwner:it.current?.deviceId===W?{...it.current}:null,wallCapturePauseOwner:Gn.current?.deviceId===W?{...Gn.current}:null,frameSubscriptions:Xn,audioSubscriptions:Hi,presentationTimers:{...zs,total:Object.values(zs).reduce((rs,wd)=>rs+wd,0)},wallFrame:f(he.frames.get(W)),controlFrame:f(ma.current.get(W)||he.controlFrames.get(W)),wallPaint:x("wall",W),controlPaint:x("control",W),controlVisiblePaint:$(W,"control-visible"),wallReuseVisiblePaint:$(W,"wall-reuse-visible"),presentationPaintSequence:hm.current,presentationPaintEvents:ke?Fu.current.filter(rs=>rs.deviceId===W&&rs.sequence>Me).sort((rs,wd)=>rs.sequence-wd.sequence).map(rs=>({...rs})):[],wallCanvas:b(at),controlDecodeCanvas:b(wt),controlPresentationCanvas:b(Et),globalCodec:Ml(void 0,{includeLifecycleEvents:ke})}}};return l.__liveDeskTransmissionProbe=L,()=>{l.__liveDeskTransmissionProbe===L&&delete l.__liveDeskTransmissionProbe}},[]);const Oi=o.useCallback(()=>{hs(!0),js(Date.now()),X(),Cr.current!==null&&window.clearTimeout(Cr.current),Cr.current=window.setTimeout(()=>{Cr.current=null,js(Date.now()),hs(!1)},650)},[X]),Sh=o.useCallback(()=>{if(nn){oa(!1);return}ca(!1),oa(!0),Oi()},[Oi,nn]),Ch=o.useCallback(()=>{if(qt){ca(!1);return}oa(!1),ca(!0),Oi()},[qt,Oi]),kh=o.useCallback(()=>{if(Vn){la(!1);return}la(!0),Oi()},[Vn,Oi]),Mh=nn||qt,Ah=JSON.stringify(Ze.filter(l=>l.connected).map(l=>l.deviceId).sort());o.useEffect(()=>{if(!Mh)return;const l=JSON.parse(Ah);if(l.length===0){hs(!1);return}const f=new AbortController,b=[];let x=!1;return Cr.current!==null&&(window.clearTimeout(Cr.current),Cr.current=null),hs(!0),js(Date.now()),Promise.allSettled(l.map(S=>Oe(`/api/remote/devices/${encodeURIComponent(S)}/status-diagnostic`,{method:"POST",body:JSON.stringify({purpose:"remote-status-current-snapshot"}),signal:f.signal,timeoutMs:1500},G))).then(()=>{x||[500,1800,4500].forEach((S,$,L)=>{const B=window.setTimeout(()=>{x||(X(),js(Date.now()),$===L.length-1&&hs(!1))},S);b.push(B)})}),()=>{x=!0,f.abort();for(const S of b)window.clearTimeout(S)}},[G,X,Ah,Mh]);const Bi=new Map,Oo=new Map;if(nn||qt||Vn)for(const l of Ze){const f=l.deviceId,b=Xe&&te===f,S=Ut(b?"control":"wall",f),$=b?Ro.get(f):Ri.get(f),L=b?Ht.current.get(f)||_n.current.get(f)||null:Tt.current.get(f)||(St?ar.current:null),B={device:l,frame:$,receiveStat:Pc[S],paintStat:Tc[S],codec:L?Ml(L):{},selectedMonitorIndex:lr(l,Ct[f]),control:b,controlInputReady:b&&ts,controlBinding:b&&Ee?.deviceId===f?Ee:void 0,hubRelay:P?.relay,capturePaused:Un.has(f),capturePauseConfirmed:l.liveCapturePause?.captureStopConfirmed===!0,capturePauseError:l.liveCapturePause?.stopError||"",clientHeartbeatMs:Number(P?.heartbeatMs||5e3),now:Date.now()},q=["open","playing","silent"].includes(ad),W=Ft.nativeCallbackDiagnosticsAvailable&&(Ft.nativeRejectedCallbackCount>0||Ft.nativeCurrentnessDropCount>0),ke=q&&!W,Me=f===fe?.deviceId&&Ie?{id:"browser-remote-audio",state:ke?"ok":"warning",label:ke?"Remote audio is healthy":"Remote audio needs attention",detail:Ft.lastUpdatedAt>0?[ad,`context ${Ft.audioContextState}`,`queue ${Math.round(Ft.queuedMs)}ms`,`packet ${Math.round(Ft.lastPacketAgeMs)}ms`,`capture ${Ft.captureHealthy?"healthy":Ft.captureAwaitingCurrentPcm?"awaiting PCM":"down"}`,Ft.backendKind?`backend ${Ft.backendKind}`:"backend unknown",Ft.helperRequired?`helper ${Ft.helperAlive&&Ft.helperPid>0?`pid ${Ft.helperPid}`:"missing"}`:"helper N/A",`drop ${Ft.drops}`,`restart ${Ft.automaticRestarts}`,Ft.nativeCallbackDiagnosticsAvailable?`native reject ${Ft.nativeRejectedCallbackCount}`:"native callback diagnostics unknown",Ft.nativeCallbackDiagnosticsAvailable?`native stale ${Ft.nativeCurrentnessDropCount}`:"",Ft.nativeLastDropReason?`native reason ${Ft.nativeLastDropReason}`:"",id?`frame #${id.frameSeq}`:"waiting for frame"].filter(Boolean).join(" · "):"Browser audio diagnostics are collecting while Remote or Debug status is open."}:null;if(nn||Vn){const he=CT(B);nn&&Me&&he.push(Me),Bi.set(f,he)}if(qt){const he=kT(B);Me&&he.push(Me),Oo.set(f,he)}}const My=Vn?MT({status:P||{},deviceDiagnostics:[...Bi.values()],codec:Ml(),browser:{hardwareConcurrency:navigator.hardwareConcurrency,deviceMemory:Number(navigator.deviceMemory||0)},frameStats:al}):[],Nh=Ni?.atlasReadyTiles??pd,fd=Ni?.atlasTileCount??pd,Ay=Nh===fd?`${fd} tiles`:`${Nh}/${fd} tiles`,Ny=Qn.length>0;Xe?`${md}${$i.toFixed($i>=10?0:1)}`:Ny?`${Ay}${md}${$i.toFixed($i>=10?0:1)}`:`${pd}${md}${$i.toFixed($i>=10?0:1)}`;const gd=An.length,Rh=Xe?fe?dn(fe):"No Client":gd===0?"No Client":gd>1?`${gd} selected`:fe?dn(fe):"No Client",Ry=Xe?[fe?.deviceId].filter(l=>!!l):An.map(l=>l.deviceId),zn=no[Or]||no.en,vl=zn.sync||no.en.sync,Ty=s||de?"checking":re?Qt==="pro"?"Pro LTD active":`Plus LTD ${Ze.length}/${Ho}`:Zw?`Free ${Ze.length}/${yl}`:`Upgrade ${Ze.length}/${yl}`,Py=re?Qt==="pro"?"Pro active":"Upgrade to Pro LTD":n?bt==="checkout"?"Opening checkout":Qt==="ltd"?"Buy Pro LTD":"Buy Plus LTD":bt==="auth"?"Opening Google":"Sign in to buy",Iy=Qt==="pro"||bt==="checkout"||bt==="auth"||s||de,Th=n?.user?.user_metadata,wl=sb(Th,"avatar_url","picture"),Bo=sb(Th,"full_name","name")||n?.user?.email||"Google",Ph=Bo.slice(0,1).toUpperCase(),jy=P?.started?"Local app ready":"Start LiveDesk",Ey=a?.active?"Published":n?"Not published":"Sign in required",Fy=/^\d{6}$/.test(P?.pairingPin||"")?P?.pairingPin:"------",La=l=>{if(typeof window<"u"&&(l==="support"?window.history.pushState({},"","/support"):jt==="support"&&window.history.pushState({},"",p?"/app":"/")),l==="control"){const f=vn||xi;if(f&&(Lo(f.deviceId),$n(!1),Se(f.deviceId)),tn(l),!Rt){$e(!1),we(Si);return}$e(!0);return}l==="wall"&&Dw(f=>f+1),tn(l),$e(!1)},ns=bt==="update"||vt?.stage==="updating"||["dispatching","waiting-for-clients","hub-restart-requested"].includes(P?.update?.state||""),Ih=!!(P?.update?.updateAvailable&&P.update.canApply||ns||vt?.error||!P&&vt),_a=aS(Or),bd=o.useCallback(l=>{if(!vt?.targetIds.includes(l))return;const f=P?.update?.operationId===vt.operationId?P.update.targets?.find(b=>b.deviceId===l):void 0;switch(f?.state){case"completed":return ri[zg(vt.operationId,f)]?{state:"updated",label:"Updated"}:void 0;case"failed":return{state:"failed",label:"Update failed",error:f.error};case"pending-offline":return{state:"offline",label:"Waiting for reconnect"};case"queued":return vt.stage==="updating"?{state:"queued",label:"Queued"}:void 0;case"waiting":return vt.stage==="updating"?f.candidateSince?{state:"updating",label:"Verifying restart..."}:{state:"updating",label:"Restarting..."}:void 0;default:return vt.stage==="updated"?{state:"updated",label:"Updated"}:vt.stage==="updating"?{state:"updating",label:"Verifying..."}:void 0}},[P?.update,ri,vt]),vd=A&&!!n&&V&&!P?.started,Dy=s?"checking":P?.started?"online":vd?O?"retrying":"connecting":"offline",Ly=s?"Checking Hub":P?.started?`${Ze.length} online`:vd?O?"Hub offline":"Connecting Hub":n?"Hub offline":"Sign in required",_y=P?.deviceName||(vd?O?"Retrying automatically…":"Trying saved Hub routes…":O?"Desktop Hub unavailable":"Remote management"),jh=A&&p&&!s&&!n;return r.jsxs("main",{className:`app-shell ${Ca||Xe?"stream-surface-active":""} ${A?"mobile-console-shell":""} ${A&&Xe?"mobile-console-control-active":""}`,"data-mobile-auth-required":jh?"true":void 0,"data-mobile-standalone":A&&N?"true":void 0,"data-mobile-ios":A&&v.isIos?"true":void 0,"data-mobile-android":A&&v.isAndroid?"true":void 0,children:[r.jsxs("aside",{className:"tool-rail","aria-label":"LiveDesk tools",children:[r.jsx("div",{className:"rail-brand",title:"LiveDesk",children:r.jsx(cb,{size:25})}),r.jsx("nav",{className:"rail-tools",children:lI.map(l=>{const f=l.icon,b=ru(l.tooltip,Or);return r.jsxs("button",{className:`rail-tool ${l.id==="sync-server"?"sync-server hub-sync-trigger":""} ${jt===l.id?"active":""} accent-${l.accent}`,onClick:()=>l.id==="sync-server"?hy():La(l.id),"data-tooltip":l.id==="sync-server"&&lt?void 0:cp(l.label,l.tooltip,Or),"aria-label":`${l.label}. ${b}`,type:"button",disabled:l.id==="sync-server"&&bt==="host","aria-busy":l.id==="sync-server"&&bt==="host","aria-expanded":l.id==="sync-server"?lt:void 0,"aria-haspopup":l.id==="sync-server"?"dialog":void 0,"aria-controls":l.id==="sync-server"&&lt?"hub-sync-popover":void 0,children:[l.id==="sync-server"&&bt==="host"?r.jsx("span",{className:"sync-server-spinner","aria-hidden":"true"}):r.jsx(f,{size:19}),r.jsx("span",{children:l.id==="sync-server"&&bt==="host"?"Syncing…":l.label})]},l.id)})}),r.jsxs("div",{className:"rail-footer",children:[uI.map(l=>{const f=l.icon;return r.jsxs("button",{className:`rail-tool compact ${jt===l.id?"active":""} accent-${l.accent}`,onClick:()=>La(l.id),title:l.label,type:"button",children:[r.jsx(f,{size:18}),r.jsx("span",{children:l.label})]},l.id)}),r.jsxs("button",{className:`rail-tool compact local-settings ${ko?"active":""}`,onClick:()=>{tn("settings"),typeof window<"u"&&window.history.pushState({},"","/"),Hr(!1),$e(!1),io(!1)},title:"Settings",type:"button",children:[r.jsx(nu,{size:18}),r.jsx("span",{children:"Settings"})]}),r.jsxs("button",{className:`rail-account ${n?"signed-in":""}`,onClick:()=>{Hr(l=>!l)},disabled:s||bt==="auth","aria-expanded":ua,title:n?`Account: ${n.user?.email||Bo}`:"Sign in with Google",type:"button",children:[n?wl?r.jsx("img",{src:wl,alt:Bo,referrerPolicy:"no-referrer"}):r.jsx("span",{className:"avatar-fallback",children:Ph}):r.jsx(Qs,{size:18}),r.jsx("span",{children:n?"Account":"Google"})]}),ua&&r.jsxs("section",{className:"account-popover",role:"dialog","aria-label":"LiveDesk account",children:[r.jsxs("div",{className:"account-popover-head",children:[r.jsx("div",{className:"account-popover-avatar",children:n&&wl?r.jsx("img",{src:wl,alt:Bo,referrerPolicy:"no-referrer"}):n?r.jsx("span",{children:Ph}):r.jsx(Qs,{size:18})}),r.jsxs("div",{children:[r.jsx("strong",{children:n?Bo:"Account"}),r.jsx("p",{children:n?.user?.email||"Not signed in"})]})]}),r.jsxs("dl",{className:"account-popover-facts",children:[r.jsx("dt",{children:"User"}),r.jsx("dd",{children:n?.user?.email||"Not signed in"}),r.jsx("dt",{children:"Network"}),r.jsx("dd",{children:jy}),r.jsx("dt",{children:"Access"}),r.jsx("dd",{children:Ey}),r.jsx("dt",{children:"Plan"}),r.jsx("dd",{children:Ty}),r.jsx("dt",{children:"Ads"}),r.jsx("dd",{children:Qt==="free"?"Standard banner":"Removed"})]}),n?r.jsxs("button",{className:"account-popover-action",onClick:my,disabled:bt==="auth",type:"button",children:[r.jsx(fb,{size:16}),"Logout"]}):r.jsxs("button",{className:"account-popover-action primary",onClick:_i,disabled:bt==="auth",type:"button",children:[r.jsx(Qs,{size:16}),"Sign in with Google"]})]})]})]}),A&&y&&r.jsx("div",{className:"mobile-pwa-guide-backdrop",role:"presentation",onClick:()=>k(!1),children:r.jsxs("section",{className:"mobile-pwa-guide",role:"dialog","aria-modal":"true","aria-labelledby":"mobile-pwa-guide-title",onClick:l=>l.stopPropagation(),children:[r.jsxs("header",{children:[r.jsx("span",{className:"mobile-pwa-guide-mark","aria-hidden":"true",children:r.jsx(kb,{size:20})}),r.jsxs("span",{children:[r.jsx("strong",{id:"mobile-pwa-guide-title",children:"Install LiveDesk on iPhone"}),r.jsx("small",{children:"Open without browser bars and tabs"})]}),r.jsx("button",{type:"button",onClick:()=>k(!1),"aria-label":"Close install guide",children:r.jsx(xn,{size:18,"aria-hidden":"true"})})]}),r.jsxs("ol",{children:[r.jsxs("li",{children:["Tap ",v.browserName==="browser"?"the browser":v.browserName,"'s ",r.jsx("strong",{children:"Share"})," button."]}),r.jsxs("li",{children:["Tap ",r.jsx("strong",{children:"Add to Home Screen"}),"."]}),r.jsx("li",{children:v.isSafari?r.jsxs(r.Fragment,{children:["Turn on ",r.jsx("strong",{children:"Open as Web App"}),", then tap ",r.jsx("strong",{children:"Add"}),"."]}):r.jsxs(r.Fragment,{children:["Confirm the app name, then tap ",r.jsx("strong",{children:"Add"}),"."]})})]}),r.jsx("button",{className:"mobile-pwa-guide-done",type:"button",onClick:()=>k(!1),children:"Got it"})]})}),jh&&r.jsxs("section",{className:"mobile-console-auth","aria-labelledby":"mobile-console-auth-title",children:[r.jsx("span",{className:"mobile-console-auth-mark","aria-hidden":"true",children:r.jsx(Zt,{size:26})}),r.jsx("h1",{id:"mobile-console-auth-title",children:s?"Checking your account":"Sign in to LiveDesk"}),r.jsx("p",{children:"Use the same Google account as your LiveDesk Hub."}),r.jsxs("button",{type:"button",onClick:()=>{_i()},disabled:s||bt==="auth","aria-busy":s||bt==="auth",children:[s||bt==="auth"?r.jsx(er,{className:"spin",size:19,"aria-hidden":"true"}):r.jsx(Qs,{size:19,"aria-hidden":"true"}),bt==="auth"?"Opening Google…":s?"Checking sign-in…":"Sign in with Google"]}),r.jsx("small",{children:"After sign-in, LiveDesk returns to this installed app."})]}),lt&&r.jsxs("section",{id:"hub-sync-popover",className:"client-hub-switch-popover hub-sync-popover",role:"dialog","aria-modal":"false","aria-labelledby":"hub-sync-title","aria-describedby":"hub-sync-description hub-sync-notice",children:[r.jsxs("header",{className:"client-hub-switch-head",children:[r.jsx("span",{className:"client-hub-switch-mark","aria-hidden":"true",children:r.jsx(ls,{size:19})}),r.jsx("span",{className:"client-hub-switch-eyebrow",children:_a.eyebrow}),r.jsx("button",{className:"client-hub-switch-close",type:"button",onClick:()=>_o(),"aria-label":_a.closeLabel,children:r.jsx(xn,{size:17})})]}),r.jsx("h2",{id:"hub-sync-title",children:_a.title}),r.jsx("p",{id:"hub-sync-description",children:_a.description}),r.jsxs("p",{id:"hub-sync-notice",className:"client-hub-switch-notice",children:[r.jsx(Zt,{size:16,"aria-hidden":"true"}),r.jsx("span",{children:_a.restartNotice})]}),r.jsxs("div",{className:"client-hub-switch-actions",children:[r.jsx("button",{type:"button",onClick:()=>_o(),children:_a.cancel}),r.jsxs("button",{ref:At,className:"primary",type:"button",onClick:fy,disabled:bt==="host",children:[r.jsx(ls,{size:16}),_a.confirm]})]})]}),r.jsxs("section",{className:`desk-stage ${Ca&&!Br?"dock-open":""} ${Xe?"control-stage":""} ${Oc?"agents-stage":""} ${Sa?"file-share-stage":""}`,children:[A&&r.jsxs("header",{className:"mobile-console-header",children:[r.jsxs("span",{className:"mobile-console-brand","aria-label":"LiveDesk mobile Console",children:[r.jsx("span",{className:"mobile-console-brand-mark",children:r.jsx(Zi,{size:18})}),r.jsxs("span",{children:[r.jsx("strong",{children:"LiveDesk"}),r.jsx("small",{children:"Mobile Console"})]})]}),r.jsxs("span",{className:`mobile-console-hub state-${Dy}`,role:"status","aria-live":"polite",children:[r.jsx("i",{"aria-hidden":"true"}),r.jsxs("span",{children:[r.jsx("strong",{children:Ly}),r.jsx("small",{children:_y})]})]}),r.jsxs("span",{className:"mobile-console-header-actions",children:[p&&!N&&(g||v.isIos)&&r.jsx("button",{className:"mobile-console-install",onClick:()=>{I()},"aria-label":"Install LiveDesk app",title:"Install LiveDesk app",type:"button",children:r.jsx(np,{size:19,"aria-hidden":"true"})}),Ih&&r.jsx("button",{className:"mobile-console-update",onClick:()=>{ph()},disabled:ns||!P?.update?.canApply,"aria-label":ns?"LiveDesk update in progress":"Update LiveDesk","aria-busy":ns,type:"button",children:ns?r.jsx("span",{className:"topbar-update-spinner","aria-hidden":"true"}):r.jsx(ic,{size:18,"aria-hidden":"true"})})]})]}),r.jsxs("header",{className:"topbar",children:[r.jsx("div",{className:"topbar-leading",children:Ih?r.jsxs("button",{className:"topbar-update-button",onClick:()=>{ph()},title:vt?.error?`LiveDesk Hub update failed: ${vt.error}`:`Update LiveDesk to ${P?.update?.latestVersion||vt?.targetManagerVersion||"latest"}`,"aria-label":vt?.error?`LiveDesk Hub update failed: ${vt.error}`:ns?"LiveDesk update in progress":`Update LiveDesk to ${P?.update?.latestVersion||vt?.targetManagerVersion||"latest"}`,type:"button",disabled:ns||!P?.update?.canApply,"aria-busy":ns,children:[ns?r.jsx("span",{className:"topbar-update-spinner","aria-hidden":"true"}):r.jsx(ic,{size:19,"aria-hidden":"true"}),ns&&P?.update?.targetCount?r.jsxs("span",{className:"topbar-update-count","aria-hidden":"true",children:[P.update.completedCount||0,"/",P.update.targetCount]}):null]}):null}),r.jsxs("div",{className:"topbar-tray",children:[Sa&&!Xe&&r.jsxs("div",{className:"file-share-top-route","aria-label":"File distribution route",children:[r.jsxs("div",{children:[r.jsx(Ua,{size:17}),r.jsxs("span",{children:[r.jsx("small",{children:"Source"}),r.jsx("strong",{children:"LiveDesk Hub"})]})]}),r.jsx(Lp,{size:15}),r.jsx(gx,{size:16}),r.jsxs("div",{children:[r.jsx("span",{className:"file-share-top-route-laptops",children:"▣ ▣ ▣"}),r.jsxs("span",{children:[r.jsx("small",{children:"Destination"}),r.jsxs("strong",{children:[Im," Client",Im===1?"":"s"]}),r.jsx("em",{children:fs.trim()||"Desktop/LiveDeskFiles"})]})]})]}),Ca&&!Xe&&r.jsxs("div",{className:"top-actions",children:[r.jsx(Ig,{active:Vn,refreshing:Vn&&$r,onClick:kh}),r.jsx(Tg,{active:nn,refreshing:nn&&$r,onClick:Sh}),r.jsx(Pg,{active:qt,refreshing:qt&&$r,onClick:Ch}),r.jsx("span",{className:"top-actions-divider","aria-hidden":"true"}),r.jsx(Rg,{controller:Lm,onError:we}),r.jsx("span",{className:"top-actions-divider","aria-hidden":"true"}),r.jsx("div",{className:"segmented-control wall-cadence-control","aria-label":"Wall frame speed",children:oI.map(l=>r.jsx("button",{className:dr===l.id?"active":"",onClick:()=>{ti(l.id),Fs(l.fps),KP(l.id)},title:l.label+" Wall streaming ("+l.fps+" fps)","aria-pressed":dr===l.id,type:"button",children:l.label},l.id))}),r.jsx("span",{className:"top-actions-divider","aria-hidden":"true"}),r.jsxs("div",{className:"wall-view-control",children:[r.jsx("div",{className:"segmented-control","aria-label":"Wall view",children:cI.map(l=>r.jsx("button",{className:Bt===l.id?"active":"",onClick:()=>bc(l.id),"aria-pressed":Bt===l.id,type:"button",children:l.label},l.id))}),r.jsx("label",{className:"wall-view-slider",htmlFor:"wall-view-scale",children:r.jsx("input",{id:"wall-view-scale",type:"range",min:lu,max:Za,step:1,value:ps,onChange:l=>ms(Number(l.currentTarget.value)),"aria-label":"Wall tile size","aria-valuetext":vc})})]})]}),Xe&&r.jsxs("div",{className:"top-actions",children:[r.jsx(Ig,{active:Vn,refreshing:Vn&&$r,onClick:kh}),r.jsx(Tg,{active:nn,refreshing:nn&&$r,onClick:Sh}),r.jsx(Pg,{active:qt,refreshing:qt&&$r,onClick:Ch}),r.jsx("span",{className:"top-actions-divider","aria-hidden":"true"}),r.jsx(Rg,{controller:Lm,onError:we})]})]})]}),Vn&&Ca&&r.jsx(mT,{items:My,collectedAt:wc,onClose:()=>la(!1)}),Mm?r.jsxs("section",{className:"doc-page",lang:Or,dir:Or==="ar"?"rtl":"ltr",children:[r.jsxs("section",{className:"doc-hero",children:[r.jsxs("div",{className:"doc-hero-copy",children:[r.jsxs("span",{className:"pricing-eyebrow",children:[r.jsx(tu,{size:16}),zn.eyebrow]}),r.jsx("h2",{children:zn.title}),r.jsx("p",{children:zn.intro})]}),r.jsxs("label",{className:"doc-language-picker",children:[r.jsxs("span",{children:[r.jsx(bx,{size:17}),zn.languageLabel]}),r.jsx("select",{value:Or,onChange:l=>yc(l.target.value),children:pI.map(l=>r.jsx("option",{value:l.id,children:l.label},l.id))})]})]}),r.jsx("section",{className:"doc-grid",children:zn.sections.map((l,f)=>{const x=[ls,Gl,Hh,Zt,bu][f]||tu;return r.jsxs("article",{className:"doc-card",children:[r.jsx("div",{className:"doc-card-icon",children:r.jsx(x,{size:19})}),r.jsxs("div",{children:[r.jsx("h3",{children:l.title}),r.jsx("p",{children:l.body}),r.jsx("ul",{children:l.points.map(S=>r.jsx("li",{children:S},S))})]})]},l.title)})}),vl&&r.jsxs("section",{className:"doc-sync",children:[r.jsxs("div",{className:"doc-sync-head",children:[r.jsx(Hh,{size:20}),r.jsxs("div",{children:[r.jsx("h3",{children:vl.title}),r.jsx("p",{children:vl.body})]})]}),r.jsx("ul",{children:vl.points.map(l=>r.jsx("li",{children:l},l))})]}),r.jsxs("section",{className:"doc-firewall",children:[r.jsxs("div",{className:"doc-firewall-head",children:[r.jsx(Zt,{size:20}),r.jsxs("div",{children:[r.jsx("h3",{children:zn.firewall.title}),r.jsx("p",{children:zn.firewall.body})]})]}),r.jsx("ul",{children:zn.firewall.points.map(l=>r.jsx("li",{children:l},l))})]}),r.jsxs("section",{className:"doc-command-panel",children:[r.jsxs("div",{className:"doc-command-head",children:[r.jsx(Gl,{size:20}),r.jsxs("div",{children:[r.jsx("h3",{children:zn.commands.title}),r.jsx("p",{children:zn.commands.body})]})]}),r.jsxs("div",{className:"doc-command-list",children:[zn.commands.manager&&r.jsxs("div",{className:"doc-command-row",children:[r.jsx("span",{children:zn.commands.manager}),r.jsx("code",{children:wh}),r.jsx("button",{className:"icon-button",onClick:()=>Vl(wh),title:"Copy command",type:"button",children:r.jsx(yd,{size:16})})]}),r.jsxs("div",{className:"doc-command-row",children:[r.jsx("span",{children:zn.commands.primary}),r.jsx("code",{children:fl}),r.jsx("button",{className:"icon-button",onClick:()=>Vl(fl),title:"Copy command",type:"button",children:r.jsx(yd,{size:16})})]}),r.jsxs("div",{className:"doc-command-row",children:[r.jsx("span",{children:zn.commands.slot}),r.jsx("code",{children:`${fl} 3`}),r.jsx("button",{className:"icon-button",onClick:()=>Vl(`${fl} 3`),title:"Copy command",type:"button",children:r.jsx(yd,{size:16})})]})]})]})]}):Oc?r.jsx(Mg,{hubUrl:G,devices:D}):Sa?r.jsx(mR,{hubUrl:G,devices:Ze,localFeatureAccess:Rt,upgradeNotice:Si,remoteDirectory:fs,onRemoteDirectoryChange:oo,targetMode:gi,selectedTargetIds:bi,onTargetModeChange:Hw,onTargetToggle:l=>Hu(f=>f.includes(l)?f.filter(b=>b!==l):[...f,l]),filePickerRef:zw,folderPickerRef:qw,onBrowserFileImport:l=>{vh(l)},onBrowserFolderImport:l=>{vh(l)},onNotice:we,onTransferChange:l=>{if(!l){Hs(null);return}const f=l.state==="failed"||l.state==="partially-failed"||l.state==="cancelled"?"failed":l.state==="completed"?"queued":l.state==="sending"?"sending":"reading";Hs({id:l.id,status:f,progress:l.progress,message:l.message}),["completed","partially-failed","failed","cancelled"].includes(l.state)&&window.setTimeout(()=>Hs(b=>b?.id===l.id?null:b),4500)}}):Am?r.jsx(Nb,{session:n,currentProductKey:"livedesk",appVersion:"",onSignIn:_i}):ko?r.jsx(Pk,{hubUrl:G,mobileLayout:A,runtimeRole:P?.runtimeRole||"hub",runtimeDeviceId:P?.deviceId||"",sessionAccessToken:n?.access_token||"",showThisComputerSetting:!A&&P?.runtimeRole==="hub",onShowThisComputerChange:ie,pin:r.jsxs(Ik,{children:[r.jsx("div",{className:"settings-section-grid",children:r.jsxs("section",{className:"settings-section-card settings-pairing-card",children:[r.jsxs("div",{className:"settings-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"Pair a Client"}),r.jsx("h3",{children:"Connect another local PC"})]}),r.jsx(pn,{size:20})]}),r.jsxs("div",{className:"settings-pin-display",children:[r.jsx("span",{children:"Hub PIN"}),r.jsx("strong",{children:Fy}),r.jsxs("button",{className:"text-button ghost compact",onClick:gy,disabled:!P?.started||bt==="pin",type:"button",children:[r.jsx(Ns,{size:15}),bt==="pin"?"Creating":"New PIN"]})]})]})}),r.jsxs("section",{className:"settings-section-card",children:[r.jsxs("div",{className:"settings-section-heading",children:[r.jsxs("div",{children:[r.jsx("span",{children:"File transfer"}),r.jsx("h3",{children:"Client destination folder"})]}),r.jsx(Ji,{size:20})]}),r.jsxs("label",{className:"settings-field",children:[r.jsx("span",{children:"Remote folder"}),r.jsx("input",{value:fs,onChange:l=>oo(l.target.value),placeholder:"Desktop/LiveDeskFiles"})]}),r.jsx("p",{className:"settings-help",children:"Blank uses Desktop/LiveDeskFiles on each Client."})]})]}),desktopUpdate:r.jsx(Rb,{}),agent:r.jsx(Ek,{hubUrl:G,showToast:we}),captureGallery:r.jsx(pT,{hubUrl:G,onToast:we})}):km?r.jsxs("section",{className:"pricing-page",children:[r.jsxs("header",{className:"pricing-header",children:[r.jsxs("div",{children:[r.jsxs("span",{className:"pricing-eyebrow",children:[r.jsx(ap,{size:15})," LiveDesk plans"]}),r.jsx("h2",{children:"Choose the plan that fits your wall"}),r.jsx("p",{children:"Free supports up to 5 personal devices with a standard banner. Upgrade for an ad-free wall, more Clients, or commercial use."})]}),r.jsx("button",{className:"pricing-close",onClick:()=>La("wall"),title:"Close pricing",type:"button",children:r.jsx(xn,{size:18})})]}),r.jsxs("div",{className:"pricing-status","aria-live":"polite",children:[r.jsx("span",{children:"Current plan"}),r.jsx("strong",{children:Fm.name}),r.jsxs("small",{children:[Ze.length,"/",xP(Ku)," connected devices"]})]}),r.jsxs("div",{className:"pricing-cards","aria-label":"LiveDesk plans",children:[r.jsxs("article",{className:`pricing-plan-card ${Qt==="free"?"current":""}`,children:[r.jsxs("div",{className:"pricing-plan-topline",children:[r.jsx("span",{className:"pricing-plan-badge free",children:"Free"}),r.jsx("strong",{children:"$0"})]}),r.jsx("p",{className:"pricing-plan-audience",children:Ms.free.audience}),r.jsx("h3",{children:"Free personal screen wall"}),r.jsx("p",{children:Ms.free.note}),r.jsxs("ul",{children:[r.jsxs("li",{children:[r.jsx(En,{size:16})," Up to ",yl," devices"]}),r.jsxs("li",{children:[r.jsx(En,{size:16})," Live view and local control"]}),r.jsxs("li",{children:[r.jsx(En,{size:16})," Standard banner helps keep Free available"]})]}),r.jsx("span",{className:"pricing-current-label",children:Qt==="free"?"Current plan":"Included for everyone"})]}),r.jsxs("article",{className:`pricing-plan-card featured ${Qt==="ltd"?"current":""}`,children:[r.jsxs("div",{className:"pricing-plan-topline",children:[r.jsxs("span",{className:"pricing-plan-badge plus",children:[r.jsx(vx,{size:14})," Plus"]}),r.jsxs("span",{className:"pricing-plan-price",children:[r.jsx("strong",{children:Ms.ltd.price}),r.jsx("small",{children:"/ month"})]})]}),r.jsx("p",{className:"pricing-plan-audience",children:Ms.ltd.audience}),r.jsx("h3",{children:"Ad-free personal wall"}),r.jsx("p",{children:"Monitor up to 30 personal computers without the standard banner."}),r.jsxs("ul",{children:[r.jsxs("li",{children:[r.jsx(En,{size:16})," Up to ",Ho," devices"]}),r.jsxs("li",{children:[r.jsx(En,{size:16})," No standard ad banner"]})]}),r.jsxs("div",{className:"pricing-ltd-offer",children:[r.jsx("span",{children:"Plus LTD"}),r.jsx("strong",{children:Ms.ltd.ltd}),r.jsx("small",{children:"One-time · available now"})]}),r.jsxs("button",{className:"pricing-plan-button",onClick:n?()=>dd("ltd"):_i,disabled:Qt!=="free"||bt==="checkout"||bt==="auth"||s||de,type:"button",children:[r.jsx(ec,{size:16}),Qt==="free"?n?"Buy Plus LTD · $79":"Sign in for Plus LTD":"Plus active"]})]}),r.jsxs("article",{className:`pricing-plan-card pro ${Qt==="pro"?"current":""}`,children:[r.jsxs("div",{className:"pricing-plan-topline",children:[r.jsxs("span",{className:"pricing-plan-badge pro",children:[r.jsx(Zt,{size:14})," Pro"]}),r.jsxs("span",{className:"pricing-plan-price",children:[r.jsx("strong",{children:Ms.pro.price}),r.jsx("small",{children:"/ month"})]})]}),r.jsx("p",{className:"pricing-plan-audience",children:Ms.pro.audience}),r.jsx("h3",{children:"Commercial monitoring"}),r.jsx("p",{children:"For studios, offices, teams, and any other business use."}),r.jsxs("ul",{children:[r.jsxs("li",{children:[r.jsx(En,{size:16})," More than ",Ho," connected Clients"]}),r.jsxs("li",{children:[r.jsx(En,{size:16})," Ad-free commercial use"]})]}),r.jsxs("div",{className:"pricing-ltd-offer pro",children:[r.jsx("span",{children:"Pro LTD"}),r.jsx("strong",{children:Ms.pro.ltd}),r.jsx("small",{children:"One-time · available now"})]}),r.jsxs("button",{className:"pricing-plan-button",onClick:n?()=>dd("pro"):_i,disabled:Qt==="pro"||bt==="checkout"||bt==="auth"||s||de,type:"button",children:[r.jsx(ec,{size:16}),Qt==="pro"?"Pro active":n?"Buy Pro LTD · $199":"Sign in for Pro LTD"]})]})]}),r.jsxs("section",{className:"pricing-includes",children:[r.jsxs("div",{children:[r.jsx(pn,{size:17}),r.jsx("span",{children:"Screen wall"}),r.jsx("strong",{children:"120+ layout slots"})]}),r.jsxs("div",{children:[r.jsx(Ko,{size:17}),r.jsx("span",{children:"Focused control"}),r.jsx("strong",{children:"Local-first"})]}),r.jsxs("div",{children:[r.jsx(xd,{size:17}),r.jsx("span",{children:"Remote audio"}),r.jsx("strong",{children:"Available"})]}),r.jsxs("div",{children:[r.jsx(Ji,{size:17}),r.jsx("span",{children:"File transfer"}),r.jsx("strong",{children:"Included"})]})]}),r.jsxs("p",{className:"pricing-note",children:[r.jsx(En,{size:15})," Free includes a standard banner for personal use. Plus removes the banner for personal, creator, and homelab use. Commercial use requires Pro."]}),r.jsxs("button",{className:"pricing-primary-cta",onClick:n?()=>dd(Qt==="ltd"?"pro":"ltd"):_i,disabled:Iy,type:"button",children:[r.jsx(ec,{size:18}),Py]})]}):r.jsx(r.Fragment,{children:r.jsxs("section",{className:`monitor-layout ${Br?"dock-collapsed":""}`,children:[r.jsxs("section",{ref:Sm,className:`screen-wall-panel ${Ow?"drop-active":""}`,onClick:l=>{l.currentTarget===l.target&&$o()},onDragEnter:l=>{l.preventDefault(),Bu(!0)},onDragOver:l=>{l.preventDefault(),l.dataTransfer.dropEffect="copy"},onDragLeave:l=>{l.currentTarget===l.target&&Bu(!1)},onDrop:xy,children:[Qn.length>0&&r.jsx("canvas",{ref:sy,className:"atlas-source-canvas",width:Ia?.width||1920,height:Ia?.height||1080,"aria-hidden":"true"}),A&&Ca&&!Xe&&r.jsxs("section",{className:"mobile-console-selection","aria-label":"Selected computer actions",children:[r.jsxs("div",{className:"mobile-console-selection-copy",children:[r.jsx("span",{children:"Selected computer"}),r.jsx("strong",{children:Rh}),r.jsx("small",{children:fe?`${fe.platform||"Client"} · ${os(fe)} display${os(fe)===1?"":"s"}`:"Tap a computer below, then choose an action."})]}),r.jsxs("div",{className:"mobile-console-actions",role:"toolbar","aria-label":"Selected computer quick actions",children:[r.jsxs("button",{onClick:()=>fe&&void Da(fe.deviceId),disabled:!Pr||!!be,type:"button",children:[r.jsx(Ko,{size:17}),r.jsx("span",{children:"Control"})]}),r.jsxs("button",{className:Ie?"active":"",onClick:()=>{hh()},disabled:!Qu||!!be,"aria-pressed":Ie,type:"button",children:[be==="audio"?r.jsx(er,{className:"spin",size:17}):r.jsx(xd,{size:17}),r.jsx("span",{children:"Audio"})]}),r.jsxs("button",{className:xs?"":"active",onClick:()=>{fh()},disabled:Kn.length===0||!!be,"aria-pressed":!xs,type:"button",children:[be==="video"?r.jsx(er,{className:"spin",size:17}):xs?r.jsx(Wh,{size:17}):r.jsx(zh,{size:17}),r.jsx("span",{children:xs?"Pause":"Resume"})]}),r.jsxs("button",{onClick:()=>{hl("restart")},disabled:!fe||!Rt||!!be||!Na,type:"button",children:[be==="restart"?r.jsx(er,{className:"spin",size:17}):r.jsx(sp,{size:17}),r.jsx("span",{children:"Restart"})]})]})]}),Xe?r.jsx("section",{className:"control-focus",children:r.jsxs("div",{className:"control-wall",children:[fe&&r.jsxs("div",{className:"control-monitor-tabs","aria-label":`Select monitor for ${dn(fe)}`,children:[r.jsx("strong",{className:"control-computer-name",title:dn(fe),children:dn(fe)}),Sy.map(l=>r.jsxs("button",{className:l.index===gl?"active":"",onClick:()=>by(fe.deviceId,l.index),title:OP(l),type:"button",children:[r.jsx("span",{children:l.name||`Display ${l.index+1}`}),l.width>0&&l.height>0&&r.jsxs("small",{children:[l.width,"x",l.height]})]},l.index))]}),fe&&ts&&r.jsxs("div",{className:"control-modifier-bar","aria-label":"Hold remote modifier keys",children:[A&&r.jsxs(r.Fragment,{children:[r.jsx("button",{className:`remote-keyboard-button ${R?"active":""}`,type:"button","aria-pressed":R,"aria-label":"Open remote keyboard",title:"Open the phone keyboard for the remote computer",onClick:()=>{const l=Y.current;l&&(l.focus({preventScroll:!0}),l.setSelectionRange(l.value.length,l.value.length))},children:r.jsx(wx,{size:15,"aria-hidden":"true"})}),r.jsx("textarea",{ref:Y,className:"remote-keyboard-input","aria-label":"Type on the remote computer",autoComplete:"off",autoCorrect:"off",autoCapitalize:"sentences",enterKeyHint:"enter",spellCheck:!1,rows:1,onFocus:()=>se(!0),onBlur:()=>{K.current=!1,se(!1)},onCompositionStart:()=>{K.current=!0},onCompositionEnd:l=>{K.current=!1;const f=l.currentTarget.value;l.currentTarget.value="",pe.current?.sendText(f)},onInput:l=>{if(K.current)return;const f=l.currentTarget.value;l.currentTarget.value="",pe.current?.sendText(f)},onKeyDown:l=>{l.nativeEvent.isComposing||!Rl(l.key)||(l.preventDefault(),l.stopPropagation(),lh(l.key,"keydown"))},onBeforeInput:l=>{const f=l.nativeEvent.inputType||"";Rl(f)&&(l.preventDefault(),l.stopPropagation(),lh(f,"beforeinput"))}})]}),ZT.map(l=>{const f=l.code==="MetaLeft"&&cs(fe.platform)?"Cmd":l.label,b=mt.includes(l.code);return r.jsx("button",{className:b?"active":"",type:"button","aria-pressed":b,title:`Hold ${f} on the remote computer`,onClick:()=>z.current?.(l.code),children:f},l.code)})]}),fe?r.jsx(tp,{device:fe,frame:Ne,selected:!1,controlEnabled:Pr&&_e&&ts,showStatus:rn.showScreenStatus,showDeviceTitle:!1,monitorIndex:lr(fe,Ct[fe.deviceId]),monitorCount:os(fe),onSelect:()=>{},onFocusDevice:()=>Se(fe.deviceId),onOpenControl:()=>Da(fe.deviceId),onCycleMonitor:l=>ud(fe.deviceId,l),onCanvasReady:ry,sendInput:Fo,remoteModifierState:rd,presentationReady:Lu,remoteDiagnostics:qt?Oo.get(fe.deviceId):nn?Bi.get(fe.deviceId):void 0,diagnosticsMode:qt?"debug":"remote"},fe.deviceId):r.jsxs("div",{className:"control-empty",children:[r.jsx(pn,{size:30}),r.jsx("strong",{children:"No Client"}),r.jsx("span",{children:"Open a Client from the Wall."})]}),fe&&Gu&&r.jsxs("div",{className:"control-connection-overlay",role:"alert",children:[r.jsx(Zt,{size:22,"aria-hidden":"true"}),r.jsx("strong",{children:"Accessibility permission required"}),r.jsx("small",{children:"On the Mac, allow Accessibility for the terminal app that starts LiveDesk, then restart the Mac client."})]}),fe&&!Gu&&!Lu&&r.jsxs("div",{className:"control-connection-overlay",role:"status","aria-live":"polite",children:[ae!=="error"&&r.jsx("span",{className:"control-connection-spinner","aria-hidden":"true"}),r.jsx("strong",{children:ae==="error"?"Connection failed":"Connecting"}),r.jsx("small",{children:ae==="error"?"See the notification for details. Reopen Control to retry.":To||ve?"Control stream is recovering. See the notification for details.":ed==="open"?"Preparing the first control frame":"Opening the Control stream"})]})]})}):Bt==="list"?r.jsxs("div",{className:"wall-device-list",role:"grid","aria-label":"Computer status list",children:[r.jsxs("div",{className:"wall-device-list-head",role:"row",children:[r.jsx("span",{role:"columnheader",children:"Computer"}),r.jsx("span",{role:"columnheader",children:"Status"}),r.jsx("span",{role:"columnheader",children:"CPU"}),r.jsx("span",{role:"columnheader",children:"GPU"}),r.jsx("span",{role:"columnheader",children:"RAM"}),r.jsx("span",{role:"columnheader",children:"VRAM"}),r.jsx("span",{role:"columnheader",children:"Network"}),r.jsx("span",{role:"columnheader",children:"HDD"}),r.jsx("span",{role:"columnheader",children:"Temp"})]}),jm.length>0?jm.map(({device:l,slotNumber:f})=>r.jsx(fI,{device:l,slotNumber:f,selected:Aa.has(l.deviceId),updateIndicator:bd(l.deviceId),remoteDiagnostics:qt?Oo.get(l.deviceId):nn?Bi.get(l.deviceId):void 0,diagnosticsMode:qt?"debug":"remote",onSelect:()=>ld(l.deviceId),onOpenControl:()=>Da(l.deviceId)},l.deviceId)):r.jsxs("div",{className:"wall-device-list-empty",children:[r.jsx(pn,{size:24,"aria-hidden":"true"}),r.jsx("strong",{children:"No connected computers"})]})]}):St?r.jsx("div",{className:`screen-wall atlas-slot-wall size-${Bt}`,style:ia,onClick:l=>{l.currentTarget===l.target&&$o()},children:Ma.map((l,f)=>l?r.jsx(tp,{device:l,frame:Ri.get(l.deviceId),selected:Aa.has(l.deviceId),controlEnabled:!1,showStatus:co,monitorIndex:lr(l,Ct[l.deviceId]),monitorCount:os(l),onSelect:()=>ld(l.deviceId),onFocusDevice:()=>cd(l.deviceId),onOpenControl:()=>Da(l.deviceId),onCycleMonitor:b=>ud(l.deviceId,b),onCanvasReady:zo({mode4Enabled:St,directMode4WallEnabled:Xr,isMac:cs(l.platform)})==="direct"?_m:ay,sendInput:Fo,remoteModifierState:rd,updateIndicator:bd(l.deviceId),presentationReady:ot.autoStartLive&&gr.includes(l.deviceId)?Eu.has(l.deviceId):void 0,showPresentationSpinner:ot.autoStartLive&&gr.includes(l.deviceId),remoteDiagnostics:qt?Oo.get(l.deviceId):nn?Bi.get(l.deviceId):void 0,diagnosticsMode:qt?"debug":"remote"},l.deviceId):r.jsx(ib,{index:f},`slot-${f}`))}):r.jsx("div",{className:`screen-wall size-${Bt}`,style:ia,onClick:l=>{l.currentTarget===l.target&&$o()},children:Ma.map((l,f)=>l?r.jsx(tp,{device:l,frame:Ri.get(l.deviceId),selected:Aa.has(l.deviceId),controlEnabled:Pr&&_e&&ts&&fe?.deviceId===l.deviceId,showStatus:co,monitorIndex:lr(l,Ct[l.deviceId]),monitorCount:os(l),onSelect:()=>ld(l.deviceId),onFocusDevice:()=>cd(l.deviceId),onOpenControl:()=>Da(l.deviceId),onCycleMonitor:b=>ud(l.deviceId,b),onCanvasReady:_m,sendInput:Fo,remoteModifierState:rd,updateIndicator:bd(l.deviceId),presentationReady:ot.autoStartLive&&gr.includes(l.deviceId)?Eu.has(l.deviceId):void 0,showPresentationSpinner:ot.autoStartLive&&gr.includes(l.deviceId),remoteDiagnostics:qt?Oo.get(l.deviceId):nn?Bi.get(l.deviceId):void 0,diagnosticsMode:qt?"debug":"remote"},l.deviceId):r.jsx(ib,{index:f},`slot-${f}`))}),r.jsx(vI,{visible:ey&&!Xe})]}),!ko&&r.jsxs("aside",{className:`right-dock actions-mode ${Br?"collapsed":""}`,"aria-label":"LiveDesk tools",children:[r.jsx("button",{className:"dock-toggle",onClick:()=>io(l=>!l),"aria-label":Br?"Show control panel":"Hide control panel",title:Br?"Show control panel":"Hide control panel",type:"button",children:Br?r.jsx(Ab,{size:18}):r.jsx(_p,{size:18})}),!Br&&r.jsxs(r.Fragment,{children:[r.jsxs("section",{className:"action-dock",children:[r.jsx("input",{ref:Cm,className:"hidden-file-input",type:"file",multiple:!0,onChange:l=>{l.currentTarget.files&&bh(l.currentTarget.files),l.currentTarget.value=""}}),r.jsxs("div",{className:"manual-action-bar",role:"toolbar","aria-label":"Manual Client controls",children:[r.jsx(Ba,{label:"Control",tooltip:fe?Gu?"Allow Accessibility for the terminal app that starts LiveDesk, then restart the Mac client.":Pr?ts?"Keyboard and mouse control is ready":"Waiting for the current Control capture session":"Remote control is not available on this Client":"Select a Client to use Control",onClick:()=>{if(fe){if(Xe&&_e){$e(!1),we("Remote control paused. Screen viewing stays on.");return}Da(fe.deviceId)}},disabled:!Pr||!!be,active:_e,pressed:Xe&&_e,children:r.jsx(Ko,{size:17})}),r.jsx(Ba,{label:"Audio",tooltip:fe?Tr?Ie?"Stop hearing this Client":"Hear this Client":"Audio is not available on this Client":"Select a Client to use Audio",onClick:()=>{hh()},disabled:!Qu||!!be,active:Ie,pressed:Ie,children:be==="audio"?r.jsx(er,{className:"spin",size:17}):r.jsx(xd,{size:17})}),r.jsx(Ba,{label:qc?"Retry pause":xs?"Pause video":"Resume video",tooltip:Ao.length===0?"Select one or more Clients to pause video":qc?"Retry every selected Client whose capture shutdown is unconfirmed":xs?`Pause video for ${Kn.length} selected Client${Kn.length===1?"":"s"}`:`Resume video for ${Kn.length} selected Client${Kn.length===1?"":"s"}`,onClick:()=>{fh()},disabled:Kn.length===0||!!be,active:!xs,pressed:!xs,children:be==="video"?r.jsx(er,{className:"spin",size:17}):!xs&&!qc?r.jsx(zh,{size:17}):r.jsx(Wh,{size:17})}),r.jsx(Ba,{label:"Send files",tooltip:An.length===0&&!Xe?"Select one or more Clients to send files":fe?"Choose files and send them to the selected Client":"Select a Client to send files",onClick:()=>{we(`Choose files to send to ${Rh}.`),Cm.current?.click()},disabled:!!be||!Rt||(Xe?!fe:An.length===0),children:r.jsx(Ji,{size:17})}),r.jsx(Ba,{label:"Restart",tooltip:fe?Na?"Restart Client":"Restart is not available on this Client":"Select a Client to restart",onClick:()=>{hl("restart")},disabled:!fe||!Rt||!!be||!Na,children:be==="restart"?r.jsx(er,{className:"spin",size:17}):r.jsx(sp,{size:17})}),r.jsx(Ba,{label:"Sleep",tooltip:fe?Na?"Put Client to sleep":"Sleep is not available on this Client":"Select a Client to put to sleep",onClick:()=>{hl("sleep")},disabled:!fe||!Rt||!!be||!Na,children:be==="sleep"?r.jsx(er,{className:"spin",size:17}):r.jsx(yx,{size:17})}),r.jsx(Ba,{label:"Shut down",tooltip:fe?Na?"Shut down Client":"Shut down is not available on this Client":"Select a Client to shut down",onClick:()=>{hl("shutdown")},disabled:!fe||!Rt||!!be||!Na,danger:!0,children:be==="shutdown"?r.jsx(er,{className:"spin",size:17}):r.jsx(vb,{size:17})})]})]}),r.jsx(Mg,{hubUrl:G,devices:D,variant:"dock",selectedDeviceIds:Ry})]})]})]})})]}),A&&r.jsxs("nav",{className:"mobile-console-nav","aria-label":"Mobile Console pages",children:[r.jsxs("button",{className:pr?"active":"",onClick:()=>sr(l=>{const f=!l;return YP(f),f}),type:"button","aria-label":pr?"Hide computer stats":"Show computer stats","aria-pressed":pr,title:pr?"Hide CPU, GPU, RAM, and online status":"Show CPU, GPU, RAM, and online status",children:[r.jsx(xx,{size:19}),r.jsx("span",{children:"Stats"})]}),r.jsxs("button",{className:jt==="wall"?"active":"",onClick:()=>La("wall"),type:"button",children:[r.jsx(Mb,{size:19}),r.jsx("span",{children:"Wall"})]}),r.jsxs("button",{className:Xe?"active":"",onClick:()=>fe&&void Da(fe.deviceId),disabled:!fe||!Pr,type:"button",children:[r.jsx(Ko,{size:19}),r.jsx("span",{children:"Control"})]}),r.jsxs("button",{className:Sa?"active":"",onClick:()=>La("share-files"),type:"button",children:[r.jsx(tc,{size:19}),r.jsx("span",{children:"Files"})]}),r.jsxs("button",{className:Oc?"active":"",onClick:()=>La("agents"),type:"button",children:[r.jsx(Gl,{size:19}),r.jsx("span",{children:"Agents"})]}),r.jsxs("button",{className:ko?"active":"",onClick:()=>La("settings"),type:"button",children:[r.jsx(nu,{size:19}),r.jsx("span",{children:"Settings"})]})]}),xa&&r.jsxs("aside",{className:`transfer-bar state-${xa.status}`,"aria-live":"polite",children:[r.jsx("span",{className:"transfer-bar-icon","aria-hidden":"true",children:xa.status==="queued"?r.jsx(En,{size:18}):xa.status==="failed"?r.jsx(xn,{size:18}):r.jsx(wb,{size:18})}),r.jsxs("div",{className:"transfer-bar-copy",children:[r.jsx("p",{children:xa.message}),r.jsx("div",{className:"transfer-bar-track",children:r.jsx("span",{style:{width:`${Math.max(0,Math.min(100,xa.progress))}%`}})})]}),r.jsxs("strong",{children:[Math.max(0,Math.min(100,xa.progress)),"%"]})]}),zt&&r.jsxs("aside",{className:`livedesk-toast tone-${zt.tone}`,role:zt.tone==="error"?"alert":"status","aria-live":zt.tone==="error"?"assertive":"polite","aria-busy":zt.tone==="progress",children:[zt.tone==="progress"&&r.jsx("span",{className:"livedesk-toast-spinner","aria-hidden":"true"}),r.jsx("span",{children:zt.message}),r.jsx("button",{className:"livedesk-toast-close",onClick:()=>we(""),type:"button","aria-label":"Dismiss notification",title:"Dismiss notification",children:r.jsx(xn,{size:15})})]})]})}const yI=1e3,xI=5e3;function SI(){return typeof window>"u"?!1:(!!window.navigator.standalone||window.matchMedia("(display-mode: standalone), (display-mode: fullscreen)").matches)&&window.matchMedia("(pointer: coarse)").matches}function CI(){return typeof window>"u"?[]:[...new Set([window.location.origin,an].filter(Boolean))]}function VI(){const t=eu(),n=SI(),s=t||n,a=t||typeof window>"u"?an:window.location.origin,i=s?{role:"hub",baseUrl:a}:null,[c,u]=o.useState(i),d=o.useRef(null);return o.useEffect(()=>{if(s){u(k=>k?.role==="hub"&&k.baseUrl===a?k:{role:"hub",baseUrl:a});return}let p=!1,h=!1,m=null;const g=new AbortController,w=async()=>{for(const k of CI()){if(g.signal.aborted)return;try{const C=(await Oe("/api/runtime/status",{signal:g.signal,timeoutMs:900},k)).role==="hub"?"hub":"client";h=!0,p||u(A=>A?.role===C&&A.baseUrl===k?A:{role:C,baseUrl:k});return}catch{if(g.signal.aborted)return}}},v=()=>{Ya(d,w).finally(()=>{!p&&!g.signal.aborted&&(m=window.setTimeout(v,h?xI:yI))}).catch(()=>{})};v();const y=window.setTimeout(()=>{!p&&!h&&u(k=>k?.role==="client"&&k.baseUrl===an?k:{role:"client",baseUrl:an})},2500);return()=>{p=!0,g.abort(new Error("LiveDesk runtime role probe stopped.")),m!==null&&window.clearTimeout(m),window.clearTimeout(y)}},[null,s,a]),c?c.role==="client"?r.jsx(vS,{runtimeBaseUrl:c.baseUrl}):r.jsx(wI,{runtimeBaseUrl:c.baseUrl}):r.jsxs("main",{className:"runtime-role-boot","aria-busy":"true","aria-label":"Starting LiveDesk",children:[r.jsx("span",{className:"runtime-role-boot-mark","aria-hidden":"true"}),r.jsx("strong",{children:"Starting LiveDesk"}),r.jsx("p",{children:"Loading this computer's assigned role..."})]})}export{VI as LiveDeskApp};