@camstack/addon-admin-ui 0.1.18 → 0.1.19
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.
- package/dist/assets/{_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-CziSE-Do.js → _virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-DP-TohD5.js} +1 -1
- package/dist/assets/{auth-records-BEfan3dC.js → auth-records-pPU2T5YK.js} +1 -1
- package/dist/assets/{capability-router-map-B3jHfbHt.js → capability-router-map-CnswfTnw.js} +1 -1
- package/dist/assets/{devices-BfsgGvwu.js → devices-DmhCpmLN.js} +1 -1
- package/dist/assets/{hostInit-7yPTCcmg.js → hostInit-Burx4GuM.js} +1 -1
- package/dist/assets/{index-cfq-Npln.js → index-CQLrpnMs.js} +1 -1
- package/dist/assets/{index-K1-f6oQr.js → index-CXbDmdLy.js} +1 -1
- package/dist/assets/{index-Bzz7AnXl.js → index-CZAjr0Nt.js} +2 -2
- package/dist/assets/{index-iCcWZGKs.js → index-DJUPuA7C.js} +1 -1
- package/dist/assets/{index-DfH297U6.js → index-DlYD2xgP.js} +1 -1
- package/dist/assets/{index-ptcmLXsE.js → index-Dq4t4mCo.js} +1 -1
- package/dist/assets/index-Dv_f5EEQ.js +1 -0
- package/dist/assets/{index-BlKJSHE9.js → index-gpRVuU7E.js} +1 -1
- package/dist/assets/{index-X-IEwb-L.js → index-hps9vVhf.js} +1 -1
- package/dist/assets/{index-Dvmk3HcY.js → index-xPcbbtKN.js} +1 -1
- package/dist/assets/{remoteEntry-Da_G1gka.js → remoteEntry-BJyQcDUE.js} +1 -1
- package/dist/assets/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-kSAHDLPS.js → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-24aug5i6.js} +2 -2
- package/dist/index.html +5 -5
- package/dist/mf-entry-bootstrap-0.js +2 -2
- package/dist/sw.js +1 -1
- package/package.json +1 -1
- package/dist/assets/index-C-M4yvxf.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import"./virtualExposes-_ivNhQLP.js";import{d as fr}from"./virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-
|
|
1
|
+
import"./virtualExposes-_ivNhQLP.js";import{d as fr}from"./virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-24aug5i6.js";import{c as r,a as $f,d as u,e as ve,g as Q1}from"./__mfe_internal__admin_ui_host__loadShare__react_mf_1_jsx_mf_2_runtime__loadShare__.mjs-C_6K4VBY.js";import{b as Oe,e as $,h as q,c as Y,f as Q,d as ye,a as _f,j as Ve,k as Me,i as ne,l as mr,m as Ws,g as Ys,R as Pl,n as El,o as U1,p as K1,q as hr,r as je,s as G1,t as W1,u as Y1,v as Z1}from"./__mfe_internal__admin_ui_host__loadShare__react__loadShare__.mjs-Dl4u0xYE.js";import{a as Df,b as vo}from"./__mfe_internal__admin_ui_host__loadShare__react_mf_2_dom__loadShare__.mjs-CzO_Esxm.js";import{a as Lf,b as Tf}from"./__mfe_internal__admin_ui_host__loadShare__react_mf_2_dom_mf_1_client__loadShare__.mjs-DNpf5SLz.js";import{_ as Rf,m as Kn,n as ke,o as Of,p as zf,h as $l,j as X1}from"./__mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.mjs-CeLhKMin.js";import{_ as Bf,c as Ff,s as jf,n as J1,B as ew,F as tw}from"./__mfe_internal__admin_ui_host__loadShare___mf_0_trpc_mf_1_client__loadShare__.mjs-DIkg6-MH.js";import{_ as Hf,a as nw}from"./__mfe_internal__admin_ui_host__loadShare___mf_0_trpc_mf_1_react_mf_2_query__loadShare__.mjs-OcRSBqRe.js";import{c as rw,D as Rn,a as at,M as ow,W as _i,S as ps}from"./auth-records-pPU2T5YK.js";import{S as Di,c as Vf}from"./devices-DmhCpmLN.js";import{E as Ne,A as sw,C as aw}from"./capability-router-map-CnswfTnw.js";import{s as iw}from"./index-xPcbbtKN.js";import{a as Pd,S as Ed,s as lw}from"./index-DlYD2xgP.js";import{r as qf}from"./__mfe_internal__admin_ui_host__loadShare__react__loadShare__.mjs_commonjs-proxy-CSyOECfO.js";import"./preload-helper-BlTxHScW.js";import"./__mfe_internal__admin_ui_host__loadShare__react_mf_2_dom__loadShare__.mjs_commonjs-proxy-xw6c6JeS.js";import"./schemas-XgIEoUz3.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))o(s);new MutationObserver(s=>{for(const a of s)if(a.type==="childList")for(const i of a.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&o(i)}).observe(document,{childList:!0,subtree:!0});function n(s){const a={};return s.integrity&&(a.integrity=s.integrity),s.referrerPolicy&&(a.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?a.credentials="include":s.crossOrigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function o(s){if(s.ep)return;s.ep=!0;const a=n(s);fetch(s.href,a)}})();const Qf={frigate:"#3b82f6",scrypted:"#a855f7",reolink:"#06b6d4",homeAssistant:"#22d3ee",rtsp:"#78716c"},Uf={primary:"#f59e42",primaryForeground:"#0c0a09",background:"#0c0a09",backgroundElevated:"#1c1917",surface:"#1c1917",surfaceHover:"#292524",border:"#292524",borderSubtle:"#1c1917",foreground:"#fafaf9",foregroundMuted:"#a8a29e",foregroundSubtle:"#78716c",foregroundDisabled:"#57534e",success:"#4ade80",warning:"#fbbf24",danger:"#f87171",info:"#60a5fa",provider:Qf},Kf={primary:"#e67e22",primaryForeground:"#ffffff",background:"#fafaf9",backgroundElevated:"#ffffff",surface:"#f5f5f4",surfaceHover:"#e7e5e4",border:"#d6d3d1",borderSubtle:"#e7e5e4",foreground:"#1c1917",foregroundMuted:"#57534e",foregroundSubtle:"#78716c",foregroundDisabled:"#a8a29e",success:"#16a34a",warning:"#d97706",danger:"#dc2626",info:"#2563eb",provider:Qf},Li={colors:{dark:Uf,light:Kf},spacing:{xs:2,sm:4,md:8,lg:12,xl:16,"2xl":24,"3xl":32},radius:{sm:4,md:6,lg:8,xl:12},typography:{fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',sizes:{xs:{fontSize:10,lineHeight:14},sm:{fontSize:11,lineHeight:16},base:{fontSize:12,lineHeight:18},lg:{fontSize:13,lineHeight:18},xl:{fontSize:14,lineHeight:20},"2xl":{fontSize:16,lineHeight:22},"3xl":{fontSize:20,lineHeight:28}},weights:{regular:400,medium:500,semibold:600,bold:700}},table:{rowHeight:28,headerHeight:24,cellPaddingX:8,cellPaddingY:6},sidebar:{width:176,itemHeight:28,iconSize:14}};function Gf(e,t){const n={...e};for(const o in t){const s=t[o],a=e[o];s!==void 0&&typeof s=="object"&&s!==null&&!Array.isArray(s)&&typeof a=="object"&&a!==null?n[o]=Gf(a,s):s!==void 0&&(n[o]=s)}return n}function cw(e){return e?Gf(structuredClone(Li),e):structuredClone(Li)}function Wf(e){return e.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`)}function dw(e){return`--color-${Wf(e)}`}function $d(e){const t=[];for(const[n,o]of Object.entries(e))n!=="provider"&&t.push(` ${dw(n)}: ${o};`);return t.join(`
|
|
2
2
|
`)}function uw(e){const t=[];for(const[n,o]of Object.entries(e))t.push(` --color-provider-${Wf(n)}: ${o};`);return t.join(`
|
|
3
3
|
`)}function pw(e){const t=[];for(const[n,o]of Object.entries(e))t.push(` --spacing-${n}: ${o}px;`);return t.join(`
|
|
4
4
|
`)}function fw(e){const t=[];for(const[n,o]of Object.entries(e))t.push(` --radius-${n}: ${o}px;`);return t.join(`
|
|
@@ -1081,7 +1081,7 @@ Please change the parent <Route path="${x}"> to <Route path="${x==="/"?"*":`${x}
|
|
|
1081
1081
|
* This source code is licensed under the MIT license found in the
|
|
1082
1082
|
* LICENSE file in the root directory of this source tree.
|
|
1083
1083
|
*/var yr=qf;function RR(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var OR=typeof Object.is=="function"?Object.is:RR,zR=yr.useState,BR=yr.useEffect,FR=yr.useLayoutEffect,jR=yr.useDebugValue;function HR(e,t){var n=t(),o=zR({inst:{value:n,getSnapshot:t}}),s=o[0].inst,a=o[1];return FR(function(){s.value=n,s.getSnapshot=t,di(s)&&a({inst:s})},[e,n,t]),BR(function(){return di(s)&&a({inst:s}),e(function(){di(s)&&a({inst:s})})},[e]),jR(n),n}function di(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!OR(e,n)}catch{return!0}}function VR(e,t){return t()}var qR=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?VR:HR;_y.useSyncExternalStore=yr.useSyncExternalStore!==void 0?yr.useSyncExternalStore:qR;$y.exports=_y;var Dy=$y.exports;const QR=(e,t)=>{if(Hn(t))return t;if(SR(t)&&Hn(t.defaultValue))return t.defaultValue;if(typeof e=="function")return"";if(Array.isArray(e)){const n=e[e.length-1];return typeof n=="function"?"":n}return e},UR={t:QR,ready:!1},KR=()=>()=>{},zt=(e,t={})=>{const{i18n:n}=t,{i18n:o,defaultNS:s}=ye(LR)||{},a=n||o||_R();a&&!a.reportNamespaces&&(a.reportNamespaces=new TR),a||sl(a,"NO_I18NEXT_INSTANCE","useTranslation: You will need to pass in an i18next instance by using initReactI18next");const i=Q(()=>({...ER(),...a?.options?.react,...t}),[a,t]),{useSuspense:l,keyPrefix:c}=i,d=s||a?.options?.defaultNS,f=Hn(d)?[d]:d||["translation"],p=Q(()=>f,f);a?.reportNamespaces?.addUsedNamespaces?.(p);const m=ne(0),h=q(I=>{if(!a)return KR;const{bindI18n:F,bindI18nStore:E}=i,B=()=>{m.current+=1,I()};return F&&a.on(F,B),E&&a.store.on(E,B),()=>{F&&F.split(" ").forEach(O=>a.off(O,B)),E&&E.split(" ").forEach(O=>a.store.off(O,B))}},[a,i]),g=ne(),b=q(()=>{if(!a)return UR;const I=!!(a.isInitialized||a.initializedStoreOnce)&&p.every(D=>kR(D,a,i)),F=t.lng||a.language,E=m.current,B=g.current;if(B&&B.ready===I&&B.lng===F&&B.keyPrefix===c&&B.revision===E)return B;const A={t:a.getFixedT(F,i.nsMode==="fallback"?p:p[0],c),ready:I,lng:F,keyPrefix:c,revision:E};return g.current=A,A},[a,p,c,i,t.lng]),[x,v]=$(0),{t:w,ready:y}=Dy.useSyncExternalStore(h,b,b);Y(()=>{if(a&&!y&&!l){const I=()=>v(F=>F+1);t.lng?Wu(a,t.lng,p,I):al(a,p,I)}},[a,t.lng,p,y,l,x]);const N=a||{},k=ne(null),S=ne(),M=I=>{const F=Object.getOwnPropertyDescriptors(I);F.__original&&delete F.__original;const E=Object.create(Object.getPrototypeOf(I),F);if(!Object.prototype.hasOwnProperty.call(E,"__original"))try{Object.defineProperty(E,"__original",{value:I,writable:!1,enumerable:!1,configurable:!1})}catch{}return E},P=Q(()=>{const I=N,F=I?.language;let E=I;I&&(k.current&&k.current.__original===I?S.current!==F?(E=M(I),k.current=E,S.current=F):E=k.current:(E=M(I),k.current=E,S.current=F));const B=!y&&!l?(...A)=>(sl(a,"USE_T_BEFORE_READY","useTranslation: t was called before ready. When using useSuspense: false, make sure to check the ready flag before using t."),w(...A)):w,O=[B,E,y];return O.t=B,O.i18n=E,O.ready=y,O},[w,N,y,N.resolvedLanguage,N.language,N.languages]);if(a&&l&&!y)throw new Promise(I=>{const F=()=>I();t.lng?Wu(a,t.lng,p,F):al(a,p,F)});return P},Yu={info:Es,success:ey,warning:xt,error:xa},GR={info:"text-blue-400",success:"text-green-400",warning:"text-amber-400",error:"text-red-400"},Zu={active:"border-l-blue-400","in-progress":"border-l-amber-400",completed:"border-l-green-400",failed:"border-l-red-400",dismissed:"border-l-foreground-subtle/30"};function WR(e){const t=Math.floor((Date.now()-e)/1e3);if(t<60)return"just now";const n=Math.floor(t/60);if(n<60)return`${String(n)}m ago`;const o=Math.floor(n/60);if(o<24)return`${String(o)}h ago`;const s=Math.floor(o/24);return`${String(s)}d ago`}function Xu({alert:e,onMarkRead:t,onDismiss:n}){const o=e.severity in Yu?e.severity:"info",s=e.status in Zu?e.status:"active",a=Yu[o],i=GR[o],l=Zu[s];return u("div",{className:`flex items-start gap-2.5 px-3 py-2.5 border-l-2 ${l} ${e.read?"opacity-60":""} hover:bg-surface-hover transition-colors`,children:[r(a,{className:`h-3.5 w-3.5 shrink-0 mt-0.5 ${i}`}),u("div",{className:"flex-1 min-w-0",children:[u("div",{className:"flex items-center gap-1.5",children:[r("span",{className:`text-[11px] font-semibold ${e.read?"text-foreground-subtle":"text-foreground"}`,children:e.title}),!e.read&&r("span",{className:"h-1.5 w-1.5 rounded-full bg-primary shrink-0"})]}),r("div",{className:"text-[10px] text-foreground-subtle mt-0.5 line-clamp-2",children:e.message}),e.status==="in-progress"&&e.progress!==void 0&&u("div",{className:"mt-1.5 flex items-center gap-2",children:[r("div",{className:"flex-1 h-1 bg-surface-hover rounded-full overflow-hidden",children:r("div",{className:"h-full bg-primary rounded-full transition-all duration-300",style:{width:`${String(Math.min(100,Math.max(0,e.progress)))}%`}})}),u("span",{className:"text-[9px] text-foreground-subtle font-mono shrink-0",children:[String(Math.round(e.progress)),"%"]})]}),r("div",{className:"text-[9px] text-foreground-subtle/60 mt-1",children:WR(e.updatedAt)})]}),u("div",{className:"flex items-center gap-0.5 shrink-0",children:[!e.read&&r("button",{type:"button",onClick:c=>{c.stopPropagation(),t(e.id)},className:"p-1 rounded hover:bg-surface-hover transition-colors",title:"Mark as read",children:r(Ct,{className:"h-3 w-3 text-foreground-subtle"})}),e.status!=="in-progress"&&r("button",{type:"button",onClick:c=>{c.stopPropagation(),n(e.id)},className:"p-1 rounded hover:bg-surface-hover transition-colors",title:"Dismiss",children:r(qe,{className:"h-3 w-3 text-foreground-subtle"})})]})]})}function Ju({variant:e="icon",compact:t=!1}={}){const[n,o]=$(!1),[s,a]=$(!1),i=ne(null),l=ne(null),c=ke(),{data:d=0}=rg(void 0,{staleTime:1e4,refetchInterval:3e4}),{data:f=[],isLoading:p}=ng({limit:50},{enabled:n,staleTime:5e3}),m=s?f:f.filter(I=>!I.read),h=f.filter(I=>I.read).length,g=()=>{c.invalidateQueries({queryKey:[["alerts"]]})},b=og({onSuccess:g}),x=sg({onSuccess:g}),v=ag({onSuccess:g});dt("alert.created",()=>{c.invalidateQueries({queryKey:[["alerts"]]})}),dt("alert.updated",()=>{c.invalidateQueries({queryKey:[["alerts"]]})}),Y(()=>{if(!n)return;const I=F=>{const E=F.target;i.current&&!i.current.contains(E)&&l.current&&!l.current.contains(E)&&o(!1)};return document.addEventListener("mousedown",I),()=>document.removeEventListener("mousedown",I)},[n]);const w=q(I=>{b.mutate({alertId:I})},[b]),y=q(I=>{I&&v.mutate({alertId:I})},[v]),N=q(()=>{x.mutate(void 0),o(!1)},[x]),k=m.filter(I=>I.status==="in-progress"),S=m.filter(I=>I.status!=="in-progress"),[M,P]=$({});return Y(()=>{if(n&&l.current){const I=l.current.getBoundingClientRect();P({position:"fixed",left:I.left,bottom:window.innerHeight-I.top+4,zIndex:9999})}},[n]),u("div",{children:[e==="sidebar"?u("button",{ref:l,type:"button",onClick:()=>o(!n),className:`flex w-full items-center gap-2.5 rounded-md ${t?"justify-center px-0 py-2":"px-2.5 py-1.5"} text-[12px] text-foreground-subtle hover:bg-surface-hover hover:text-foreground transition-colors`,title:t?`Alerts${d>0?` (${d})`:""}`:void 0,children:[u("span",{className:"relative inline-flex shrink-0",children:[r(Xe,{className:"h-3.5 w-3.5"}),t&&d>0&&r("span",{className:"absolute -top-1 -right-1 h-2 w-2 rounded-full bg-primary"})]}),!t&&r("span",{className:"flex-1 text-left",children:"Alerts"}),!t&&d>0&&r("span",{className:"flex items-center justify-center h-4 min-w-4 px-1 rounded-full bg-primary text-primary-foreground text-[9px] font-bold leading-none",children:d>99?"99+":String(d)})]}):u("button",{ref:l,type:"button",onClick:()=>o(!n),className:"relative p-1.5 rounded-md hover:bg-surface-hover text-foreground-subtle hover:text-foreground transition-colors","aria-label":"Alerts",children:[r(Xe,{className:"h-4.5 w-4.5"}),d>0&&r("span",{className:"absolute -top-0.5 -right-0.5 flex items-center justify-center h-4 min-w-4 px-0.5 rounded-full bg-primary text-primary-foreground text-[9px] font-bold leading-none",children:d>99?"99+":String(d)})]}),n&&vo(u("div",{ref:i,style:M,className:"w-80 max-h-[28rem] bg-surface border border-border rounded-lg shadow-xl flex flex-col overflow-hidden",children:[u("div",{className:"flex items-center justify-between px-3 py-2 border-b border-border shrink-0",children:[r("span",{className:"text-[12px] font-semibold text-foreground",children:"Alerts"}),u("div",{className:"flex items-center gap-2",children:[h>0&&u("label",{className:"flex items-center gap-1 text-[10px] text-foreground-subtle cursor-pointer select-none",children:[r("input",{type:"checkbox",checked:s,onChange:I=>a(I.target.checked),className:"h-3 w-3 rounded border-border accent-primary cursor-pointer"}),"Show read"]}),d>0&&u("button",{type:"button",onClick:N,className:"flex items-center gap-1 text-[10px] text-primary hover:text-primary/80 transition-colors",children:[r(uD,{className:"h-3 w-3"}),"Mark all read"]})]})]}),u("div",{className:"flex-1 overflow-y-auto",children:[p&&r("div",{className:"flex items-center justify-center py-8",children:r(Pe,{className:"h-4 w-4 animate-spin text-foreground-subtle"})}),!p&&m.length===0&&u("div",{className:"flex flex-col items-center justify-center py-8 text-foreground-subtle",children:[r(Xe,{className:"h-6 w-6 mb-2 opacity-40"}),r("span",{className:"text-[11px]",children:f.length>0?"No unread alerts":"No alerts"}),f.length>0&&!s&&u("button",{type:"button",onClick:()=>a(!0),className:"text-[10px] text-primary mt-1 hover:underline",children:["Show ",h," read alert",h!==1?"s":""]})]}),k.length>0&&u("div",{className:"border-b border-border",children:[r("div",{className:"px-3 py-1.5 bg-surface-hover/50",children:r("span",{className:"text-[9px] font-semibold uppercase tracking-widest text-foreground-subtle/60",children:"In Progress"})}),k.map(I=>r(Xu,{alert:I,onMarkRead:w,onDismiss:y},I.id))]}),S.map(I=>r(Xu,{alert:I,onMarkRead:w,onDismiss:y},I.id))]})]}),document.body)]})}function Ly(e){return e.map(t=>({id:t.page.id,addonId:t.addonId,label:t.page.label,icon:t.page.icon,path:t.page.path,remoteName:t.page.remoteName,bundle:t.page.bundle,bundleUrl:t.bundleUrl}))}const ep=new Map,Zo=new Map,tp=new Set;function YR(e){return!e||typeof e!="object"?!1:typeof e.default=="function"}async function ZR(e,t){const n=ep.get(e);if(n)return n;const o=Zo.get(e);if(o)return o;tp.has(e)||(Ll(),fr.registerRemotes([{name:e,entry:t,type:"module"}],{force:!1}),tp.add(e));const s=fr.loadRemote(`${e}/page`).then(a=>{if(!YR(a))throw new Error(`Addon page remote ${e} (${t}) does not expose a default React component on './page'`);return ep.set(e,a.default),Zo.delete(e),a.default}).catch(a=>{throw Zo.delete(e),a});return Zo.set(e,s),s}function XR(){const{pagePath:e}=zc(),t=Le(),{data:n}=ic(void 0,{staleTime:6e4}),o=Q(()=>n?Ly(n):void 0,[n]),s=o?.find(d=>d.path===`/addon/${e}`),[a,i]=$(null),[l,c]=$(null);return Y(()=>{if(!s)return;c(null),i(null);let d=!1;return ZR(s.remoteName,s.bundleUrl).then(f=>{d||i(()=>f)}).catch(f=>{if(d)return;const p=f instanceof Error?f.message:String(f);c(`Failed to load addon page: ${p}`)}),()=>{d=!0}},[s]),o?s?l?r("div",{className:"flex items-center justify-center h-full text-red-400 text-sm",children:l}):a?r(a,{trpc:t.trpcClient,theme:{isDark:document.documentElement.classList.contains("dark")},navigate:d=>{window.location.href=d}}):r("div",{className:"flex items-center justify-center h-full",children:r("div",{className:"animate-spin h-6 w-6 border-2 border-primary border-t-transparent rounded-full"})}):r("div",{className:"flex items-center justify-center h-full text-foreground-subtle",children:"Addon page not found"}):r("div",{className:"flex items-center justify-center h-full",children:r("div",{className:"animate-spin h-6 w-6 border-2 border-primary border-t-transparent rounded-full"})})}const JR={dark:dy,light:sT,system:xL},e6={gauge:oy,puzzle:$s,bot:nD,cpu:ut,terminal:by,box:ga,wrench:xT,activity:Io,plug:Yc};function t6(){const e=ht(),t=et(),{user:n,logout:o}=Tr(),s=Ir(),{t:a,i18n:i}=zt(),l=Xn(),c=rh(),d=B_(),f=d!=="connected",p=d==="connecting",[m,h]=$(!1),[g,b]=$(()=>typeof window>"u"?!1:window.localStorage.getItem("camstack:sidebar-collapsed")==="1");Y(()=>{typeof window>"u"||window.localStorage.setItem("camstack:sidebar-collapsed",g?"1":"0")},[g]);const[x,v]=$(()=>{if(typeof window>"u")return new Set;try{const T=window.localStorage.getItem("camstack:sidebar-collapsed-groups");if(!T)return new Set;const W=JSON.parse(T);return Array.isArray(W)?new Set(W.filter(G=>typeof G=="string")):new Set}catch{return new Set}});Y(()=>{typeof window>"u"||window.localStorage.setItem("camstack:sidebar-collapsed-groups",JSON.stringify([...x]))},[x]),Y(()=>{c&&window.localStorage.getItem("camstack:sidebar-collapsed")===null&&b(!0)},[c]);const{data:w=[]}=cc(void 0,{staleTime:3e4,refetchInterval:3e4}),y=w.length,N=ke(),k=ne(Date.now()),S=3e4,M=2e3,{data:P}=ic(void 0,{staleTime:0,refetchOnMount:"always",refetchInterval:T=>{const W=T.state.data;return W&&W.length>0||Date.now()-k.current>=S?!1:M}}),I=Q(()=>P?Ly(P):[],[P]);dt("addon.page-ready",()=>{N.invalidateQueries({queryKey:[["addonPages","listPages"]]})});const F=()=>{o(),t("/login")},E=T=>!!(e.pathname===T||e.pathname.startsWith(T+"/")),O=["/pipeline","/timeline"].some(T=>e.pathname===T||e.pathname.startsWith(T+"/")),A=()=>{const T=i.language==="en"?"it":"en";i.changeLanguage(T)},D=[{label:a("nav.devices","Devices"),icon:gr,path:"/devices"},{label:a("nav.integrations"),icon:Yc,path:"/integrations"},{label:a("nav.timeline","Timeline"),icon:SD,path:"/timeline"},{label:a("nav.pipeline","Pipeline"),icon:sy,path:"/pipeline"}],_=[{label:a("system.identity","Identity & Access"),icon:ly,path:"/system/identity"},{label:a("system.network","Network"),icon:br,path:"/system/network"},{label:a("system.data","Data"),icon:ny,path:"/system/data"},{label:a("system.cluster","Cluster"),icon:an,path:"/system/cluster"},{label:a("system.addons"),icon:$s,path:"/system/addons"},{label:a("system.addonSettings","Addon Settings"),icon:wt,path:"/system/settings"},{label:a("system.logs","Logs"),icon:Xe,path:"/system/logs"}],R=s?.mode??"system",L={dark:a("theme.dark"),light:a("theme.light"),system:a("theme.system")},z=g&&!l,j=(T,W="md")=>`flex w-full items-center gap-2.5 rounded-md ${z?"justify-center px-0 py-2":"px-2.5 py-1.5"} ${W==="lg"?"text-[13px] font-medium":"text-[12px]"} transition-all ${T?W==="lg"?"bg-primary/12 text-primary shadow-sm shadow-primary/5":"bg-primary/12 text-primary":"text-foreground-subtle hover:bg-surface-hover hover:text-foreground"}`,H=u(ve,{children:[u("div",{className:`flex h-14 items-center border-b border-border ${z?"justify-center px-1":"pl-3 pr-4 gap-2"}`,children:[!z&&r("img",{src:s?.resolvedMode==="light"?"/brand/logo-horizontal-light.svg":"/brand/logo-horizontal-dark.svg",alt:"CamStack Admin",className:"h-9 flex-1 min-w-0"}),!l&&r("button",{onClick:()=>b(T=>!T),className:`p-1.5 rounded-md hover:bg-surface-hover text-foreground-subtle transition-colors flex-shrink-0 ${z?"":"mr-2"}`,"aria-label":g?"Expand sidebar":"Collapse sidebar",title:g?"Expand sidebar":"Collapse sidebar",children:g?r(Mt,{className:"h-4 w-4"}):r(Kc,{className:"h-4 w-4"})})]}),u("nav",{className:`flex-1 overflow-y-auto py-3 ${z?"px-1.5":"px-2"} space-y-0.5`,children:[(()=>{const T=E("/dashboard");return u("button",{"data-testid":"nav-dashboard",onClick:()=>{t("/dashboard"),h(!1)},className:j(T,"lg"),title:z?a("nav.dashboard"):void 0,children:[r(iy,{className:`h-4 w-4 shrink-0 ${T?"text-primary":""}`}),!z&&a("nav.dashboard")]})})(),!z&&r("div",{className:"pt-4 pb-1.5 px-2.5",children:r("span",{className:"text-[10px] font-semibold uppercase tracking-widest text-foreground-subtle/60",children:a("nav.camerasSection","Cameras")})}),z&&r("div",{className:"pt-3 mb-1 mx-2 border-t border-border/60"}),D.map(T=>{const W=T.icon,G=E(T.path),ee=`nav-${T.path.replace(/^\//,"").replace(/\//g,"-")}`;return u("button",{"data-testid":ee,onClick:()=>{t(T.path),h(!1)},className:j(G),title:z?T.label:void 0,children:[r(W,{className:`h-3.5 w-3.5 shrink-0 ${G?"text-primary":""}`}),!z&&T.label]},T.path)}),!z&&r("div",{className:"pt-4 pb-1.5 px-2.5",children:r("span",{className:"text-[10px] font-semibold uppercase tracking-widest text-foreground-subtle/60",children:a("system.title")})}),z&&r("div",{className:"pt-3 mb-1 mx-2 border-t border-border/60"}),_.map(T=>{const W=T.icon,G=E(T.path),ee=T.path==="/system/addons",se=`nav-${T.path.replace(/^\//,"").replace(/\//g,"-")}`;return u("button",{"data-testid":se,onClick:()=>{t(T.path),h(!1)},className:j(G),title:z?T.label:void 0,children:[r(W,{className:`h-3.5 w-3.5 shrink-0 ${G?"text-primary":""}`}),!z&&u(ve,{children:[r("span",{className:"flex-1 text-left",children:T.label}),ee&&y>0&&r("span",{className:"ml-auto rounded-full bg-primary px-1.5 py-0.5 text-[9px] font-bold text-primary-foreground leading-none",children:y})]}),z&&ee&&y>0&&r("span",{className:"absolute mt-[-14px] ml-3 h-2 w-2 rounded-full bg-primary"})]},T.path)}),I&&I.length>0&&!z&&r("div",{className:"pt-4 pb-1.5 px-2.5",children:r("span",{className:"text-[10px] font-semibold uppercase tracking-widest text-foreground-subtle/60",children:a("nav.addonPages","Addon Pages")})}),z&&I&&I.length>0&&r("div",{className:"pt-3 mb-1 mx-2 border-t border-border/60"}),I?.map(T=>{const W=E(T.path),G=e6[T.icon]??$s;return u("button",{onClick:()=>{t(T.path),h(!1)},className:j(W),title:z?T.label:void 0,children:[r(G,{className:`h-3.5 w-3.5 shrink-0 ${W?"text-primary":""}`}),!z&&T.label]},T.id)})]}),u("div",{className:`border-t border-border ${z?"p-1.5":"p-2"} space-y-0.5`,children:[u("button",{onClick:A,title:a("language.select"),className:j(!1),children:[r(XD,{className:"h-3.5 w-3.5 shrink-0"}),!z&&r("span",{children:i.language==="en"?a("language.en"):a("language.it")})]}),u("button",{onClick:()=>s?.toggleMode(),className:j(!1),title:z?L[R]:void 0,children:[(()=>{const T=JR[R];return r(T,{className:"h-3.5 w-3.5 shrink-0"})})(),!z&&r("span",{children:L[R]})]}),r(Ju,{variant:"sidebar",compact:z}),u("button",{onClick:F,className:j(!1).replace("hover:text-foreground","hover:text-danger"),title:z?n?.username??"Logout":void 0,children:[r(cy,{className:"h-3.5 w-3.5 shrink-0"}),!z&&r("span",{className:"truncate",children:n?.username??"User"})]})]})]});return u("div",{className:"flex h-screen bg-background text-foreground",children:[!l&&r("aside",{className:`flex flex-col border-r border-border bg-surface/80 backdrop-blur-sm shrink-0 transition-[width] duration-150 ease-out ${z?"w-12":"w-48"}`,children:H}),l&&r(Gl,{open:m,onClose:()=>h(!1),width:"w-64",children:H}),u("div",{className:"flex flex-1 flex-col min-w-0",children:[f&&u("div",{className:"flex items-center justify-center gap-2 bg-danger/90 px-3 py-2 text-[12px] font-medium text-white shrink-0",children:[r(vy,{className:"h-3.5 w-3.5"}),r("span",{children:p?a("connection.reconnecting","Reconnecting…"):a("connection.disconnected","Server unreachable — reconnecting…")}),r(Pe,{className:"h-3.5 w-3.5 animate-spin"})]}),l&&u("header",{className:"flex items-center h-12 border-b border-border px-3 shrink-0 bg-surface/80 backdrop-blur-sm",children:[r("button",{onClick:()=>h(!0),className:"p-1.5 -ml-1.5 rounded-md hover:bg-surface-hover text-foreground-muted transition-colors","aria-label":"Open menu",children:r(fL,{className:"h-5 w-5"})}),r("div",{className:"flex-1 flex justify-center",children:r("img",{src:s?.resolvedMode==="light"?"/brand/logo-horizontal-light.svg":"/brand/logo-horizontal-dark.svg",alt:"CamStack",className:"h-7"})}),r(Ju,{})]}),u("main",{className:`relative flex-1 min-h-0 bg-background ${O?"overflow-hidden":"overflow-auto"}`,children:[f&&r("div",{className:"absolute inset-0 z-40 bg-background/60 backdrop-blur-[2px]"}),r(Z$,{})]})]})]})}function n6(){const{login:e}=Tr(),t=Ir(),n=et(),[o,s]=$(""),[a,i]=$(""),[l,c]=$(!1),[d,f]=$(""),[p,m]=$(!1),h=async g=>{g.preventDefault(),f(""),m(!0);try{await e(o,a),n(a==="changeme"?"/change-password":"/dashboard",{replace:!0})}catch(b){f(b instanceof Error?b.message:"Login failed")}finally{m(!1)}};return r("div",{className:"flex min-h-screen items-center justify-center bg-background p-4",children:u("div",{className:"w-full max-w-sm",children:[r("div",{className:"flex justify-center mb-8",children:r("img",{src:t?.resolvedMode==="light"?"/brand/logo-horizontal-light.svg":"/brand/logo-horizontal-dark.svg",alt:"CamStack Admin",className:"h-12"})}),u("form",{onSubmit:h,className:"space-y-4 rounded-xl border border-border bg-surface p-6 shadow-xl shadow-black/10",children:[d&&r("div",{className:"rounded-md bg-danger/10 border border-danger/20 px-3 py-2 text-xs text-danger",children:d}),u("div",{className:"space-y-1.5",children:[r("label",{className:"text-xs font-medium text-foreground-subtle",children:"Username"}),r("input",{"data-testid":"login-username",type:"text",placeholder:"Username",value:o,onChange:g=>s(g.target.value),className:"w-full rounded-lg border border-border bg-background px-3 py-2.5 text-sm text-foreground placeholder:text-foreground-disabled focus:border-primary focus:ring-1 focus:ring-primary/30 outline-none transition-all",autoFocus:!0})]}),u("div",{className:"space-y-1.5",children:[r("label",{className:"text-xs font-medium text-foreground-subtle",children:"Password"}),u("div",{className:"relative",children:[r("input",{"data-testid":"login-password",type:l?"text":"password",placeholder:"Password",value:a,onChange:g=>i(g.target.value),className:"w-full rounded-lg border border-border bg-background px-3 py-2.5 pr-10 text-sm text-foreground placeholder:text-foreground-disabled focus:border-primary focus:ring-1 focus:ring-primary/30 outline-none transition-all"}),r("button",{type:"button",onClick:()=>c(!l),className:"absolute right-2.5 top-1/2 -translate-y-1/2 text-foreground-subtle hover:text-foreground transition-colors",tabIndex:-1,children:l?r(ry,{className:"h-4 w-4"}):r(ya,{className:"h-4 w-4"})})]})]}),r("button",{"data-testid":"login-submit",type:"submit",disabled:p||!o||!a,className:"w-full rounded-lg bg-primary px-4 py-2.5 text-sm font-semibold text-primary-foreground shadow-md shadow-primary/20 hover:shadow-lg hover:shadow-primary/30 disabled:opacity-50 disabled:shadow-none transition-all",children:p?u("span",{className:"flex items-center justify-center gap-2",children:[r("span",{className:"h-4 w-4 animate-spin rounded-full border-2 border-primary-foreground/30 border-t-primary-foreground"}),"Logging in..."]}):"Log in"})]}),r(r6,{}),r("p",{className:"mt-6 text-center text-[10px] text-foreground-subtle/50",children:"CamStack v0.1.0"})]})})}function r6(){const t=(uc().data??[]).filter(n=>n.enabled&&n.hasRedirectFlow&&n.kind!=="local");return t.length===0?null:u("div",{className:"mt-6 space-y-3",children:[u("div",{className:"flex items-center gap-3",children:[r("div",{className:"h-px flex-1 bg-border"}),r("span",{className:"text-[10px] uppercase tracking-wider text-foreground-subtle",children:"Or continue with"}),r("div",{className:"h-px flex-1 bg-border"})]}),r("div",{className:"space-y-2",children:t.map(n=>u("a",{href:`/addon/${encodeURIComponent(n.addonId)}/start`,className:"flex items-center justify-center gap-2 w-full rounded-lg border border-border bg-surface px-4 py-2.5 text-sm font-medium text-foreground hover:bg-surface-hover transition-colors",children:[r(xr,{className:"h-4 w-4 text-primary"}),n.displayName]},n.addonId))})]})}const np=8;function o6(){const{user:e,mustChangePassword:t,clearMustChangePassword:n,logout:o}=Tr(),s=Ir(),a=et(),[i,l]=$(""),[c,d]=$(""),[f,p]=$(!1),[m,h]=$(""),g=Sc({onSuccess:()=>{n(),a("/dashboard",{replace:!0})},onError:x=>{h(x instanceof Error?x.message:"Could not change password")}}),b=async x=>{if(x.preventDefault(),h(""),!e){h("Not signed in");return}if(i.length<np){h(`Password must be at least ${np} characters`);return}if(i!==c){h("The two passwords do not match");return}if(i==="changeme"){h("Choose a password different from the seed default");return}g.mutate({id:e.id,newPassword:i})};return r("div",{className:"flex min-h-screen items-center justify-center bg-background p-4",children:u("div",{className:"w-full max-w-sm",children:[r("div",{className:"flex justify-center mb-8",children:r("img",{src:s?.resolvedMode==="light"?"/brand/logo-horizontal-light.svg":"/brand/logo-horizontal-dark.svg",alt:"CamStack Admin",className:"h-12"})}),u("form",{onSubmit:b,className:"space-y-4 rounded-xl border border-border bg-surface p-6 shadow-xl shadow-black/10",children:[u("div",{className:"space-y-1",children:[r("h1",{className:"text-sm font-semibold text-foreground",children:"Set a new password"}),r("p",{className:"text-xs text-foreground-subtle",children:t?"You must rotate the seed password before continuing.":"Choose a new password for your account."})]}),m&&r("div",{className:"rounded-md bg-danger/10 border border-danger/20 px-3 py-2 text-xs text-danger",children:m}),u("div",{className:"space-y-1.5",children:[r("label",{className:"text-xs font-medium text-foreground-subtle",children:"New password"}),u("div",{className:"relative",children:[r("input",{"data-testid":"change-password-new",type:f?"text":"password",value:i,onChange:x=>l(x.target.value),className:"w-full rounded-lg border border-border bg-background px-3 py-2.5 pr-10 text-sm text-foreground placeholder:text-foreground-disabled focus:border-primary focus:ring-1 focus:ring-primary/30 outline-none transition-all",autoFocus:!0}),r("button",{type:"button",onClick:()=>p(!f),className:"absolute right-2.5 top-1/2 -translate-y-1/2 text-foreground-subtle hover:text-foreground transition-colors",tabIndex:-1,children:f?r(ry,{className:"h-4 w-4"}):r(ya,{className:"h-4 w-4"})})]})]}),u("div",{className:"space-y-1.5",children:[r("label",{className:"text-xs font-medium text-foreground-subtle",children:"Confirm new password"}),r("input",{"data-testid":"change-password-confirm",type:f?"text":"password",value:c,onChange:x=>d(x.target.value),className:"w-full rounded-lg border border-border bg-background px-3 py-2.5 text-sm text-foreground placeholder:text-foreground-disabled focus:border-primary focus:ring-1 focus:ring-primary/30 outline-none transition-all"})]}),r("button",{"data-testid":"change-password-submit",type:"submit",disabled:g.isPending||!i||!c,className:"w-full rounded-lg bg-primary px-4 py-2.5 text-sm font-semibold text-primary-foreground shadow-md shadow-primary/20 hover:shadow-lg hover:shadow-primary/30 disabled:opacity-50 disabled:shadow-none transition-all",children:g.isPending?"Saving…":"Save and continue"}),t&&r("button",{type:"button",onClick:()=>{o(),a("/login",{replace:!0})},className:"w-full text-xs text-foreground-subtle hover:text-foreground transition-colors",children:"Sign out instead"})]})]})})}function s6(){const e=et();return u("div",{className:"flex min-h-screen flex-col items-center justify-center bg-background text-foreground p-4",children:[r("div",{className:"flex h-16 w-16 items-center justify-center rounded-2xl bg-danger/10 mb-4",children:r(WL,{className:"h-8 w-8 text-danger"})}),r("h1",{className:"text-xl font-bold",children:"Access Denied"}),r("p",{className:"mt-2 text-sm text-foreground-subtle",children:"You don't have permission to access this page."}),r("button",{onClick:()=>e("/dashboard"),className:"mt-6 rounded-lg bg-primary px-5 py-2.5 text-sm font-medium text-primary-foreground shadow-md shadow-primary/20 hover:shadow-lg transition-all",children:"Go to Dashboard"})]})}const Ty="camstack:dashboard-layout",ui={version:1,widgets:[]};function a6(){try{const e=localStorage.getItem(Ty);if(!e)return ui;const t=JSON.parse(e);return t&&t.version===1&&Array.isArray(t.widgets)?{version:1,widgets:t.widgets}:ui}catch{return ui}}function i6(e){try{localStorage.setItem(Ty,JSON.stringify(e))}catch{}}function l6(){const e=typeof crypto<"u"?crypto:void 0;return e?.randomUUID?e.randomUUID():`widget-${Date.now().toString(36)}-${Math.floor(Math.random()*1e6).toString(36)}`}function c6(){const[e,t]=$(a6),[n,o]=$(!1),s=px(),a=Q(()=>s.filter(d=>d.hosts.includes("dashboard")),[s]),i=q(d=>{t(d),i6(d)},[]),l=q(d=>{i({version:1,widgets:[...e.widgets,d]})},[e,i]),c=q(d=>{i({version:1,widgets:e.widgets.filter(f=>f.instanceId!==d)})},[e,i]);return u("div",{className:"p-4",children:[u("div",{className:"flex items-center justify-between mb-4",children:[r("h1",{className:"text-lg font-semibold text-foreground",children:"Dashboard"}),u("button",{onClick:()=>o(!0),className:"flex items-center gap-1.5 rounded-md bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90 transition-colors",children:[r(Ot,{className:"h-3.5 w-3.5"}),"Add widget"]})]}),e.widgets.length===0?r(d6,{onAdd:()=>o(!0)}):r("div",{className:"grid grid-cols-12 gap-3 auto-rows-[minmax(80px,_auto)]",children:e.widgets.map(d=>r(u6,{entry:d,onRemove:()=>c(d.instanceId)},d.instanceId))}),n&&r(f6,{widgets:a,onClose:()=>o(!1),onAdd:d=>{l(d),o(!1)}})]})}function d6({onAdd:e}){return u("div",{className:"flex flex-col items-center justify-center py-24 text-foreground-subtle",children:[r("div",{className:"flex h-16 w-16 items-center justify-center rounded-2xl bg-surface border border-border mb-4",children:r(iy,{className:"h-8 w-8 text-foreground-subtle/40"})}),r("p",{className:"text-sm font-medium text-foreground/70",children:"Your dashboard is empty"}),r("p",{className:"text-xs text-foreground-subtle mt-1 mb-4",children:"Add widgets to monitor your cameras and system"}),u("button",{onClick:e,className:"flex items-center gap-1.5 rounded-lg bg-primary px-4 py-2 text-xs font-semibold text-primary-foreground shadow-md shadow-primary/20 hover:shadow-lg transition-all",children:[r(Ot,{className:"h-3.5 w-3.5"}),"Add your first widget"]})]})}function u6({entry:e,onRemove:t}){const n=p6(e.columns),o=Math.max(1,Math.min(12,e.rows));return u("div",{className:"relative group rounded-lg border border-border bg-surface overflow-hidden flex flex-col",style:{gridColumn:`span ${n} / span ${n}`,gridRow:`span ${o} / span ${o}`},children:[r("button",{type:"button",onClick:t,title:"Remove widget",className:"absolute right-1.5 top-1.5 z-10 inline-flex h-5 w-5 items-center justify-center rounded-md border border-border/60 bg-surface/80 text-foreground-subtle opacity-0 group-hover:opacity-100 hover:bg-danger/10 hover:text-danger hover:border-danger/40 transition-all",children:r(qe,{className:"h-3 w-3"})}),r("div",{className:"flex-1 min-h-0 overflow-auto p-2",children:r(it,{widgetId:e.widgetId,host:"dashboard",instanceId:e.instanceId,config:e.config,deviceId:e.deviceId,size:e.size,columns:e.columns,rows:e.rows})})]})}function p6(e){return!Number.isFinite(e)||e<1?6:Math.min(12,Math.floor(e))}function f6({widgets:e,onClose:t,onAdd:n}){const[o,s]=$(null);return r("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm",onClick:t,children:u("div",{className:"w-full max-w-2xl rounded-xl border border-border bg-surface p-5 shadow-2xl shadow-black/20",onClick:a=>a.stopPropagation(),children:[u("div",{className:"flex items-center justify-between mb-4",children:[r("h2",{className:"text-sm font-semibold text-foreground",children:o?`Configure: ${o.label}`:"Add widget"}),r("button",{onClick:t,className:"p-1 rounded-md hover:bg-surface-hover text-foreground-subtle hover:text-foreground transition-colors",children:r(qe,{className:"h-4 w-4"})})]}),o===null?r(m6,{widgets:e,onSelect:s}):r(h6,{widget:o,onCancel:()=>s(null),onAdd:n})]})})}function m6({widgets:e,onSelect:t}){return e.length===0?r("div",{className:"text-center py-8 text-xs text-foreground-subtle italic",children:"No dashboard-host widgets registered. Make sure the contributing addons are enabled and have rebuilt their widget bundles."}):r("div",{className:"grid grid-cols-2 gap-2 max-h-96 overflow-auto",children:e.map(n=>u("button",{onClick:()=>t(n),className:"flex flex-col rounded-lg border border-border p-3 text-left hover:bg-surface-hover hover:border-primary/30 transition-all group",children:[r("span",{className:"text-xs font-medium text-foreground block",children:n.label}),r("span",{className:"text-[10px] text-foreground-subtle truncate",title:n.widgetId,children:n.widgetId}),n.description&&r("span",{className:"text-[10px] text-foreground-subtle mt-1 line-clamp-2",children:n.description})]},n.widgetId))})}function h6({widget:e,onCancel:t,onAdd:n}){const[o,s]=$(e.defaultSize),[a,i]=$(e.defaultColumns),[l,c]=$(e.defaultRows),[d,f]=$(null),{data:p}=Jn({},{enabled:e.requires.deviceContext,staleTime:3e4}),m=!e.requires.deviceContext||d!==null&&d>0,h=()=>{if(!m)return;const g={instanceId:l6(),widgetId:e.widgetId,size:o,columns:a,rows:l,...e.requires.deviceContext&&d!==null?{deviceId:d}:{}};n(g)};return u("div",{className:"space-y-3",children:[u("div",{children:[r("label",{className:"block text-[11px] font-medium text-foreground-subtle mb-1",children:"Size"}),r("div",{className:"flex items-center gap-1",children:e.allowedSizes.map(g=>r("button",{onClick:()=>s(g),className:`px-3 py-1 rounded-md text-[11px] font-medium border transition-colors ${o===g?"bg-primary/10 text-primary border-primary/30":"border-border text-foreground-subtle hover:bg-surface-hover hover:text-foreground"}`,children:g.toUpperCase()},g))})]}),u("div",{className:"grid grid-cols-2 gap-3",children:[r(rp,{label:"Columns (1-12)",value:a,min:1,max:12,onChange:i}),r(rp,{label:"Rows (1-12)",value:l,min:1,max:12,onChange:c})]}),e.requires.deviceContext&&u("div",{children:[r("label",{className:"block text-[11px] font-medium text-foreground-subtle mb-1",children:"Device"}),u("select",{value:d??"",onChange:g=>f(g.target.value===""?null:Number(g.target.value)),className:"w-full rounded-md border border-border bg-surface px-2 py-1.5 text-foreground text-xs focus:border-primary outline-none",children:[r("option",{value:"",children:"— select a device —"}),(p??[]).map(g=>u("option",{value:g.id,children:[g.name??g.stableId," (#",g.id,")"]},g.id))]})]}),u("div",{className:"flex items-center justify-end gap-2 pt-2 border-t border-border",children:[r("button",{onClick:t,className:"px-3 py-1.5 rounded-md text-xs font-medium border border-border text-foreground-subtle hover:bg-surface-hover hover:text-foreground transition-colors",children:"Back"}),r("button",{disabled:!m,onClick:h,className:"px-3 py-1.5 rounded-md text-xs font-medium bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:"Add to dashboard"})]})]})}function rp({label:e,value:t,min:n,max:o,onChange:s}){return u("div",{children:[r("label",{className:"block text-[11px] font-medium text-foreground-subtle mb-1",children:e}),r("input",{type:"number",min:n,max:o,value:t,onChange:a=>{const i=Number(a.target.value);Number.isFinite(i)&&s(Math.max(n,Math.min(o,Math.floor(i))))},className:"w-full rounded-md border border-border bg-surface px-2 py-1.5 text-foreground text-xs focus:border-primary outline-none"})]})}function g6(){return r(c6,{})}function It({icon:e,title:t,subtitle:n,actions:o,children:s}){return u("div",{className:"p-6 space-y-4",children:[u("div",{className:"flex items-center justify-between gap-4",children:[u("div",{className:"min-w-0",children:[u("h1",{className:"text-lg font-semibold text-foreground flex items-center gap-2",children:[e&&r(e,{className:"h-4 w-4 text-foreground-subtle"}),t]}),n&&r("p",{className:"text-xs text-foreground-subtle mt-0.5",children:n})]}),o&&r("div",{className:"shrink-0 flex items-center gap-2",children:o})]}),s]})}const op=["camera","hub","nvr","light","siren","switch","sensor","thermostat","button","generic"];function b6(){const{t:e}=zt(),t=et(),n=Le();yt(["deviceManager"],["device.registered","device.unregistered","device.online","device.offline","device.disabled","device.enabled"]),yt(["integrations"],["integration.enabled","integration.disabled","integration.deleted","provider.started","provider.stopped","addon.installed","addon.uninstalled","addon.started","addon.stopped"]);const{data:o}=Jn({},{staleTime:3e4}),{data:s}=aa(void 0,{staleTime:3e4}),a=Q(()=>o??[],[o]),{activeDevices:i,orphanDevices:l}=Q(()=>{const h=new Set((s??[]).map(k=>k.addonId)),g=k=>typeof k.addonId=="string"&&k.addonId.length>0&&!h.has(k.addonId),b=new Set;for(const k of a)g(k)&&b.add(k.id);const x=new Set(b),v=new Map;for(const k of a)v.set(k.id,k);const w=(k,S=0)=>{if(S>32)return!1;if(b.has(k.id))return!0;if(k.parentDeviceId==null)return!1;const M=v.get(k.parentDeviceId);return M?w(M,S+1):!1};for(const k of a)w(k)&&x.add(k.id);const y=[],N=[];for(const k of a)x.has(k.id)?N.push(k):y.push(k);return{activeDevices:y,orphanDevices:N}},[a,s]),c=Q(()=>{const h=new Map;for(const g of a)h.set(g.id,{id:g.id,name:g.name??g.stableId??`#${String(g.id)}`});return h},[a]),d=q(h=>c.get(h)??null,[c]),f=Q(()=>(s??[]).map(h=>({id:h.addonId,name:h.name??h.addonId,icon:r(cn,{type:h.addonId,size:"sm"})})),[s]),p=q(h=>r(cn,{type:h,size:"sm"}),[]),m=q(h=>t(`/devices/${String(h)}`),[t]);return u(It,{icon:gr,title:e("nav.devices","Devices"),children:[r(ao,{devices:i,trpc:n.trpcClient,filters:{types:op,addons:f},resolveIntegrationIcon:p,resolveParent:d,onNavigate:m}),l.length>0&&u("div",{className:"mt-6 space-y-2",children:[u("div",{className:"flex items-baseline gap-2",children:[r(xt,{className:"h-3.5 w-3.5 text-warning shrink-0"}),r("h2",{className:"text-sm font-semibold text-foreground",children:"Orphan devices"}),u("span",{className:"text-[10px] text-foreground-subtle",children:[l.length," device",l.length===1?"":"s"," pointing at integrations no longer registered"]})]}),u("div",{className:"rounded-lg border border-warning/30 bg-warning/5 p-2",children:[r("p",{className:"text-[11px] text-foreground-subtle px-2 pb-2",children:"These devices reference an addonId that has no matching integration. Delete them, or re-install the missing integration to bring them back online. The provider scope (`addonId`) shown beside each row is what's failing to resolve."}),r(ao,{devices:l,trpc:n.trpcClient,filters:{types:op,addons:f},urlScope:"nested",lsKey:"devices:orphan",resolveIntegrationIcon:p,resolveParent:d,onNavigate:m})]})]})]})}function x6({onSelect:e,onClose:t,pendingAddonId:n=null}){const{t:o}=zt(),s=et(),{data:a,isLoading:i}=Og();if(i)return r("div",{className:"space-y-2 p-2",children:[1,2,3].map(c=>r("div",{className:"h-14 rounded-lg bg-surface animate-pulse"},c))});const l=n!==null;return u("div",{className:"space-y-2",children:[(a??[]).map(c=>{const d=c.instanceMode==="unique"&&c.existingInstances.length>0,f=n===c.addonId,p=l;return u("button",{disabled:p,onClick:()=>{if(!p)if(d){const m=c.existingInstances[0].id;t(),s(`/integrations/${m}`)}else e(c.addonId,c.instanceMode,c.discoveryMode,c.name)},className:"flex w-full items-center gap-3 rounded-lg border border-border bg-surface p-3 text-left hover:border-foreground-subtle/30 transition-colors disabled:opacity-60 disabled:cursor-not-allowed disabled:hover:border-border",children:[c.iconUrl?r("div",{className:"flex h-9 w-9 items-center justify-center rounded-lg flex-shrink-0",style:{backgroundColor:`${c.color}15`},children:r("img",{src:c.iconUrl,alt:"",className:"h-5 w-5"})}):r("div",{className:"flex h-9 w-9 items-center justify-center rounded-lg flex-shrink-0",style:{backgroundColor:`${c.color}15`},children:r("span",{className:"text-sm",style:{color:c.color},children:"◉"})}),u("div",{className:"flex-1 min-w-0",children:[r("p",{className:"text-xs font-semibold text-foreground",children:c.name}),c.description&&r("p",{className:"text-[10px] text-foreground-subtle mt-0.5 truncate",children:c.description})]}),f?r(Pe,{className:"h-4 w-4 animate-spin text-primary flex-shrink-0"}):d?u("span",{className:"flex items-center gap-1 text-[10px] font-medium text-foreground-subtle",children:[r(wt,{className:"h-3 w-3"}),o("integrations.manage")]}):r(Mt,{className:"h-4 w-4 text-foreground-subtle flex-shrink-0"})]},c.addonId)}),(a??[]).length===0&&r("div",{className:"py-8 text-center text-xs text-foreground-subtle",children:o("integrations.noProviders")})]})}function y6(e){return/^[a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)+$/.test(e)}function sp(e,t){if(e!==void 0)return t&&y6(e)?t(e):e}function v6({section:e,values:t,onChange:n,disabled:o,translationFn:s,onTestField:a,probeResults:i,onAction:l}){const[c,d]=$(e.defaultCollapsed??!1),f=e.style==="accordion";if(e.fields.reduce((b,x)=>b+(Cc(x,t,e.fields)?1:0),0)===0)return null;const m=e.columns??2,h=m===1?"grid-cols-1":m===3?"grid-cols-1 @[420px]:grid-cols-2 @[680px]:grid-cols-3":m===4?"grid-cols-1 @[420px]:grid-cols-2 @[900px]:grid-cols-4":"grid-cols-1 @[480px]:grid-cols-2",g=!e.title&&!e.description;return u("div",{className:"@container rounded-lg border border-border bg-surface p-3",style:{containerType:"inline-size"},children:[!g&&u("div",{className:["flex items-center justify-between mb-2",f?"cursor-pointer":""].join(" "),onClick:f?()=>d(b=>!b):void 0,children:[u("div",{children:[e.title&&r("h3",{className:"text-[11px] font-semibold text-foreground-subtle uppercase tracking-wider",children:sp(e.title,s)}),e.description&&r("p",{className:"text-[10px] text-foreground-subtle mt-0.5",children:sp(e.description,s)})]}),f&&r("span",{className:"text-foreground-subtle text-xs ml-2",children:c?"▸":"▾"})]}),!c&&r("div",{className:`grid ${h} gap-x-3 gap-y-2.5`,children:e.fields.map(b=>r(tr,{field:b,values:t,onChange:n,disabled:o,translationFn:s,onTestField:a,externalProbe:i?.[b.key],allFields:e.fields,onAction:l},b.key))})]})}function Nn({schema:e,values:t,onChange:n,disabled:o,translationFn:s,onTestField:a,probeResults:i,onClearProbe:l,onAction:c}){const d=(f,p)=>{n({...t,[f]:p}),l?.(f)};return r("div",{className:"space-y-4",children:e.sections.map((f,p)=>r(v6,{section:f,values:t,onChange:d,disabled:o,translationFn:s,onTestField:a,probeResults:i,onAction:c},`${f.id}-${p}`))})}function w6({addonId:e,configSchema:t,onSave:n,onBack:o}){const{t:s}=zt(),[a,i]=$(""),[l,c]=$({}),[d,f]=$(null),p=zg({onSuccess:m=>f(m),onError:m=>f({success:!1,error:String(m)})});return u("div",{className:"space-y-4",children:[u("div",{children:[r("label",{className:"block text-[11px] font-medium text-foreground mb-1",children:s("integrations.integrationName")}),r("input",{type:"text",value:a,onChange:m=>i(m.target.value),placeholder:s("integrations.integrationNamePlaceholder"),className:"w-full rounded-lg border border-border bg-surface px-3 py-2 text-xs text-foreground placeholder:text-foreground-subtle focus:outline-none focus:border-primary/50"})]}),t&&r(Nn,{schema:t,values:l,onChange:c}),d&&r("div",{className:`rounded-lg border px-3 py-2 text-xs ${d.success?"border-success/30 bg-success/5 text-success":"border-danger/30 bg-danger/5 text-danger"}`,children:d.success?s("integrations.connectionSuccess"):`${s("integrations.errorPrefix")} ${d.error}`}),u("div",{className:"flex items-center justify-between pt-2",children:[r("button",{onClick:o,className:"rounded-lg border border-border px-3 py-1.5 text-xs text-foreground-subtle hover:text-foreground transition-colors",children:s("integrations.back")}),u("div",{className:"flex items-center gap-2",children:[r("button",{onClick:()=>p.mutate({addonId:e,settings:l}),disabled:p.isPending,className:"rounded-lg border border-border px-3 py-1.5 text-xs text-foreground hover:bg-surface-hover transition-colors disabled:opacity-50",children:p.isPending?s("integrations.testing"):s("integrations.testConnection")}),r("button",{onClick:()=>n({name:a,config:l}),disabled:!a.trim(),className:"rounded-lg bg-primary px-4 py-1.5 text-xs font-medium text-primary-foreground shadow-sm disabled:opacity-50",children:s("integrations.forward")})]})]})]})}function N6({providerId:e,onImport:t,onSkip:n}){const{t:o}=zt(),[s,a]=$(new Set),i=hc(),l=i.data,c=i.isPending||!i.data&&!i.isError;Y(()=>{e&&(i.isPending||i.data||i.mutate({addonId:e}))},[e,i]);function d(p){a(m=>{const h=new Set(m);return h.has(p)?h.delete(p):h.add(p),h})}if(c)return u("div",{className:"flex flex-col items-center py-12",children:[r("div",{className:"h-6 w-6 animate-spin rounded-full border-2 border-primary border-t-transparent"}),r("p",{className:"mt-3 text-xs text-foreground-subtle",children:o("integrations.searchingDevices")})]});const f=l??[];return u("div",{className:"space-y-4",children:[r("p",{className:"text-xs text-foreground-subtle",children:f.length>0?o("integrations.foundDevices",{count:f.length}):o("integrations.noDevicesFound")}),f.length>0&&r("div",{className:"space-y-1.5 max-h-64 overflow-y-auto",children:f.map(p=>{const m=p.stableId,h=p.suggestedName??m,g=s.has(m);return u("button",{onClick:()=>d(m),className:`flex w-full items-center gap-3 rounded-lg border p-3 text-left transition-colors ${g?"border-primary/40 bg-primary/5":"border-border bg-surface hover:border-foreground-subtle/30"}`,children:[r("div",{className:`flex h-5 w-5 items-center justify-center rounded border flex-shrink-0 ${g?"border-primary bg-primary":"border-border"}`,children:g&&r(Ct,{className:"h-3 w-3 text-primary-foreground"})}),r(gr,{className:"h-3.5 w-3.5 text-foreground-subtle flex-shrink-0"}),r("span",{className:"text-xs font-medium text-foreground truncate",children:h})]},m)})}),u("div",{className:"flex items-center justify-between pt-2",children:[r("button",{onClick:n,className:"rounded-lg border border-border px-3 py-1.5 text-xs text-foreground-subtle hover:text-foreground transition-colors",children:o("integrations.skip")}),f.length>0&&u("button",{onClick:()=>t(Array.from(s)),disabled:s.size===0,className:"rounded-lg bg-primary px-4 py-1.5 text-xs font-medium text-primary-foreground shadow-sm disabled:opacity-50",children:[o("integrations.importSelected")," (",s.size,")"]})]})]})}function k6(e){const t=n=>{if(n.type==="separator"||n.type==="info"||n.type==="button")return n;if(n.type==="group")return{...n,fields:n.fields.map(i=>t(i))};const o=n,{value:s,...a}=o;return a};return{...e.tabs?{tabs:e.tabs}:{},sections:e.sections.map(n=>({...n,fields:n.fields.map(t)}))}}function S6({open:e,onClose:t}){const{t:n}=zt(),o=et(),s=ke(),[a,i]=$("picker"),[l,c]=$(null),[d,f]=$(null),[p,m]=$("manual"),{data:h}=dc({addonId:l??"",nodeId:"hub"},{enabled:l!=null}),g=Q(()=>h?k6(h):null,[h]),b=Lg({onSuccess:()=>s.invalidateQueries({queryKey:[["integrations"]]})}),x=hc(),v=x.data;Y(()=>{a!=="discovery"||!d||!l||x.isPending||x.data||x.mutate({addonId:l})},[a,d,l,x]);const w=Pg({onSuccess:()=>s.invalidateQueries({queryKey:[["deviceManager"]]})});async function y(O,A,D,_){if(!b.isPending){if(c(O),m(D),A==="unique"){try{const R=await b.mutateAsync({addonId:O,name:_,settings:{}});t(),M(),o(`/integrations/${R.id}`)}catch{}return}i("config")}}async function N(O){if(l)try{const A=await b.mutateAsync({addonId:l,name:O.name,settings:O.config});f(A.id),p==="auto"||p==="both"?i("discovery"):S(A.id)}catch{}}async function k(O){if(l){for(const A of O){const D=v?.find(_=>_.stableId===A);D&&await w.mutateAsync({addonId:l,candidate:D})}S()}}function S(O){const A=O??d??l;t(),M(),A&&o(`/integrations/${A}`)}function M(){i("picker"),c(null),f(null),m("manual")}function P(){t(),M()}if(!e)return null;const I={picker:n("integrations.newIntegration"),config:n("integrations.configureIntegration"),discovery:n("integrations.importDevices")},F=b.isPending,E=F?l:null,B=b.error;return u("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[r("div",{className:"absolute inset-0 bg-black/60",onClick:F?void 0:P}),u("div",{className:"relative z-10 w-full max-w-lg rounded-xl border border-border bg-background shadow-2xl",children:[u("div",{className:"flex items-center justify-between border-b border-border px-5 py-4",children:[r("h2",{className:"text-sm font-semibold text-foreground",children:I[a]}),r("button",{onClick:P,disabled:F,className:"rounded-md p-1 text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors disabled:opacity-40 disabled:cursor-not-allowed",children:r(qe,{className:"h-4 w-4"})})]}),u("div",{className:"relative px-5 py-4",children:[B&&!F&&r("div",{className:"mb-3 rounded-lg border border-destructive/40 bg-destructive/10 px-3 py-2 text-xs text-destructive",children:B instanceof Error?B.message:String(B)}),a==="picker"&&r(x6,{onSelect:y,onClose:P,pendingAddonId:E}),a==="config"&&l&&r(w6,{addonId:l,configSchema:g??null,onSave:N,onBack:()=>i("picker")}),a==="discovery"&&d&&r(N6,{providerId:d,onImport:k,onSkip:S}),F&&u("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-2 bg-background/85 backdrop-blur-sm",children:[r(Pe,{className:"h-6 w-6 animate-spin text-primary"}),r("p",{className:"text-xs font-medium text-foreground",children:n("integrations.creating",{defaultValue:"Creating integration…"})}),r("p",{className:"text-[10px] text-foreground-subtle",children:n("integrations.creatingHint",{defaultValue:"Waiting for the addon to restart and register"})})]})]})]})]})}const ap={running:{bg:"bg-success/10",text:"text-success",dot:"bg-success",label:"Running"},stopped:{bg:"bg-foreground-subtle/10",text:"text-foreground-subtle",dot:"bg-foreground-subtle",label:"Stopped"},error:{bg:"bg-danger/10",text:"text-danger",dot:"bg-danger",label:"Error"},online:{bg:"bg-success/10",text:"text-success",dot:"bg-success",label:"Online"},offline:{bg:"bg-foreground-subtle/10",text:"text-foreground-subtle",dot:"bg-foreground-subtle",label:"Offline"},idle:{bg:"bg-info/10",text:"text-info",dot:"bg-info",label:"Idle"},disabled:{bg:"bg-warning/10",text:"text-warning",dot:"bg-warning",label:"Disabled"},enabled:{bg:"bg-success/10",text:"text-success",dot:"bg-success",label:"Enabled"}};function ka({status:e}){const t=ap[e]??ap.stopped;return u("span",{className:`inline-flex items-center gap-1.5 rounded-full px-2 py-0.5 text-[10px] font-medium ${t.bg} ${t.text}`,children:[r("span",{className:`h-1.5 w-1.5 rounded-full ${t.dot}`}),t.label]})}const pi="px-3 py-2 text-left text-[10px] font-semibold uppercase tracking-wider text-foreground-subtle";function C6({integrations:e,expandedAddonId:t,onToggleExpand:n,onOpenSettings:o,renderExpanded:s}){const a=q(i=>n(i),[n]);return r("div",{className:"overflow-hidden rounded-lg border border-border bg-surface",children:u("table",{className:"w-full table-fixed text-xs",children:[r("thead",{className:"bg-surface-hover/40",children:u("tr",{children:[r("th",{className:K(pi,"w-[60%]"),children:"Integration"}),r("th",{className:K(pi,"w-[15%]"),children:"Devices"}),r("th",{className:K(pi,"w-[25%]"),children:"Status"})]})}),r("tbody",{children:e.map(i=>{const l=t===i.addonId;return r(M6,{integration:i,isExpanded:l,onClick:a,onOpenSettings:o,renderExpanded:s},i.id)})})]})})}function M6({integration:e,isExpanded:t,onClick:n,onOpenSettings:o,renderExpanded:s}){const a=q(c=>{c.stopPropagation(),o(e.id)},[e.id,o]),i=q(()=>{n(e.addonId)},[e.addonId,n]),l=q(c=>{(c.key==="Enter"||c.key===" ")&&(c.preventDefault(),i())},[i]);return u(ve,{children:[u("tr",{role:"button",tabIndex:0,"aria-expanded":t,className:K("cursor-pointer border-t border-border transition-colors hover:bg-surface-hover","focus:outline-none focus-visible:ring-1 focus-visible:ring-primary/40",t&&"bg-surface-hover/60"),onClick:i,onKeyDown:l,children:[r("td",{className:"px-3 py-2.5",children:u("div",{className:"flex items-center gap-2.5",children:[t?r(Rt,{className:"h-3.5 w-3.5 flex-shrink-0 text-foreground-subtle"}):r(Mt,{className:"h-3.5 w-3.5 flex-shrink-0 text-foreground-subtle"}),r(cn,{type:e.addonId,size:"sm"}),u("div",{className:"flex min-w-0 flex-col",children:[r("span",{className:"truncate text-xs font-semibold text-foreground",children:e.name}),r("span",{className:"truncate text-[10px] text-foreground-subtle",children:e.addonId})]})]})}),u("td",{className:"px-3 py-2.5 text-[11px] text-foreground-subtle",children:[e.deviceCount," device",e.deviceCount!==1?"s":""]}),r("td",{className:"px-3 py-2.5",children:u("div",{className:"flex items-center justify-between gap-2",children:[r(ka,{status:e.status}),u("button",{type:"button",onClick:a,className:"flex items-center gap-1 rounded-md px-2 py-1 text-[10px] font-medium text-foreground-subtle transition-colors hover:bg-primary/10 hover:text-primary",title:"Open integration settings",children:[r(wt,{className:"h-3 w-3"}),"Settings"]})]})})]}),t&&r("tr",{className:"border-t border-border bg-surface",children:r("td",{colSpan:3,className:"px-3 py-3",children:s(e.addonId)})})]})}function I6(e){if(!e.enabled)return"disabled";switch(e.processState){case"running":return"running";case"stopped":case"crashed":case"unknown":default:return"stopped"}}const Xo="expand";function A6(){const{t:e}=zt(),t=et(),n=Le(),[o]=Qc(),[s,a]=$(!1),i=q(()=>a(!0),[]),l=q(()=>a(!1),[]);yt(["integrations"],["integration.enabled","integration.disabled","integration.deleted","provider.started","provider.stopped","addon.installed","addon.uninstalled","addon.started","addon.stopped","addon.updated"]),yt(["deviceManager"],["device.registered","device.unregistered","device.online","device.offline","device.disabled","device.enabled"]);const{data:c,isLoading:d,refetch:f}=aa(void 0,{staleTime:3e4}),{data:p,isLoading:m,refetch:h}=Jn({},{staleTime:3e4}),g=Q(()=>p??[],[p]),b=Q(()=>c??[],[c]),x=Q(()=>{const O=new Map;for(const A of g)O.set(A.id,{id:A.id,name:A.name??A.stableId??`#${String(A.id)}`});return O},[g]),v=Q(()=>{const O=new Map;for(const A of g){if(A.parentDeviceId!==null&&A.parentDeviceId!==void 0&&!!A.role)continue;const _=A.addonId??"";_&&O.set(_,(O.get(_)??0)+1)}return O},[g]),w=Q(()=>b.map(O=>({id:O.id,addonId:O.addonId,name:O.name,enabled:O.enabled,status:I6(O),deviceCount:v.get(O.addonId)??0})),[b,v]),y=o.get(Xo),N=q(O=>{const A=new URLSearchParams(window.location.search);A.get(Xo)===O?A.delete(Xo):A.set(Xo,O);const _=A.toString(),R=`${window.location.pathname}${_?`?${_}`:""}${window.location.hash}`;window.history.replaceState(window.history.state,"",R),window.dispatchEvent(new PopStateEvent("popstate"))},[]),k=q(O=>t(`/integrations/${O}`),[t]),S=q(O=>x.get(O)??null,[x]),M=q(O=>r(cn,{type:O,size:"sm"}),[]),P=q(O=>t(`/devices/${String(O)}`),[t]),I=q(O=>r(ao,{devices:g,trpc:n.trpcClient,forceAddon:O,urlScope:"nested",lsKey:`integrations:nested:${O}`,resolveIntegrationIcon:M,resolveParent:S,onNavigate:P}),[g,n.trpcClient,M,S,P]),F=q(()=>{f(),h()},[f,h]),E=d||m,B=b.length>0;return u(It,{icon:Yc,title:e("nav.integrations","Integrations"),actions:u(ve,{children:[r("button",{onClick:F,disabled:E,className:"flex items-center gap-1 rounded-lg border border-border bg-surface px-2.5 py-1.5 text-xs font-medium text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors disabled:opacity-50",title:"Refresh",children:r(pt,{className:K("h-3.5 w-3.5",E&&"animate-spin")})}),u("button",{onClick:i,className:"flex items-center gap-1.5 rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground shadow-sm",children:[r(Ot,{className:"h-3.5 w-3.5"}),"New Integration"]})]}),children:[E&&r("div",{className:"space-y-2",children:[1,2,3].map(O=>r("div",{className:"h-12 rounded-lg border border-border bg-surface animate-pulse"},O))}),!E&&!B&&u("div",{className:"flex flex-col items-center py-20 text-foreground-subtle",children:[r("p",{className:"text-sm",children:"No integrations configured."}),r("p",{className:"text-xs mt-1",children:'Click "New Integration" to connect cameras and devices.'})]}),!E&&B&&r(C6,{integrations:w,expandedAddonId:y,onToggleExpand:N,onOpenSettings:k,renderExpanded:I}),r(S6,{open:s,onClose:l})]})}function Ry(e){const t=[];for(const n of e)n.type==="probe"&&t.push(n.key),n.type==="group"&&"fields"in n&&t.push(...Ry(n.fields));return t}function P6(e,t,n){const[o,s]=$("idle"),[a,i]=$({}),l=Q(()=>{const p=[];for(const m of e.sections)p.push(...Ry(m.fields));return p},[e]),c=l.length>0&&n!==void 0,d=q(p=>{i(m=>{if(!m[p])return m;const h={...m};return delete h[p],h})},[]),f=q(async()=>{if(!n)return;const p=l.filter(b=>{const x=t[b];return x!=null&&String(x).trim()!==""});if(p.length===0)return;s("testing");const m={};for(const b of p)m[b]={status:"probing"};i(m);const h=await Promise.allSettled(p.map(async b=>{try{const x=await n(b,t[b]);return{key:b,result:x}}catch(x){const w={status:"error",error:x instanceof Error?x.message:String(x)};return{key:b,result:w}}})),g={};for(const b of h)if(b.status==="fulfilled"){const{key:x,result:v}=b.value;g[x]={status:v.status==="ok"?"ok":"error",result:v}}i(g),s("idle")},[n,l,t]);return{testAllStatus:o,hasProbeFields:c,probeResults:a,handleTestAll:f,clearProbeResult:d}}function Oy(e){const t=[];for(const n of e)"required"in n&&n.required===!0&&"key"in n&&n.key&&t.push(n.key),n.type==="group"&&"fields"in n&&t.push(...Oy(n.fields));return t}function fi(e){return e==null?!0:typeof e=="string"?e.trim()==="":!1}function ll(e,t={}){for(const n of e){if(n.type==="group"&&"fields"in n){ll(n.fields,t);continue}"key"in n&&n.key&&"default"in n&&n.default!==void 0&&(t[n.key]=n.default)}return t}function ip(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`probe-${crypto.randomUUID()}`:`probe-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function E6({open:e,integrationId:t,addonId:n,onClose:o}){const{t:s}=zt(),a=ke(),[i,l]=$({}),[c,d]=$(!1),[f,p]=$(null),[m,h]=$(ip),g=Eg({addonId:n,type:at.Camera},{enabled:e}),b=g.data??null;Y(()=>{if(e){const A=b?ll(b.sections.flatMap(D=>D.fields)):{};l(A),h(ip()),d(!1),p(null)}},[e,t,b]);const x=Q(()=>({...i,_probeRequestId:m}),[i,m]),v=$g({onSuccess:()=>{a.invalidateQueries({queryKey:[["deviceManager"]]})}}),w=gc(),y=q(async(A,D)=>{d(!0);const _=await w.mutateAsync({addonId:n,type:at.Camera,key:A,value:D,formValues:x});return _.status==="ok"&&_.suggestedValues&&l(R=>{let L=!1;const z={...R};for(const[j,H]of Object.entries(_.suggestedValues??{}))fi(R[j])&&!fi(H)&&(z[j]=H,L=!0);return L?z:R}),_},[w,n,x]),{testAllStatus:N,hasProbeFields:k,probeResults:S,handleTestAll:M,clearProbeResult:P}=P6(b??{sections:[]},i,y);async function I(A){p(null);try{if(await v.mutateAsync({addonId:n,type:at.Camera,config:i}),A){const D=b?ll(b.sections.flatMap(_=>_.fields)):{};l(D)}else o()}catch(D){p(D instanceof Error?D.message:String(D))}}if(!e)return null;const E=Oy((b?.sections??[]).flatMap(A=>A.fields)).filter(A=>fi(i[A])),B=E.length===0,O=!g.isLoading&&(g.isError||b===null);return u("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[r("div",{className:"absolute inset-0 bg-black/60",onClick:o}),u("div",{className:"relative z-10 flex w-full max-w-2xl flex-col max-h-[90vh] rounded-xl border border-border bg-background shadow-2xl",children:[u("div",{className:"flex items-center justify-between border-b border-border px-5 py-4 shrink-0",children:[r("h2",{className:"text-sm font-semibold text-foreground",children:s("integrations.addDevice")}),r("button",{onClick:o,className:"rounded-md p-1 text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors",children:r(qe,{className:"h-4 w-4"})})]}),r("div",{className:"flex-1 min-h-0 overflow-y-auto px-5 py-4 space-y-3",children:g.isLoading?r("div",{className:"flex items-center justify-center py-8",children:r(Pe,{className:"h-5 w-5 animate-spin text-primary"})}):O?u("div",{className:"flex items-start gap-3 rounded-lg border border-destructive/40 bg-destructive/10 px-4 py-3",children:[r(xt,{className:"h-4 w-4 text-destructive mt-0.5 shrink-0"}),u("div",{className:"space-y-1",children:[r("p",{className:"text-xs font-medium text-destructive",children:"Provider unavailable"}),u("p",{className:"text-xs text-foreground-subtle",children:["The addon ",r("span",{className:"font-mono",children:n})," is not ready or does not support manual device creation. Check that the integration is online and try again."]})]})]}):r(Nn,{schema:b,values:i,onChange:l,onTestField:y,probeResults:S,onClearProbe:P})}),!O&&!g.isLoading&&u("div",{className:"border-t border-border bg-surface/50 shrink-0",children:[u("button",{type:"button",onClick:()=>d(A=>!A),className:"flex w-full items-center justify-between px-5 py-2 text-[11px] text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors",children:[u("span",{className:"flex items-center gap-2",children:[r(Xe,{className:"h-3.5 w-3.5"}),"Test logs",r("span",{className:"font-mono text-[9px] opacity-60",children:m.slice(0,14)})]}),r(Rt,{className:`h-3.5 w-3.5 transition-transform ${c?"rotate-180":""}`})]}),c&&r("div",{className:"border-t border-border max-h-64 overflow-hidden",children:r(Wt,{addonId:n,requestId:m,limit:50,maxHeight:"max-h-64",showFilters:!1,showScope:!1,className:"border-0 rounded-none"})})]}),!O&&!g.isLoading&&(f||E.length>0)&&r("div",{className:"border-t border-destructive/30 bg-destructive/5 px-5 py-2 shrink-0",children:u("div",{className:"flex items-start gap-2",children:[r(xt,{className:"h-3.5 w-3.5 text-destructive mt-0.5 shrink-0"}),r("p",{className:"text-[11px] text-destructive",children:f||`Required: ${E.join(", ")}`})]})}),u("div",{className:"flex items-center justify-between border-t border-border px-5 py-3 shrink-0",children:[u("div",{className:"flex items-center gap-2",children:[r("button",{onClick:o,className:"rounded-lg border border-border px-3 py-1.5 text-xs text-foreground-subtle hover:text-foreground transition-colors",children:s("integrations.cancel")}),!O&&k&&u("button",{type:"button",onClick:M,disabled:N==="testing",className:"inline-flex items-center gap-1.5 rounded-lg border border-border px-3 py-1.5 text-xs font-medium text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors disabled:opacity-50",children:[N==="testing"?r(Pe,{className:"h-3.5 w-3.5 animate-spin"}):r(jn,{className:"h-3.5 w-3.5"}),"Test All"]})]}),u("div",{className:"flex items-center gap-2",children:[r("button",{onClick:()=>I(!0),disabled:O||!B||v.isPending,className:"rounded-lg border border-border px-3 py-1.5 text-xs text-foreground hover:bg-surface-hover transition-colors disabled:opacity-50",children:s("integrations.saveAndNew")}),r("button",{onClick:()=>I(!1),disabled:O||!B||v.isPending,className:"rounded-lg bg-primary px-4 py-1.5 text-xs font-medium text-primary-foreground shadow-sm disabled:opacity-50",children:v.isPending?s("integrations.saving"):s("integrations.save")})]})]})]})]})}function $6(){const{t:e}=zt(),{integrationId:t}=zc(),n=ke(),o=et(),s=Le(),[a,i]=$(!1),[l,c]=$(!1),[d,f]=$(!1),[p,m]=$(!1),{data:h,isLoading:g}=_g({id:t??""},{enabled:!!t}),{data:b}=dc({addonId:h?.addonId??"",nodeId:"hub"},{enabled:!!h?.addonId}),x=b!=null&&Array.isArray(b.sections)&&b.sections.some(B=>B.fields.length>0),{data:v}=Jn({},{refetchInterval:5e3}),w=[["integrations","get"],{input:{id:t??""},type:"query"}],y=Tg({onMutate:async B=>{await n.cancelQueries({queryKey:w});const O=n.getQueryData(w);return O!=null&&n.setQueryData(w,{...O,enabled:B.enabled}),{previous:O}},onError:(B,O,A)=>{const D=A;D?.previous!=null&&n.setQueryData(w,D.previous)},onSettled:()=>{n.invalidateQueries({queryKey:[["integrations"]]}),n.invalidateQueries({queryKey:[["deviceManager"]]})}}),N=Rg({onSuccess:()=>{n.invalidateQueries({queryKey:[["integrations"]]}),n.invalidateQueries({queryKey:[["deviceManager"]]}),f(!1),o("/integrations")}}),k=sa({onSuccess:()=>{n.invalidateQueries({queryKey:[["integrations"]]}),n.invalidateQueries({queryKey:[["deviceManager"]]})}}),S=Q(()=>v??[],[v]),M=Q(()=>{const B=new Map;for(const O of S)B.set(O.id,{id:O.id,name:O.name??O.stableId??`#${String(O.id)}`});return B},[S]),P=q(B=>M.get(B)??null,[M]),I=q(B=>r(cn,{type:B,size:"sm"}),[]),F=q(B=>o(`/devices/${String(B)}`),[o]),E=Q(()=>{const B=h?.addonId;if(!B)return 0;let O=0;for(const A of S)A.addonId!==B||A.parentDeviceId!==null&&A.parentDeviceId!==void 0&&A.role||(O+=1);return O},[S,h?.addonId]);return g?u("div",{className:"p-6",children:[r("div",{className:"h-16 rounded-lg bg-surface animate-pulse mb-4"}),r("div",{className:"h-40 rounded-lg bg-surface animate-pulse"})]}):h?u("div",{className:"p-6 space-y-5",children:[r(Wl,{items:[{label:"Integrations",onClick:()=>o("/integrations")},{label:h.name}]}),u("div",{className:"flex items-center justify-between",children:[u("div",{className:"flex items-center gap-3",children:[r("img",{src:`/api/addon-assets/${h.addonId}/assets/icon.svg`,alt:"",className:"h-8 w-8 rounded-lg",onError:B=>{B.target.style.display="none"}}),u("div",{children:[r("h1",{className:"text-lg font-semibold text-foreground",children:h.name}),u("p",{className:"text-[11px] text-foreground-subtle mt-0.5",children:[h.addonId," · ",E," ",e("integrations.devices")]})]})]}),u("div",{className:"flex items-center gap-3",children:[u("div",{className:`inline-flex items-center gap-2 rounded-lg border px-3 py-1.5 transition-colors ${y.isPending?"opacity-60":""} ${h.enabled?"border-success/30 bg-success/5":"border-border bg-surface"}`,title:e("integrations.toggleHint",{defaultValue:"Click to toggle"}),children:[r(Vl,{checked:h.enabled,onCheckedChange:B=>y.mutate({id:t,enabled:B}),disabled:y.isPending,"aria-label":h.enabled?"Disable integration":"Enable integration"}),r("span",{className:`text-[11px] font-medium ${h.enabled?"text-success":"text-foreground-subtle"}`,children:h.enabled?"Enabled":"Disabled"}),y.isPending&&r(Pe,{className:"h-3 w-3 animate-spin text-foreground-subtle"})]}),x&&u("button",{onClick:()=>c(!0),className:"flex items-center gap-1.5 rounded-lg border border-border bg-surface px-3 py-1.5 text-[11px] text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors",children:[r(wt,{className:"h-3 w-3"}),e("integrations.config")]}),u("button",{onClick:()=>m(!0),className:"flex items-center gap-1.5 rounded-lg border border-border bg-surface px-3 py-1.5 text-[11px] text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors",title:e("integrations.logs",{defaultValue:"View logs"}),children:[r(Xe,{className:"h-3 w-3"}),e("integrations.logs",{defaultValue:"Logs"})]}),r(Mx,{label:"Restart",icon:pt,title:`Restart "${h.name}"?`,description:`Restarting the addon will briefly disconnect every device backed by it (${E} active). Streams will reconnect automatically.`,confirmLabel:"Restart",triggerVariant:"outline",confirmVariant:"danger",disabled:k.isPending,action:()=>k.mutateAsync({addonId:h.addonId})}),u("button",{onClick:()=>f(!0),className:"flex items-center gap-1.5 rounded-lg border border-danger bg-danger/10 px-3 py-1.5 text-[11px] font-medium text-danger hover:bg-danger hover:text-background transition-colors",title:e("integrations.delete",{defaultValue:"Delete integration"}),children:[r(We,{className:"h-3 w-3"}),e("integrations.delete",{defaultValue:"Delete"})]})]})]}),r(ao,{devices:S,trpc:s.trpcClient,defaultView:"cards",forceAddon:h.addonId,urlScope:"root",lsKey:`integration-detail:${h.addonId}`,resolveIntegrationIcon:I,resolveParent:P,onNavigate:F}),r("button",{onClick:()=>i(!0),className:"fixed bottom-6 right-6 flex h-12 w-12 items-center justify-center rounded-full bg-primary shadow-lg shadow-primary/30 hover:shadow-primary/40 transition-shadow",title:e("integrations.addDevice"),children:r(Ot,{className:"h-5 w-5 text-primary-foreground"})}),a&&t&&r(E6,{open:a,integrationId:t,addonId:h.addonId,onClose:()=>i(!1)}),l&&r("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",onClick:()=>c(!1),children:u("div",{className:"rounded-xl border border-border bg-surface p-6 shadow-xl w-80",onClick:B=>B.stopPropagation(),children:[r("h2",{className:"text-sm font-semibold text-foreground mb-2",children:e("integrations.providerConfig")}),r("p",{className:"text-[11px] text-foreground-subtle",children:e("integrations.configComingSoon")}),r("button",{onClick:()=>c(!1),className:"mt-4 w-full rounded-lg bg-primary px-3 py-1.5 text-[11px] text-primary-foreground hover:bg-primary/90 transition-colors",children:"Close"})]})}),p&&r("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-6",onClick:()=>m(!1),children:u("div",{className:"flex flex-col rounded-xl border border-border bg-surface shadow-xl w-full max-w-5xl h-[80vh]",onClick:B=>B.stopPropagation(),children:[u("div",{className:"flex items-center justify-between border-b border-border px-4 py-2.5",children:[u("div",{className:"flex items-center gap-2 min-w-0",children:[r(Xe,{className:"h-4 w-4 text-primary shrink-0"}),r("h2",{className:"text-sm font-semibold text-foreground truncate",children:h.name}),u("span",{className:"text-[10px] text-foreground-subtle font-mono truncate",children:[h.addonId,t?` · ${t}`:""]})]}),r("button",{onClick:()=>m(!1),className:"flex h-7 w-7 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors","aria-label":"Close logs",children:r(qe,{className:"h-4 w-4"})})]}),r("div",{className:"flex-1 min-h-0 overflow-hidden",children:r(Wt,{addonId:h.addonId,limit:200,maxHeight:"max-h-full",showScope:!1,className:"h-full border-0 rounded-none"})})]})}),d&&r("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60",onClick:()=>!N.isPending&&f(!1),children:u("div",{className:"rounded-xl border border-border bg-background p-5 shadow-2xl w-96 space-y-3",onClick:B=>B.stopPropagation(),children:[u("div",{className:"flex items-start gap-3",children:[r("div",{className:"flex h-9 w-9 items-center justify-center rounded-lg bg-danger/10 shrink-0",children:r(xt,{className:"h-4 w-4 text-danger"})}),u("div",{className:"min-w-0",children:[r("h2",{className:"text-sm font-semibold text-foreground",children:e("integrations.deleteTitle",{defaultValue:"Delete integration?"})}),r("p",{className:"mt-1 text-[11px] text-foreground-subtle",children:e("integrations.deleteWarning",{defaultValue:'This removes the integration "{{name}}" and its {{count}} device(s). The addon will restart. This cannot be undone.',name:h.name,count:E})})]})]}),N.error&&r("div",{className:"rounded-lg border border-danger/40 bg-danger/10 px-3 py-2 text-[11px] text-danger",children:N.error instanceof Error?N.error.message:String(N.error)}),u("div",{className:"flex items-center justify-end gap-2 pt-1",children:[r("button",{onClick:()=>f(!1),disabled:N.isPending,className:"rounded-lg border border-border px-3 py-1.5 text-[11px] text-foreground-subtle hover:text-foreground transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:e("integrations.cancel",{defaultValue:"Cancel"})}),r("button",{onClick:()=>N.mutate({id:t}),disabled:N.isPending,className:"inline-flex items-center gap-1.5 rounded-lg bg-danger px-3 py-1.5 text-[11px] font-medium text-background hover:bg-danger/90 transition-colors disabled:opacity-60 disabled:cursor-not-allowed",children:N.isPending?u(ve,{children:[r(Pe,{className:"h-3 w-3 animate-spin"}),e("integrations.deleting",{defaultValue:"Deleting…"})]}):u(ve,{children:[r(We,{className:"h-3 w-3"}),e("integrations.confirmDelete",{defaultValue:"Delete integration"})]})})]})]})})]}):u("div",{className:"flex flex-col items-center justify-center py-20 px-6 text-center gap-4",children:[r("div",{className:"flex h-12 w-12 items-center justify-center rounded-full bg-foreground-subtle/10",children:r(VL,{className:"h-6 w-6 text-foreground-subtle"})}),u("div",{className:"space-y-1 max-w-sm",children:[r("h2",{className:"text-sm font-semibold text-foreground",children:e("integrations.integrationNotFound",{defaultValue:"Integration not found"})}),r("p",{className:"text-[11px] text-foreground-subtle",children:e("integrations.integrationNotFoundHint",{defaultValue:'The integration "{{id}}" does not exist. It may have been deleted, or the URL may be wrong.',id:t??""})})]}),u("button",{onClick:()=>o("/integrations"),className:"inline-flex items-center gap-1.5 rounded-lg border border-border bg-surface px-3 py-1.5 text-[11px] font-medium text-foreground hover:bg-surface-hover transition-colors",children:[r(Yx,{className:"h-3 w-3"}),e("integrations.backToList",{defaultValue:"Back to integrations"})]})]})}function _6({label:e,color:t,title:n,style:o}){return u("div",{className:"absolute top-1/2 -translate-y-1/2 -translate-x-1/2 z-10 group cursor-pointer",style:o,title:n,children:[r("div",{className:"h-2.5 w-2.5 rounded-full border-2 border-background shadow-sm transition-transform group-hover:scale-150",style:{backgroundColor:t}}),n&&r("div",{className:"absolute bottom-full left-1/2 -translate-x-1/2 mb-1.5 hidden group-hover:block z-20 pointer-events-none",children:u("div",{className:"bg-surface border border-border rounded px-2 py-1 text-[10px] text-foreground whitespace-nowrap shadow-lg",children:[r("span",{className:"inline-block h-1.5 w-1.5 rounded-full mr-1 align-middle",style:{backgroundColor:t}}),e]})})]})}const mi=36e5;function D6(e){return String(e).padStart(2,"0")}function L6(e){const t=new Date(e);return`${D6(t.getHours())}:00`}function T6({startMs:e,endMs:t,segments:n,events:o,playheadMs:s,onSeek:a}){const i=ne(null),l=t-e,c=q(h=>Math.max(0,Math.min(100,(h-e)/l*100)),[e,l]);function d(h){if(!i.current)return;const g=i.current.getBoundingClientRect(),b=Math.max(0,Math.min(1,(h.clientX-g.left)/g.width));a(Math.round(e+b*l))}const f=[],p=Math.floor(e/mi),m=Math.ceil(t/mi);for(let h=p;h<=m;h++){const g=h*mi;g<e||g>t||f.push({percent:c(g),label:L6(g)})}return u("div",{className:"select-none",children:[r("div",{className:"relative h-5 mb-1",children:f.map(({percent:h,label:g})=>r("span",{className:"absolute -translate-x-1/2 text-[10px] text-foreground-subtle",style:{left:`${h}%`},children:g},g))}),u("div",{ref:i,className:"relative h-8 rounded bg-surface-hover cursor-pointer overflow-hidden border border-border",onClick:d,onPointerMove:h=>{h.buttons===1&&d(h)},children:[n.map((h,g)=>{const b=c(h.startMs),x=c(h.endMs)-b;return r("div",{className:"absolute top-1 bottom-1 rounded-sm bg-success/60",style:{left:`${b}%`,width:`${Math.max(x,.1)}%`}},g)}),o.map(h=>r(_6,{label:h.label,color:h.color,title:`${h.label} — ${new Date(h.timestampMs).toLocaleTimeString()}`,style:{left:`${c(h.timestampMs)}%`}},h.id)),r("div",{className:"absolute top-0 bottom-0 w-0.5 bg-danger z-20 pointer-events-none",style:{left:`${c(s)}%`},children:r("div",{className:"absolute -top-0.5 left-1/2 -translate-x-1/2 w-2.5 h-2.5 bg-danger rotate-45"})})]})]})}const lp={person:"#f59e0b",vehicle:"#3b82f6",car:"#3b82f6",face:"#a855f7",plate:"#ec4899",animal:"#10b981",motion:"#ef4444",unknown:"#6b7280"};function cl(e){return lp[e.toLowerCase()]??lp.unknown}function R6(e){const t=new Date(e);return t.setHours(0,0,0,0),t.getTime()}function O6(e){return new Date(e).toISOString().slice(0,10)}function z6(e){return new Date(e+"T00:00:00").getTime()}function B6(e){return[{startMs:e+0*36e5,endMs:e+4*36e5},{startMs:e+6*36e5,endMs:e+10*36e5},{startMs:e+12*36e5,endMs:e+16*36e5},{startMs:e+18*36e5,endMs:e+23*36e5}]}function F6(e){const t=["person","vehicle","face","motion"];return Array.from({length:24},(n,o)=>({id:`placeholder-${o}`,timestampMs:e+Math.floor(Math.random()*24*36e5),label:t[o%t.length],color:cl(t[o%t.length])})).sort((n,o)=>n.timestampMs-o.timestampMs)}function j6(){const{t:e}=zt(),t=R6(new Date),[n,o]=$(t),[s,a]=$(null),[i,l]=$(t+12*36e5),c=n,d=n+24*36e5,{data:f,isLoading:p}=Jn({},{staleTime:3e4}),m=f??[],h=Q(()=>m.filter(N=>{const k=N.type.toLowerCase();return k==="camera"||k.includes("camera")||N.features.some(S=>S.toLowerCase().includes("video")||S.toLowerCase().includes("stream"))}).map(N=>({id:N.id,name:N.name??N.stableId})),[m]),g=s??h[0]?.id??null,{data:b}=Kn({queryKey:["events",g,c],queryFn:()=>Promise.resolve(null),enabled:!!g,staleTime:6e4}),x=Q(()=>{const y=Array.isArray(b)?b:(()=>{const k=Pd(b)?.events;return Array.isArray(k)?k:[]})();return y.length===0?g?F6(c):[]:y.flatMap((N,k)=>{const S=Pd(N);if(!S)return[];const M=String(S.class??S.type??S.label??"unknown").toLowerCase(),P=typeof S.timestamp=="number"?S.timestamp:c;return[{id:String(S.id??k),timestampMs:P,label:M,color:cl(M)}]})},[b,g,c]),v=Q(()=>g?B6(c):[],[g,c]);function w(y){o(N=>N+y*24*36e5),l(N=>N+y*24*36e5)}return u("div",{className:"flex flex-col h-full p-6 gap-5 overflow-hidden",children:[u("div",{className:"flex items-center justify-between gap-4 shrink-0",children:[r("h1",{className:"text-lg font-semibold text-foreground",children:e("nav.timeline","Timeline")}),u("div",{className:"flex items-center gap-2",children:[r("button",{onClick:()=>w(-1),className:"p-1 rounded hover:bg-surface-hover text-foreground-subtle hover:text-foreground transition-colors",children:r(Kc,{className:"h-4 w-4"})}),u("div",{className:"relative flex items-center",children:[r(Xx,{className:"absolute left-2 h-3.5 w-3.5 text-foreground-subtle pointer-events-none"}),r("input",{type:"date",value:O6(n),onChange:y=>{if(y.target.value){const N=z6(y.target.value);o(N),l(N+12*36e5)}},className:"rounded-lg border border-border bg-surface pl-7 pr-3 py-1.5 text-xs text-foreground focus:outline-none focus:border-primary/50"})]}),r("button",{onClick:()=>w(1),className:"p-1 rounded hover:bg-surface-hover text-foreground-subtle hover:text-foreground transition-colors",disabled:n>=t,children:r(Mt,{className:"h-4 w-4"})})]})]}),u("div",{className:"flex gap-1.5 shrink-0 overflow-x-auto pb-1",children:[p&&r("div",{className:"h-8 w-48 rounded-lg bg-surface animate-pulse"}),!p&&h.length===0&&r("span",{className:"text-xs text-foreground-subtle",children:"No cameras found"}),h.map(y=>{const N=y.id===g;return r("button",{onClick:()=>a(y.id),className:`shrink-0 rounded-lg px-3 py-1.5 text-[12px] font-medium transition-all border ${N?"bg-primary/12 text-primary border-primary/30":"bg-surface text-foreground-subtle border-border hover:bg-surface-hover hover:text-foreground"}`,children:y.name},y.id)})]}),u("div",{className:"relative w-full aspect-video rounded-xl border border-border bg-black shrink-0 overflow-hidden max-h-[45vh]",children:[u("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-3 text-foreground-subtle",children:[r(Zr,{className:"h-12 w-12 opacity-20"}),r("p",{className:"text-sm opacity-50",children:g?`${h.find(y=>y.id===g)?.name??g} — seek to play`:"Select a camera"})]}),r("div",{className:"absolute top-3 left-3 rounded bg-black/60 px-2 py-1 text-[11px] text-white font-mono",children:new Date(i).toLocaleTimeString()})]}),u("div",{className:"rounded-xl border border-border bg-surface px-4 pt-3 pb-4 shrink-0",children:[u("div",{className:"flex flex-wrap items-center gap-4 mb-3",children:[r("span",{className:"text-[10px] font-semibold text-foreground-subtle uppercase tracking-wider",children:"Timeline"}),u("div",{className:"flex items-center gap-1.5",children:[r("span",{className:"inline-block h-2 w-4 rounded-sm bg-success/60"}),r("span",{className:"text-[10px] text-foreground-subtle",children:"Recording"})]}),Array.from(new Set(x.map(y=>y.label))).slice(0,5).map(y=>u("div",{className:"flex items-center gap-1.5",children:[r("span",{className:"inline-block h-2.5 w-2.5 rounded-full",style:{backgroundColor:cl(y)}}),r("span",{className:"text-[10px] text-foreground-subtle capitalize",children:y})]},y))]}),g?r(T6,{startMs:c,endMs:d,segments:v,events:x,playheadMs:i,onSeek:l}):r("div",{className:"h-8 rounded bg-surface-hover flex items-center justify-center text-xs text-foreground-subtle",children:"Select a camera to view timeline"})]})]})}function H6({selectedNodeId:e,onSelect:t,refreshToken:n}){const{data:o}=In(void 0,{staleTime:3e4}),{data:s}=la(void 0,{staleTime:3e4}),a=new Map;for(const d of s??[])a.set(d.agentNodeId,(a.get(d.agentNodeId)??0)+1);const i=o??[],l=i.filter(d=>d.isOnline).length,c=i.filter(d=>!d.isOnline).length;return u("div",{className:"flex flex-col h-full",children:[u("button",{type:"button",onClick:()=>t(eo),className:`flex items-center gap-3 px-4 py-3 border-b border-border text-left transition-colors ${e===eo?"bg-primary/10 text-primary":"text-foreground hover:bg-surface-hover"}`,children:[r(br,{className:"h-4 w-4 flex-shrink-0"}),u("div",{className:"min-w-0 flex-1",children:[r("div",{className:"text-xs font-semibold truncate",children:"Cluster"}),r("div",{className:"text-[10px] text-foreground-subtle",children:"Balancer + failover + assignments"})]})]}),r("div",{className:"flex-1 overflow-y-auto",children:i.map(d=>{const f=e===d.id,p=a.get(d.id)??0,m=d.isHub?ln:ut;return u("button",{type:"button",onClick:()=>t(d.id),className:`flex items-center gap-3 w-full px-4 py-3 border-b border-border text-left transition-colors ${f?"bg-primary/10 text-primary":"text-foreground hover:bg-surface-hover"}`,children:[r(m,{className:"h-4 w-4 flex-shrink-0"}),u("div",{className:"min-w-0 flex-1",children:[u("div",{className:"flex items-center gap-2",children:[r("span",{className:"text-xs font-semibold truncate",children:d.name}),d.isHub&&r("span",{className:"text-[9px] uppercase tracking-wider text-foreground-subtle border border-border rounded px-1 py-0.5",children:"hub"}),!d.isOnline&&r("span",{className:"h-1.5 w-1.5 rounded-full bg-destructive flex-shrink-0"}),d.isOnline&&r("span",{className:"h-1.5 w-1.5 rounded-full bg-success flex-shrink-0"})]}),u("div",{className:"text-[10px] text-foreground-subtle flex items-center gap-2 mt-0.5",children:[u("span",{children:[d.cpuCores," cores"]}),r("span",{children:"•"}),u("span",{children:[Math.round(d.memoryMB/1024)," GB"]}),p>0&&u(ve,{children:[r("span",{children:"•"}),u("span",{className:"inline-flex items-center gap-0.5 text-foreground",children:[r(yy,{className:"h-2.5 w-2.5"}),p]})]})]})]})]},d.id)})}),u("div",{className:"px-4 py-2 border-t border-border text-[10px] text-foreground-subtle flex items-center justify-between",children:[u("span",{children:[l," online"]}),c>0&&u("span",{className:"text-destructive",children:[c," offline"]})]})]})}function V6({nodeId:e,refreshToken:t}){const{data:n}=In(void 0,{staleTime:3e4}),o=n?.find(i=>i.id===e),a=Ar("pipeline.runner-load-snapshot",i=>i.nodeId===e)?.load??null;return o?u("div",{className:"px-6 py-4 border-b border-border",children:[u("div",{className:"flex items-center gap-2 mb-1",children:[r("h2",{className:"text-base font-semibold text-foreground",children:o.name}),o.isOnline?r("span",{className:"text-[10px] px-2 py-0.5 rounded-full bg-success/10 text-success",children:"online"}):r("span",{className:"text-[10px] px-2 py-0.5 rounded-full bg-destructive/10 text-destructive",children:"offline"}),o.isHub&&r("span",{className:"text-[9px] uppercase tracking-wider text-foreground-subtle border border-border rounded px-1 py-0.5",children:"hub"})]}),u("div",{className:"text-[11px] text-foreground-subtle flex items-center gap-2 flex-wrap",children:[r("span",{children:o.cpuModel??"CPU"}),r("span",{children:"•"}),u("span",{children:[o.cpuCores," cores"]}),r("span",{children:"•"}),u("span",{children:[Math.round(o.memoryMB/1024)," GB"]}),a&&u(ve,{children:[r("span",{children:"•"}),u("span",{children:[a.attachedCameras," cameras (",a.activeCameras," active)"]}),r("span",{children:"•"}),u("span",{children:[a.avgInferenceTimeMs.toFixed(0),"ms avg inference"]}),r("span",{children:"•"}),u("span",{children:["queue ",a.queueDepthTotal]}),a.hardware.hasGpu&&u(ve,{children:[r("span",{children:"•"}),r("span",{className:"text-success",children:"GPU"})]})]})]})]}):r("div",{className:"px-6 py-4 border-b border-border",children:u("div",{className:"text-xs text-foreground-subtle",children:["Node not found: ",e]})})}function zy({refreshToken:e,nodeId:t}){const[n,o]=$(new Map),{nodes:s}=Pr();dt("pipeline.camera-metrics-snapshot",p=>{const m=p.data;typeof m?.deviceId=="number"&&o(h=>{const g=new Map(h);return g.set(m.deviceId,m),g})});const{data:a}=Nb(void 0,{staleTime:5e3}),i=Q(()=>{const p=new Map;for(const m of a??[])p.set(m.nodeId,m.deviceCount);return p},[a]),l=Q(()=>{const p=new Map,m=Date.now()-3e4;for(const h of n.values()){if(h.timestamp<m)continue;const g=h.nodeId??"hub",b=p.get(g)??{attachedCameras:0,activeCameras:0,totalFps:0,totalInferenceWeighted:0,queueDepth:0};b.attachedCameras++,h.metrics.phase==="active"&&b.activeCameras++,b.totalFps+=h.metrics.actualFps,b.totalInferenceWeighted+=h.metrics.avgInferenceTimeMs,b.queueDepth+=h.metrics.queueDepth,p.set(g,b)}return p},[n]),c=Q(()=>{const p=new Map;for(const m of s)p.set(m.id,m.shortName);return p},[s]),d=Q(()=>{let p=0,m=0,h=0,g=0,b=0;for(const v of l.values())p+=v.attachedCameras,m+=v.activeCameras,h+=v.totalFps,g+=v.totalInferenceWeighted,b+=v.queueDepth;const x=p>0?g/p:0;return{totalAgents:s.length,onlineAgents:s.filter(v=>v.isOnline).length,attachedCameras:p,activeCameras:m,avgInferenceTimeMs:x,queueDepth:b,totalFps:h}},[l,s]);if(t){const p=l.get(t);return u("div",{className:"@container/liveload",children:[r("h3",{className:"text-sm font-semibold text-foreground mb-2",children:"Live load"}),u("div",{className:"grid grid-cols-2 @md/liveload:grid-cols-3 @3xl/liveload:grid-cols-5 gap-2 mb-3",children:[r(Ht,{label:"FPS",value:p?p.totalFps.toFixed(1):"—"}),r(Ht,{label:"Cameras",value:p?`${p.activeCameras}/${p.attachedCameras}`:"—"}),r(Ht,{label:"Avg infer ms",value:p&&p.attachedCameras>0?(p.totalInferenceWeighted/p.attachedCameras).toFixed(0):"—"}),r(Ht,{label:"Queue",value:p?String(p.queueDepth):"—"}),r(Ht,{label:"Audio",value:String(i.get(t)??"—")})]})]})}const f=[...l.entries()].sort(([p],[m])=>p==="hub"?-1:m==="hub"?1:p.localeCompare(m));return u("div",{className:"@container/liveload",children:[r("h3",{className:"text-sm font-semibold text-foreground mb-2",children:"Live load"}),u("div",{className:"grid grid-cols-2 @md/liveload:grid-cols-3 @3xl/liveload:grid-cols-5 gap-2 sm:gap-3 mb-3",children:[r(Ht,{label:"Total agents",value:`${d.onlineAgents}/${d.totalAgents}`}),r(Ht,{label:"Cameras",value:`${d.activeCameras}/${d.attachedCameras}`}),r(Ht,{label:"Total FPS",value:d.totalFps.toFixed(1)}),r(Ht,{label:"Avg inference ms",value:d.avgInferenceTimeMs.toFixed(0)}),r(Ht,{label:"Queue depth",value:String(d.queueDepth)})]}),r("div",{className:"rounded-lg border border-border overflow-x-auto",children:u("table",{className:"w-full text-xs min-w-[480px]",children:[r("thead",{className:"bg-surface",children:u("tr",{className:"text-foreground-subtle text-[10px] uppercase tracking-wider",children:[r("th",{className:"text-left px-3 py-2",children:"Agent"}),r("th",{className:"text-right px-3 py-2",children:"FPS"}),r("th",{className:"text-right px-3 py-2",children:"Cameras"}),r("th",{className:"text-right px-3 py-2",children:"Inference ms"}),r("th",{className:"text-right px-3 py-2",children:"Queue"}),r("th",{className:"text-right px-3 py-2",children:"Audio"})]})}),u("tbody",{children:[f.map(([p,m])=>u("tr",{className:"border-t border-border",children:[r("td",{className:"px-3 py-2 text-foreground font-medium",children:c.get(p)??p}),r("td",{className:"px-3 py-2 text-right text-foreground",children:m.totalFps.toFixed(1)}),r("td",{className:"px-3 py-2 text-right text-foreground",children:m.attachedCameras}),r("td",{className:"px-3 py-2 text-right text-foreground",children:m.attachedCameras>0?(m.totalInferenceWeighted/m.attachedCameras).toFixed(0):"—"}),r("td",{className:"px-3 py-2 text-right text-foreground",children:m.queueDepth}),r("td",{className:"px-3 py-2 text-right text-foreground",children:i.get(p)??"—"})]},p)),f.length===0&&r("tr",{children:r("td",{colSpan:6,className:"px-3 py-4 text-center text-foreground-subtle text-[11px]",children:"No camera metrics received yet"})})]})]})})]})}function Ht({label:e,value:t}){return u("div",{className:"rounded-lg border border-border bg-surface/60 p-3",children:[r("div",{className:"text-[10px] uppercase tracking-wider text-foreground-subtle mb-1",children:e}),r("div",{className:"text-lg font-semibold text-foreground",children:t})]})}function By(e){return Jn({addonId:e})}function q6(e){return Fn({deviceId:e},{enabled:Number.isFinite(e)})}const Q6=3e4,U6=2e3;function Fy(e){const t=ne(0);return t.current===0&&(t.current=Date.now()),wg({parentDeviceId:e},{enabled:Number.isFinite(e),staleTime:0,refetchOnMount:"always",refetchInterval:n=>{const o=n.state.data;return o&&o.length>0||Date.now()-t.current>=Q6?!1:U6}})}const hi={active:!1,pinned:!1,nodeId:null,reason:""},gi=["pipeline.camera-assigned","pipeline.camera-unassigned","pipeline.camera-updated","agent.online","agent.offline"],K6={pipeline:ut,decoder:Zr,audio:nl},cp={pipeline:"Pipeline",decoder:"Decoder",audio:"Audio"};function jy({mode:e,nodeId:t,compact:n=!1}){if(e==="agent"&&!t)throw new Error('CameraAssignmentsTable: nodeId is required when mode === "agent"');const o=ke(),[s,a]=$(null),[i,l]=$(null),[c,d]=$(new Map);yt(["pipelineOrchestrator","getPipelineAssignments"],gi),yt(["pipelineOrchestrator","getDecoderAssignments"],gi),yt(["pipelineOrchestrator","getAudioAssignments"],gi);const{data:f}=la(void 0,{staleTime:3e4}),{data:p}=yb(void 0,{staleTime:3e4}),{data:m}=kb(void 0,{staleTime:3e4}),{nodes:h}=Pr(),{data:g}=By();dt("pipeline.camera-metrics-snapshot",E=>{const B=E.data;typeof B.deviceId=="number"&&d(O=>{const A=new Map(O);return A.set(B.deviceId,B),A})}),Y(()=>{if(c.size===0)return;const E=setInterval(()=>{d(B=>{const O=Date.now()-1e4;let A=!1;const D=new Map(B);for(const[_,R]of B)R.timestamp<O&&(D.delete(_),A=!0);return A?D:B})},5e3);return()=>clearInterval(E)},[c.size]);const b=Q(()=>{const E=new Map;for(const B of g??[])E.set(B.id,B.name);return E},[g]),x=Q(()=>{const E=new Map,B=A=>{const D=E.get(A);if(D)return D;const _={deviceId:A,deviceName:b.get(A)??`Device ${A}`,pipeline:hi,decoder:hi,audio:hi};return E.set(A,_),_};for(const A of f??[]){const D=B(A.deviceId);E.set(A.deviceId,{...D,pipeline:{active:e==="cluster"?!0:A.agentNodeId===t,pinned:A.pinned,nodeId:A.agentNodeId,reason:A.reason??""}})}for(const A of p??[]){const D=B(A.deviceId);E.set(A.deviceId,{...D,decoder:{active:e==="cluster"?!0:A.decoderNodeId===t,pinned:A.pinned,nodeId:A.decoderNodeId,reason:A.reason??""}})}for(const A of m??[]){const D=B(A.deviceId);E.set(A.deviceId,{...D,audio:{active:e==="cluster"?!0:A.nodeId===t,pinned:A.pinned,nodeId:A.nodeId,reason:"capacity"}})}let O=[...E.values()];return e==="agent"&&(O=O.filter(A=>A.pipeline.active||A.decoder.active||A.audio.active)),O.sort((A,D)=>A.deviceId-D.deviceId),O},[f,p,m,b,e,t]),v=Q(()=>(h??[]).filter(E=>E.isOnline).map(E=>({id:E.id,name:E.name})),[h]),w=()=>{o.invalidateQueries({queryKey:[["pipelineOrchestrator","getPipelineAssignments"]]}),o.invalidateQueries({queryKey:[["pipelineOrchestrator","getDecoderAssignments"]]}),o.invalidateQueries({queryKey:[["pipelineOrchestrator","getAudioAssignments"]]})},y=ub({onSuccess:w}),N=pb({onSuccess:w}),k=bb({onSuccess:w}),S=xb({onSuccess:w}),M=vb({onSuccess:w}),P=wb({onSuccess:w}),I=(E,B,O)=>{B==="pipeline"?y.mutate({deviceId:E,agentNodeId:O}):B==="decoder"?k.mutate({deviceId:E,nodeId:O}):M.mutate({deviceId:E,nodeId:O}),a(null)},F=(E,B)=>{B==="pipeline"?N.mutate({deviceId:E}):B==="decoder"?S.mutate({deviceId:E}):P.mutate({deviceId:E}),a(null)};return r("div",{className:"rounded-lg border border-border overflow-x-auto",children:u("table",{className:"w-full text-xs min-w-[640px]",children:[r("thead",{className:"bg-surface",children:u("tr",{className:"text-foreground-subtle text-[10px] uppercase tracking-wider",children:[!n&&r("th",{className:"w-6"}),r("th",{className:"text-left px-3 py-2 align-middle",children:"Camera"}),r("th",{className:"text-left px-3 py-2 align-middle",children:"Pipeline"}),r("th",{className:"text-left px-3 py-2 align-middle",children:"Decoder"}),r("th",{className:"text-left px-3 py-2 align-middle",children:"Audio"}),r("th",{className:"text-left px-3 py-2 align-middle",children:"Status"})]})}),u("tbody",{children:[x.map(E=>{const B=c.get(E.deviceId),O=i===E.deviceId;return u(Pl.Fragment,{children:[u("tr",{className:"border-t border-border align-middle relative",children:[!n&&r("td",{className:"px-2 py-2 align-middle",children:r("button",{type:"button",onClick:()=>l(O?null:E.deviceId),className:"p-1 rounded hover:bg-surface-hover text-foreground-subtle","aria-label":O?"Collapse broker details":"Expand broker details",children:O?r(Rt,{className:"h-3.5 w-3.5"}):r(Mt,{className:"h-3.5 w-3.5"})})}),u("td",{className:"px-3 py-2 align-middle",children:[r("div",{className:"text-foreground font-medium leading-tight",children:E.deviceName}),u("div",{className:"text-[10px] text-foreground-subtle leading-tight",children:["#",E.deviceId]})]}),r(bi,{role:"pipeline",state:E.pipeline,mode:e,deviceId:E.deviceId,onlineNodes:v,isMenuOpen:s?.deviceId===E.deviceId&&s.role==="pipeline",onToggleMenu:()=>a(s?.deviceId===E.deviceId&&s.role==="pipeline"?null:{deviceId:E.deviceId,role:"pipeline"}),onCloseMenu:()=>a(null),onMove:A=>I(E.deviceId,"pipeline",A),onUnpin:()=>F(E.deviceId,"pipeline")}),r(bi,{role:"decoder",state:E.decoder,mode:e,deviceId:E.deviceId,onlineNodes:v,isMenuOpen:s?.deviceId===E.deviceId&&s.role==="decoder",onToggleMenu:()=>a(s?.deviceId===E.deviceId&&s.role==="decoder"?null:{deviceId:E.deviceId,role:"decoder"}),onCloseMenu:()=>a(null),onMove:A=>I(E.deviceId,"decoder",A),onUnpin:()=>F(E.deviceId,"decoder")}),r(bi,{role:"audio",state:E.audio,mode:e,deviceId:E.deviceId,onlineNodes:v,isMenuOpen:s?.deviceId===E.deviceId&&s.role==="audio",onToggleMenu:()=>a(s?.deviceId===E.deviceId&&s.role==="audio"?null:{deviceId:E.deviceId,role:"audio"}),onCloseMenu:()=>a(null),onMove:A=>I(E.deviceId,"audio",A),onUnpin:()=>F(E.deviceId,"audio")}),r("td",{className:"px-3 py-2 align-middle",children:r(Y6,{snap:B})})]}),O&&!n&&u("tr",{className:"bg-surface/50",children:[r("td",{}),r("td",{colSpan:5,className:"px-3 py-2",children:r(it,{widgetId:"stream-broker/stream-broker-panel",host:"device-tab",deviceId:E.deviceId,instanceId:`pipeline-row/${E.deviceId}`,config:{variant:"compact",title:"Stream brokers & clients"}})})]})]},E.deviceId)}),x.length===0&&r("tr",{children:r("td",{colSpan:n?5:6,className:"px-3 py-4 text-center text-foreground-subtle text-[11px]",children:e==="agent"?"No cameras assigned to this node":"No cameras currently assigned"})})]})]})})}function bi({role:e,state:t,mode:n,onlineNodes:o,isMenuOpen:s,onToggleMenu:a,onCloseMenu:i,onMove:l,onUnpin:c}){const d=K6[e],f=o.filter(h=>h.id!==(t.nodeId??"")),m=(t.active||n==="cluster")&&(f.length>0||t.pinned);return u("td",{className:"px-3 py-2 align-middle relative",children:[u("div",{className:"flex items-center gap-2",children:[n==="agent"?r(G6,{state:t,Icon:d}):r(W6,{state:t,Icon:d}),r("div",{className:"ml-auto",children:m&&r("button",{type:"button",onClick:a,className:"p-1 rounded hover:bg-surface-hover","aria-label":`${cp[e]} actions`,children:r(DD,{className:"h-3 w-3 text-foreground-subtle"})})})]}),s&&m&&r(Z6,{title:cp[e],targets:f,pinned:t.pinned,onMove:l,onUnpin:c,onClose:i})]})}function G6({state:e,Icon:t}){const n=e.active?gy:Eo;return u("div",{className:"flex items-center gap-1.5",children:[r(n,{className:`h-3.5 w-3.5 ${e.active?"text-success":"text-foreground-subtle/50"}`}),r(t,{className:`h-3 w-3 ${e.active?"text-foreground-subtle":"text-foreground-subtle/40"}`}),e.pinned&&r(py,{className:"h-2.5 w-2.5 text-amber-400"})]})}function W6({state:e,Icon:t}){return!e.active||!e.nodeId?u("div",{className:"flex items-center gap-1.5 text-foreground-subtle/60",children:[r(t,{className:"h-3 w-3"}),r("span",{className:"text-[10px] italic",children:"—"})]}):u("div",{className:"flex items-center gap-1.5 min-w-0",children:[r(t,{className:"h-3 w-3 text-foreground-subtle shrink-0"}),u("div",{className:"flex flex-col leading-tight min-w-0",children:[r("span",{className:"font-mono text-[11px] text-foreground truncate",children:e.nodeId}),r("span",{className:"flex items-center gap-1 text-[10px]",children:e.pinned?u("span",{className:"inline-flex items-center gap-0.5 text-amber-400",children:[r(py,{className:"h-2.5 w-2.5"})," manual"]}):u("span",{className:"text-foreground-subtle truncate",children:["auto · ",e.reason||"capacity"]})})]})]})}function Y6({snap:e}){if(!e)return r("span",{className:"text-[10px] text-foreground-subtle italic",children:"—"});const{phase:t,actualFps:n,avgInferenceTimeMs:o,queueDepth:s,configuredFps:a}=e.metrics,i=Wn(t);return u("div",{className:"flex flex-col gap-0.5 font-mono text-[10px] tabular-nums leading-tight",children:[u("span",{className:`inline-flex items-center gap-1 ${i.textColor}`,children:[r(Pc,{phase:t,className:"h-2.5 w-2.5"}),r("span",{className:"font-semibold uppercase tracking-wider",children:i.label})]}),u("span",{className:"text-foreground-subtle",children:[r("span",{className:"text-foreground",children:n.toFixed(1)}),u("span",{children:["/",a.toFixed(0)," fps"]})]}),u("span",{className:"text-foreground-subtle",children:[r("span",{className:"text-foreground",children:o.toFixed(0)}),r("span",{children:" ms"}),s>0&&u("span",{className:"text-warning ml-1",children:["q",s]})]})]})}function Z6({title:e,targets:t,pinned:n,onMove:o,onUnpin:s,onClose:a}){const i=ne(null);return Y(()=>{const l=c=>{i.current?.contains(c.target)||a()};return window.addEventListener("mousedown",l),()=>window.removeEventListener("mousedown",l)},[a]),u("div",{ref:i,className:"absolute right-2 top-full mt-1 w-48 rounded-lg border border-border bg-surface shadow-lg z-20 text-left",children:[r("div",{className:"px-3 py-1 text-[9px] uppercase tracking-wider text-foreground-subtle border-b border-border",children:e}),t.length>0&&r("div",{className:"py-1",children:t.map(l=>u("button",{type:"button",onClick:()=>o(l.id),className:"block w-full text-left px-3 py-1 text-[11px] text-foreground hover:bg-surface-hover",children:["Move to ",l.name]},l.id))}),n&&u("button",{type:"button",onClick:s,className:"block w-full text-left px-3 py-1.5 text-[11px] text-destructive hover:bg-destructive/10 border-t border-border",children:["Unpin ",e.toLowerCase()]}),t.length===0&&!n&&r("div",{className:"px-3 py-1.5 text-[10px] text-foreground-subtle italic",children:"Already auto · no other nodes online"})]})}function X6({nodeId:e,refreshToken:t}){return u("div",{className:"space-y-6",children:[r(zy,{refreshToken:t,nodeId:e}),u("div",{children:[r("h3",{className:"text-sm font-semibold text-foreground mb-1",children:"Cameras on this node"}),u("p",{className:"text-[11px] text-foreground-subtle",children:["Checkboxes mark the roles currently running on ",e,". Use the kebab to move a role to another node or unpin it; live KPIs come from the runner snapshot stream."]})]}),r(jy,{mode:"agent",nodeId:e,compact:!0})]})}function J6(e,t){const n=Math.max(0,t-e),o=Math.floor(e/1e3),s=Math.floor(n/1e3);return`${o}s idle · ${s}s left`}function eO({nodeId:e,refreshToken:t}){const n=ke(),o=db({onSettled:()=>{n.invalidateQueries({queryKey:["pipelineExecutor","listLoadedEngines"]})}}),{data:s}=cb({nodeId:e},{staleTime:5e3}),i=Ar("pipeline.engine-metrics-snapshot",m=>m.nodeId===e)?.engines??s??null,l=i===null;yt(["pipelineRunner","getLocalCameras"],["pipeline.camera-assigned","pipeline.camera-unassigned"]);const{data:c}=_b({nodeId:e},{staleTime:3e4}),{values:d}=ec("pipeline.camera-metrics-snapshot",m=>m.deviceId,m=>m.nodeId===e),f=Q(()=>d.filter(m=>m.metrics.phase==="active").length,[d]),p=m=>{const h=c??[];h.length>0&&!window.confirm(`${h.length} camera(s) are dispatching through this engine. Killing it forces a respawn on the next frame. Continue?`)||o.mutate({nodeId:e,engine:m,force:h.length>0})};return u("div",{className:"space-y-6",children:[u("div",{children:[r("h3",{className:"text-sm font-semibold text-foreground mb-1",children:"Inference engines on this node"}),u("p",{className:"text-[11px] text-foreground-subtle",children:[(i??[]).length," engine(s) resident in RAM. ",(c??[]).length," camera(s) attached, ",f," actively dispatching frames. Refreshes every 5s."]})]}),r("div",{className:"rounded-lg border border-border overflow-x-auto",children:u("table",{className:"w-full text-xs min-w-[640px]",children:[r("thead",{className:"bg-surface",children:u("tr",{className:"text-foreground-subtle text-[10px] uppercase tracking-wider",children:[r("th",{className:"text-left px-3 py-2 whitespace-nowrap",children:"Kind"}),r("th",{className:"text-left px-3 py-2 whitespace-nowrap",children:"Runtime / Backend / Device"}),r("th",{className:"text-left px-3 py-2",children:"Models"}),r("th",{className:"text-right px-3 py-2 whitespace-nowrap",children:"Pool PID"}),r("th",{className:"text-right px-3 py-2 whitespace-nowrap",children:"Auto-kill"}),r("th",{className:"text-right px-3 py-2 whitespace-nowrap",children:"In use"}),r("th",{className:"w-20"})]})}),u("tbody",{children:[l&&r("tr",{children:r("td",{colSpan:7,className:"px-3 py-4 text-center text-foreground-subtle text-[11px]",children:"Loading…"})}),!l&&(i??[]).map(m=>{const h=m.kind==="warm-override";return u("tr",{className:`border-t border-border ${h?"bg-amber-500/5":""}`,children:[r("td",{className:"px-3 py-2",children:u("span",{className:`inline-flex items-center gap-1 px-1.5 py-0.5 rounded-full text-[10px] font-medium ${h?"bg-amber-500/15 text-amber-400":"bg-success/15 text-success"}`,children:[h?r(BD,{className:"h-3 w-3"}):r(ut,{className:"h-3 w-3"}),h?"warm":"runtime"]})}),r("td",{className:"px-3 py-2",children:u("span",{className:"inline-flex items-center gap-1 text-[11px] text-sky-400",children:[r(Jc,{className:"h-3 w-3"}),m.engine.runtime,"/",m.engine.backend,m.engine.device?`/${m.engine.device}`:"",m.engine.format?` · ${m.engine.format}`:""]})}),r("td",{className:"px-3 py-2",children:m.modelsLoaded.length===0?r("span",{className:"text-foreground-subtle text-[11px]",children:"—"}):r("div",{className:"flex flex-wrap gap-1",children:m.modelsLoaded.map(g=>r("span",{className:"inline-block rounded bg-surface px-1.5 py-0.5 text-[10px] font-mono text-foreground-subtle",children:g},g))})}),r("td",{className:"px-3 py-2 text-right font-mono text-foreground",children:m.poolPid??"—"}),r("td",{className:"px-3 py-2 text-right text-[11px]",children:m.idleMs!==null&&m.idleTtlMs!==null?r("span",{className:"text-foreground-subtle",children:J6(m.idleMs,m.idleTtlMs)}):r("span",{className:"text-foreground-subtle/50",children:"never"})}),r("td",{className:"px-3 py-2 text-right text-foreground",children:h?"—":(c??[]).length}),r("td",{className:"px-3 py-2 text-right",children:u("button",{type:"button",disabled:o.isPending,onClick:()=>p(m.engine),className:"inline-flex items-center gap-1 px-2 py-1 rounded border border-destructive/30 text-destructive text-[11px] hover:bg-destructive/10 disabled:opacity-50",children:[r(We,{className:"h-3 w-3"}),"Kill"]})})]},m.engineKey)}),!l&&(i??[]).length===0&&r("tr",{children:r("td",{colSpan:7,className:"px-3 py-4 text-center text-foreground-subtle text-[11px]",children:"No engines resident — the factory spins up on the first pipeline run."})})]})]})}),u("div",{className:"text-[10px] text-foreground-subtle leading-relaxed",children:[r("strong",{className:"text-foreground",children:"runtime"}),": main camera-serving engine; never auto-killed while cameras attached. ",r("strong",{className:"text-foreground",children:"warm"}),": benchmark/test override held in cache for fast re-use; auto-disposed after the idle TTL."]}),o.isError&&u("div",{className:"rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-[11px] text-destructive",children:["Kill failed: ",o.error instanceof Error?o.error.message:"unknown"]})]})}function Nt(e){if(!Number.isFinite(e)||e<0)return"—";if(e<1024)return`${Math.round(e)} B`;const t=["KB","MB","GB","TB","PB"];let n=e/1024,o="KB";for(const a of t){if(o=a,n<1024)break;n/=1024}return`${n>=100?Math.round(n).toString():n.toFixed(1)} ${o}`}function Hy(e){return Nt(e*1024*1024)}const tO=new Set(ow);function dp(e){return tO.has(e)}function xi(e,t,n){return`${e}/${t}/${n}`}function dl(e){return{coreml:"CoreML",openvino:"OpenVINO",onnx:"ONNX"}[e.format]??e.format.toUpperCase()}function up(e){return{coreml:"Apple Neural Engine / GPU — .mlpackage",openvino:"Intel CPU / GPU / NPU — .xml",onnx:"CPU, CUDA, Node.js — .onnx"}[e.format]??`.${e.format}`}function _n(e){return e.format}function nO(e,t){let n=0,o=0,s=0;for(const a of e)for(const i of a.addons)for(const l of i.models){const c=l.formats[t];c&&(n++,c.downloaded&&(o++,s+=c.sizeMB))}return{total:n,downloaded:o,downloadedSizeMB:s}}function rO({addonId:e,model:t,format:n,isActive:o,progress:s,errorMsg:a,onDownload:i,onDelete:l}){const c=t.formats[n];return c?u("div",{className:"flex items-center gap-3 px-4 py-3 border-b border-border/50 last:border-b-0 hover:bg-surface-hover/30 transition-colors",children:[r("div",{className:`h-2 w-2 rounded-full shrink-0 ${c.downloaded?"bg-success":"bg-foreground-subtle/30"}`}),u("div",{className:"flex-1 min-w-0",children:[u("div",{className:"flex items-center gap-2",children:[r("span",{className:"text-sm font-medium text-foreground",children:t.name}),u("span",{className:"text-[10px] text-foreground-subtle font-mono",children:["(",t.id,")"]})]}),s&&s.progress>=0&&s.progress<100&&u("div",{className:"mt-1.5 flex items-center gap-2 max-w-xs",children:[r("div",{className:"flex-1 h-1 bg-surface-hover rounded-full overflow-hidden",children:r("div",{className:"bg-primary h-full rounded-full transition-all duration-300",style:{width:`${s.progress}%`}})}),u("span",{className:"text-[9px] text-primary font-mono tabular-nums shrink-0",children:[Math.round(s.progress),"%"]})]})]}),r("span",{className:"text-xs text-foreground-subtle tabular-nums shrink-0",children:Hy(c.sizeMB)}),a&&u("span",{className:"flex items-center gap-1 text-[10px] text-danger max-w-[160px] truncate shrink-0",title:a,children:[r(xa,{className:"h-3 w-3 shrink-0"}),a]}),c.downloaded?u("button",{onClick:l,disabled:o,className:"inline-flex items-center gap-1.5 px-3 py-1.5 text-[11px] font-medium rounded-md border border-danger/30 text-danger hover:bg-danger/10 disabled:opacity-50 transition-colors shrink-0",children:[o?r(Pe,{className:"h-3 w-3 animate-spin"}):r(We,{className:"h-3 w-3"}),o?"Deleting...":"Delete"]}):u("button",{onClick:i,disabled:o,className:"inline-flex items-center gap-1.5 px-3 py-1.5 text-[11px] font-medium rounded-md bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-50 transition-colors shrink-0",children:[o?r(Pe,{className:"h-3 w-3 animate-spin"}):r(wn,{className:"h-3 w-3"}),o?"Downloading...":"Download"]})]}):null}function oO({engines:e,activeEngine:t,viewEngine:n,onSelect:o}){const[s,a]=$(!1);return u("div",{className:"relative",children:[u("button",{type:"button",onClick:()=>a(!s),className:"flex items-center gap-2 rounded-lg border border-border bg-surface px-4 py-2.5 w-full text-left hover:bg-surface-hover transition-colors",children:[r(ut,{className:"h-4 w-4 text-primary shrink-0"}),u("div",{className:"flex-1 min-w-0",children:[u("div",{className:"flex items-center gap-2",children:[r("span",{className:"text-sm font-medium text-foreground",children:dl(n)}),_n(n)===_n(t)&&r("span",{className:"text-[9px] px-1.5 py-0.5 rounded-full bg-success/10 text-success font-medium",children:"Active"})]}),r("div",{className:"text-[10px] text-foreground-subtle",children:up(n)})]}),r(Rt,{className:`h-4 w-4 text-foreground-subtle transition-transform ${s?"rotate-180":""}`})]}),s&&r("div",{className:"absolute top-full left-0 right-0 mt-1 rounded-lg border border-border bg-surface shadow-lg z-50 overflow-hidden",children:e.map(i=>{const l=_n(i)===_n(n),c=_n(i)===_n(t);return u("button",{type:"button",onClick:()=>{o(i),a(!1)},className:`flex items-center gap-3 px-4 py-2.5 w-full text-left transition-colors ${l?"bg-primary/5":"hover:bg-surface-hover"}`,children:[r(ut,{className:`h-4 w-4 shrink-0 ${l?"text-primary":"text-foreground-subtle"}`}),u("div",{className:"flex-1",children:[u("div",{className:"flex items-center gap-2",children:[r("span",{className:`text-sm font-medium ${l?"text-primary":"text-foreground"}`,children:dl(i)}),c&&r("span",{className:"text-[9px] px-1.5 py-0.5 rounded-full bg-success/10 text-success font-medium",children:"Active"})]}),r("div",{className:"text-[10px] text-foreground-subtle",children:up(i)})]}),l&&r(ey,{className:"h-4 w-4 text-primary shrink-0"})]},_n(i))})})]})}function sO({embedded:e=!1,nodeId:t}={}){const n=ke(),o=t??"hub",[s,a]=$(null),[i,l]=$(new Set),[c,d]=$(new Map),[f,p]=$(new Map),[m,h]=$(""),{data:g=[]}=ob({nodeId:o},{staleTime:6e4}),x=g.filter((R,L,z)=>z.findIndex(j=>j.format===R.format)===L),{data:v}=sb({nodeId:o},{staleTime:3e4}),w=v,{data:y,isLoading:N}=So({nodeId:o},{staleTime:1e4}),k=ib(),S=lb();dt("model.download.progress",R=>{const L=R.data,z=typeof L.modelId=="string"?L.modelId:void 0,j=typeof L.progress=="number"?L.progress:void 0,H=typeof L.totalMB=="number"?L.totalMB:0;z===void 0||j===void 0||(d(T=>{const W=new Map(T);return j===100||j===-1?W.delete(z):W.set(z,{modelId:z,progress:j,totalMB:H}),W}),j===100&&n.invalidateQueries({queryKey:[["pipelineExecutor","getSchema"]]}))});const M=w??{runtime:"node",backend:"cpu",format:"onnx"},P=x.find(R=>R.format===s)??M,I=P.format,F=y?.slots??[],E=F.map(R=>({...R,addons:R.addons.map(L=>({...L,models:L.models.filter(z=>z.formats[I]!==void 0)})).filter(L=>L.models.length>0)})).filter(R=>R.addons.length>0),B=nO(E,I),O=q(async(R,L,z)=>{if(!dp(z))return;const j=xi(R,L,z);l(H=>new Set([...H,j])),p(H=>{const T=new Map(H);return T.delete(j),T});try{await k.mutateAsync({addonId:R,modelId:L,format:z,nodeId:o}),n.invalidateQueries({queryKey:[["pipelineExecutor","getSchema"]]})}catch(H){p(T=>new Map([...T,[j,H instanceof Error?H.message:"Download failed"]]))}finally{l(H=>{const T=new Set(H);return T.delete(j),T})}},[k,n,o]),A=q(async(R,L,z)=>{if(!dp(z))return;const j=xi(R,L,z);l(H=>new Set([...H,j])),p(H=>{const T=new Map(H);return T.delete(j),T});try{await S.mutateAsync({addonId:R,modelId:L,format:z,nodeId:o}),n.invalidateQueries({queryKey:[["pipelineExecutor","getSchema"]]})}catch(H){p(T=>new Map([...T,[j,H instanceof Error?H.message:"Delete failed"]]))}finally{l(H=>{const T=new Set(H);return T.delete(j),T})}},[S,n,o]),D=q(R=>{a(R.format)},[]),_=m.trim()?E.map(R=>({...R,addons:R.addons.map(L=>({...L,models:L.models.filter(z=>z.name.toLowerCase().includes(m.toLowerCase())||z.id.toLowerCase().includes(m.toLowerCase())||L.name.toLowerCase().includes(m.toLowerCase()))})).filter(L=>L.models.length>0)})).filter(R=>R.addons.length>0):E;return u("div",{className:e?"space-y-4":"p-6 space-y-6 max-w-5xl mx-auto",children:[!e&&u("div",{children:[r("h1",{className:"text-lg font-bold text-foreground",children:"Models"}),r("p",{className:"text-xs text-foreground-subtle mt-0.5",children:"Manage ML models for the detection pipeline. Select an engine to see its compatible models."})]}),N&&r("div",{className:"flex items-center justify-center py-16",children:r(Pe,{className:"h-5 w-5 animate-spin text-foreground-subtle"})}),!N&&F.length===0&&u("div",{className:"flex flex-col items-center justify-center py-16 text-foreground-subtle",children:[r(lo,{className:"h-8 w-8 mb-3 opacity-30"}),r("span",{className:"text-sm",children:"No pipeline steps available"}),r("span",{className:"text-xs mt-1",children:"Configure the detection pipeline to see available models."})]}),!N&&F.length>0&&u(ve,{children:[r(oO,{engines:x,activeEngine:M,viewEngine:P,onSelect:D}),u("div",{className:"flex items-center gap-4 text-xs text-foreground-subtle",children:[u("span",{children:[r("span",{className:"font-semibold text-foreground tabular-nums",children:B.total}),r("span",{className:"ml-1",children:"compatible models"})]}),r("span",{className:"text-border",children:"|"}),u("span",{children:[r("span",{className:"font-semibold text-success tabular-nums",children:B.downloaded}),r("span",{className:"ml-1",children:"downloaded"})]}),r("span",{className:"text-border",children:"|"}),u("span",{className:"tabular-nums",children:[Hy(B.downloadedSizeMB),r("span",{className:"ml-1",children:"on disk"})]})]}),B.total>5&&u("div",{className:"relative",children:[r(hy,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-foreground-subtle"}),r("input",{type:"text",value:m,onChange:R=>h(R.target.value),placeholder:"Search models...",className:"w-full pl-9 pr-3 py-2 text-sm rounded-lg border border-border bg-surface text-foreground placeholder:text-foreground-subtle/50 focus:outline-none focus:ring-1 focus:ring-primary"})]}),_.map(R=>{const L=R.addons.reduce((j,H)=>j+H.models.length,0),z=R.addons.reduce((j,H)=>j+H.models.filter(T=>T.formats[I]?.downloaded).length,0);return u("div",{children:[u("div",{className:"flex items-center gap-2 mb-2",children:[r("h2",{className:"text-sm font-semibold text-foreground",children:R.label}),r("div",{className:"flex-1 h-px bg-border"}),u("span",{className:"text-[10px] text-foreground-subtle tabular-nums",children:[z,"/",L]})]}),r("div",{className:"rounded-lg border border-border bg-surface overflow-hidden",children:R.addons.map(j=>j.models.map(H=>{const T=xi(j.id,H.id,I);return r(rO,{addonId:j.id,model:H,format:I,isActive:i.has(T),progress:c.get(H.id),errorMsg:f.get(T),onDownload:()=>O(j.id,H.id,I),onDelete:()=>A(j.id,H.id,I)},`${j.id}/${H.id}`)}))})]},R.id)}),_.length===0&&r("div",{className:"text-center py-8 text-sm text-foreground-subtle",children:m.trim()?u(ve,{children:["No models matching “",m,"”"]}):u(ve,{children:["No models available for ",dl(P)," format"]})})]})]})}function aO({nodeId:e,refreshToken:t}){return r(sO,{embedded:!0,nodeId:e})}function Vy({nodeId:e,title:t}){const{data:n}=By(),{data:o}=la(void 0,{staleTime:3e4}),s=Q(()=>{const d=new Map;for(const f of n??[])d.set(f.id,f.name);return d},[n]),a=Q(()=>{if(!e)return null;const d=new Set;for(const f of o??[])f.agentNodeId===e&&d.add(f.deviceId);return d},[e,o]),[i,l]=$(new Map);dt("pipeline.camera-metrics-snapshot",d=>{const f=d.data;typeof f.deviceId=="number"&&(e&&f.nodeId!==e||l(p=>{const m=new Map(p);return m.set(f.deviceId,f),m}))}),Y(()=>{if(i.size===0)return;const d=setInterval(()=>{l(f=>{const p=Date.now()-1e4;let m=!1;const h=new Map(f);for(const[g,b]of f)b.timestamp<p&&(h.delete(g),m=!0);return m?h:f})},5e3);return()=>clearInterval(d)},[i.size]);const c=Q(()=>{const d=[];for(const f of i.values())a&&!a.has(f.deviceId)||d.push(f);return d.sort((f,p)=>f.deviceId-p.deviceId),d},[i,a]);return c.length===0?u("div",{className:"rounded-md border border-border bg-surface px-3 py-2 text-[11px] text-foreground-subtle italic",children:[t??"Cameras",": no live snapshots yet"]}):u("div",{className:"rounded-md border border-border bg-surface px-3 py-2",children:[u("div",{className:"flex items-center gap-2 mb-1.5",children:[r("span",{className:"text-[10px] uppercase tracking-wider text-foreground-subtle",children:t??"Cameras"}),r("span",{className:"text-[10px] text-foreground-subtle",children:c.length})]}),r("div",{className:"flex flex-wrap gap-1.5",children:c.map(d=>{const f=s.get(d.deviceId)??`#${d.deviceId}`,p=Wn(d.metrics.phase);return u("div",{title:`${f} · ${p.label} · ${d.metrics.actualFps.toFixed(1)} fps · ${d.metrics.avgInferenceTimeMs.toFixed(0)}ms infer · q=${d.metrics.queueDepth}`,className:`inline-flex items-center gap-1 rounded border px-1.5 py-0.5 text-[10px] ${p.badgeClass}`,children:[r(Pc,{phase:d.metrics.phase,className:"h-2.5 w-2.5"}),r("span",{className:"font-medium text-foreground/90 max-w-[120px] truncate",children:f}),r("span",{className:"font-mono tabular-nums",children:d.metrics.actualFps.toFixed(1)}),r("span",{className:"opacity-60",children:"fps"})]},d.deviceId)})})]})}function yi(e,t){if(!e)return null;for(const n of e.slots)for(const o of n.addons)if(o.id===t)return o;return null}function iO({nodeId:e,refreshToken:t}){const n=ke(),[o,s]=$(null),[a,i]=$(null),l=So({nodeId:e},{refetchOnMount:"always"}),c=xc({agentNodeId:e},{refetchOnMount:"always"}),d=yc({onSuccess:()=>{n.invalidateQueries({queryKey:[["addonSettings"]]}),n.invalidateQueries({queryKey:[["pipelineOrchestrator"]]}),n.invalidateQueries({queryKey:[["pipelineExecutor"]]})}}),f=l.data??null,p=c.data,m=f?.selectedEngine.format??"coreml",h=Q(()=>f?ta(f):[],[f]),g=Q(()=>[{agentNodeId:e,engineLabel:m}],[e,m]),b=(S,M)=>{const P=p?.addonDefaults[S];return yi(f,S)?.models.some(E=>!!E.formats[m])?P?P.enabled?{kind:"enabled",modelId:P.modelId}:{kind:"disabled"}:{kind:"na"}:{kind:"na"}},x=o&&f?yi(f,o.addonId):null,v=S=>{const M=p?.addonDefaults[S]??null;s({addonId:S,agentNodeId:e}),i(M)},w=(S,M)=>{if(!p)return;const P=p.addonDefaults[S],I=yi(f,S);if(!P&&!I)return;const F={enabled:M,modelId:P?.modelId??I?.defaultModelId??"",settings:P?.settings??{}};d.mutate({agentNodeId:e,defaults:{...p.addonDefaults,[S]:F}})},y=()=>{s(null),i(null)},N=()=>{!a||!o||!p||d.mutate({agentNodeId:e,defaults:{...p.addonDefaults,[o.addonId]:a}},{onSuccess:y})};if(l.isLoading||c.isLoading)return r("div",{className:"text-xs text-foreground-subtle animate-pulse",children:"Loading pipeline…"});if(l.error)return u("div",{className:"text-xs text-red-400",children:["Failed to load catalog: ",String(l.error)]});if(!f)return r("div",{className:"text-xs text-foreground-subtle",children:"Catalog unavailable for this node (runner offline?)."});const k=o!==null&&x!==null&&a!==null;return u("div",{className:"relative h-full w-full space-y-3",children:[r(Vy,{nodeId:e}),r("div",{className:k?"pr-[360px]":"",children:h.length>0?r(Zl,{tree:h,agents:g,getCellState:b,onCellClick:v,selectedCell:o,onToggleEnabled:w}):r("div",{className:"text-xs text-foreground-subtle",children:"Catalog empty."})}),r(Yl,{open:k,onClose:y,title:x?.name??"",subtitle:o?`${o.agentNodeId} · ${m}`:"",footer:u(ve,{children:[r("button",{type:"button",className:"px-3 py-1 text-xs border border-border rounded bg-surface hover:bg-muted",onClick:y,children:"Cancel"}),r("button",{type:"button",disabled:!a||!o||d.isPending,className:"px-3 py-1 text-xs bg-primary text-primary-foreground rounded disabled:opacity-50",onClick:N,children:d.isPending?"Saving…":"Save"})]}),children:x&&a&&o&&r(ra,{mode:"agent",addon:x,agentDefault:a,agentNodeId:o.agentNodeId,engineFormat:m,onChangeAgentConfig:S=>i(S)})})]})}function qy({pendingCount:e,onSave:t,onDiscard:n,saving:o=!1,saveLabel:s="Save",discardLabel:a="Discard"}){return e<=0?null:u("div",{className:"sticky bottom-0 -mb-3 flex items-center justify-between gap-3 rounded-lg border border-primary/40 bg-primary/5 px-3 py-2 shadow-sm z-10",children:[u("span",{className:"text-xs text-foreground",children:[e," unsaved change",e===1?"":"s"]}),u("div",{className:"flex items-center gap-2",children:[r("button",{type:"button",onClick:n,disabled:o,className:"inline-flex items-center rounded-md border border-border px-2.5 py-1 text-xs text-foreground-subtle hover:bg-surface-hover disabled:opacity-50",children:a}),r("button",{type:"button",onClick:t,disabled:o,className:"inline-flex items-center rounded-md bg-primary px-3 py-1 text-xs font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50",children:o?"Saving…":s})]})]})}function Qy({tabs:e,activeId:t,onChange:n,countByTab:o,pendingByTab:s}){return e.length===0?null:r("div",{className:"flex flex-wrap items-center gap-1 border-b border-border shrink-0",children:e.map(a=>{const i=a.id===t,l=o?.get(a.id)??0,c=s?.get(a.id)??0;return u("button",{type:"button",onClick:()=>n(a.id),className:`relative px-3 py-1.5 text-xs font-medium rounded-t-md transition-colors -mb-px border-b-2 whitespace-nowrap ${i?"text-primary border-primary bg-primary/5":"text-foreground-subtle border-transparent hover:text-foreground hover:bg-surface-hover"}`,children:[a.label,l>0&&u("span",{className:"ml-1.5 text-[10px] opacity-60",children:["(",l,")"]}),c>0&&r("span",{className:"ml-1.5 inline-flex h-1.5 w-1.5 rounded-full bg-primary"})]},a.id)})})}function lO(e,t){for(const n of e)for(const o of n.fields){if(!("key"in o)||o.key!==t)continue;if(o.type==="button"||o.type==="separator"||o.type==="info")return!0;const s=o.immediate;return s===!0?!0:s===!1?!1:n.immediate===!0}return!1}function Uy({schema:e,serverValues:t,onImmediateSave:n,onDeferredSave:o}){const[s,a]=$({}),[i,l]=$(!1),c=ne(null),d=e?.sections??[],f=Object.keys(s).length>0,p=Q(()=>({...t,...s}),[t,s]);Y(()=>{if(f){l(!0);return}c.current&&clearTimeout(c.current),c.current=setTimeout(()=>l(!1),500)},[f]);const m=q(()=>{l(!0),c.current&&clearTimeout(c.current),c.current=setTimeout(()=>l(!1),2e3)},[]),h=q(v=>{m();const w={},y={},N={...t,...s};for(const[k,S]of Object.entries(v))N[k]!==S&&(lO(d,k)?w[k]=S:y[k]=S);Object.keys(w).length>0&&n(w),a(k=>{const S={...k};for(const M of Object.keys(w))delete S[M];for(const[M,P]of Object.entries(y))S[M]=P;return S})},[m,t,s,d,n]),g=q(v=>{const w={},y={};for(const[N,k]of Object.entries(s))v.includes(N)?w[N]=k:y[N]=k;a(y),Object.keys(w).length>0&&o(w)},[s,o]),b=q(v=>{a(w=>{const y={...w};for(const N of v)delete y[N];return y})},[]),x=q(()=>{a({})},[]);return{values:p,pendingKeys:Object.keys(s),hasPendingEdits:f,editingPaused:i,handleChange:h,handleSave:g,handleDiscard:b,resetAll:x}}const cO=Ve(function({addonId:t,schema:n,serverValues:o,onImmediateSave:s,onStateChange:a,onAction:i,disabled:l},c){const d=Uy({schema:n,serverValues:o,onImmediateSave:q(b=>s(t,b),[t,s]),onDeferredSave:q(()=>{},[])});W1(c,()=>({flush:()=>{const b={};for(const x of d.pendingKeys)b[x]=d.values[x];return d.handleDiscard(d.pendingKeys),b},discard:()=>d.resetAll()}),[d]);const f=d.pendingKeys,p=f.join("|"),m=Q(()=>f.map(b=>`${b}=${JSON.stringify(d.values[b])}`).join(","),[f,d.values]),h=ne(a);Y(()=>{h.current=a},[a]),Y(()=>{const b={};for(const x of f)b[x]=d.values[x];h.current({addonId:t,pendingKeys:f,pendingValues:b})},[t,p,m]);const g=Q(()=>{if(i)return(b,x,v)=>i(t,b,x,v)},[t,i]);return r(Nn,{schema:n,values:d.values,onChange:d.handleChange,disabled:l,onAction:g})});function Ky(e,t){if(e.type==="separator"||e.type==="info"||e.type==="button")return e;if(e.type==="group"){const a=e.fields.map(i=>Ky(i,t));return{...e,fields:a}}const n=e;t[e.key]=n.value;const{value:o,...s}=n;return s}function dO(e,t){return{...e,fields:e.fields.map(n=>Ky(n,t))}}function uO(e){const t={};return{schema:{...e.tabs?{tabs:e.tabs}:{},sections:e.sections.map(o=>dO(o,t))},values:t}}function Rr({nodeId:e,addonIds:t,level:n,deviceId:o,sectionIds:s,sectionTab:a,extraTabs:i,title:l,description:c}){const d=ke(),f=Le().trpcClient,p=Jh(),m=eg(),h=ab(),g=hg(),b=ig(),x=!!(i&&i.length>0),[v,w]=$(null);if(n==="device"&&!o)throw new Error('NodeAddonsSettingsPanel: deviceId is required when level === "device"');const y=e??"hub",N=X1({queries:t.map(Z=>({queryKey:[["addonSettings",n==="global"?"getGlobalSettings":"getDeviceSettings"],{addonId:Z,nodeId:y,deviceId:o??null}],queryFn:async()=>{if(n==="global"){const J=await f.addonSettings.getGlobalSettings.query({addonId:Z,nodeId:y});return{addonId:Z,result:J}}const U=await f.addonSettings.getDeviceSettings.query({addonId:Z,deviceId:o,nodeId:y});return{addonId:Z,result:U}},staleTime:3e4}))}),k=N.some(Z=>Z.isLoading),S=N.map(Z=>{if(!Z.data)return"-";if(Z.data.result===null)return`${Z.data.addonId}:n`;const U=[];for(const J of Z.data.result.sections){U.push(`s:${J.id}:${J.tab??"general"}`);for(const ae of J.fields){if(!("key"in ae))continue;const fe="options"in ae&&Array.isArray(ae.options)?ae.options.map(ie=>ie.value).join(","):"",he=ae.value,V=he===void 0?"":typeof he=="string"?he:JSON.stringify(he);U.push(`f:${ae.key}:${fe}:${V}`)}}return`${Z.data.addonId}:${U.join("|")}`}).join("||"),M=Q(()=>{const Z=new Set;for(const U of N){const J=U.data?.result?.sections;if(J)for(const ae of J)Z.add(ae.tab??"general")}return[...Z]},[S+"::"+N.map(Z=>(Z.data?.result?.sections??[]).map(U=>U.tab??"general").join(",")).join("::")]),P=Q(()=>new Map((i??[]).map(Z=>[Z.id,Z])),[i]),I=Q(()=>{if(!x)return[];const Z=[...new Set([...M,...(i??[]).map(J=>J.id)])],U=J=>{const ae=P.get(J);if(ae?.order!==void 0)return ae.order;const fe=_i[J];return fe?fe.order:50};return Z.sort((J,ae)=>{const fe=U(J),he=U(ae);return fe!==he?fe-he:J.localeCompare(ae)})},[x,M,i,P]),F=Q(()=>{const Z=new Map;for(const U of M){const J=_i[U];Z.set(U,J?.label??U.charAt(0).toUpperCase()+U.slice(1))}for(const U of i??[])Z.set(U.id,U.label);return Z},[M,i]),E=x?v&&I.includes(v)?v:I[0]??null:null,B=E!==null&&P.has(E),O=x?E&&!B?E:void 0:a,{data:A}=oa(void 0,{staleTime:6e4}),D=Q(()=>{const Z=new Map;for(const U of A??[]){const J=U.manifest?.id;if(!J)continue;const ae=U.manifest?.name??U.manifest?.packageDisplayName??J;Z.set(J,ae)}return Z},[A]),_=Q(()=>{const Z=s?new Set(s):null,U=[];for(const J of N){if(!J.data||J.data.result===null)continue;const{schema:ae,values:fe}=uO(J.data.result),he=ae.sections.filter(ue=>Z?Z.has(ue.id):!0);if(he.length===0)continue;const V={...J.data.result,sections:J.data.result.sections.filter(ue=>Z?Z.has(ue.id):!0)},ie={...ae,sections:he};U.push({addonId:J.data.addonId,schemaWithValues:V,schema:ie,serverValues:fe})}return U},[S,s]),[R,L]=$(new Map),z=q(Z=>{L(U=>{const J=new Map(U);return J.set(Z.addonId,Z),J})},[]),j=ne(new Map),H=q(Z=>U=>{U?j.current.set(Z,U):j.current.delete(Z)},[]),T=q(async(Z,U)=>{n==="global"?await p.mutateAsync({addonId:Z,nodeId:y,patch:U}):await m.mutateAsync({addonId:Z,deviceId:o,nodeId:y,patch:U}),d.invalidateQueries({queryKey:[["addonSettings"]]})},[p,m,y,n,o,d]),W=q(async(Z,U,J,ae)=>{const fe=y;try{switch(U){case"reprobe-engine":await h.mutateAsync({nodeId:fe}),d.invalidateQueries({queryKey:[["addonSettings"]]});return;case"reprobe-hwaccel":await g.mutateAsync({nodeId:fe}),d.invalidateQueries({queryKey:[["addonSettings"]]});return;case"reprobe-audio-engine":await b.mutateAsync({nodeId:fe}),d.invalidateQueries({queryKey:[["addonSettings"]]});return;default:{const he=await f.addons.custom.mutate({addonId:Z,action:U,input:ae});return d.invalidateQueries({queryKey:[["addonSettings"]]}),he}}}catch(he){throw console.error("[NodeAddonsSettingsPanel] action failed",{addonId:Z,action:U,err:he}),he}},[h,g,b,y,d,f]),G=q((Z,U)=>{T(Z,U)},[T]),ee=$l({mutationFn:async()=>{const Z=[];for(const J of _){const ae=R.get(J.addonId);!ae||ae.pendingKeys.length===0||Z.push({addonId:J.addonId,patch:ae.pendingValues})}return Z.length===0?{saved:[]}:{saved:await Promise.all(Z.map(async({addonId:J,patch:ae})=>(n==="global"?await p.mutateAsync({addonId:J,nodeId:y,patch:ae}):await m.mutateAsync({addonId:J,deviceId:o,nodeId:y,patch:ae}),J)))}},onSuccess:({saved:Z})=>{for(const U of Z)j.current.get(U)?.discard();d.invalidateQueries({queryKey:[["addonSettings"]]})}}),se=q(()=>{for(const Z of j.current.values())Z.discard()},[]),te=Q(()=>{let Z=0;for(const U of _){const J=R.get(U.addonId);J&&(Z+=J.pendingKeys.length)}return Z},[_,R]),X=Q(()=>{const Z=new Map;for(const U of _){const J=R.get(U.addonId);if(!J||J.pendingKeys.length===0)continue;const ae=new Set(J.pendingKeys);for(const fe of U.schema.sections){const he=fe.tab??"general";for(const V of fe.fields)"key"in V&&ae.has(V.key)&&Z.set(he,(Z.get(he)??0)+1)}}return Z},[_,R]);if(k)return r("div",{className:"h-24 rounded-lg border border-border bg-surface animate-pulse"});const re=E&&B?P.get(E):void 0;if(!x&&_.length===0)return u("div",{className:"text-[11px] text-foreground-subtle italic",children:["No addons in ",t.length>0?`[${t.join(", ")}]`:"the current selection"," ","expose ",n,"-level settings on this node."]});const ge=ee.isPending;return u("div",{className:"space-y-4",children:[(l||c)&&u("div",{className:"border-b border-border pb-2",children:[l&&r("h2",{className:"text-sm font-semibold text-foreground",children:l}),c&&r("p",{className:"text-[11px] text-foreground-subtle mt-0.5",children:c})]}),x&&r(Qy,{tabs:I.map(Z=>({id:Z,label:F.get(Z)??Z})),activeId:E,onChange:w,pendingByTab:X}),ee.isError&&u("div",{className:"rounded-md border border-red-500/40 bg-red-500/10 px-3 py-2 text-[11px] text-red-400",children:["Save failed: ",String(ee.error?.message??ee.error)]}),re?re.content:(()=>{const Z=O?_.reduce((ae,fe)=>ae+fe.schemaWithValues.sections.filter(he=>(he.tab??"general")===O).length,0):0,U=O!==null&&Z<=1,J=_.map(ae=>({...ae,renderedWithValues:{...ae.schemaWithValues,sections:ae.schemaWithValues.sections.filter(fe=>O?(fe.tab??"general")===O:!0).map(fe=>U?{...fe,title:"",description:void 0}:fe)}})).filter(ae=>ae.renderedWithValues.sections.length>0).sort((ae,fe)=>{const he=ue=>{let de=Number.POSITIVE_INFINITY;for(const le of ue)typeof le.order=="number"&&le.order<de&&(de=le.order);return de},V=he(ae.renderedWithValues.sections),ie=he(fe.renderedWithValues.sections);return V!==ie?V-ie:0});return J.length===0?r("div",{className:"text-[11px] text-foreground-subtle italic",children:"Nothing to configure here for this node."}):r(pO,{entries:J,paneStates:R,displayNames:D,disabled:ge,setPaneRef:H,onPaneStateChange:z,onImmediateSave:G,onAction:W,inline:x||!!a})})(),!k&&r(qy,{pendingCount:te,onSave:()=>ee.mutate(),onDiscard:se,saving:ge})]})}function pO({entries:e,paneStates:t,displayNames:n,disabled:o,setPaneRef:s,onPaneStateChange:a,onImmediateSave:i,onAction:l,inline:c}){const d=Q(()=>[...e].sort((x,v)=>{if(x.addonId==="system-config")return-1;if(v.addonId==="system-config")return 1;const w=n.get(x.addonId)??x.addonId,y=n.get(v.addonId)??v.addonId;return w.localeCompare(y)}),[e,n]),f=d[0]?.addonId??"",[p,m]=$(f);Y(()=>{d.length!==0&&(d.find(x=>x.addonId===p)||m(d[0].addonId))},[d,p]);const h=d.find(x=>x.addonId===p)??d[0];if(!h)return null;const g=Q(()=>l?(x,v,w,y)=>l(x,v,w,y):void 0,[l]),b=x=>r(cO,{ref:s(x.addonId),addonId:x.addonId,schema:x.renderedWithValues,serverValues:x.serverValues,onImmediateSave:i,onStateChange:a,onAction:g,disabled:o},x.addonId);return d.length===1||c?r("div",{className:"flex flex-col gap-4",children:d.map(b)}):u("div",{className:"flex flex-col gap-3",children:[r("div",{className:"flex flex-wrap items-center gap-1 border-b border-border shrink-0",children:d.map(x=>{const v=n.get(x.addonId)??x.addonId,w=x.addonId===h.addonId,y=(t.get(x.addonId)?.pendingKeys.length??0)>0;return u("button",{type:"button",onClick:()=>m(x.addonId),className:`relative px-3 py-1.5 text-xs font-medium rounded-t-md transition-colors -mb-px border-b-2 whitespace-nowrap ${w?"text-primary border-primary bg-primary/5":"text-foreground-subtle border-transparent hover:text-foreground hover:bg-surface-hover"}`,children:[v,y&&r("span",{className:"ml-1.5 inline-flex h-1.5 w-1.5 rounded-full bg-amber-400"})]},x.addonId)})}),r("div",{className:"space-y-2",children:d.map(x=>r("div",{style:x.addonId===h.addonId?void 0:{display:"none"},children:b(x)},x.addonId))})]})}const fO=["detection-pipeline","decoder-nodeav","audio-analyzer","pipeline-runner"];function mO({nodeId:e,refreshToken:t}){return u("div",{className:"flex flex-col h-full",children:[r(V6,{nodeId:e,refreshToken:t}),r("div",{className:"flex-1 min-h-0 overflow-y-auto p-6",children:r(Rr,{nodeId:e,addonIds:fO,level:"global",extraTabs:[{id:"assignments",label:"Assignments",order:-10,content:r(X6,{nodeId:e,refreshToken:t})},{id:"tree",label:"Pipeline",order:39,content:r(iO,{nodeId:e,refreshToken:t})},{id:"engines",label:"Warm instances",order:180,content:r(eO,{nodeId:e,refreshToken:t})},{id:"models",label:"Models",order:200,content:r(aO,{nodeId:e,refreshToken:t})}]})})]})}function hO({refreshToken:e}){const t=ke(),n=fb({onSuccess:()=>{t.invalidateQueries({queryKey:[["pipelineOrchestrator","getPipelineAssignments"]]}),t.invalidateQueries({queryKey:[["pipelineOrchestrator","getDecoderAssignments"]]}),t.invalidateQueries({queryKey:[["pipelineOrchestrator","getAudioAssignments"]]})}});return u("div",{className:"space-y-6",children:[r(zy,{refreshToken:e}),u("div",{className:"flex flex-col gap-3 @md/clustertab:flex-row @md/clustertab:items-center @md/clustertab:justify-between",children:[u("div",{className:"min-w-0",children:[r("h3",{className:"text-sm font-semibold text-foreground mb-1",children:"Placement matrix"}),r("p",{className:"text-[11px] text-foreground-subtle",children:"Pipeline · decoder · audio assignments per camera. Click the kebab to pin / unpin / move any role; expand the chevron for the per-camera broker drill-down."})]}),u("button",{type:"button",onClick:()=>n.mutate(void 0),disabled:n.isPending,className:"inline-flex items-center gap-1.5 rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-white hover:bg-primary/90 disabled:opacity-50 shrink-0 self-start @md/clustertab:self-auto whitespace-nowrap",children:[r(Jc,{className:"h-3.5 w-3.5"}),n.isPending?"Rebalancing…":"Rebalance pipelines"]})]}),r(jy,{mode:"cluster"})]})}const gO=["pipeline-orchestrator"];function bO({refreshToken:e}){return r("div",{className:"space-y-4 max-w-3xl",children:r(Rr,{nodeId:"hub",addonIds:gO,level:"global",title:"Cluster settings",description:"Cluster-wide orchestration knobs: enabled nodes, load balancer thresholds, and failover policy. Per-camera pipelines live in Device Overrides; live cluster load is on the Assignments tab."})})}function xO({refreshToken:e}){const t=ke(),{data:n,isLoading:o}=Pb(),[s,a]=$(null),[i,l]=$(""),[c,d]=$(""),f=()=>{t.invalidateQueries({queryKey:[["pipelineOrchestrator","listTemplates"]]})},p=Eb({onSuccess:()=>{a(null),f()}}),m=$b({onSuccess:f}),h=v=>{a(v.id),l(v.name),d(v.description??"")},g=()=>{a(null),l(""),d("")},b=()=>{if(!s)return;const v=c.trim();p.mutate({id:s,name:i.trim()||"Untitled",...v?{description:v}:{}})};if(o)return r("div",{className:"text-xs text-foreground-subtle animate-pulse",children:"Loading templates…"});const x=[...n??[]].sort((v,w)=>v.name.localeCompare(w.name));return r("div",{className:"space-y-6 max-w-4xl",children:u("section",{className:"rounded-lg border border-border bg-surface overflow-hidden",children:[u("div",{className:"border-b border-border px-4 py-3 flex items-center justify-between",children:[u("div",{children:[r("h3",{className:"text-sm font-semibold text-foreground",children:"Templates"}),r("p",{className:"text-[11px] text-foreground-subtle mt-0.5",children:"Curated pipeline presets operators can apply to any camera. Apply-time is a copy — future edits to a template don't retroactively change cameras that were seeded from it. Save a template from the device Pipeline tab."})]}),u("div",{className:"text-[11px] text-foreground-subtle",children:[x.length," template",x.length===1?"":"s"]})]}),x.length===0?u("div",{className:"px-4 py-8 text-xs text-foreground-subtle flex flex-col items-center gap-2",children:[r(Ot,{className:"h-6 w-6 opacity-40"}),r("div",{children:'No templates yet. Create one from a device Pipeline tab ("Save as template").'})]}):r("ul",{className:"divide-y divide-border",children:x.map(v=>{const w=s===v.id;return r("li",{className:"px-4 py-3 text-xs",children:u("div",{className:"flex items-start gap-3",children:[r("div",{className:"flex-1 min-w-0",children:w?u("div",{className:"space-y-2",children:[r("input",{className:"w-full rounded border border-border bg-surface-hover px-2 py-1 text-xs text-foreground focus:outline-none focus:border-primary",value:i,onChange:y=>l(y.target.value),placeholder:"Template name",autoFocus:!0}),r("input",{className:"w-full rounded border border-border bg-surface-hover px-2 py-1 text-[11px] text-foreground focus:outline-none focus:border-primary",value:c,onChange:y=>d(y.target.value),placeholder:"Description (optional)"})]}):u(ve,{children:[r("div",{className:"font-medium text-foreground",children:v.name}),v.description&&r("div",{className:"text-foreground-subtle mt-0.5",children:v.description}),u("div",{className:"mt-1 font-mono text-[10px] text-foreground-subtle",children:["engine ",v.config.engine.runtime,"/",v.config.engine.backend," · ",v.config.steps.length," step(s)",v.config.audio?.enabled?" · audio":"",u("span",{className:"ml-2",children:["updated ",new Date(v.updatedAt).toLocaleString()]})]})]})}),r("div",{className:"flex items-center gap-1 shrink-0",children:w?u(ve,{children:[u("button",{type:"button",onClick:b,disabled:p.isPending,className:"inline-flex items-center gap-1 rounded px-2 py-1 text-[11px] font-medium bg-primary text-white hover:bg-primary/90 disabled:opacity-50",children:[r(Ct,{className:"h-3 w-3"}),"Save"]}),u("button",{type:"button",onClick:g,className:"inline-flex items-center gap-1 rounded px-2 py-1 text-[11px] text-foreground-subtle hover:bg-surface-hover",children:[r(qe,{className:"h-3 w-3"}),"Cancel"]})]}):u(ve,{children:[r("button",{type:"button",onClick:()=>h(v),title:"Rename",className:"inline-flex items-center gap-1 rounded px-2 py-1 text-[11px] text-foreground-subtle hover:text-foreground hover:bg-surface-hover",children:r(Po,{className:"h-3 w-3"})}),r("button",{type:"button",onClick:()=>{confirm(`Delete template "${v.name}"?`)&&m.mutate({id:v.id})},disabled:m.isPending,title:"Delete",className:"inline-flex items-center gap-1 rounded px-2 py-1 text-[11px] text-foreground-subtle hover:text-red-400 hover:bg-surface-hover disabled:opacity-50",children:r(We,{className:"h-3 w-3"})})]})})]})},v.id)})})]})})}function pp(e,t){if(!e)return null;for(const n of e.slots)for(const o of n.addons)if(o.id===t)return o;return null}function yO({nodeId:e,refreshToken:t}){const n=ke(),o=Le().trpcClient,[s,a]=$(null),[i,l]=$(null),c=$r(void 0,{refetchOnMount:"always"});yt(["nodes","topology"],["agent.online","agent.offline","agent.unregistered","addon.installed","addon.uninstalled","addon.updated"]);const d=In(void 0,{staleTime:3e4,refetchOnMount:"always"}),f=Q(()=>{const I=new Set;for(const F of d.data??[])F.isOnline&&I.add(F.id);return I},[d.data]),p=So({nodeId:e},{refetchOnMount:"always"}),m=Q(()=>(c.data??[]).filter(I=>f.has(I.nodeId)).map(I=>I.nodeId),[c.data,f]),h=Kn({enabled:m.length>0,queryKey:[["pipelineExecutor","getSchema"],"schema-by-agent",m.join(","),t],queryFn:async()=>{const I={};for(const F of m)try{const E=await o.pipelineExecutor.getSchema.query({nodeId:F});I[F]=E.selectedEngine.format}catch{I[F]="coreml"}return I}}),g=yc({onSuccess:()=>{n.invalidateQueries({queryKey:[["pipelineOrchestrator"]]}),n.invalidateQueries({queryKey:[["pipelineExecutor"]]}),n.invalidateQueries({queryKey:[["addonSettings"]]})}}),b=Q(()=>p.data?ta(p.data):[],[p.data]),x=Q(()=>{const I=c.data??[],F=f;return(F.size===0?[]:I.filter(B=>F.has(B.nodeId))).map(B=>{const O=h.data?.[B.nodeId];return{agentNodeId:B.nodeId,engineLabel:O??"(engine unknown)"}})},[c.data,h.data,f]),v=(I,F)=>{const B=c.data?.find(_=>_.nodeId===F)?.settings.addonDefaults[I],O=h.data?.[F];return pp(p.data??null,I)?.models.some(_=>O!==void 0&&!!_.formats[O])?B?B.enabled?{kind:"enabled",modelId:B.modelId}:{kind:"disabled"}:{kind:"na"}:{kind:"na"}},w=s?c.data?.find(I=>I.nodeId===s.agentNodeId)??null:null,y=s&&p.data?pp(p.data,s.addonId):null,N=s?h.data?.[s.agentNodeId]??"coreml":"coreml",k=()=>{a(null),l(null)},S=(I,F)=>{const B=c.data?.find(O=>O.nodeId===F)?.settings.addonDefaults[I]??null;a({addonId:I,agentNodeId:F}),l(B)},M=()=>{!i||!s||!w||g.mutate({agentNodeId:s.agentNodeId,defaults:{...w.settings.addonDefaults,[s.addonId]:i}},{onSuccess:k})};if(c.isLoading||p.isLoading)return r("div",{className:"text-xs text-foreground-subtle animate-pulse",children:"Loading agents…"});if(!p.data)return u("div",{className:"text-xs text-foreground-subtle",children:["Catalog unavailable for ",e,"."]});const P=s!==null&&y!==null&&i!==null;return u("div",{className:"relative h-full w-full space-y-3",children:[r(Vy,{title:"Cluster cameras"}),r("div",{className:P?"pr-[360px]":"",children:b.length>0&&x.length>0?r(Zl,{tree:b,agents:x,getCellState:v,onCellClick:S,selectedCell:s}):r("div",{className:"text-xs text-foreground-subtle",children:"No agents or catalog empty."})}),r(Yl,{open:P,onClose:k,title:y?.name??"",subtitle:s?`${s.agentNodeId} · ${N}`:"",footer:u(ve,{children:[r("button",{type:"button",className:"px-3 py-1 text-xs border border-border rounded bg-surface hover:bg-muted",onClick:k,children:"Cancel"}),r("button",{type:"button",disabled:!i||!s||g.isPending,className:"px-3 py-1 text-xs bg-primary text-primary-foreground rounded disabled:opacity-50",onClick:M,children:g.isPending?"Saving…":"Save"})]}),children:y&&i&&s&&r(ra,{mode:"agent",addon:y,agentDefault:i,agentNodeId:s.agentNodeId,engineFormat:N,onChangeAgentConfig:I=>l(I)})})]})}const vO=[{id:"assignments",label:"Assignments"},{id:"pipeline",label:"Pipeline"},{id:"settings",label:"Settings"},{id:"templates",label:"Templates"}];function wO({refreshToken:e}){const[t,n]=$("assignments"),{data:o}=In(void 0,{staleTime:3e4}),s=o?.find(a=>a.isHub&&a.isOnline)?.id??o?.find(a=>a.isOnline)?.id??null;return u("div",{className:"flex flex-col h-full",children:[u("div",{className:"px-6 py-4 border-b border-border",children:[r("h2",{className:"text-base font-semibold text-foreground",children:"Cluster Orchestration"}),r("div",{className:"text-[11px] text-foreground-subtle mt-1",children:"Assignments with live load, cluster-wide settings, pipeline template library, per-camera pipeline overrides."})]}),r("div",{className:"flex items-center gap-1 px-6 border-b border-border",children:vO.map(a=>r("button",{type:"button",onClick:()=>n(a.id),className:`px-3 py-2 text-xs font-medium border-b-2 transition-colors ${t===a.id?"border-primary text-primary":"border-transparent text-foreground-subtle hover:text-foreground"}`,children:a.label},a.id))}),u("div",{className:"flex-1 min-h-0 overflow-y-auto p-4 sm:p-6 @container/clustertab",children:[t==="assignments"&&r(hO,{refreshToken:e}),t==="pipeline"&&(s?r(yO,{nodeId:s,refreshToken:e}):r("div",{className:"text-xs text-foreground-subtle",children:"No online node available — schema unreachable."})),t==="settings"&&r(bO,{refreshToken:e}),t==="templates"&&r(xO,{refreshToken:e})]})]})}const eo="__cluster__";function NO(){const[e,t]=Qc(),n=e.get("node")??eo,[o,s]=$(0);return Y(()=>{e.get("node")||t({node:eo},{replace:!0})},[e,t]),u("div",{className:"flex flex-col h-full overflow-hidden",children:[u("div",{className:"flex items-center justify-between gap-4 px-6 py-4 border-b border-border shrink-0",children:[u("div",{className:"flex items-center gap-2",children:[r(sy,{className:"h-4 w-4 text-foreground-subtle"}),r("h1",{className:"text-lg font-semibold text-foreground",children:"Pipeline"})]}),u("button",{type:"button",onClick:()=>s(i=>i+1),title:"Refresh",className:"inline-flex items-center gap-1.5 rounded-lg px-2.5 py-1.5 text-[11px] font-medium border border-border text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors",children:[r(pt,{className:"h-3.5 w-3.5"}),"Refresh"]})]}),u("div",{className:"flex-1 flex flex-col md:flex-row overflow-hidden min-h-0",children:[r("aside",{className:"w-full md:w-72 shrink-0 border-b md:border-b-0 md:border-r border-border overflow-y-auto",children:r(H6,{selectedNodeId:n,onSelect:i=>{t({node:i},{replace:!0})},refreshToken:o})}),r("section",{className:"flex-1 min-h-0 overflow-hidden",children:n===eo?r(wO,{refreshToken:o}):r(mO,{nodeId:n,refreshToken:o})})]})]})}function kO(e){const[t,n]=$("idle"),[o,s]=$(null),a=ne(null),i=ne(null),l=ne(null),c=ne(!0),d=Bg(),f=Fg(),p=jg(),m=q(()=>{if(a.current){try{a.current.close()}catch{}a.current=null}if(i.current){for(const b of i.current.getTracks())try{b.stop()}catch{}i.current=null}l.current=null},[]),h=q(async()=>{if(t==="idle")return;n("stopping");const b=l.current;if(b&&e!==null)try{await Promise.race([p.mutateAsync({deviceId:e,sessionId:b}),new Promise((v,w)=>setTimeout(()=>w(new Error("server stopSession timeout")),2e3))])}catch(v){console.warn("[intercom] server stopSession failed (continuing teardown)",v)}m(),c.current&&(n("idle"),s(null))},[t,e,p,m]),g=q(async()=>{if(e===null||t!=="idle"&&t!=="error")return;s(null);let b=null,x=null,v=null;try{n("requesting-mic"),b=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1}),i.current=b,n("starting");const w=await d.mutateAsync({deviceId:e});v=w.sessionId,l.current=v,n("connecting"),x=new RTCPeerConnection,a.current=x,x.oniceconnectionstatechange=()=>{if(!c.current)return;const k=x.iceConnectionState;k==="connected"||k==="completed"?n("talking"):(k==="failed"||k==="closed"||k==="disconnected")&&c.current&&(s(k==="failed"?"WebRTC connection failed":null),h())};for(const k of b.getAudioTracks())x.addTrack(k,b);await x.setRemoteDescription({type:"offer",sdp:w.sdpOffer});const y=await x.createAnswer();await x.setLocalDescription(y);const N=x.localDescription?.sdp??y.sdp??"";await f.mutateAsync({deviceId:e,sessionId:v,sdpAnswer:N})}catch(w){const y=w instanceof Error?w.message:String(w);if(console.warn("[intercom] start failed",w),x)try{x.close()}catch{}if(b)for(const N of b.getTracks())try{N.stop()}catch{}if(a.current=null,i.current=null,v!==null)try{await p.mutateAsync({deviceId:e,sessionId:v})}catch{}l.current=null,c.current&&(s(y),n("error"))}},[e,t,d,f,p,h]);return Y(()=>(c.current=!0,()=>{c.current=!1;const b=l.current;if(b!==null&&e!==null&&p.mutate({deviceId:e,sessionId:b}),a.current){try{a.current.close()}catch{}a.current=null}if(i.current){for(const x of i.current.getTracks())try{x.stop()}catch{}i.current=null}l.current=null}),[e]),{state:t,error:o,start:g,stop:h,isTalking:t==="talking"}}let SO=0;function st(){return++SO}function vi(e){switch(e.type){case"system":return"system";case"device":return`#${e.deviceId}`;case"provider":return e.providerId;case"addon":return e.addonId}}function CO(e){return["","Commands"," help Show this help"," examples Show usage examples for the current scope"," context Show every available variable + full API surface"," clear Clear terminal (also Ctrl+L)","","Shortcuts"," Enter Execute expression"," Arrow Up/Down Navigate command history"," Ctrl+L Clear terminal","",`Try: ${{system:" sm.summary() // fleet overview",device:" device.state.battery.value?.sleeping // sync read",provider:" devices.map(d => d.name)",addon:" manifest.version"}[e.type]}`,"","Top-level objects: sm (SystemMirror), DeviceType, Math, JSON, Date, …"]}function MO(e){switch(e.type){case"device":return["","── State (sync, zero round-trip) ─────────────────────────"," device.state.battery.value"," device.state.battery.value?.percentage"," device.state.motion.value?.detected","","── Actions (async, through wrapper chain) ────────────────"," await device.snapshot.getSnapshot({})"," await device.ptz.move({ direction: 'left', steps: 1 })"," await device.switch.setState({ on: true })","","── Wait for condition ───────────────────────────────────"," await sm.waitForState(deviceId, 'battery', s => !s.sleeping, 30_000)","","── Subscribe to changes ─────────────────────────────────"," const off = device.state.battery.subscribe(s => console.log(s))","","── Quick info ───────────────────────────────────────────"," info.name device name"," info.addonId owning addon"," sm.dump(deviceId) full debug dump"];case"system":return["","── Lookups ──────────────────────────────────────────────"," sm.getDeviceById(8)"," sm.getDeviceByName('Sala da pranzo')"," sm.getDevicesByAddon('reolink')"," sm.getDevicesByType(DeviceType.Camera)","","── Filters (typed query) ────────────────────────────────"," sm.query({ addonId: 'reolink', online: true })"," sm.query({ caps: ['battery', 'snapshot'] })"," sm.query({ name: /^Cam-/ })","","── Cross-device ─────────────────────────────────────────"," sm.whereState('battery', s => s.percentage < 20).length"," sm.mapState('battery', s => s.percentage)"," sm.countByCap('snapshot')","","── Batch action ─────────────────────────────────────────"," await sm.invokeCap('snapshot', 'getSnapshot', {}, { parallelism: 4 })","","── Listen ───────────────────────────────────────────────"," sm.listenCap('motion', (id, s) => console.log(id, s))"," sm.onDeviceAdded((id, info) => console.log('+', info.name))","","── Diagnostics ──────────────────────────────────────────"," sm.summary()"," sm.dump(8)"];case"provider":return[""," devices.map(d => d.name)"," await getIntegration()"," sm.getDevicesByAddon('<this-addon-id>').length"];case"addon":return[""," manifest.name"," manifest.version"," declaration"]}}function IO(e){const t=["",`Scope: ${e.type}`,""];switch(e.type){case"system":return[...t,"Primary API — sm (SystemMirror):"," sm.getDeviceById(id) DeviceProxy | null (sync)"," sm.getDeviceByName(name) DeviceProxy | null"," sm.getDeviceByStableId(sid) DeviceProxy | null"," sm.getAllDevices() readonly DeviceProxy[]"," sm.getDeviceInfo(id) DeviceInfo | null"," sm.summary() fleet stats","","Filters — sm.query({...}):"," sm.query({ addonId: 'reolink', online: true })"," sm.query({ caps: ['battery', 'snapshot'] }) // ALL caps required"," sm.query({ anyCap: ['ptz', 'motion'] }) // ANY cap"," sm.query({ name: { contains: 'sala' } }) // case-insensitive"," sm.query({ name: /^Cam-\\d+$/ })"," sm.query({ type: DeviceType.Camera })"," sm.query({ parentDeviceId: 8 }) // accessories of cam 8"," sm.query({ where: (info, dev) => dev.state.battery.value?.sleeping })","","State queries:"," sm.whereState('battery', s => s.percentage < 20)"," sm.mapState('battery', s => s.percentage)"," sm.findState('motion', s => s.detected)"," sm.countByCap('snapshot')","","Listeners (return unsubscribe fn):"," sm.listen((id, cap, slice) => …) // every state change"," sm.listenCap('motion', (id, slice) => …)"," sm.listenDevice(8, (id, cap, slice) => …)"," sm.onDeviceAdded((id, info) => …)"," sm.onDeviceRemoved((id, info) => …)","","Wait primitives:"," await sm.waitForState(8, 'battery', s => !s.sleeping, 30_000)"," await sm.waitForDevice(99, 30_000)","","Batch:"," await sm.invokeCap('snapshot', 'getSnapshot', {}, { parallelism: 4 })"," await sm.forEachCap('reboot', d => d.reboot.reboot({}))","","Diagnostics:"," sm.dump(8) debug dump (one device)"," sm.dump() full fleet dump"," sm.summary() breakdown by cap/addon/type","","Legacy: deviceRegistry, addonRegistry, eventBus, devices(), addons()"];case"device":return[...t,"Pre-bound variables:"," device DeviceProxy for this device (sync state + async methods)"," deviceId number"," info DeviceInfo metadata (name, addonId, type, online, …)"," sm SystemMirror (full cluster view)"," rawDevice legacy IDevice instance (escape hatch)","","Reactive state (sync, zero round-trip):"," device.state.battery.value BatteryStatus | undefined"," device.state.battery.value?.sleeping"," device.state.battery.value?.percentage"," device.state.motion.value?.detected"," device.state.switch.value?.on"," device.state.brightness.value?.percentage"," device.state.doorbell.value?.lastPressedAt","","Cap actions (async, through wrapper chain):"," await device.snapshot.getSnapshot({})"," await device.snapshot.getSnapshot({ streamId: 'high' })"," await device.ptz.move({ direction: 'left', steps: 1 })"," await device.ptz.goToPreset({ presetId: 'home' })"," await device.switch.setState({ on: true })"," await device.brightness.setBrightness({ percentage: 60 })"," await device.reboot.reboot({})","","Subscribe to slice changes:"," const off = device.state.battery.subscribe(s => console.log(s))"," // off() to unsubscribe","","Wait for a state condition:"," await sm.waitForState(deviceId, 'battery', s => !s.sleeping, 30_000)","","Diagnostics:"," info.name device name"," info.addonId which addon owns it"," info.online transport health"," sm.dump(deviceId) full debug dump (binding + state + info)"];case"provider":return[...t,"Pre-bound variables:"," devices Devices belonging to this provider (raw IDevice[])"," getIntegration() Integration metadata","","For typed device access use the SystemMirror:"," await getSystemMirror()"," sm.getDevicesByAddon('this-addon-id')"];case"addon":return[...t,"Pre-bound variables:"," manifest { name, version, ... }"," declaration addon declaration"," source addon source location","","Examples:"," manifest.name"," manifest.version"]}}function AO({scope:e,greeting:t,className:n}){const o=Le(),[s,a]=$(()=>{const y=[];return t&&y.push({id:st(),kind:"info",text:t}),y.push({id:st(),kind:"info",text:`scope: ${vi(e)} — type help or context for available commands`}),y}),[i,l]=$(""),[c,d]=$([]),[f,p]=$(-1),m=ne(null),h=ne(null);Y(()=>{const y=h.current;y&&(y.scrollTop=y.scrollHeight)},[s]);const g=q(()=>{m.current?.focus()},[]),b=$l({mutationFn:y=>o.trpcClient.repl.execute.mutate({code:y,scope:e}),onSuccess:y=>{const N=y??{},k=typeof N.output=="string"?N.output:y==null?"undefined":typeof y=="string"?y:JSON.stringify(y,null,2),S=N.type==="error";a(M=>[...M,{id:st(),kind:S?"error":"result",text:k}])},onError:y=>{const N=y instanceof Error?y.message:String(y);a(k=>[...k,{id:st(),kind:"error",text:N}])}});function x(y){const N=y.trim();if(N){if(N==="clear"){a([{id:st(),kind:"info",text:`scope: ${vi(e)}`}]),l("");return}if(N==="help"){a(k=>[...k,{id:st(),kind:"input",text:`> ${N}`},...CO(e).map(S=>({id:st(),kind:"info",text:S}))]),l("");return}if(N==="context"){a(k=>[...k,{id:st(),kind:"input",text:`> ${N}`},...IO(e).map(S=>({id:st(),kind:"info",text:S}))]),l("");return}if(N==="examples"){a(k=>[...k,{id:st(),kind:"input",text:`> ${N}`},...MO(e).map(S=>({id:st(),kind:"info",text:S}))]),l("");return}d(k=>[...k,N]),p(-1),a(k=>[...k,{id:st(),kind:"input",text:`> ${N}`}]),l(""),b.mutate(N)}}function v(y){if(y.key==="Enter"){y.preventDefault(),x(i);return}if(y.key==="ArrowUp"){if(y.preventDefault(),c.length===0)return;const N=f===-1?c.length-1:Math.max(0,f-1);p(N),l(c[N]??"");return}if(y.key==="ArrowDown"){if(y.preventDefault(),f===-1)return;const N=f+1;N>=c.length?(p(-1),l("")):(p(N),l(c[N]??""));return}y.ctrlKey&&y.key==="l"&&(y.preventDefault(),a([{id:st(),kind:"info",text:`scope: ${vi(e)}`}]))}const w={input:"text-zinc-300",result:"text-emerald-300",error:"text-red-300",info:"text-zinc-400"};return u("div",{className:`flex flex-col bg-[#0c0a09] rounded-lg border border-border overflow-hidden font-mono text-xs ${n??""}`,onClick:g,children:[u("div",{ref:h,className:"flex-1 overflow-y-auto p-3 space-y-1 min-h-[120px]",children:[s.map(y=>r("pre",{className:`whitespace-pre-wrap break-words leading-relaxed ${w[y.kind]}`,children:y.text},y.id)),b.isPending&&r("span",{className:"text-zinc-500 animate-pulse",children:"…thinking"})]}),u("div",{className:"flex items-center gap-2 border-t border-zinc-800 px-3 py-2 bg-[#0c0a09]",children:[r("span",{className:"text-emerald-400 flex-shrink-0 select-none font-bold",children:">"}),r("input",{ref:m,value:i,onChange:y=>l(y.target.value),onKeyDown:v,disabled:b.isPending,placeholder:"device.state.battery.value",autoFocus:!0,className:"flex-1 bg-transparent text-zinc-100 placeholder:text-zinc-600 focus:outline-none caret-emerald-400 disabled:opacity-50",spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off"})]})]})}function PO(e){const t=ke(),n=e!==null&&Number.isFinite(e),o=Db({deviceId:e??0},{enabled:n,refetchInterval:5e3,retry:1}),s=Lb({onSuccess:()=>{t.invalidateQueries({queryKey:[["ptzAutotrack"]]})}}),a=Tb({onSuccess:()=>{t.invalidateQueries({queryKey:[["ptzAutotrack"]]})}}),i=q(async d=>{e!==null&&await s.mutateAsync({deviceId:e,enabled:d})},[e,s]),l=q(async d=>{e!==null&&await a.mutateAsync({deviceId:e,settings:d})},[e,a]),c=o.error?o.error.message:s.error?s.error.message:a.error?a.error.message:null;return{status:o.data??null,isLoading:o.isLoading,isPending:s.isPending||a.isPending,error:c,setEnabled:i,setSettings:l}}function EO({deviceId:e}){const{status:t,isLoading:n,isPending:o,error:s,setEnabled:a,setSettings:i}=PO(Number.isFinite(e)?e:null),[l,c]=$({targetType:"",stopDelaySeconds:30,disappearDelaySeconds:15}),[d,f]=$(!1);return Y(()=>{if(d)return;const p=t?.currentSettings;p&&c({targetType:p.targetType,stopDelaySeconds:p.stopDelaySeconds,disappearDelaySeconds:p.disappearDelaySeconds})},[t,d]),n&&!t?u("div",{className:"flex items-center gap-2 px-3 py-2 text-[10.5px] text-foreground-subtle",children:[r(Pe,{className:"h-3 w-3 animate-spin"}),"Loading autotrack…"]}):u("div",{className:"border-t border-border/40 mt-2 pt-2 px-1 space-y-2",children:[u("div",{className:"flex items-center justify-between px-2",children:[u("div",{className:"flex items-center gap-1.5 text-[10.5px] font-semibold text-foreground",children:[r(PD,{className:"h-3 w-3 text-primary"}),"Autotracking"]}),u("button",{type:"button",onClick:()=>{a(!(t?.enabled??!1))},disabled:o,className:`flex items-center gap-1.5 rounded-md px-2 py-1 text-[10px] font-medium transition-colors ${t?.enabled?"bg-success/15 text-success hover:bg-success/25":"bg-surface-elevated/40 text-foreground-subtle hover:bg-surface-hover hover:text-foreground"} disabled:opacity-50`,"aria-pressed":t?.enabled??!1,children:[r("span",{className:`h-1.5 w-1.5 rounded-full ${t?.enabled?"bg-success":"bg-foreground-subtle/40"}`}),t?.enabled?"Enabled":"Disabled"]})]}),s&&u("div",{className:"flex items-start gap-1.5 rounded-md border border-danger/30 bg-danger/5 px-2 py-1.5 text-[10px] text-danger",children:[r(xa,{className:"h-3 w-3 flex-shrink-0 mt-0.5"}),r("span",{className:"leading-snug break-words",children:s})]}),u("div",{className:"grid grid-cols-2 gap-2 px-2",children:[(t?.supportedTargetTypes?.length??0)>0&&u("label",{className:"col-span-2 flex flex-col gap-1",children:[r("span",{className:"text-[10px] font-medium text-foreground-subtle",children:"Target type"}),r("select",{value:l.targetType,onFocus:()=>f(!0),onChange:p=>c(m=>({...m,targetType:p.target.value})),onBlur:()=>{f(!1);const p=t?.currentSettings?.targetType??"";l.targetType!==p&&i({targetType:l.targetType})},disabled:o,className:"rounded-md border border-border bg-surface px-2 py-1 text-[11px] text-foreground focus:border-primary focus:outline-none disabled:opacity-50",children:(t?.supportedTargetTypes??[]).map(p=>r("option",{value:p.value,children:p.label},p.value))})]}),u("label",{className:"flex flex-col gap-1",children:[r("span",{className:"text-[10px] font-medium text-foreground-subtle",children:"Stop delay (s)"}),r("input",{type:"number",min:0,max:300,value:l.stopDelaySeconds,onFocus:()=>f(!0),onChange:p=>c(m=>({...m,stopDelaySeconds:Number(p.target.value)||0})),onBlur:()=>{f(!1);const p=t?.currentSettings?.stopDelaySeconds??30;l.stopDelaySeconds!==p&&i({stopDelaySeconds:l.stopDelaySeconds})},disabled:o,className:"rounded-md border border-border bg-surface px-2 py-1 text-[11px] text-foreground focus:border-primary focus:outline-none disabled:opacity-50"})]}),u("label",{className:"flex flex-col gap-1",children:[r("span",{className:"text-[10px] font-medium text-foreground-subtle",children:"Disappear delay (s)"}),r("input",{type:"number",min:0,max:300,value:l.disappearDelaySeconds,onFocus:()=>f(!0),onChange:p=>c(m=>({...m,disappearDelaySeconds:Number(p.target.value)||0})),onBlur:()=>{f(!1);const p=t?.currentSettings?.disappearDelaySeconds??15;l.disappearDelaySeconds!==p&&i({disappearDelaySeconds:l.disappearDelaySeconds})},disabled:o,className:"rounded-md border border-border bg-surface px-2 py-1 text-[11px] text-foreground focus:border-primary focus:outline-none disabled:opacity-50"})]})]}),r("p",{className:"px-2 text-[9.5px] text-foreground-subtle leading-snug italic",children:"Settings save on blur. Vendor support varies — Reolink honours all three; Hikvision honours target type + stop delay only (disappear delay is accepted but ignored at firmware push)."})]})}function $O({deviceId:e,intercomAvailable:t=!1}){const n=Le(),o=typeof window<"u"?window.location.origin:"",s=Number.isFinite(e),a=wy(s?e:null),{streams:i,pipelineMetrics:l,createSession:c,sendAnswer:d,closeSession:f}=Dc(n.trpcClient,s?e:null),p=nc(n.trpcClient,s?e:null),m=kO(s&&t?e:null),h=m.state==="requesting-mic"||m.state==="starting"||m.state==="connecting"||m.state==="stopping",g=m.isTalking||h,b=()=>{m.state==="idle"||m.state==="error"?m.start():m.state!=="stopping"&&m.stop()},x=wx(),v=x.length>0?r(ve,{children:x.map(w=>r("div",{className:"absolute inset-0",children:w.node},w.id))}):null;return r(Ac,{serverUrl:o,createSession:c,sendAnswer:d,closeSession:f,streams:i,pipelineMetrics:l,phase:a.phase,detections:a,defaultShowDetections:!0,defaultShowMotion:!0,showPlayStop:!0,snapshotSrc:p.src,snapshotLoading:p.loading,onRefreshSnapshot:p.refresh,intercomAvailable:t,intercomShown:g,onIntercomToggle:b,extraOverlay:v,chromeless:!0,className:"h-full"})}function _O({deviceId:e}){return Number.isFinite(e)?r("div",{className:"flex flex-col h-full",children:r(Wt,{deviceId:e,limit:50,maxHeight:"max-h-full",showScope:!1,showFilters:!1})}):u("div",{className:"flex items-center justify-center h-full text-[11px] text-foreground-subtle italic",children:["Device #",e," not loaded."]})}function DO({deviceId:e}){if(!Number.isFinite(e))return u("div",{className:"flex items-center justify-center h-full text-[11px] text-foreground-subtle italic",children:["Device #",e," not loaded."]});const t=[`CamStack REPL — device #${e}`,""," device.state.battery.value sync state read"," await device.snapshot.getSnapshot({}) cap action",""," type 'examples' for more, 'context' for the full API"].join(`
|
|
1084
|
-
`);return r(AO,{scope:{type:"device",deviceId:e},greeting:t,className:"h-full border-0 rounded-none"})}function LO({deviceId:e}){const t=Le(),n=Number.isFinite(e),o=Lc(t.trpcClient,n?e:0,{enabled:n}),{data:s}=q6(n?e:0);if(!n)return u("div",{className:"flex items-center justify-center h-full text-[11px] text-foreground-subtle italic",children:["Device #",e," not loaded."]});const a=(s?.features??[]).includes(Rn.PtzAutotrack);return u("div",{className:"flex flex-col h-full overflow-y-auto",children:[r($c,{controls:o,mode:"panel"}),a&&r(EO,{deviceId:e})]})}function TO({deviceId:e}){return Number.isFinite(e)?r("div",{className:"flex flex-col h-full overflow-y-auto",children:r(nr,{deviceId:e,limit:50,maxHeight:"max-h-full"})}):u("div",{className:"flex items-center justify-center h-full text-[11px] text-foreground-subtle italic",children:["Device #",e," not loaded."]})}function RO({deviceId:e}){return Number.isFinite(e)?r("div",{className:"flex flex-col h-full overflow-y-auto",children:r(Ec,{deviceId:e,limit:50,maxHeight:"max-h-full"})}):u("div",{className:"flex items-center justify-center h-full text-[11px] text-foreground-subtle italic",children:["Device #",e," not loaded."]})}function OO({parentDeviceId:e}){const{t}=zt(),n=et(),o=Le(),{data:s,isLoading:a,isError:i}=Fy(e);if(a)return r("div",{className:"rounded-lg border border-border bg-surface p-3",children:r("p",{className:"text-[10px] text-foreground-subtle",children:t("common.loading",{defaultValue:"Loading…"})})});if(i)return r("div",{className:"rounded-lg border border-border bg-surface p-3",children:r("p",{className:"text-[10px] text-warning",children:t("integrations.childrenLoadError",{defaultValue:"Failed to load children"})})});const l=s??[];if(l.length===0)return null;const c=l.some(p=>!!p.role),d=l.some(p=>!p.role),f=c&&!d?t("device.accessories",{defaultValue:"Accessories"}):!c&&d?t("device.adoptedDevices",{defaultValue:"Adopted devices"}):t("device.children",{defaultValue:"Children"});return u("div",{className:"rounded-lg border border-border bg-surface p-3",children:[r("div",{className:"text-[10px] font-semibold uppercase tracking-wide text-foreground-subtle mb-1.5",children:f}),r("div",{className:"space-y-1",children:l.map(p=>r(so,{trpc:o.trpcClient,device:p,variant:"minimal",onNavigate:m=>n(`/devices/${String(m)}`)},p.id))})]})}function wi(e){return e<1e3?`${e.toFixed(0)} kbps`:`${(e/1e3).toFixed(1)} Mbps`}function zO({device:e}){const t=et(),n=typeof e.id=="number"?e.id:null,o=String(e.type??""),s=o===at.Camera,a=o===at.Hub,i=e.features??[],{data:l}=bc({deviceId:n??0},{enabled:n!==null&&s,refetchInterval:5e3}),c=l?.streams??{},d=Object.entries(c),f=i.includes(Rn.DoorbellButton),p=Tc(f?{deviceId:n??void 0,historyLimit:10}:void 0),m=p.latest?Date.now()-p.latest.timestamp<3e4:!1;return u("div",{className:"space-y-5",children:[a&&n!==null&&r(Cx,{deviceId:n,onOpenChild:h=>t(`/devices/${h}`)}),s&&n!==null&&r(it,{widgetId:"pipeline-orchestrator/pipeline-quick-stats",host:"device-tab",deviceId:n}),f&&r(_c,{history:p.history,latestIsFresh:m}),s&&n!==null&&r(it,{widgetId:"stream-broker/stream-broker-panel",host:"device-tab",deviceId:n}),s&&d.length>0&&u("div",{className:"@container rounded-lg border border-border bg-surface overflow-hidden",style:{containerType:"inline-size"},children:[r("div",{className:"border-b border-border px-4 py-2",children:r("h2",{className:"text-xs font-semibold text-foreground uppercase tracking-wider",children:"Stream Network"})}),r("div",{className:"divide-y divide-border",children:d.map(([h,g])=>u("div",{className:"px-4 py-2.5",children:[u("div",{className:"flex items-center gap-2 mb-2",children:[r(jn,{className:"h-3 w-3 text-foreground-subtle"}),r("span",{className:"text-[11px] font-medium text-foreground",children:h})]}),u("div",{className:"grid grid-cols-2 @[640px]:grid-cols-4 gap-2",children:[r(Jo,{label:"Nominal",value:wi(g.nominalBitrateKbps??0)}),r(Jo,{label:"Observed",value:wi(g.observedBitrateKbps??0)}),r(Jo,{label:"Peak",value:wi(g.peakBitrateKbps??0)}),r(Jo,{label:"Packet Loss",value:`${(g.packetLossPercent??0).toFixed(2)}%`,warning:(g.packetLossPercent??0)>1})]})]},h))})]}),r(ky,{})]})}function Jo({label:e,value:t,warning:n}){return u("div",{children:[r("p",{className:"text-[10px] text-foreground-subtle",children:e}),r("p",{className:`text-xs font-medium ${n?"text-warning":"text-foreground"}`,children:t})]})}function BO({schema:e,values:t,pendingKeys:n,onChange:o,onAction:s,onSave:a,onDiscard:i,disabled:l}){const c=e.tabs??[],d=Q(()=>{const k=new Map;for(const S of e.sections){const M=S.tab??"general",P=k.get(M)??[];P.push(S),k.set(M,P)}return k},[e.sections]),f=new Set(c.map(k=>k.id)),p=[...c,...[...d.keys()].filter(k=>!f.has(k)).map(k=>({id:k,label:k,icon:"wrench",order:100}))],m=p[0]?.id??"general",[h,g]=$(m),b=d.get(h)??[],v={sections:b.length<=1?b.length===1?[{...b[0],title:""}]:b:b.every(S=>!S.title)?[{...b[0],title:"",fields:b.flatMap(S=>S.fields)}]:b},w=r(qy,{pendingCount:n.length,onSave:()=>a(n),onDiscard:()=>i(n),saving:l});if(p.length<=1)return u("div",{className:"flex flex-col gap-3",children:[r(Nn,{schema:e,values:t,onChange:o,onAction:s,disabled:l}),w]});const y=new Map,N=new Map;for(const[k,S]of d){y.set(k,S.length);const M=new Set,P=F=>{for(const E of F)if("key"in E&&typeof E.key=="string"&&M.add(E.key),E.type==="group")P(E.fields);else if(E.type==="sub-tabs")for(const B of E.tabs)P(B.fields)};for(const F of S)P(F.fields);const I=n.filter(F=>M.has(F)).length;I>0&&N.set(k,I)}return u("div",{className:"flex flex-col gap-3",children:[r(Qy,{tabs:p.map(k=>({id:k.id,label:k.label})),activeId:h,onChange:g,countByTab:y,pendingByTab:N}),r(Nn,{schema:v,values:t,onChange:o,onAction:s,disabled:l}),w]})}const fp={viewer:10,admin:20,super_admin:30};function FO(e,t){if(!t)return!0;const n=fp[t];return n===void 0?!0:(e?fp[e]??0:0)>=n}function jO(e){if(!e)return null;const n={sections:[...e.sections].sort((o,s)=>{const a=o.tab??"general",i=s.tab??"general";return a!==i?a.localeCompare(i):(o.order??0)-(s.order??0)})};return e.tabs?{...n,tabs:e.tabs}:n}function Gy(e){return e.type==="separator"||e.type==="info"||e.type==="button"||e.type==="widget"||e.type==="addon-action-button"}function Wy(e){return e.key}function HO(e){if(!Gy(e))return e.value}function Yy(e){return Gy(e)?null:e}function Ts(e,t){for(const n of e)if(t(n),n.type==="group")Ts(n.fields,t);else if(n.type==="sub-tabs")for(const o of n.tabs)Ts(o.fields,t)}function VO(e){if(!e)return{};const t={};for(const n of e.sections)Ts(n.fields,o=>{const s=Wy(o);s!==null&&(t[s]=HO(o))});return t}function mp(e,t){if(!e)return null;let n=null;for(const o of e.sections)if(Ts(o.fields,s=>{if(n!==null||Wy(s)!==t)return;const a=Yy(s);a&&a.writerCapName&&a.writerAddonId&&(n={capName:a.writerCapName,addonId:a.writerAddonId})}),n!==null)break;return n}function qO(e){return{...e,fields:e.fields.map(Zy)}}function Zy(e){return e.type==="separator"||e.type==="info"||e.type==="button"||e.type==="object-array"?e:{...e,readonlyField:!0}}function QO(e,t){return e&&{...e,sections:e.sections.map(n=>({...n,fields:n.fields.map(o=>{const s=Yy(o);return s?FO(t,s.minRole)?o:Zy(o):o})}))}}function Xy({deviceId:e,sectionFilter:t}){const n=ke(),{user:o}=Tr(),s=o?.role,a=ne(!1),{data:i,isLoading:l}=mc({deviceId:e},{refetchInterval:()=>a.current?!1:2500,staleTime:6e4,enabled:Number.isFinite(e)}),{data:c}=Fn({deviceId:e},{staleTime:6e4,enabled:Number.isFinite(e)}),d=i?.settings??null,f=i?.live??null,p=Q(()=>{if(!d&&!f)return null;const B=d?.sections??[],O=(f?.sections??[]).map(qO),A=[...B,...O],D=t?A.filter(t):A.filter(z=>z.location!=="top-tab");if(D.length===0)return null;const _=new Set;for(const z of D)_.add(z.tab??"general");const L=[...d?.tabs??[],...(f?.tabs??[]).filter(z=>!(d?.tabs??[]).some(j=>j.id===z.id))].filter(z=>_.has(z.id));return L.length>0?{tabs:L,sections:D}:{sections:D}},[d,f,t]),m=Q(()=>jO(p),[p]),h=Q(()=>QO(m,s),[m,s]),g=Q(()=>VO(h),[h]),b=Wb(),x=gc(),v=Ag({onSuccess:()=>{n.invalidateQueries({queryKey:[["deviceManager","getDeviceAggregate"]]})}}),w={isPending:v.isPending,mutate:B=>{v.mutate({deviceId:e,changes:[...B]})}},y=q(B=>{const O=Object.entries(B).map(([A,D])=>{const _=mp(h,A);return _?{writerCapName:_.capName,writerAddonId:_.addonId,key:A,value:D}:null}).filter(A=>A!==null);O.length>0&&w.mutate(O)},[h,w]),N=q(B=>{const O=Object.entries(B).map(([A,D])=>{const _=mp(h,A);return _?{writerCapName:_.capName,writerAddonId:_.addonId,key:A,value:D}:null}).filter(A=>A!==null);O.length>0&&w.mutate(O)},[h,w]),k=Uy({schema:h,serverValues:g,onImmediateSave:y,onDeferredSave:N}),{values:S,pendingKeys:M,handleChange:P,handleSave:I,handleDiscard:F}=k;if(a.current=k.editingPaused,l)return u("div",{className:"flex items-center justify-center py-12 text-foreground-subtle",children:[r(Pe,{className:"h-4 w-4 animate-spin mr-2"}),r("span",{className:"text-xs",children:"Loading device aggregate…"})]});if(!h||h.sections.length===0)return r("div",{className:"text-xs text-foreground-subtle italic py-4 text-center",children:"No aggregate contributions for this device."});async function E(B,O,A){if(B==="regenerate-rtsp-token"){const D=["rtspUrl:","regenerateToken:"].find(L=>O.startsWith(L));if(!D)throw new Error(`regenerate-rtsp-token: unrecognised key "${O}" (expected "rtspUrl:<streamId>" or "regenerateToken:<streamId>")`);const _=O.slice(D.length);if(!_)throw new Error(`regenerate-rtsp-token: key "${O}" has no streamId after prefix`);const R=`${e}/${_}`;await b.mutateAsync({brokerId:R}),n.invalidateQueries({queryKey:[["deviceManager","getDeviceAggregate"]]});return}if(B==="test-probe"){if(!c)return{status:"error",error:"Device metadata not loaded yet"};try{return await x.mutateAsync({addonId:c.addonId,type:c.type,key:O,value:A})}catch(D){return{status:"error",error:D instanceof Error?D.message:String(D)}}}if(B==="refresh-driver-data"){await v.mutateAsync({deviceId:e,changes:[{writerCapName:"device-manager",writerAddonId:"device-manager",key:O,value:Date.now()}]});return}throw new Error(`[device-aggregate] unknown action "${B}"`)}return r(BO,{schema:h,values:S,pendingKeys:M,onChange:P,onAction:E,onSave:I,onDiscard:F,disabled:w.isPending})}function UO({deviceId:e}){return r(Xy,{deviceId:e})}const Jy=6e4,ul=60*Jy,hp=24*ul;function Sa(e){if(e==null||e<=0)return"—";const t=Date.now()-e;return t<0||t<3e4?"just now":t<ul?`${String(Math.floor(t/Jy))}m ago`:t<hp?`${String(Math.floor(t/ul))}h ago`:`${String(Math.floor(t/hp))}d ago`}function KO(e,t=new Date){const n=new Date(e);return n.getFullYear()===t.getFullYear()&&n.getMonth()===t.getMonth()&&n.getDate()===t.getDate()}function e0({dev:e,busy:t,setBusy:n}){const o=e?.motionTrigger,s=on(e?.state.motionTrigger),[a,i]=$(!1);if(!o)return null;const l=s?.enabled===!0,c=s!==void 0,d=async()=>{if(t||!c)return;const p=!l;n(!0),i(!0);try{await o.setMotionTrigger({enabled:p})}finally{n(!1),i(!1)}};return u("button",{type:"button",onClick:()=>{d()},disabled:t||!c,title:c?l?"Disable trigger on motion":"Enable trigger on motion":"Awaiting state…","aria-pressed":l,className:`inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-[11px] font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50 ${l?"border-primary/50 bg-primary/15 text-primary":"border-border bg-surface text-foreground-subtle hover:text-foreground"}`,children:[r(Io,{className:"h-3 w-3"}),r("span",{children:a?l?"Disabling…":"Enabling…":c?l?"On motion: on":"On motion: off":"On motion: …"})]})}function t0({deviceId:e,deviceName:t,useSiren:n=!1}){const o=Le(),s=kt(o.trpcClient,e),a=on(s?.state.switch),[i,l]=$(!1),c=a?.on??!1,d=a?.lastChangedAt??null,f=a!==void 0,p=n?Ao:fy,m=async()=>{if(!(i||!f||!s?.switch)){l(!0);try{await s.switch.setState({on:!c})}finally{l(!1)}}};return u("div",{className:"flex h-full w-full flex-col items-center justify-center gap-3 p-4",children:[r("button",{type:"button",onClick:()=>{m()},disabled:i||!f||!s?.switch,title:f?c?`Turn off ${t}`:`Turn on ${t}`:"Awaiting state…","aria-pressed":c,className:`flex h-24 w-24 items-center justify-center rounded-full border-2 transition-all disabled:cursor-not-allowed disabled:opacity-50 ${c?"border-success bg-success/20 text-success shadow-lg shadow-success/20":"border-border bg-surface text-foreground-subtle hover:border-foreground-subtle hover:text-foreground"}`,children:r(p,{className:"h-10 w-10"})}),r(e0,{dev:s,busy:i,setBusy:l}),u("div",{className:"text-center",children:[r("div",{className:`text-sm font-semibold ${c?"text-success":"text-foreground-subtle"}`,children:f?c?"On":"Off":"Unknown"}),r("div",{className:"text-[10px] text-foreground-subtle mt-0.5",children:f?`Changed ${Sa(d)}`:"Awaiting state…"})]})]})}function GO({deviceId:e,deviceName:t}){const n=Le(),o=kt(n.trpcClient,e),s=on(o?.state.switch),a=on(o?.state.brightness),i=s?.on??!1,l=s?.lastChangedAt??null,c=s!==void 0,d=a!==void 0,f=o?.brightness!==void 0,[p,m]=$(!1),[h,g]=$(a?.percentage??0);Y(()=>{a?.percentage!==void 0&&g(a.percentage)},[a?.percentage]);const b=async()=>{if(!(p||!c||!o?.switch)){m(!0);try{await o.switch.setState({on:!i})}finally{m(!1)}}},x=async()=>{if(!(p||!d||!o?.brightness)){m(!0);try{await o.brightness.setBrightness({percentage:h})}finally{m(!1)}}};return u("div",{className:"flex h-full w-full flex-col items-center justify-center gap-3 p-4",children:[r("button",{type:"button",onClick:()=>{b()},disabled:p||!c||!o?.switch,title:c?i?`Turn off ${t}`:`Turn on ${t}`:"Awaiting state…","aria-pressed":i,className:`flex h-20 w-20 items-center justify-center rounded-full border-2 transition-all disabled:cursor-not-allowed disabled:opacity-50 ${i?"border-warning bg-warning/20 text-warning shadow-lg shadow-warning/30":"border-border bg-surface text-foreground-subtle hover:border-foreground-subtle hover:text-foreground"}`,children:r(rL,{className:"h-9 w-9"})}),f?u("div",{className:"flex w-full max-w-xs flex-col items-center gap-1",children:[r("input",{type:"range",min:0,max:100,step:1,value:h,disabled:p||!i||!d,onChange:v=>g(Number(v.currentTarget.value)),onPointerUp:()=>{x()},onKeyUp:v=>{v.key==="Enter"&&x()},"aria-label":"Brightness",className:"w-full accent-warning disabled:cursor-not-allowed disabled:opacity-50"}),r("div",{className:"text-[10px] text-foreground-subtle tabular-nums",children:d?`${String(h)}%`:"Brightness unavailable"})]}):null,r(e0,{dev:o,busy:p,setBusy:m}),u("div",{className:"text-center",children:[r("div",{className:`text-sm font-semibold ${i?"text-warning":"text-foreground-subtle"}`,children:c?i?"On":"Off":"Unknown"}),r("div",{className:"text-[10px] text-foreground-subtle mt-0.5",children:c?`Changed ${Sa(l)}`:"Awaiting state…"})]})]})}function WO({deviceId:e}){const t=Le(),n=kt(t.trpcClient,e),o=on(n?.state.motion),s=o?.detected??!1,a=o?.lastDetectedAt??null,i=o!==void 0;return u("div",{className:"flex h-full w-full flex-col items-center justify-center gap-3 p-4",children:[r("div",{className:`flex h-24 w-24 items-center justify-center rounded-full border-2 transition-all ${s?"border-danger bg-danger/20 text-danger shadow-lg shadow-danger/30 animate-pulse":"border-border bg-surface text-foreground-subtle"}`,"aria-live":"polite",title:s?"Motion detected":"Idle",children:s?r(LL,{className:"h-10 w-10"}):r(Io,{className:"h-10 w-10"})}),u("div",{className:"text-center",children:[r("div",{className:`text-sm font-semibold ${s?"text-danger":"text-foreground-subtle"}`,children:i?s?"Triggered":"Idle":"Unknown"}),r("div",{className:"text-[10px] text-foreground-subtle mt-0.5",children:i?`Last trip ${Sa(a)}`:"Awaiting state…"})]})]})}function YO({deviceId:e}){const t=Le(),n=kt(t.trpcClient,e),o=on(n?.state.doorbell),s=o?.lastPressedAt??null,a=o!==void 0,i=s!==null&&Date.now()-s<6e4,[l,c]=$(0),[d,f]=$(null);return Y(()=>{s===null||s===d||(f(s),KO(s)&&c(p=>p+1))},[s,d]),u("div",{className:"flex h-full w-full flex-col items-center justify-center gap-3 p-4",children:[r("div",{className:`flex h-24 w-24 items-center justify-center rounded-full border-2 transition-all ${i?"border-primary bg-primary/20 text-primary shadow-lg shadow-primary/30 animate-pulse":"border-border bg-surface text-foreground-subtle"}`,"aria-live":"polite",title:i?"Just pressed":"Idle",children:r(Ao,{className:"h-10 w-10"})}),u("div",{className:"text-center",children:[r("div",{className:`text-sm font-semibold ${i?"text-primary":"text-foreground-subtle"}`,children:a?`Last press ${Sa(s)}`:"Unknown"}),r("div",{className:"text-[10px] text-foreground-subtle mt-0.5 tabular-nums",children:a?`${String(l)} ring${l===1?"":"s"} today`:"Awaiting state…"})]})]})}function ZO({deviceName:e,deviceType:t,provider:n,isOnline:o,features:s}){return u("div",{className:"flex h-full w-full flex-col items-center justify-center gap-3 rounded-lg border border-dashed border-border bg-surface p-6 text-center",children:[r(cn,{type:n,size:"lg"}),u("div",{children:[r("div",{className:"text-sm font-semibold text-foreground",children:e}),r("div",{className:"text-[10px] text-foreground-subtle uppercase tracking-wider mt-0.5",children:t})]}),u("div",{className:"flex items-center gap-2 flex-wrap justify-center",children:[r(ka,{status:o?"online":"offline"}),s.length>0&&r(wa,{capabilities:s})]}),r("div",{className:"text-[10px] text-foreground-subtle italic max-w-xs mt-1",children:"No live view for this device type. Use the Config tab or the shortcut row to interact."})]})}function XO({deviceId:e}){const t=ke(),n=gg({deviceId:e},{refetchInterval:1e4,retry:!1}),o=bg({onSuccess:()=>{t.invalidateQueries({queryKey:[["deviceDiscovery","listDiscovered"]]}),t.invalidateQueries({queryKey:[["deviceDiscovery","getStatus"]]})}}),s=Q(()=>JO(n.data??[]),[n.data]);return u("div",{className:"flex h-full w-full flex-col gap-3 p-3 sm:p-4",children:[u("div",{className:"flex flex-wrap items-stretch gap-2 sm:gap-3",children:[r(Ni,{label:"Discovered",value:s.total,icon:r(an,{className:"h-3.5 w-3.5"})}),r(Ni,{label:"Adopted",value:s.adopted,accent:"success"}),r(Ni,{label:"Available",value:s.available,accent:s.available>0?"primary":void 0}),u("button",{type:"button",onClick:()=>{o.mutateAsync({deviceId:e}).catch(()=>{})},disabled:o.isPending,className:"inline-flex items-center justify-center gap-1.5 rounded-lg border border-border px-3 py-2 text-xs font-medium text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors disabled:opacity-50 self-stretch shrink-0",children:[o.isPending?r(Pe,{className:"h-3.5 w-3.5 animate-spin"}):r(pt,{className:"h-3.5 w-3.5"}),r("span",{className:"hidden sm:inline",children:"Discover"})]})]}),u("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 text-[11px] text-foreground-subtle border-t border-border-subtle pt-2",children:[r(es,{icon:r(jn,{className:"h-3 w-3 text-emerald-500"}),label:`${s.online} online`}),r(es,{icon:r(dy,{className:"h-3 w-3 text-amber-500"}),label:`${s.sleeping} sleeping`}),r(es,{icon:r(vy,{className:"h-3 w-3 text-destructive"}),label:`${s.offline} offline`}),s.unknown>0?r(es,{icon:r(ND,{className:"h-3 w-3 text-foreground-subtle"}),label:`${s.unknown} unknown`}):null]})]})}function JO(e){const t={total:e.length,adopted:0,available:0,online:0,sleeping:0,offline:0,unknown:0};for(const n of e)n.alreadyAdopted?t.adopted+=1:t.available+=1,t[n.status]+=1;return t}function Ni({label:e,value:t,icon:n,accent:o}){return u("div",{className:`flex flex-1 basis-[140px] min-w-0 flex-col gap-1 rounded-lg border px-2 py-1.5 sm:px-3 sm:py-2 ${o==="success"?"bg-emerald-500/10 border-emerald-500/30 text-emerald-500":o==="primary"?"bg-primary/10 border-primary/30 text-primary":"bg-surface-hover border-border text-foreground"}`,children:[u("div",{className:"flex items-center gap-1.5 text-[10px] uppercase tracking-wider opacity-70 truncate",children:[n,r("span",{className:"truncate",children:e})]}),r("div",{className:"text-xl sm:text-2xl font-semibold tabular-nums leading-none",children:t})]})}function es({icon:e,label:t}){return u("span",{className:"inline-flex items-center gap-1",children:[e,r("span",{children:t})]})}const e8=e=>r(t0,{...e,useSiren:!0}),t8={[at.Switch]:t0,[at.Siren]:e8,[at.Light]:GO,[at.Sensor]:WO,[at.Button]:YO,[at.Hub]:XO};function n8(e){const t=t8[e.deviceType]??ZO;return r(t,{...e})}function ed(e){if(e<60)return`${Math.round(e)}s`;const t=Math.floor(e/60),n=Math.round(e%60);if(t<60)return n>0?`${t}m ${n}s`:`${t}m`;const o=Math.floor(t/60),s=t%60;return s>0?`${o}h ${s}m`:`${o}h`}function Rs(e){return new Date(e).toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit",second:"2-digit"})}function Os(e){return e.toISOString().slice(0,10)}function r8(e,t){return Os(e)===Os(t)}function Ur(e){const t=new Date(e);return t.setHours(0,0,0,0),t}function o8(e){const t=new Date(e);return t.setHours(23,59,59,999),t}function At({className:e=""}){return r("div",{className:`animate-pulse rounded bg-foreground-subtle/10 ${e}`})}function Dn(){return u("div",{className:"flex items-center gap-3 px-4 py-3",children:[r(At,{className:"h-4 w-4"}),r(At,{className:"h-3 w-24"}),r(At,{className:"h-3 w-16 ml-auto"})]})}function jr({children:e,actions:t}){return u("div",{className:"border-b border-border px-4 py-2.5 flex items-center justify-between",children:[r("h2",{className:"text-xs font-semibold text-foreground uppercase tracking-wider",children:e}),t]})}function gp({icon:e,label:t,value:n}){return u("div",{className:"flex items-center gap-2",children:[r(e,{className:"h-3.5 w-3.5 text-foreground-subtle flex-shrink-0"}),u("div",{className:"min-w-0",children:[r("p",{className:"text-[10px] text-foreground-subtle leading-tight",children:t}),r("p",{className:"text-xs font-medium text-foreground leading-tight",children:n})]})]})}function s8({segments:e,selectedDate:t}){const n=Ur(t).getTime(),o=1440*60*1e3,s=Array.from({length:25},(a,i)=>i);return u("div",{className:"space-y-1",children:[r("div",{className:"flex justify-between px-0.5",children:s.filter(a=>a%3===0).map(a=>r("span",{className:"text-[9px] text-foreground-subtle font-mono",children:String(a).padStart(2,"0")},a))}),u("div",{className:"relative h-6 rounded bg-background border border-border overflow-hidden",children:[e.map(a=>{const i=new Date(a.startTime).getTime()-n,l=new Date(a.endTime).getTime()-n,c=Math.max(0,i/o*100),d=Math.min(100-c,(l-i)/o*100);return d<=0?null:r("div",{className:"absolute top-0 bottom-0 bg-primary/60 hover:bg-primary/80 transition-colors",style:{left:`${c}%`,width:`${Math.max(d,.3)}%`},title:`${Rs(a.startTime)} - ${Rs(a.endTime)} (${ed(a.duration)})`},a.id)}),s.slice(1,-1).map(a=>r("div",{className:"absolute top-0 bottom-0 w-px bg-border/50",style:{left:`${a/24*100}%`}},a))]})]})}function a8({segment:e,selected:t,onToggle:n,onPlay:o,onDownload:s,onDelete:a}){return u("div",{className:`flex items-center gap-3 px-4 py-2 border-b border-border last:border-b-0 hover:bg-background/50 transition-colors ${t?"bg-primary/5":""}`,children:[r("button",{onClick:n,className:"flex-shrink-0 text-foreground-subtle hover:text-foreground",children:t?r(gy,{className:"h-4 w-4 text-primary"}):r(Eo,{className:"h-4 w-4"})}),u("div",{className:"flex-1 min-w-0",children:[u("p",{className:"text-xs font-mono text-foreground",children:[Rs(e.startTime)," - ",Rs(e.endTime)]}),u("p",{className:"text-[10px] text-foreground-subtle",children:[ed(e.duration),e.sizeBytes!=null&&` · ${Nt(e.sizeBytes)}`]})]}),u("div",{className:"flex items-center gap-1 flex-shrink-0",children:[r("button",{onClick:o,title:"Play",className:"p-1 rounded hover:bg-foreground-subtle/10 text-foreground-subtle hover:text-foreground transition-colors",children:r(va,{className:"h-3.5 w-3.5"})}),r("button",{onClick:s,title:"Download",className:"p-1 rounded hover:bg-foreground-subtle/10 text-foreground-subtle hover:text-foreground transition-colors",children:r(wn,{className:"h-3.5 w-3.5"})}),r("button",{onClick:a,title:"Delete",className:"p-1 rounded hover:bg-danger/10 text-foreground-subtle hover:text-danger transition-colors",children:r(We,{className:"h-3.5 w-3.5"})})]})]})}function i8({deviceId:e}){const t=ke(),[n,o]=$(()=>Ur(new Date)),[s,a]=$(new Set),i=Hb({deviceId:e},{refetchInterval:5e3}),l=Bb({deviceId:e}),c=l.data?.streams[0]?.streamId??"stream0",d=Fb({deviceId:e,streamId:c,startTime:Ur(n).getTime(),endTime:o8(n).getTime()}),f=jb({deviceId:e,streamId:c},{refetchInterval:3e4}),p=Vb({deviceId:e,dataCategory:"recording:main"}),m=q(()=>{t.invalidateQueries({queryKey:["recordingEngine","getPolicyStatus"]}),t.invalidateQueries({queryKey:["recordingEngine","getSegments"]}),t.invalidateQueries({queryKey:["recordingEngine","getStorageUsage"]})},[t]),h=Ob({onSuccess:m}),g={isPending:h.isPending,error:h.error,mutate:()=>{const _=l.data,R=_?{mode:_.mode,streams:_.streams,enabled:!0,preBufferSec:_.preBufferSec,postBufferSec:_.postBufferSec,scheduleRules:_.scheduleRules}:{mode:"continuous",streams:[{streamId:c,mode:"always"}],enabled:!0,preBufferSec:10,postBufferSec:5};h.mutate({deviceId:e,policy:R})}},b=zb({onSuccess:m}),x=i.data??void 0,v=l.data??void 0,w=d.data??[],y=f.data,N=p.data??void 0,k=(x?.enabled??!1)&&(x?.activeStreams??0)>0,S=g.isPending||b.isPending,M=r8(n,new Date),P=Q(()=>[...w].sort((_,R)=>new Date(R.startTime).getTime()-new Date(_.startTime).getTime()),[w]),I=Q(()=>w.reduce((_,R)=>_+(R.duration??0),0),[w]),F=Q(()=>w.reduce((_,R)=>_+(R.sizeBytes??0),0),[w]);function E(){k?b.mutate({deviceId:e}):g.mutate()}function B(){o(_=>{const R=new Date(_);return R.setDate(R.getDate()-1),Ur(R)}),a(new Set)}function O(){M||(o(_=>{const R=new Date(_);return R.setDate(R.getDate()+1),Ur(R)}),a(new Set))}function A(_){a(R=>{const L=new Set(R);return L.has(_)?L.delete(_):L.add(_),L})}function D(){s.size===P.length?a(new Set):a(new Set(P.map(_=>_.id)))}return i.isLoading&&l.isLoading?u("div",{className:"space-y-4",children:[u("div",{className:"rounded-lg border border-border bg-surface overflow-hidden",children:[r(jr,{children:"Recording Status"}),u("div",{className:"px-4 py-4 space-y-3",children:[r(At,{className:"h-10 w-full"}),r(At,{className:"h-4 w-48"})]})]}),u("div",{className:"rounded-lg border border-border bg-surface overflow-hidden",children:[r(jr,{children:"Segments"}),u("div",{className:"divide-y divide-border",children:[r(Dn,{}),r(Dn,{}),r(Dn,{})]})]})]}):u("div",{className:"space-y-4",children:[u("div",{className:"rounded-lg border border-border bg-surface overflow-hidden",children:[r(jr,{children:"Recording Status"}),u("div",{className:"px-4 py-4 flex items-center justify-between gap-4",children:[u("div",{className:"flex items-center gap-3 min-w-0",children:[r("div",{className:`flex items-center justify-center rounded-full p-2 flex-shrink-0 ${k?"bg-danger/10":"bg-foreground-subtle/10"}`,children:r(ty,{className:`h-5 w-5 ${k?"text-danger animate-pulse":"text-foreground-subtle"}`})}),u("div",{className:"min-w-0",children:[r("p",{className:`text-sm font-medium ${k?"text-danger":"text-foreground-subtle"}`,children:k?"Recording":"Not Recording"}),r("p",{className:"text-[11px] text-foreground-subtle mt-0.5 truncate",children:k&&x?`${x.mode} – ${x.activeStreams} stream(s)`:"No active recording session"})]})]}),r("button",{onClick:E,disabled:S,className:`inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-medium transition-colors flex-shrink-0 disabled:opacity-50 ${k?"bg-danger/10 text-danger hover:bg-danger/20":"bg-primary text-primary-foreground hover:bg-primary/90"}`,children:k?u(ve,{children:[r(Eo,{className:"h-3.5 w-3.5"}),S?"Stopping...":"Stop Recording"]}):u(ve,{children:[r(va,{className:"h-3.5 w-3.5"}),S?"Starting...":"Start Recording"]})})]}),k&&x&&u("div",{className:"border-t border-border px-4 py-2 flex items-center gap-2 text-[11px] text-foreground-subtle",children:[r(Zr,{className:"h-3.5 w-3.5 text-primary flex-shrink-0"}),u("span",{children:[x.activeStreams," active stream",x.activeStreams!==1?"s":""," · mode: ",x.mode]})]})]}),u("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[u("div",{className:"rounded-lg border border-border bg-surface overflow-hidden",children:[r(jr,{children:u("span",{className:"flex items-center gap-1.5",children:[r(wt,{className:"h-3.5 w-3.5"}),"Settings"]})}),l.isLoading?u("div",{className:"px-4 py-3 space-y-2",children:[r(At,{className:"h-3 w-32"}),r(At,{className:"h-3 w-40"}),r(At,{className:"h-3 w-28"})]}):u("div",{className:"divide-y divide-border",children:[r(Hr,{label:"Stream",value:c}),r(Hr,{label:"Pre-buffer",value:v?`${v.preBufferSec}s`:"N/A"}),r(Hr,{label:"Mode",value:v?.mode??"continuous"}),r(Hr,{label:"Retention",value:N?.retentionDays!=null?`${N.retentionDays} days`:"N/A"}),N?.retentionGb!=null&&r(Hr,{label:"Max Storage",value:`${N.retentionGb} GB`})]})]}),u("div",{className:"rounded-lg border border-border bg-surface overflow-hidden",children:[r(jr,{children:u("span",{className:"flex items-center gap-1.5",children:[r(lo,{className:"h-3.5 w-3.5"}),"Storage"]})}),f.isLoading?u("div",{className:"px-4 py-3 space-y-2",children:[r(At,{className:"h-3 w-28"}),r(At,{className:"h-3 w-36"}),r(At,{className:"h-3 w-24"})]}):f.error?u("div",{className:"px-4 py-4 flex items-center gap-2 text-xs text-danger",children:[r(xt,{className:"h-4 w-4"}),"Failed to load storage info"]}):u("div",{className:"px-4 py-3 grid grid-cols-2 gap-3",children:[r(gp,{icon:lo,label:"Total",value:y?.totalBytes!=null?Nt(y.totalBytes):"N/A"}),r(gp,{icon:Zr,label:"Segments",value:y?.segmentCount!=null?String(y.segmentCount):"N/A"})]})]})]}),u("div",{className:"rounded-lg border border-border bg-surface overflow-hidden",children:[u("div",{className:"border-b border-border px-4 py-2.5 flex items-center justify-between",children:[r("h2",{className:"text-xs font-semibold text-foreground uppercase tracking-wider",children:"Segment Browser"}),u("div",{className:"flex items-center gap-2",children:[r("button",{onClick:B,className:"p-1 rounded hover:bg-foreground-subtle/10 text-foreground-subtle hover:text-foreground transition-colors",children:r(Kc,{className:"h-4 w-4"})}),u("div",{className:"flex items-center gap-1.5 text-xs text-foreground font-medium",children:[r(Xx,{className:"h-3.5 w-3.5 text-foreground-subtle"}),M?"Today":Os(n)]}),r("button",{onClick:O,disabled:M,className:"p-1 rounded hover:bg-foreground-subtle/10 text-foreground-subtle hover:text-foreground transition-colors disabled:opacity-30 disabled:cursor-not-allowed",children:r(Mt,{className:"h-4 w-4"})})]})]}),u("div",{className:"px-4 py-3 border-b border-border",children:[r(s8,{segments:w,selectedDate:n}),u("div",{className:"flex items-center gap-4 mt-2 text-[10px] text-foreground-subtle",children:[u("span",{children:[w.length," segment",w.length!==1?"s":""]}),I>0&&u("span",{children:[ed(I)," recorded"]}),F>0&&r("span",{children:Nt(F)})]})]}),P.length>0&&u("div",{className:"border-b border-border px-4 py-2 flex items-center justify-between",children:[r("button",{onClick:D,className:"text-[11px] text-foreground-subtle hover:text-foreground transition-colors",children:s.size===P.length?"Deselect All":"Select All"}),s.size>0&&u("div",{className:"flex items-center gap-2",children:[u("span",{className:"text-[10px] text-foreground-subtle",children:[s.size," selected"]}),u("button",{className:"inline-flex items-center gap-1 rounded px-2 py-0.5 text-[10px] font-medium bg-foreground-subtle/10 text-foreground-subtle hover:text-foreground transition-colors",title:"Download selected",children:[r(wn,{className:"h-3 w-3"}),"Download"]}),u("button",{className:"inline-flex items-center gap-1 rounded px-2 py-0.5 text-[10px] font-medium bg-danger/10 text-danger hover:bg-danger/20 transition-colors",title:"Delete selected",children:[r(We,{className:"h-3 w-3"}),"Delete"]})]})]}),d.isLoading?u("div",{className:"divide-y divide-border",children:[r(Dn,{}),r(Dn,{}),r(Dn,{}),r(Dn,{})]}):P.length===0?u("div",{className:"flex flex-col items-center justify-center py-12 text-foreground-subtle",children:[r(Zr,{className:"h-8 w-8 mb-3 opacity-30"}),r("p",{className:"text-sm",children:"No recorded segments"}),r("p",{className:"text-xs mt-1 opacity-70",children:M?"Recorded clips will appear here as they are created":`No recordings found for ${Os(n)}`})]}):r("div",{className:"max-h-[400px] overflow-y-auto",children:P.map(_=>r(a8,{segment:_,selected:s.has(_.id),onToggle:()=>A(_.id),onPlay:()=>{},onDownload:()=>{},onDelete:()=>{}},_.id))})]}),i.error&&u("div",{className:"rounded-lg border border-danger/30 bg-danger/5 px-4 py-3 flex items-center gap-2 text-xs text-danger",children:[r(xt,{className:"h-4 w-4 flex-shrink-0"}),"Failed to load recording status. Will retry automatically."]}),(g.error||b.error)&&u("div",{className:"rounded-lg border border-danger/30 bg-danger/5 px-4 py-3 flex items-center gap-2 text-xs text-danger",children:[r(xt,{className:"h-4 w-4 flex-shrink-0"}),g.error?`Failed to start recording: ${g.error instanceof Error?g.error.message:"Unknown error"}`:`Failed to stop recording: ${b.error instanceof Error?b.error.message:"Unknown error"}`]})]})}function Hr({label:e,value:t}){return u("div",{className:"flex items-center justify-between px-4 py-2.5",children:[r("span",{className:"text-xs text-foreground-subtle",children:e}),r("span",{className:"text-xs font-medium text-foreground",children:t})]})}function l8({deviceId:e}){const t=ke(),n=Number.isFinite(e),{data:o}=Fn({deviceId:e},{enabled:n}),s=typeof o?.type=="string"?o.type:"camera";yt(["deviceManager","getBindings"],["capability.binding-changed"]);const{data:a,isLoading:i,isError:l,error:c}=Cg({deviceId:e},{staleTime:3e4,enabled:n}),{data:d}=Ig({deviceType:s},{staleTime:3e4,enabled:!!s}),f=Mg({onSuccess:()=>{t.invalidateQueries({queryKey:[["deviceManager","getBindings"]]})}});if(i)return r("div",{className:"p-4",children:r("div",{className:"h-20 rounded-lg border border-border bg-surface animate-pulse"})});if(l)return u("div",{className:"p-4 text-xs text-red-400",children:["Failed to load bindings: ",c instanceof Error?c.message:String(c)]});const p=new Map,m={};for(const b of d??[])m[b.capName]=b.wrappers;for(const b of a?.entries??[])p.set(b.capName,{...b,wrappers:m[b.capName]??[]});for(const b of d??[])p.has(b.capName)||p.set(b.capName,{capName:b.capName,kind:"unbound",providerAddonId:"",providerNodeId:"",nativeAddonId:"",wrappers:b.wrappers});const h=[...p.values()].sort((b,x)=>b.capName.localeCompare(x.capName));if(h.length===0)return u("div",{className:"flex flex-col items-center justify-center gap-2 p-8 text-foreground-subtle",children:[r(ba,{className:"h-8 w-8 opacity-40"}),r("p",{className:"text-xs",children:"No capability providers applicable to this device yet."}),r("p",{className:"text-[10px] opacity-60",children:"Native providers show up here as soon as the owning addon registers them."})]});const g=h.filter(b=>b.kind!=="unbound").length;return u("div",{className:"flex flex-col gap-3 p-1",children:[u("div",{className:"text-[11px] text-foreground-subtle",children:[r("span",{className:"font-medium text-foreground",children:g})," ","of ",h.length," capabilit",h.length===1?"y":"ies"," bound — rows marked ",r("em",{children:"unbound"})," have a wrapper available you can activate."]}),r("div",{className:"overflow-hidden rounded-lg border border-border bg-surface",children:u("table",{className:"w-full border-collapse text-[11px]",children:[r("thead",{children:u("tr",{className:"bg-surface-hover/50 text-left text-[10px] uppercase tracking-wide text-foreground-subtle",children:[r("th",{className:"px-3 py-2 font-medium",children:"Capability"}),r("th",{className:"px-3 py-2 font-medium",children:"Kind"}),r("th",{className:"px-3 py-2 font-medium",children:"Active Provider"}),r("th",{className:"px-3 py-2 font-medium",children:"Node"}),r("th",{className:"px-3 py-2 font-medium",children:"Native"}),r("th",{className:"px-3 py-2 font-medium",children:"Wrapper"})]})}),r("tbody",{children:h.map(b=>{const x=b.kind==="wrapped"?b.providerAddonId:null;return u("tr",{className:"border-t border-border align-middle",children:[r("td",{className:"px-3 py-2 font-mono text-foreground",children:b.capName}),r("td",{className:"px-3 py-2",children:r(c8,{kind:b.kind})}),r("td",{className:"px-3 py-2 font-mono text-foreground-subtle",children:b.providerAddonId||r("span",{className:"opacity-40",children:"—"})}),r("td",{className:"px-3 py-2",children:b.providerNodeId?r(d8,{nodeId:b.providerNodeId}):r("span",{className:"text-[10px] opacity-40",children:"—"})}),r("td",{className:"px-3 py-2 font-mono text-foreground-subtle",children:b.nativeAddonId||r("span",{className:"opacity-40",children:"—"})}),r("td",{className:"px-3 py-2",children:r(u8,{wrappers:b.wrappers,activeWrapperId:x,disabled:f.isPending,onPick:v=>{const w=x===v;f.mutate({deviceId:e,capName:b.capName,wrapperAddonId:v,active:!w})}})})]},b.capName)})})]})})]})}function c8({kind:e}){return e==="native"?u("span",{className:"inline-flex items-center gap-1 rounded-md border border-success/30 text-success bg-success/5 px-1.5 py-0.5 text-[10px] font-medium",children:[r(ln,{className:"h-3 w-3"}),"native"]}):e==="wrapped"?u("span",{className:"inline-flex items-center gap-1 rounded-md border border-primary/30 text-primary bg-primary/5 px-1.5 py-0.5 text-[10px] font-medium",children:[r(eL,{className:"h-3 w-3"}),"wrapped"]}):u("span",{className:"inline-flex items-center gap-1 rounded-md border border-border text-foreground-subtle/70 px-1.5 py-0.5 text-[10px] font-medium",children:[r(gL,{className:"h-3 w-3"}),"unbound"]})}function d8({nodeId:e}){return r("span",{className:`inline-flex items-center rounded-md border border-border px-1.5 py-0.5 font-mono text-[10px] ${e==="hub"?"text-foreground-subtle":"text-foreground"}`,children:e})}function u8({wrappers:e,activeWrapperId:t,disabled:n,onPick:o}){return e.length===0?r("span",{className:"text-[10px] opacity-40",children:"none available"}):r("div",{className:"flex flex-wrap gap-1",children:e.map(s=>{const a=s===t;return u("button",{disabled:n,onClick:()=>o(s),title:a?"Click to deactivate (revert to native)":`Activate wrapper ${s}`,className:`inline-flex items-center gap-1 rounded-md border px-1.5 py-0.5 font-mono text-[10px] transition-colors disabled:opacity-50 ${a?"border-primary/40 bg-primary/10 text-primary":"border-border text-foreground-subtle hover:text-foreground hover:bg-surface-hover"}`,children:[a?r(Ct,{className:"h-3 w-3"}):r(my,{className:"h-3 w-3"}),s]},s)})})}function p8(e,t){if(!e)return null;for(const n of e.slots)for(const o of n.addons)if(o.id===t)return o;return null}function f8(e,t,n){const o=e?.stepOverridesByAgent?.[t]?.[n];if(o)return o.enabled===!1?"off":(o.enabled===!0,"on");const s=e?.stepToggles?.[n];return s===!1?"off":s===!0?"on":"inherit"}function m8({agents:e,currentAgent:t,onPick:n}){const[o,s]=$(!1);return u("div",{className:"relative",children:[r("button",{type:"button",className:"px-3 py-1 text-xs border border-border rounded bg-surface hover:bg-muted",onClick:()=>s(a=>!a),children:"Mirror from ▾"}),o&&r("div",{className:"absolute top-full left-0 mt-1 min-w-[140px] bg-surface border border-border rounded shadow-lg z-10",children:e.filter(a=>a!==t).map(a=>r("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-muted",onClick:()=>{s(!1),n(a)},children:a},a))})]})}function h8({deviceId:e,refreshToken:t}){const n=ke(),[o,s]=$(null),[a,i]=$(null),[l,c]=$(null),[d,f]=$(null),p=vc({deviceId:e}),m=$r(),h=ca({deviceId:e}),g=mb(),b=Q(()=>{const D=h.data?.agentNodeId;if(D)return D;const _=g.data?.find(R=>R.online)?.nodeId;return _||"hub"},[h.data?.agentNodeId,g.data]),x=a??b,v=So({nodeId:x??""},{enabled:!!x}),w=Mb({onSuccess:()=>{n.invalidateQueries({queryKey:[["pipelineOrchestrator","getCameraSettings"]]}),c(null)}}),y=Q(()=>v.data?ta(v.data):[],[v.data]),N=Q(()=>{const D=p.data??null,_={};for(const R of m.data??[])for(const L of Object.keys(R.settings.addonDefaults)){const z=_[L]??[];z.push({agentNodeId:R.nodeId,state:f8(D,R.nodeId,L)}),_[L]=z}return _},[p.data,m.data]),k=o?p8(v.data??null,o):null,S=x?m.data?.find(D=>D.nodeId===x)??null:null,M=o&&S?S.settings.addonDefaults[o]??null:null,P=o&&x?p.data?.stepOverridesByAgent?.[x]?.[o]??null:null,I=v.data?.selectedEngine.format??"coreml",F=D=>{i(D),c(null),f(null)},E=D=>{s(D),c(null),f(null)},B=D=>{if(!x||!o||!v.data||!m.data)return;const _=m.data.find(z=>z.nodeId===D),R=m.data.find(z=>z.nodeId===x);if(!_||!R)return;const[L]=bm({source:{nodeId:_.nodeId,engine:{format:I},defaults:_.settings.addonDefaults},target:{nodeId:R.nodeId,engine:{format:I},defaults:R.settings.addonDefaults},catalog:v.data,addonIds:[o]});if(!L){f("no mirror result");return}if(L.outcome==="skip"){f(`skipped: ${L.reason??"no candidate"}`);return}c(L.patch),f(`${L.outcome} from ${D}`)},O=()=>{!x||!o||w.mutate({deviceId:e,agentNodeId:x,addonId:o,patch:l})},A=()=>{!x||!o||w.mutate({deviceId:e,agentNodeId:x,addonId:o,patch:null})};return m.isLoading||v.isLoading?r("div",{className:"text-xs text-foreground-subtle animate-pulse p-4",children:"Loading pipeline…"}):v.data?r("div",{className:"@container h-full",style:{containerType:"inline-size"},children:u("div",{className:"flex flex-col @[720px]:flex-row h-full",children:[r("aside",{className:"w-full @[720px]:w-[300px] @[720px]:flex-shrink-0 border-b @[720px]:border-b-0 @[720px]:border-r border-border overflow-y-auto max-h-[40vh] @[720px]:max-h-none",children:r(fh,{tree:y,selectedAddonId:o,onSelect:E,agentDots:N})}),r("section",{className:"flex-1 min-w-0 p-4 overflow-y-auto",children:!o||!k?r("div",{className:"text-sm text-foreground-subtle",children:"Select a step on the left to configure it for this camera."}):u("div",{className:"space-y-4",children:[u("div",{children:[r("div",{className:"text-[10px] uppercase tracking-widest text-foreground-subtle",children:"Selected step"}),r("div",{className:"text-base font-semibold",children:k.name})]}),u("div",{className:"flex items-end gap-3 flex-wrap",children:[u("div",{children:[r("div",{className:"text-[10px] uppercase tracking-widest text-foreground-subtle mb-1",children:"Agent"}),r("div",{className:"flex rounded border border-border overflow-hidden",children:(m.data??[]).map(D=>r("button",{type:"button",onClick:()=>F(D.nodeId),className:`px-3 py-1 text-xs ${x===D.nodeId?"bg-primary text-primary-foreground":"bg-surface hover:bg-muted"}`,children:D.nodeId},D.nodeId))})]}),r(m8,{agents:(m.data??[]).map(D=>D.nodeId),currentAgent:x,onPick:B}),d&&r("div",{className:"text-[10px] text-foreground-subtle",children:d})]}),M&&r(ra,{mode:"device",addon:k,agentDefault:M,agentNodeId:x??"",currentPatch:l??P,engineFormat:I,onChangePatch:c}),u("div",{className:"flex items-center justify-between gap-2 pt-4 border-t border-border",children:[r("button",{type:"button",className:"px-3 py-1 text-xs border border-border rounded bg-surface hover:bg-muted text-foreground-subtle",disabled:!P||w.isPending,onClick:A,children:"Clear override"}),u("div",{className:"flex items-center gap-2",children:[r("button",{type:"button",className:"px-3 py-1 text-xs border border-border rounded bg-surface hover:bg-muted",onClick:()=>c(null),children:"Reset draft"}),r("button",{type:"button",className:"px-3 py-1 text-xs bg-primary text-primary-foreground rounded disabled:opacity-50",disabled:!x||!o||w.isPending,onClick:O,children:w.isPending?"Saving…":"Save"})]})]})]})})]})}):r("div",{className:"text-xs text-foreground-subtle p-4",children:"Catalog unavailable."})}const g8=[{id:"overview",label:"Overview",cameraOnly:!1},{id:"config",label:"Config",cameraOnly:!1},{id:"pipeline",label:"Pipeline",cameraOnly:!0},{id:"bindings",label:"Bindings",cameraOnly:!0},{id:"recording",label:"Recording",cameraOnly:!0}];function b8(e){const t=e===at.Camera;return g8.filter(n=>t||!n.cameraOnly).map(({id:n,label:o})=>({id:n,label:o}))}const x8=[{id:"logs",icon:Xe,label:"Logs"},{id:"repl",icon:by,label:"REPL"},{id:"events",icon:Ao,label:"Events"},{id:"state",icon:ny,label:"State"},{id:"ptz",icon:wL,label:"PTZ",featureGate:Rn.PanTiltZoom}];function y8(){const e=zc(),t=Number(e.deviceId),n=Number.isFinite(t),o=et(),s=ke(),a=rt(),i=Le(),[l,c]=$("overview"),[d,f]=$("logs"),p="device-detail.left-col-width-px",[m,h]=$(()=>{if(typeof window>"u")return null;const de=window.localStorage.getItem(p),le=de?Number(de):NaN;return Number.isFinite(le)&&le>0?le:null}),g=ne(m);g.current=m;function b(de){de.preventDefault();const le=de.clientX,Se=de.currentTarget.previousElementSibling?.getBoundingClientRect().width??m??0,pe=280,Ie=Math.max(pe+50,Math.floor(window.innerWidth*.7)),Te=ot=>{const rr=Math.max(pe,Math.min(Ie,Se+(ot.clientX-le)));h(rr)},Ye=()=>{document.removeEventListener("mousemove",Te),document.removeEventListener("mouseup",Ye);const ot=g.current;if(ot!==null)try{window.localStorage.setItem(p,String(Math.round(ot)))}catch{}document.body.style.userSelect="",document.body.style.cursor=""};document.body.style.userSelect="none",document.body.style.cursor="col-resize",document.addEventListener("mousemove",Te),document.addEventListener("mouseup",Ye)}const{data:x,isLoading:v,isError:w}=Fn({deviceId:t},{enabled:n,refetchInterval:5e3,retry:1}),{data:y}=mc({deviceId:t},{enabled:n,staleTime:3e4}),N=Q(()=>{const de=y?.settings?.sections??[],le=y?.live?.sections??[],Se=[...de,...le],pe=new Set;for(const Ie of Se)Ie.location==="top-tab"&&Ie.tab&&pe.add(Ie.tab);return[...pe].map(Ie=>{const Te=_i[Ie];return{id:Ie,label:Te?.label??Ie,isAddonContrib:!0}})},[y]),k=x,S=String(k?.name??e.deviceId??"Device"),M=k?.online===!0,P=M?"online":"offline",I=String(k?.addonId??"rtsp"),F=k?.features??[],E=k?.type,B=E===at.Camera,O=typeof k?.parentDeviceId=="number"?k.parentDeviceId:null,{data:A}=Fn({deviceId:O??0},{enabled:O!==null,staleTime:3e4}),D=Xn(),_=Q(()=>[...b8(E),...N],[E,N]),{data:R}=Fy(n?t:0),L=(R??[]).length>0,z=Q(()=>x8.filter(({featureGate:de})=>!de||F.includes(de)),[F]),{data:j}=Dg({addonId:I},{enabled:!!I&&I!=="rtsp"}),H=Sg({onSuccess:()=>{s.invalidateQueries({queryKey:[["deviceManager"]]}),o(j?.id?`/integrations/${j.id}`:"/integrations")}}),T=Ng({onSuccess:()=>{s.invalidateQueries({queryKey:[["deviceManager"]]})}}),W=kg({onSuccess:()=>{s.invalidateQueries({queryKey:[["deviceManager"]]})}}),G=Rb(),ee=sa({onSuccess:()=>{s.invalidateQueries({queryKey:[["deviceManager"]]})}}),se=F.includes(Rn.Rebootable),te=F.includes(Rn.BatteryOperated),X=tc(i.trpcClient,te&&n?t:null),[re,ge]=$(!1),Z=kt(i.trpcClient,n?t:null),U=async()=>{if(!(re||!Z)){ge(!0);try{await Z.snapshot?.invalidateCache({});const de=await Z.snapshot?.getSnapshot({});if(!de)return;const le=`data:${de.contentType};base64,${de.base64}`,Se=de.contentType.includes("png")?"png":"jpg",pe=S.replace(/[^a-zA-Z0-9_.-]+/g,"_"),Ie=new Date().toISOString().replace(/[:.]/g,"-"),Te=document.createElement("a");Te.href=le,Te.download=`${pe}-${Ie}.${Se}`,document.body.appendChild(Te),Te.click(),document.body.removeChild(Te)}finally{ge(!1)}}},J=T.isPending||W.isPending,{data:ae}=ca({deviceId:t},{enabled:n,refetchInterval:1e4}),fe=ae?.agentNodeId??null,V=typeof fe=="string"&&fe.length>0&&!fe.startsWith("addon:")?fe:void 0,{data:ie}=wc({deviceId:t,...V?{nodeId:V}:{}},{enabled:n,refetchInterval:3e3,retry:!1});function ue(){if(!n)return null;switch(l){case"overview":return r(zO,{device:k??{}});case"config":return r(UO,{deviceId:t});case"pipeline":return r(h8,{deviceId:t,refreshToken:0});case"bindings":return r(l8,{deviceId:t});case"recording":return r(i8,{deviceId:t});default:{const de=l;return N.some(Se=>Se.id===de)?r(Xy,{deviceId:t,sectionFilter:Se=>Se.location==="top-tab"&&Se.tab===de}):null}}}return n?v?u("div",{className:"flex flex-col h-full",children:[u("div",{className:"border-b border-border bg-surface px-6 py-4",children:[r("div",{className:"h-4 w-48 rounded bg-surface-hover animate-pulse mb-3"}),r("div",{className:"h-8 w-64 rounded bg-surface-hover animate-pulse"})]}),r("div",{className:"flex-1 p-6",children:r("div",{className:"h-40 rounded-lg border border-border bg-surface animate-pulse"})})]}):w||!x?u("div",{className:"flex flex-col items-center justify-center h-full gap-3 text-foreground-subtle",children:[r("p",{className:"text-lg font-semibold text-foreground",children:"Device not found"}),u("p",{className:"text-xs",children:["No device with ID ",u("code",{className:"font-mono bg-surface px-1.5 py-0.5 rounded text-[11px]",children:["#",t]})]}),r("button",{onClick:()=>o("/integrations"),className:"mt-2 rounded-lg bg-primary px-4 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90 transition-colors",children:"Back to Integrations"})]}):u("div",{className:"absolute inset-0 flex flex-col overflow-hidden",children:[u("div",{className:"border-b border-border bg-surface px-6 py-3 flex-shrink-0",children:[r("div",{className:"mb-2",children:r(Wl,{items:[{label:"Integrations",onClick:()=>o("/integrations")},{label:j?.name??I,onClick:()=>j?.id&&o(`/integrations/${j.id}`)},{label:S}]})}),u("div",{className:"flex items-center gap-2 sm:gap-3",children:[r(cn,{type:I,size:"lg"}),u("div",{className:"min-w-0 flex-1",children:[u("div",{className:"flex items-center gap-2 flex-wrap",children:[r("h1",{className:"text-sm sm:text-base font-semibold text-foreground truncate",children:S}),r(ka,{status:P}),te&&r(rc,{status:X,variant:"full"})]}),O!==null&&A&&u("button",{type:"button",onClick:()=>o(`/devices/${O}`),className:"text-[10px] text-foreground-subtle hover:text-primary transition-colors mt-0.5 inline-flex items-center gap-1",title:`Open parent device ${A.name}`,children:[r("span",{children:"↑"}),r("span",{className:"truncate",children:String(A.name??`Device #${O}`)})]}),r("div",{className:"hidden md:flex items-center gap-3 mt-0.5 text-[10px] text-foreground-subtle",children:F.length>0&&r(wa,{capabilities:F})})]}),ie&&r("div",{className:"hidden lg:flex",children:r(v8,{metrics:ie})}),u("div",{className:"flex items-center gap-1 shrink-0",children:[u("button",{onClick:async()=>{await a({title:`Disable "${S}"?`,message:"The device will stop processing streams and events. You can re-enable it later.",confirmLabel:"Disable",variant:"danger"})&&W.mutate({deviceId:t})},disabled:J,title:"Disable device",className:"inline-flex items-center gap-1.5 rounded-lg px-2 sm:px-2.5 py-1.5 text-[11px] font-medium border transition-colors disabled:opacity-50 border-success/30 text-success hover:bg-success/10",children:[r(fy,{className:"h-3.5 w-3.5"}),r("span",{className:"hidden sm:inline",children:J?"Updating…":"Enabled"})]}),r("div",{className:"hidden sm:block h-5 w-px bg-border mx-1"}),r(Ix,{triggerClassName:"ml-1",items:[{id:"snapshot",label:"Take snapshot",description:"Fetch a fresh frame and download it.",icon:gr,disabled:re,onClick:()=>{U()}},{id:"reboot",label:"Reboot device",description:"Camera goes offline for ~30 seconds.",icon:bt,hidden:!se,disabled:G.isPending,danger:!0,onClick:async()=>{await a({title:`Reboot "${S}"?`,message:"The camera will go offline for around 30 seconds while the firmware reboots.",confirmLabel:"Reboot",variant:"danger"})&&G.mutate({deviceId:t})}},{id:"restart-addon",label:"Restart addon",description:`Bounces every device served by ${j?.name??I}.`,icon:pt,disabled:ee.isPending,danger:!0,onClick:async()=>{await a({title:`Restart "${j?.name??I}"?`,message:`Restarting the addon will briefly disconnect every device served by it (not just "${S}"). Streams will reconnect automatically.`,confirmLabel:"Restart",variant:"danger"})&&ee.mutate({addonId:I})}},{id:"delete",label:"Delete device",description:"Remove the device and all its settings.",icon:We,separatorBefore:!0,disabled:H.isPending,danger:!0,onClick:async()=>{await a({title:`Delete "${S}"?`,message:"This will remove the device and all its settings. This action cannot be undone.",confirmLabel:"Delete",variant:"danger"})&&H.mutate({deviceId:t})}}]})]})]})]}),r(jh,{deviceId:t,device:k??void 0,children:r(vx,{children:r(Px,{children:u("main",{className:D?"flex-1 overflow-y-auto flex flex-col":"flex-1 min-h-0 overflow-hidden flex flex-row",children:[u("div",{className:D?"flex flex-col bg-surface":`${m===null?"w-1/2 lg:w-1/3":""} flex-shrink-0 flex flex-col bg-surface min-h-0 overflow-hidden`,style:!D&&m!==null?{width:`${String(m)}px`}:void 0,children:[r("div",{className:`flex-shrink-0 border-b border-border-subtle ${B?"aspect-video bg-black":"bg-surface"}`,children:B?r($O,{deviceId:t,intercomAvailable:F.includes(Rn.TwoWayAudio)}):r(n8,{deviceId:t,deviceName:S,deviceType:E??"unknown",provider:I,isOnline:M,features:F})}),u("div",{className:D?"flex flex-col border-b border-border":"flex-1 min-h-0 flex flex-col overflow-hidden",children:[r("div",{className:"flex-shrink-0 border-b border-border-subtle px-2 py-1.5",children:r("div",{className:"flex gap-1 overflow-x-auto -mx-1 px-1 pb-0.5",children:z.map(({id:de,label:le,icon:Se})=>u("button",{onClick:()=>f(de),title:le,className:`flex items-center gap-1 rounded px-2 py-1 text-[10px] font-medium transition-colors flex-shrink-0 ${d===de?"bg-primary/15 text-primary":"text-foreground-subtle hover:text-foreground hover:bg-surface-hover"}`,children:[r(Se,{className:"h-3 w-3"}),le]},de))})}),u("div",{className:D?"h-72 overflow-hidden":"flex-1 min-h-0 overflow-hidden",children:[d==="logs"&&r(_O,{deviceId:t}),d==="repl"&&r(DO,{deviceId:t}),d==="events"&&r(TO,{deviceId:t}),d==="state"&&r(RO,{deviceId:t}),d==="ptz"&&r(LO,{deviceId:t})]})]})]}),!D&&r("div",{role:"separator","aria-orientation":"vertical",title:"Drag to resize",onMouseDown:b,className:"flex-shrink-0 w-1 cursor-col-resize bg-border hover:bg-primary/40 transition-colors group relative z-10",children:r("span",{className:"absolute inset-y-0 -left-1 -right-1"})}),u("div",{className:D?"flex flex-col":"flex-1 min-w-0 min-h-0 flex flex-col overflow-hidden",children:[r("div",{className:"flex-shrink-0 border-b border-border bg-surface px-4",children:r("div",{className:"flex flex-wrap items-center gap-0",children:_.map(de=>{const le=l===de.id;return u("button",{onClick:()=>c(de.id),className:`relative flex-shrink-0 px-3 py-2 text-xs font-medium transition-colors ${le?"text-primary":"text-foreground-subtle hover:text-foreground"}`,children:[de.label,le&&r("span",{className:"absolute bottom-0 left-0 right-0 h-0.5 rounded-full bg-primary"})]},de.id)})})}),u("div",{className:D?"p-3 flex flex-col gap-3":"flex-1 min-h-0 overflow-y-auto p-4 flex flex-col gap-3",children:[l==="overview"&&L&&r(OO,{parentDeviceId:t}),ue()]})]})]})})})})]}):u("div",{className:"flex flex-col items-center justify-center h-full gap-3 text-foreground-subtle",children:[r("p",{className:"text-lg font-semibold text-foreground",children:"Invalid device id"}),u("p",{className:"text-xs",children:["The URL segment ",r("code",{className:"font-mono bg-surface px-1.5 py-0.5 rounded text-[11px]",children:e.deviceId})," is not a number."]}),r("button",{onClick:()=>o("/integrations"),className:"mt-2 rounded-lg bg-primary px-4 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90 transition-colors",children:"Back to Integrations"})]})}function v8({metrics:e}){const t=e.phase??"idle",n=Wn(t);return u("div",{className:"flex items-center gap-3 flex-shrink-0",children:[u("div",{className:"flex items-center gap-1.5",children:[r("span",{className:`h-1.5 w-1.5 rounded-full ${n.dotClass}`}),r("span",{className:`text-[10px] font-medium ${n.textColor}`,children:n.label})]}),r("div",{className:"h-3 w-px bg-border"}),u("div",{className:"flex items-center gap-1 text-[10px] text-foreground-subtle",children:[r(Io,{className:"h-3 w-3"}),r("span",{className:"text-foreground tabular-nums",children:(e.actualFps??0).toFixed(1)}),r("span",{children:"fps"})]}),u("div",{className:"flex items-center gap-1 text-[10px] text-foreground-subtle",children:[r(ut,{className:"h-3 w-3"}),r("span",{className:"text-foreground tabular-nums",children:(e.avgInferenceTimeMs??0).toFixed(0)}),r("span",{children:"ms"})]}),(e.queueDepth??0)>0&&u("span",{className:"text-[10px] text-warning tabular-nums",children:["q:",e.queueDepth]})]})}function w8({packageName:e,currentVersion:t,onInstall:n,onClose:o}){const{data:s,isLoading:a}=Kh({name:e},{staleTime:3e5});return u("div",{className:"fixed z-50 w-72 rounded-lg border border-border bg-surface shadow-xl overflow-hidden",style:{top:"auto",bottom:"auto"},ref:i=>{if(!i)return;const l=i.parentElement?.getBoundingClientRect();if(!l)return;const c=window.innerHeight-l.bottom,d=l.top;c<280&&d>c?(i.style.bottom=`${window.innerHeight-l.top+4}px`,i.style.top="auto"):(i.style.top=`${l.bottom+4}px`,i.style.bottom="auto"),i.style.right=`${window.innerWidth-l.right}px`},onClick:i=>i.stopPropagation(),children:[u("div",{className:"flex items-center justify-between px-3 py-2 border-b border-border",children:[r("span",{className:"text-[10px] uppercase tracking-wide text-foreground-subtle font-medium",children:"Versions"}),r("button",{type:"button",onClick:o,className:"text-foreground-subtle hover:text-foreground",children:r(qe,{className:"h-3 w-3"})})]}),a&&u("div",{className:"flex items-center justify-center gap-2 py-6 text-[10px] text-foreground-subtle",children:[r(Pe,{className:"h-3.5 w-3.5 animate-spin"}),"Loading versions..."]}),s&&r("div",{className:"max-h-64 overflow-auto divide-y divide-border",children:s.map(i=>{const l=i.version===t,c=/-(alpha|beta|rc|dev|canary|next)/i.test(i.version);return u("div",{className:`flex items-center gap-2 px-3 py-2 text-[11px] ${l?"bg-primary/5":"hover:bg-surface-hover"} transition-colors`,children:[r("span",{className:`font-mono flex-1 ${l?"text-primary font-semibold":c?"text-amber-400":"text-foreground"}`,children:i.version}),i.distTags.map(d=>r("span",{className:`text-[9px] rounded-full px-1.5 py-0.5 font-medium ${d==="latest"?"bg-emerald-500/15 text-emerald-400":d==="beta"?"bg-amber-500/15 text-amber-400":"bg-gray-500/15 text-gray-400"}`,children:d},d)),i.deprecated&&r("span",{className:"text-[9px] text-red-400 line-through",children:"deprecated"}),r("span",{className:"text-[9px] text-foreground-subtle shrink-0",children:new Date(i.publishedAt).toLocaleDateString()}),l?r(Ct,{className:"h-3 w-3 text-primary shrink-0"}):r("button",{type:"button",onClick:()=>n(i.version),className:"shrink-0 rounded p-0.5 hover:bg-primary/20 text-foreground-subtle hover:text-primary transition-colors",title:`Install ${i.version}`,children:r(wn,{className:"h-3 w-3"})})]},i.version)})}),s&&s.length===0&&r("div",{className:"py-4 text-center text-[10px] text-foreground-subtle",children:"No versions found"})]})}function N8({isBundle:e,installSource:t}){return u("div",{className:"relative flex-shrink-0",children:[r("div",{className:`h-9 w-9 rounded-lg flex items-center justify-center ${e?"bg-indigo-500/20 text-indigo-700 dark:text-indigo-300":"bg-purple-500/20 text-purple-700 dark:text-purple-300"}`,children:e?r(uy,{className:"h-4 w-4"}):r($s,{className:"h-4 w-4"})}),t==="local"&&r("span",{className:"absolute -top-1.5 -left-1.5 text-[7px] font-bold leading-none bg-orange-500 text-white px-1 py-0.5 rounded -rotate-12 shadow-sm",children:"DEV"}),t==="npm"&&r("span",{className:"absolute -top-1 -left-1 w-4 h-4 rounded bg-[#cb3837] flex items-center justify-center -rotate-12 shadow-sm",children:r("svg",{viewBox:"0 0 780 250",className:"w-[11px] h-[11px]",children:r("path",{fill:"#fff",d:"M240 250h100V50h100v200h340V0H0v250z"})})}),t==="upload"&&r("span",{className:"absolute -top-1.5 -left-1.5 flex items-center justify-center h-4 w-4 rounded bg-cyan-500 -rotate-12 shadow-sm",children:r(Xc,{className:"h-2.5 w-2.5 text-white"})})]})}function k8({addonId:e}){const t=ke(),{data:n="inherit"}=Yh({addonId:e},{staleTime:3e4}),o=Zh({onSuccess:()=>{t.invalidateQueries({queryKey:[["addons","getAddonAutoUpdate"]]})}});return r("div",{className:"flex rounded-lg border border-border overflow-hidden text-[10px] font-medium",children:["inherit","off","latest","beta"].map(s=>r("button",{type:"button",onClick:a=>{a.stopPropagation(),o.mutate({addonId:e,channel:s})},disabled:o.isPending,className:`px-2.5 py-1 transition-colors capitalize ${n===s?s==="inherit"?"bg-gray-700/50 text-gray-700 dark:text-gray-300":s==="off"?"bg-gray-700 text-gray-700 dark:text-gray-300":s==="latest"?"bg-blue-500/20 text-blue-400":"bg-amber-500/20 text-amber-400":"bg-transparent text-foreground-subtle hover:bg-surface-hover"} ${s!=="inherit"?"border-l border-border":""}`,children:s},s))})}function pl({addon:e,agents:t=[],clusterStatus:n,hideVersion:o,availableUpdate:s,onUpdate:a,isUpdating:i,bundle:l}){const[c,d]=$(!1),[f,p]=$(!1),[m,h]=$(!1),[g,b]=$(!1),[x,v]=$(!1),[w,y]=$("logs"),N=ke(),k=rt(),{manifest:S}=e,M=e.installedOn??[],P=!l&&!S.protected&&S.removable!==!1,I=!!l,F=l?.displayName??S.name,E=l?.packageName??S.packageName,B=l?.version??S.packageVersion??S.version,O=l?.installSource??e.installSource,A=l?l.bundle?.description??l.addons[0]?.manifest.description:S.description;!l&&(S.components&&S.components.length>0||t.length>=2);const D=Hh({onSuccess:()=>{N.invalidateQueries({queryKey:[["addons"]]}),N.invalidateQueries({queryKey:[["addonPages"]]}),N.invalidateQueries({queryKey:[["capabilities"]]})}}),_=sa({onSuccess:()=>{N.invalidateQueries({queryKey:[["addons"]]})}}),R=lc({onSuccess:()=>{N.invalidateQueries({queryKey:[["addons"]]}),N.invalidateQueries({queryKey:[["addonPages"]]}),N.invalidateQueries({queryKey:[["capabilities"]]}),N.invalidateQueries({queryKey:[["integrations"]]})}}),L=Gh({onSuccess:()=>{N.invalidateQueries({queryKey:[["addons"]]}),N.invalidateQueries({queryKey:[["alerts"]]})}}),z=e.health,j=z?.phase==="failed"&&!z.inGracePeriod,H=j&&z?.nextRetryAt&&!z.retrying;return u("div",{className:`rounded-lg border bg-surface overflow-hidden ${j?"border-red-500/50":"border-border"}`,children:[j&&z&&u("div",{className:"bg-danger/10 border-b border-danger/30 px-4 py-2.5 flex items-start gap-2.5",children:[r(SL,{className:"h-4 w-4 text-danger shrink-0 mt-0.5"}),u("div",{className:"flex-1 min-w-0",children:[u("div",{className:"text-xs font-semibold text-danger",children:["Failed to load (attempt #",z.retryCount,")"]}),r("div",{className:"text-[11px] text-foreground mt-0.5 break-words font-mono",children:z.lastError?.message??"Unknown error"}),H&&z.nextRetryAt&&u("div",{className:"text-[10px] text-foreground-subtle mt-1",children:["Auto-retry at ",new Date(z.nextRetryAt).toLocaleTimeString()]})]}),u("button",{type:"button",disabled:L.isPending||z.retrying,onClick:T=>{T.stopPropagation(),L.mutate({packageName:E})},className:"inline-flex items-center gap-1.5 rounded-md px-2.5 py-1 text-[11px] font-semibold border border-red-400/40 bg-red-400/10 text-red-700 dark:text-red-300 hover:bg-red-400/20 disabled:opacity-50 disabled:cursor-not-allowed transition-colors shrink-0",title:"Reset retry counter and force immediate reload",children:[r(pt,{className:`h-3 w-3 ${L.isPending||z.retrying?"animate-spin":""}`}),"Retry now"]})]}),u("div",{className:"flex items-start gap-3 px-4 py-3",children:[r(N8,{isBundle:I||!!S.components&&S.components.length>1,installSource:O}),u("div",{className:"flex-1 min-w-0",children:[u("div",{className:"flex items-center gap-2",children:[r("span",{className:"text-sm font-semibold text-foreground truncate",children:F}),u("span",{className:"text-[10px] text-foreground-subtle font-mono shrink-0",children:["(",E,")"]}),I&&u("span",{className:"text-[10px] rounded-full bg-primary/10 text-primary px-2 py-0.5 font-medium shrink-0 inline-flex items-center gap-1",children:[r(uy,{className:"h-3 w-3"}),l.addons.length]})]}),A&&r("p",{className:"text-[10px] text-foreground-subtle mt-0.5 line-clamp-1",children:A}),!I&&e.process&&u("div",{className:"flex items-center gap-1.5 mt-1",children:[r("span",{className:`text-[9px] rounded-full px-1.5 py-0.5 font-medium ${e.process.mode==="forked"?"bg-blue-500/15 text-blue-400":"bg-gray-500/15 text-gray-400"}`,children:e.process.mode==="forked"?"forked":"in-process"}),e.process.pid!=null&&u("span",{className:"text-[9px] font-mono text-foreground-subtle",children:["PID ",e.process.pid]}),r("span",{className:`text-[9px] rounded-full px-1.5 py-0.5 font-medium ${e.process.state==="running"?"bg-emerald-500/15 text-emerald-400":e.process.state==="crashed"?"bg-red-500/15 text-red-400":"bg-gray-500/15 text-gray-400"}`,children:e.process.state})]})]}),!o&&u("div",{className:"relative inline-flex items-center gap-1.5 shrink-0 pt-0.5",children:[i?u("span",{className:"inline-flex items-center gap-1 rounded-md px-2 py-1 text-[10px] font-medium border border-blue-500/30 bg-blue-500/10 text-blue-400",children:[r(Pe,{className:"h-3 w-3 animate-spin"}),"Updating to ",s,"…"]}):s&&a?u("button",{type:"button",onClick:T=>{T.stopPropagation(),a()},className:"inline-flex items-center gap-1 rounded-md px-2 py-1 text-[10px] font-semibold border border-primary/40 bg-primary/10 text-primary hover:bg-primary/20 transition-colors animate-pulse",title:`Update to ${s}`,children:[r(wn,{className:"h-3 w-3"}),s]}):null,u("button",{type:"button",onClick:T=>{T.stopPropagation(),h(W=>!W)},className:["inline-flex items-center gap-1 rounded-md px-2 py-1 text-[10px] font-bold font-mono border transition-colors",O==="local"?"border-orange-500/30 bg-orange-500/10 text-orange-400 hover:bg-orange-500/20":s?"border-amber-500/30 bg-amber-500/10 text-amber-400 hover:bg-amber-500/20":"border-emerald-500/30 bg-emerald-500/10 text-emerald-400 hover:bg-emerald-500/20"].join(" "),title:s?`Current ${B} — newer ${s} available`:"View all versions",children:[B,r(Rt,{className:"h-3 w-3 opacity-50"})]}),m&&r(w8,{packageName:E,currentVersion:B,onInstall:T=>{h(!1),R.mutate({packageName:E,version:T})},onClose:()=>h(!1)})]})]}),!I&&u("div",{className:"flex items-center gap-1 px-4 py-1.5 border-t border-border/50 bg-surface-hover/20",children:[u("button",{type:"button",onClick:T=>{T.stopPropagation(),_.mutate({addonId:S.id})},disabled:_.isPending,className:"inline-flex items-center gap-1 rounded-md px-2 py-1 text-[10px] font-medium border border-border text-foreground-subtle hover:text-blue-400 hover:border-blue-500/30 hover:bg-blue-500/10 disabled:opacity-50 transition-colors",children:[r(pt,{className:`h-3 w-3 ${_.isPending?"animate-spin":""}`}),"Restart"]}),u("button",{type:"button",onClick:T=>{T.stopPropagation(),b(W=>!W)},className:`inline-flex items-center gap-1 rounded-md px-2 py-1 text-[10px] font-medium border transition-colors ${g?"border-primary/30 bg-primary/10 text-primary":"border-border text-foreground-subtle hover:text-foreground hover:border-primary/30 hover:bg-primary/10"}`,children:[r(Xe,{className:"h-3 w-3"}),"Logs"]}),!I&&u("button",{type:"button",onClick:T=>{T.stopPropagation(),v(!0)},className:`inline-flex items-center gap-1 rounded-md px-2 py-1 text-[10px] font-medium border transition-colors ${x?"border-primary/30 bg-primary/10 text-primary":"border-border text-foreground-subtle hover:text-foreground hover:border-primary/30 hover:bg-primary/10"}`,children:[r(wt,{className:"h-3 w-3"}),"Settings"]}),r("div",{className:"flex-1"}),P&&u("button",{type:"button",onClick:async T=>{T.stopPropagation(),await k({title:`Uninstall ${S.name}?`,message:"This will remove the addon package and all its data. This action cannot be undone.",confirmLabel:"Uninstall",variant:"danger"})&&D.mutate({packageName:S.packageName})},disabled:D.isPending,className:"inline-flex items-center gap-1 rounded-md px-2 py-1 text-[10px] font-medium border border-border text-foreground-subtle hover:text-red-400 hover:border-red-500/30 hover:bg-red-500/10 disabled:opacity-50 transition-colors",children:[r(We,{className:"h-3 w-3"}),D.isPending?"Removing...":"Uninstall"]})]}),n&&n.nodes.length>1&&!I&&u("div",{className:"border-t border-border px-4 py-2 bg-muted/10",children:[r("div",{className:"text-[10px] font-medium text-foreground-subtle mb-1.5",children:"Cluster Deployment"}),r("div",{className:"space-y-1",children:n.nodes.map(T=>u("div",{className:"flex items-center gap-2 text-[10px]",children:[r("div",{className:`h-1.5 w-1.5 rounded-full shrink-0 ${T.status==="offline"?"bg-muted-foreground/30":T.synced?"bg-success":"bg-amber-500"}`}),r("span",{className:"font-medium text-foreground min-w-[60px]",children:T.name}),r("span",{className:"font-mono text-foreground-subtle",children:T.version}),!T.synced&&T.status!=="offline"&&r("span",{className:"text-[9px] px-1 py-0.5 rounded bg-amber-500/10 text-amber-400 border border-amber-500/20",children:"outdated"}),T.status==="offline"&&r("span",{className:"text-[9px] px-1 py-0.5 rounded bg-muted text-muted-foreground",children:"offline"}),T.synced&&T.status!=="offline"&&r("span",{className:"text-[9px] text-success",children:"synced"})]},T.nodeId))})]}),g&&!I&&u("div",{className:"border-t border-border",children:[u("div",{className:"flex items-center px-4 py-1 bg-surface-hover/20 border-b border-border/50",children:[u("div",{className:"flex rounded border border-border overflow-hidden text-[9px]",children:[r("button",{type:"button",onClick:()=>y("logs"),className:`px-2 py-0.5 transition-colors ${w==="logs"?"bg-primary/10 text-primary":"text-foreground-subtle hover:bg-surface-hover"}`,children:"Logs"}),r("button",{type:"button",onClick:()=>y("events"),className:`px-2 py-0.5 border-l border-border transition-colors ${w==="events"?"bg-primary/10 text-primary":"text-foreground-subtle hover:bg-surface-hover"}`,children:"Events"})]}),r("div",{className:"flex-1"}),r("button",{type:"button",onClick:T=>{T.stopPropagation(),b(!1)},className:"text-foreground-subtle hover:text-foreground",children:r(qe,{className:"h-3.5 w-3.5"})})]}),w==="logs"&&r(Wt,{addonId:S.id,maxHeight:"max-h-64",showFilters:!1}),w==="events"&&r(nr,{addonId:S.id,category:"addon.*",maxHeight:"max-h-64"})]}),I&&u(ve,{children:[r("button",{type:"button",onClick:()=>d(T=>!T),className:"w-full flex items-center justify-center border-t border-border py-1 hover:bg-surface-hover/50 transition-colors",children:c?r(bD,{className:"h-3.5 w-3.5 text-foreground-subtle"}):r(Rt,{className:"h-3.5 w-3.5 text-foreground-subtle"})}),c&&r("div",{className:"border-t border-border px-3 py-2 space-y-2",children:l.addons.map(T=>r(pl,{addon:T,agents:t,hideVersion:!0},T.manifest.id))})]}),x&&!I&&r("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm p-4",onClick:()=>v(!1),children:u("div",{className:"w-full max-w-lg max-h-[80vh] rounded-xl border border-border bg-surface shadow-2xl flex flex-col overflow-hidden",onClick:T=>T.stopPropagation(),children:[u("div",{className:"flex items-center justify-between px-5 py-3 border-b border-border flex-shrink-0",children:[u("div",{className:"flex items-center gap-2",children:[r(wt,{className:"h-4 w-4 text-primary"}),u("h2",{className:"text-sm font-semibold text-foreground",children:[F," Settings"]})]}),r("button",{onClick:()=>v(!1),className:"text-foreground-subtle hover:text-foreground transition-colors p-1 rounded",children:r(qe,{className:"h-4 w-4"})})]}),u("div",{className:"flex-1 overflow-y-auto px-5 py-4 space-y-4",children:[r(Rr,{nodeId:"hub",addonIds:[S.id],level:"global"}),O==="npm"&&u("div",{children:[r("div",{className:"text-[10px] font-medium text-foreground-subtle uppercase tracking-wide mb-2",children:"Auto-Update"}),r(k8,{addonId:S.id})]}),S.components&&S.components.length>0&&u("div",{children:[u("div",{className:"text-[10px] font-medium text-foreground-subtle uppercase tracking-wide mb-2",children:["Components (",S.components.length,")"]}),r("div",{className:"flex flex-wrap gap-1",children:S.components.map(T=>r("span",{className:"text-[10px] rounded bg-background border border-border px-1.5 py-0.5 text-foreground-subtle font-mono",children:T},T))})]}),t.length>=2&&u("div",{children:[r("div",{className:"text-[10px] font-medium text-foreground-subtle uppercase tracking-wide mb-2",children:"Installed on"}),u("div",{className:"flex items-center gap-1.5 flex-wrap",children:[M.length===0&&r("span",{className:"text-[10px] text-foreground-subtle",children:"Hub (local)"}),M.map(T=>r("span",{className:"rounded-full bg-surface-hover border border-border px-2 py-0.5 text-[10px] text-foreground-subtle",children:T},T)),u("div",{className:"relative",children:[u("button",{type:"button",onClick:T=>{T.stopPropagation(),p(W=>!W)},className:"inline-flex items-center gap-1 rounded-full border border-dashed border-border px-2 py-0.5 text-[10px] text-foreground-subtle hover:text-foreground hover:border-primary transition-colors",title:"Install on more agents",children:[r(Ot,{className:"h-3 w-3"}),"Add agent"]}),f&&u("div",{className:"absolute left-0 top-full mt-1 z-10 min-w-[160px] rounded-md border border-border bg-surface shadow-lg overflow-hidden",children:[t.filter(T=>!T.isHub&&!M.includes(T.name)).map(T=>r("button",{type:"button",onClick:W=>{W.stopPropagation(),p(!1)},className:"w-full text-left px-3 py-1.5 text-[10px] text-foreground hover:bg-surface-hover transition-colors",children:T.name},T.id)),t.filter(T=>!T.isHub&&!M.includes(T.name)).length===0&&r("div",{className:"px-3 py-1.5 text-[10px] text-foreground-subtle",children:"No available agents"})]})]})]})]})]}),r("div",{className:"flex items-center justify-end px-5 py-3 border-t border-border flex-shrink-0",children:r("button",{type:"button",onClick:()=>v(!1),className:"rounded-lg border border-border px-3 py-1.5 text-xs font-medium text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors",children:"Close"})})]})})]})}const S8=".tgz,.tar.gz,.zip";function C8({onUploadSuccess:e}){const[t,n]=$(!1),o=ne(null),s=q(async i=>{n(!0);const l=new FormData;l.append("file",i);const c=localStorage.getItem("camstack_admin_token")??"";try{(await(await fetch("/api/addons/upload",{method:"POST",headers:{Authorization:`Bearer ${c}`},body:l})).json()).success&&e()}finally{n(!1)}},[e]),a=q(i=>{const l=i.target.files?.[0];l&&s(l),i.target.value=""},[s]);return u(ve,{children:[r("input",{ref:o,type:"file",accept:S8,onChange:a,className:"hidden"}),u("button",{type:"button",onClick:()=>o.current?.click(),disabled:t,className:"flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-md bg-surface hover:bg-surface-hover border border-border disabled:opacity-50 transition-colors",children:[t?r(Pe,{className:"w-3.5 h-3.5 animate-spin"}):r(Xc,{className:"w-3.5 h-3.5"}),t?"Uploading...":"Upload"]})]})}function M8(e,t){const n=e??"hub-only";return n==="any-node"?!0:n==="hub-only"?t:!t}function I8(e){const t=e;if(!t?.manifest)return null;const n={...t.manifest,name:t.manifest.name??t.manifest.id,version:t.manifest.version??"0.0.0",capabilities:t.manifest.capabilities??[]},o=t.process,s=o?{pid:o.pid,mode:o.mode==="forked"?"forked":"in-process",state:o.state??"unknown"}:void 0,a=t.health;return{manifest:n,enabled:!0,source:t.source,installSource:t.installSource,installedOn:[],...s?{process:s}:{},hasBackup:t.hasBackup,...a?{health:a}:{}}}function A8(e){const t=new Map,n=[];for(const s of e){const a=s.manifest.packageName;if(!a){n.push(s);continue}const i=t.get(a);if(i)i.addons.push(s);else{const l=s.manifest.bundle,c={packageName:a,displayName:l?.displayName??s.manifest.packageDisplayName??s.manifest.name,version:s.manifest.packageVersion,addons:[s],...s.installSource!==void 0?{installSource:s.installSource}:{},...l!==void 0?{bundle:l}:{}};t.set(a,c)}}const o=[];for(const s of t.values())s.bundle!==void 0||s.addons.length>=2?o.push({bundle:s,representative:s.addons[0]}):o.push(s.addons[0]);return o.push(...n),o}function Xt(e){return"bundle"in e}function P8({addons:e,clusterStatus:t,selectedNode:n,onRefresh:o,isRefreshing:s}){const a=ke(),[i,l]=$(""),c=Y1(i),[d,f]=$(!1),p=ne(null);Y(()=>{if(!d)return;const L=z=>{p.current&&!p.current.contains(z.target)&&f(!1)};return document.addEventListener("mousedown",L),()=>document.removeEventListener("mousedown",L)},[d]);const{data:m}=cc(void 0,{staleTime:5*6e4}),h=Q(()=>{const L=new Map;for(const z of m??[])L.set(z.name,z.latestVersion);return L},[m]),[g,b]=$(null),[x,v]=$(null),w=Ui({onMutate:L=>{b(L.name),v(null)},onSuccess:(L,z)=>{b(null);const j=L;if(j&&j.success===!1){v({name:z.name,message:j.error??"Update failed (no error message returned by server)"});return}a.invalidateQueries({queryKey:[["addons"]]}),a.invalidateQueries({queryKey:[["addons","listUpdates"]]})},onError:(L,z)=>{b(null),v({name:z.name,message:L instanceof Error?L.message:String(L)})}}),{data:y}=Wh(void 0,{staleTime:3e4}),N=Xh({onSuccess:()=>{a.invalidateQueries({queryKey:[["addons","getAutoUpdateSettings"]]})}}),{data:k,isFetching:S}=qh({query:c||void 0},{enabled:d,staleTime:6e4}),M=Ui(),P=async()=>{const L=m??[];for(const z of L)await M.mutateAsync({name:z.name,version:z.latestVersion});a.invalidateQueries({queryKey:[["addons"]]})},I=lc({onSuccess:()=>{a.invalidateQueries({queryKey:[["addons"]]}),a.invalidateQueries({queryKey:[["addonPages"]]}),a.invalidateQueries({queryKey:[["capabilities"]]}),a.invalidateQueries({queryKey:[["integrations"]]})}}),[F,E]=$("type"),[B,O]=$(()=>typeof window>"u"?"grouped":window.localStorage.getItem("camstack.addons.viewMode")==="flat"?"flat":"grouped"),A=L=>{O(L),typeof window<"u"&&window.localStorage.setItem("camstack.addons.viewMode",L)},D=Q(()=>n.isHub?e:e.filter(L=>{const z=L.manifest.execution;return M8(z?.placement,n.isHub)}),[e,n.isHub]),_=B==="flat"?D:A8(D),R=Q(()=>{const L=[..._];switch(F){case"type":L.sort((z,j)=>{const H=Xt(z)?0:1,T=Xt(j)?0:1;if(H!==T)return H-T;const W=Xt(z)?z.bundle.displayName:z.manifest.name,G=Xt(j)?j.bundle.displayName:j.manifest.name;return W.localeCompare(G)});break;case"name":L.sort((z,j)=>{const H=Xt(z)?z.bundle.displayName:z.manifest.name,T=Xt(j)?j.bundle.displayName:j.manifest.name;return H.localeCompare(T)});break;case"source":L.sort((z,j)=>{const H=Xt(z)?z.bundle.installSource??"":z.installSource??"",T=Xt(j)?j.bundle.installSource??"":j.installSource??"";return H.localeCompare(T)});break}return L},[_,F]);return u("div",{className:"space-y-4",children:[x&&r("div",{className:"rounded-md border border-danger/30 bg-danger/5 px-3 py-2 text-[11px]",children:u("div",{className:"flex items-start justify-between gap-3",children:[u("div",{className:"space-y-0.5",children:[u("div",{className:"font-medium text-danger",children:["Failed to update ",x.name]}),r("div",{className:"text-foreground-subtle font-mono",children:x.message})]}),r("button",{type:"button",onClick:()=>v(null),className:"text-foreground-subtle hover:text-foreground text-[10px]",children:"dismiss"})]})}),u("div",{className:"flex items-center gap-2 flex-wrap",children:[u("div",{className:"flex items-center gap-1.5",children:[r("span",{className:"text-[10px] text-foreground-subtle",children:"Sort:"}),u("select",{value:F,onChange:L=>E(L.target.value),className:"rounded-md border border-border bg-surface px-2 py-1.5 text-[11px] text-foreground focus:outline-none focus:border-primary/50",children:[r("option",{value:"type",children:"Bundles first"}),r("option",{value:"name",children:"Name"}),r("option",{value:"source",children:"Install source"})]})]}),u("div",{className:"flex items-center gap-1.5",children:[r("span",{className:"text-[10px] text-foreground-subtle",children:"View:"}),r("div",{className:"flex rounded-md border border-border overflow-hidden text-[10px] font-medium",children:["grouped","flat"].map(L=>r("button",{type:"button",onClick:()=>A(L),className:`px-2.5 py-1.5 transition-colors capitalize ${B===L?"bg-primary/10 text-primary":"bg-transparent text-foreground-subtle hover:bg-surface-hover"}`,title:L==="grouped"?"Group multi-addon packages into a bundle card":"Show every addon as its own card",children:L},L))})]}),u("div",{className:"flex items-center gap-1.5",children:[r(pt,{className:"h-3 w-3 text-foreground-subtle"}),r("span",{className:"text-[10px] text-foreground-subtle",children:"Auto-Update:"}),r("div",{className:"flex rounded-md border border-border overflow-hidden text-[10px] font-medium",children:["off","latest","beta"].map(L=>r("button",{type:"button",onClick:()=>N.mutate({channel:L}),disabled:N.isPending,className:`px-2.5 py-1.5 transition-colors capitalize ${y?.channel===L?L==="off"?"bg-gray-700 text-gray-200":L==="latest"?"bg-blue-500/20 text-blue-400":"bg-amber-500/20 text-amber-400":"bg-transparent text-foreground-subtle hover:bg-surface-hover"} ${L!=="off"?"border-l border-border":""}`,children:L},L))})]}),(m?.length??0)>0&&u("button",{type:"button",onClick:()=>void P(),disabled:M.isPending,className:"flex items-center gap-1.5 px-2.5 py-1.5 text-[11px] rounded-md bg-blue-500/10 text-blue-400 hover:bg-blue-500/20 border border-blue-500/30 disabled:opacity-50 transition-colors font-medium",children:[r(wn,{className:`w-3 h-3 ${M.isPending?"animate-bounce":""}`}),"Update All (",m.length,")"]}),u("button",{type:"button",onClick:o,disabled:s,className:"flex items-center gap-1.5 px-2.5 py-1.5 text-[11px] rounded-md bg-surface hover:bg-surface-hover border border-border disabled:opacity-50 transition-colors",children:[r(pt,{className:`w-3 h-3 ${s?"animate-spin":""}`}),"Refresh"]})]}),u("div",{className:"flex items-center gap-3",children:[u("div",{className:"relative flex-1 min-w-[200px]",ref:p,children:[r(hy,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-foreground-subtle"}),r("input",{type:"text",value:i,onChange:L=>{l(L.target.value),f(!0)},onFocus:()=>f(!0),placeholder:"Search addons on npm...",className:"w-full rounded-lg border border-border bg-background pl-9 pr-3 py-2 text-xs text-foreground placeholder:text-foreground-subtle focus:outline-none focus:ring-1 focus:ring-primary"}),S&&r(Pe,{className:"absolute right-2.5 top-1/2 -translate-y-1/2 h-3 w-3 text-foreground-subtle animate-spin"}),d&&k&&k.length>0&&u("div",{className:"absolute left-0 right-0 top-full mt-1 z-40 rounded-lg border border-border bg-surface shadow-xl overflow-hidden",children:[k.length>0&&u("div",{className:"px-3 py-1.5 text-[10px] uppercase tracking-wide text-foreground-subtle border-b border-border",children:["npm results (",k.length,")"]}),k&&k.length>0&&r("div",{className:"max-h-72 overflow-auto divide-y divide-border",children:k.map(L=>u("div",{className:"flex items-center gap-3 px-3 py-2 hover:bg-surface-hover transition-colors",children:[r("div",{className:"w-6 h-6 rounded-md bg-primary/10 flex items-center justify-center text-primary text-[9px] font-bold shrink-0",children:L.name.replace("@camstack/addon-","").charAt(0).toUpperCase()}),u("div",{className:"flex-1 min-w-0",children:[u("div",{className:"flex items-center gap-2",children:[r("span",{className:"text-[11px] font-semibold truncate",children:L.name}),u("span",{className:"text-[10px] text-foreground-subtle",children:["v",L.version]})]}),L.description&&r("div",{className:"text-[10px] text-foreground-subtle truncate",children:L.description})]}),L.installed?u("span",{className:"inline-flex items-center gap-1 px-2 py-1 text-[10px] font-medium rounded-md border border-emerald-500/30 bg-emerald-500/10 text-emerald-400 shrink-0",children:[r(Ct,{className:"h-3 w-3"}),L.installedVersion??"Installed"]}):u("button",{type:"button",onClick:()=>I.mutate({packageName:L.name}),disabled:I.isPending,className:"inline-flex items-center gap-1 px-2 py-1 text-[10px] font-medium rounded-md bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-50 transition-colors shrink-0",children:[I.isPending?r(Pe,{className:"h-3 w-3 animate-spin"}):r(wn,{className:"h-3 w-3"}),"Install"]})]},L.name))})]})]}),r(C8,{onUploadSuccess:()=>{a.invalidateQueries({queryKey:[["addons"]]}),o()}})]}),D.length===0&&r("div",{className:"text-xs text-foreground-subtle",children:e.length===0?"No addons installed":`No addons compatible with ${n.name} (placement filter active)`}),r("div",{className:"space-y-2",children:R.map(L=>{if(Xt(L)){const H=L.bundle.packageName,T=h.get(H);return r(pl,{addon:L.representative,clusterStatus:t?.[L.representative.manifest.id],bundle:L.bundle,availableUpdate:T,isUpdating:g===H,onUpdate:T?()=>w.mutate({name:H,version:T}):void 0},H)}const z=L.manifest.packageName,j=h.get(z);return r(pl,{addon:L,clusterStatus:t?.[L.manifest.id],availableUpdate:j,isUpdating:g===z,onUpdate:j?()=>w.mutate({name:L.manifest.packageName,version:j}):void 0},L.manifest.id)})})]})}function E8(){const e=ke(),{data:t,isLoading:n,isError:o}=oa(),{data:s}=nb(void 0,{staleTime:15e3}),{data:a}=In(void 0,{staleTime:3e4,refetchInterval:1e4}),i=Q(()=>{const x=new Map;x.set("hub",{id:"hub",name:"Hub",isHub:!0});for(const v of a??[]){const w=String(v.id??"");w&&x.set(w,{id:w,name:String(v.name??w),isHub:!!v.isHub})}return[...x.values()]},[a]),[l,c]=$("hub"),d=i.find(x=>x.id===l)??i[0],f=Qh(),p=Vh(),m=f.isPending||p.isPending,h=async()=>{await f.mutateAsync(),await p.mutateAsync(),e.invalidateQueries({queryKey:[["addons"]]})},g=ne(f);g.current=f,Y(()=>{g.current.mutate()},[]);const b=(t??[]).map(I8).filter(x=>x!==null);return u("div",{className:"p-6 space-y-5",children:[u("div",{className:"flex items-center justify-between gap-4 flex-wrap",children:[u("div",{children:[r("h1",{className:"text-lg font-semibold text-foreground",children:"Addons"}),r("p",{className:"text-xs text-foreground-subtle mt-0.5",children:"Manage installed addons and explore capability providers."})]}),u("div",{className:"flex items-center gap-3 flex-wrap",children:[r(gh,{selectedNodeId:l,onSelect:c}),!n&&!o&&u("span",{className:"text-[10px] rounded-full bg-primary/10 text-primary px-2 py-0.5 font-medium",children:[b.length," installed"]}),u("button",{type:"button",onClick:()=>void h(),disabled:m,className:"inline-flex items-center gap-1.5 px-2.5 py-1.5 text-[11px] rounded-md bg-surface hover:bg-surface-hover border border-border disabled:opacity-50 transition-colors",title:"Re-fetch addons + check npm for new versions",children:[r(pt,{className:`w-3 h-3 ${m?"animate-spin":""}`}),"Check for updates"]})]})]}),!d.isHub&&u("div",{className:"rounded-md border border-warning/30 bg-warning/5 px-3 py-2 text-[11px] text-foreground-subtle",children:["Showing only addons compatible with"," ",r("span",{className:"font-medium text-foreground",children:d.name})," ","— agents only run ",r("code",{className:"font-mono",children:"agent-only"})," and"," ",r("code",{className:"font-mono",children:"any-node"})," addons. Install / uninstall is hub-driven; agents auto-sync from the hub."]}),n&&r("div",{className:"text-xs text-foreground-subtle animate-pulse",children:"Loading…"}),o&&r("div",{className:"text-xs text-danger",children:"Failed to load addons"}),!n&&!o&&r(P8,{addons:b,clusterStatus:s,selectedNode:d,onRefresh:()=>void h(),isRefreshing:m})]})}function $8(){return r(It,{icon:Xe,title:"Logs",children:r("div",{className:"rounded-lg border border-border bg-surface overflow-hidden",children:r(Wt,{limit:500,maxHeight:"max-h-[calc(100vh-250px)]",showScope:!0,showFilters:!0})})})}function td({tabs:e,defaultTab:t}){const[n,o]=Qc(),s=n.get("tab"),a=t??e[0]?.id??"",i=e.some(d=>d.id===s)?s:a,l=e.find(d=>d.id===i)??e[0],c=d=>{const f=new URLSearchParams(n);f.set("tab",d),o(f,{replace:!0})};return u("div",{className:"space-y-3",children:[r("div",{className:"flex border-b border-border",children:e.map(d=>{const f=d.icon,p=d.id===i;return u("button",{onClick:()=>c(d.id),className:`flex items-center gap-1.5 px-3 py-2 text-xs font-medium border-b-2 transition-colors ${p?"border-primary text-primary":"border-transparent text-foreground-subtle hover:text-foreground"}`,children:[f&&r(f,{className:"h-3.5 w-3.5"}),d.label]},d.id)})}),r("div",{children:l?.content})]})}const bp={super_admin:"bg-danger/10 text-danger",admin:"bg-primary/10 text-primary",viewer:"bg-foreground-subtle/10 text-foreground-subtle"};function _8(){const e=ke(),[t,n]=$(!1),[o,s]=$(""),[a,i]=$(""),[l,c]=$("viewer"),[d,f]=$(null),{data:p,isLoading:m,isError:h}=kc(),g=rt(),b=()=>e.invalidateQueries({queryKey:[["userManagement","listUsers"]]}),x=ex({onSuccess:()=>{b(),n(!1),s(""),i(""),c("viewer"),f(null)},onError:I=>{f(I instanceof Error?I.message:"Failed to create user")}}),v=nx({onSuccess:b}),w=tx({onSuccess:b}),y=Sc({onSuccess:b}),N=p??[];async function k(I){await g({title:"Delete user",message:`Permanently delete user "${I.username}"? This cannot be undone — any active sessions will be revoked on next request.`,confirmLabel:"Delete",variant:"danger"})&&v.mutate({id:I.id})}async function S(I){const F=window.prompt(`New password for "${I.username}":`);if(!F)return;if(F.length<8){window.alert("Password must be at least 8 characters.");return}await g({title:"Reset password",message:`Reset the password for "${I.username}"? They will need to use the new password on their next login.`,confirmLabel:"Reset"})&&y.mutate({id:I.id,newPassword:F})}function M(I,F){F!==I.role&&w.mutate({id:I.id,role:F})}function P(I){return I?new Date(typeof I=="number"?I:String(I)).toLocaleDateString("en-GB",{day:"2-digit",month:"short",year:"numeric"}):"—"}return u(It,{icon:xy,title:"Users",actions:u("button",{onClick:()=>n(!0),className:"inline-flex items-center gap-1.5 rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground shadow-sm hover:bg-primary/90",children:[r(Ot,{className:"h-3.5 w-3.5"}),"Create User"]}),children:[t&&u("div",{className:"rounded-lg border border-border bg-surface p-4 space-y-3",children:[u("div",{className:"flex items-center justify-between",children:[r("span",{className:"text-xs font-medium text-foreground",children:"New User"}),r("button",{onClick:()=>n(!1),className:"text-foreground-subtle hover:text-foreground",children:r(qe,{className:"h-4 w-4"})})]}),u("div",{className:"grid grid-cols-3 gap-3",children:[u("div",{className:"space-y-1",children:[r("label",{className:"text-[10px] text-foreground-subtle uppercase tracking-wide",children:"Username"}),r("input",{type:"text",value:o,onChange:I=>s(I.target.value),placeholder:"john",className:"w-full rounded border border-border bg-background px-2 py-1.5 text-xs text-foreground placeholder:text-foreground-subtle focus:outline-none focus:ring-1 focus:ring-primary"})]}),u("div",{className:"space-y-1",children:[r("label",{className:"text-[10px] text-foreground-subtle uppercase tracking-wide",children:"Password"}),r("input",{type:"password",value:a,onChange:I=>i(I.target.value),placeholder:"••••••••",className:"w-full rounded border border-border bg-background px-2 py-1.5 text-xs text-foreground placeholder:text-foreground-subtle focus:outline-none focus:ring-1 focus:ring-primary"})]}),u("div",{className:"space-y-1",children:[r("label",{className:"text-[10px] text-foreground-subtle uppercase tracking-wide",children:"Role"}),u("select",{value:l,onChange:I=>c(I.target.value),className:"w-full rounded border border-border bg-background px-2 py-1.5 text-xs text-foreground focus:outline-none focus:ring-1 focus:ring-primary",children:[r("option",{value:"viewer",children:"Viewer"}),r("option",{value:"admin",children:"Admin"}),r("option",{value:"super_admin",children:"Super Admin"})]})]})]}),d&&r("p",{className:"text-[10px] text-danger",children:d}),u("div",{className:"flex justify-end gap-2",children:[r("button",{onClick:()=>n(!1),className:"rounded px-3 py-1.5 text-xs text-foreground-subtle border border-border hover:text-foreground",children:"Cancel"}),r("button",{onClick:()=>x.mutate({username:o,password:a,role:l}),disabled:x.isPending||!o||!a,className:"rounded bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50",children:x.isPending?"Creating...":"Create"})]})]}),m&&r("div",{className:"text-xs text-foreground-subtle animate-pulse",children:"Loading..."}),h&&r("div",{className:"text-xs text-danger",children:"Failed to load"}),!m&&!h&&N.length===0&&r("div",{className:"text-xs text-foreground-subtle",children:"No data"}),(()=>{const I=E=>v.isPending&&v.variables?.id===E.id||w.isPending&&w.variables?.id===E.id||y.isPending&&y.variables?.id===E.id;return r(uh,{columns:[{key:"username",header:"Username",render:E=>E.username},{key:"role",header:"Role",render:E=>{const B=E.role??"viewer",O=bp[B]??bp.viewer;return u("select",{value:B,onChange:A=>M(E,A.target.value),disabled:I(E),className:`rounded border border-border bg-background px-2 py-0.5 text-xs focus:outline-none focus:ring-1 focus:ring-primary disabled:opacity-50 ${O}`,title:"Change role",children:[r("option",{value:"viewer",children:"Viewer"}),r("option",{value:"admin",children:"Admin"}),r("option",{value:"super_admin",children:"Super Admin"})]})}},{key:"createdAt",header:"Created",render:E=>r("span",{className:"text-foreground-subtle",children:P(E.createdAt)})},{key:"actions",header:"Actions",align:"right",render:E=>{const B=I(E);return u("div",{className:"flex items-center justify-end gap-1",children:[u("button",{onClick:()=>S(E),disabled:B,className:"inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] text-foreground-subtle hover:bg-foreground-subtle/10 hover:text-foreground disabled:opacity-50",title:"Reset password",children:[r(YD,{className:"h-3 w-3"}),"Reset password"]}),u("button",{onClick:()=>k(E),disabled:B,className:"inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] text-danger hover:bg-danger/10 disabled:opacity-50",title:"Delete user",children:[B?r(Pe,{className:"h-3 w-3 animate-spin"}):r(We,{className:"h-3 w-3"}),"Delete"]})]})}}],rows:N,rowKey:E=>E.id,minWidthPx:560})})()]})}const D8={super_admin:"bg-danger/10 text-danger",admin:"bg-primary/10 text-primary",viewer:"bg-foreground-subtle/10 text-foreground-subtle",agent:"bg-warning/10 text-warning"};function to(e){if(!e)return"—";const t=new Date(e);return Number.isNaN(t.getTime())?"—":t.toLocaleString()}function L8(e){return e?e==="*"?"*":e.join(", "):""}function T8(e){return e.type==="integration"?{type:"addon",target:e.target}:{type:e.type,target:e.target}}function R8(){const e=ke(),t=rt(),{data:n,isLoading:o}=rx(),{data:s}=kc(),a=Q(()=>n??[],[n]),i=Q(()=>s??[],[s]),l=()=>e.invalidateQueries({queryKey:[["userManagement","listApiKeys"]]}),c=()=>e.invalidateQueries({queryKey:[["userManagement","listScopedTokens"]]}),[d,f]=$(!1),[p,m]=$(null),h=ox({onSuccess:l}),g=sx({onSuccess:({token:w,record:y})=>{c(),f(!1),m({token:w,label:y.name})}}),b=ax({onSuccess:c}),x=async(w,y)=>{await t({title:`Revoke "${y}"?`,message:"Any client using this token will lose access immediately. This cannot be undone.",confirmLabel:"Revoke",variant:"danger"})&&h.mutate({id:w})},v=async(w,y)=>{await t({title:`Revoke "${y}"?`,message:"The scoped token will be invalid on its next use.",confirmLabel:"Revoke",variant:"danger"})&&b.mutate({id:w})};return u(It,{icon:ay,title:"Tokens",subtitle:"Issue scoped tokens to grant a user a narrow surface — a specific addon, integration, route prefix, or capability. Every token MUST be scoped: revoking it has predictable blast radius.",actions:u("button",{onClick:()=>f(!0),className:"inline-flex items-center gap-1.5 rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50",disabled:i.length===0,title:i.length===0?"Create a user first":"Issue a scoped token",children:[r(xr,{className:"h-3.5 w-3.5"}),"New token"]}),children:[u(xp,{title:"Scoped tokens",subtitle:"Grouped per user",children:[i.length===0&&r(z8,{text:"No users yet — scoped tokens are issued on behalf of an existing user."}),i.map(w=>r(B8,{userId:w.id,username:w.username,onRevoke:(y,N)=>{v(y,N)},revokePending:b.isPending,revokeId:b.variables?.id},w.id))]}),a.length>0&&r(xp,{title:"Legacy API keys",subtitle:`${a.length} pre-existing — revoke only`,children:r(n0,{headers:["Label","Role","Prefix","Allowed providers","Created","Last used",""],rows:a.map(w=>{const y=w.role??"viewer",N=h.isPending&&h.variables?.id===w.id;return u("tr",{className:"hover:bg-primary/5",children:[r("td",{className:"px-3 py-2 text-foreground border-b border-border font-medium",children:w.label}),r("td",{className:"px-3 py-2 text-foreground border-b border-border",children:r("span",{className:`inline-block rounded px-2 py-0.5 text-[10px] uppercase tracking-wide ${D8[y]}`,children:y})}),u("td",{className:"px-3 py-2 text-foreground border-b border-border font-mono text-[11px]",children:[w.tokenPrefix,"…"]}),r("td",{className:"px-3 py-2 text-foreground border-b border-border text-foreground-subtle",children:L8(w.allowedProviders)||"all"}),r("td",{className:"px-3 py-2 text-foreground-subtle border-b border-border",children:to(w.createdAt)}),r("td",{className:"px-3 py-2 text-foreground-subtle border-b border-border",children:to(w.lastUsedAt)}),r("td",{className:"px-3 py-2 border-b border-border text-right",children:u("button",{onClick:()=>{x(w.id,w.label)},disabled:N,className:"inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] text-danger hover:bg-danger/10 disabled:opacity-50",title:"Revoke",children:[N?r(Pe,{className:"h-3 w-3 animate-spin"}):r(We,{className:"h-3 w-3"}),"Revoke"]})})]},w.id)})})}),o&&r(O8,{}),d&&r(F8,{users:i.map(w=>({id:w.id,username:w.username})),onClose:()=>f(!1),onSubmit:w=>g.mutate({name:w.name,scopes:w.scopes,...w.expiresAt!==void 0?{expiresAt:w.expiresAt}:{}}),submitting:g.isPending}),p&&r(H8,{token:p.token,label:p.label,onClose:()=>m(null)})]})}function xp({title:e,subtitle:t,children:n}){return u("div",{className:"space-y-2",children:[u("div",{className:"flex items-baseline justify-between",children:[r("h2",{className:"text-sm font-semibold text-foreground",children:e}),t&&r("span",{className:"text-[10px] text-foreground-subtle",children:t})]}),n]})}function O8(){return r("div",{className:"space-y-2",children:[1,2].map(e=>r("div",{className:"h-10 rounded border border-border bg-surface animate-pulse"},e))})}function z8({text:e}){return r("div",{className:"rounded border border-dashed border-border bg-surface px-3 py-4 text-xs text-foreground-subtle text-center",children:e})}function n0({headers:e,rows:t}){return r("div",{className:"rounded-lg border border-border bg-surface overflow-x-auto",children:u("table",{className:"w-full text-xs min-w-[640px]",children:[r("thead",{children:r("tr",{children:e.map((n,o)=>r("th",{className:`px-3 py-2 text-foreground-subtle font-medium bg-surface border-b border-border whitespace-nowrap ${o===e.length-1?"text-right":"text-left"}`,children:n},o))})}),r("tbody",{children:t})]})})}function B8({userId:e,username:t,onRevoke:n,revokePending:o,revokeId:s}){const{data:a,isLoading:i}=ix({userId:e}),l=a??[];return i||l.length===0?null:u("div",{className:"space-y-1.5",children:[r("div",{className:"text-[11px] font-medium text-foreground",children:t}),r(n0,{headers:["Name","Prefix","Scopes","Expires","Last used","Created",""],rows:l.map(c=>{const d=o&&s===c.id;return u("tr",{className:"hover:bg-primary/5",children:[r("td",{className:"px-3 py-2 text-foreground border-b border-border font-medium",children:c.name}),u("td",{className:"px-3 py-2 text-foreground border-b border-border font-mono text-[11px]",children:[c.tokenPrefix,"…"]}),r("td",{className:"px-3 py-2 text-foreground border-b border-border",children:r("div",{className:"flex flex-wrap gap-1",children:c.scopes.map((f,p)=>u("span",{className:"inline-block rounded bg-foreground-subtle/10 px-1.5 py-0.5 text-[10px] font-mono",children:[f.type,":",f.target]},p))})}),r("td",{className:"px-3 py-2 text-foreground-subtle border-b border-border",children:to(c.expiresAt)}),r("td",{className:"px-3 py-2 text-foreground-subtle border-b border-border",children:to(c.lastUsedAt)}),r("td",{className:"px-3 py-2 text-foreground-subtle border-b border-border",children:to(c.createdAt)}),r("td",{className:"px-3 py-2 border-b border-border text-right",children:u("button",{onClick:()=>n(c.id,c.name),disabled:d,className:"inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] text-danger hover:bg-danger/10 disabled:opacity-50",children:[d?r(Pe,{className:"h-3 w-3 animate-spin"}):r(We,{className:"h-3 w-3"}),"Revoke"]})})]},c.id)})})]})}function F8({users:e,onClose:t,onSubmit:n,submitting:o}){const[s,a]=$(e[0]?.id??""),[i,l]=$(""),[c,d]=$([{type:"addon",target:""}]),[f,p]=$(""),{data:m=[]}=oa(),{data:h=[]}=aa(),g=(w,y)=>{d(N=>N.map((k,S)=>{if(S!==w)return k;const M={...k,...y};return y.type!==void 0&&y.type!==k.type&&(M.target=""),M}))},b=c.filter(w=>w.target.trim().length>0).map(T8),x=s!==""&&i.trim().length>0&&b.length>0&&!o,v=()=>{const w=parseInt(f,10),y=Number.isFinite(w)&&w>0?Date.now()+w*864e5:void 0;n({userId:s,name:i.trim(),scopes:b,expiresAt:y})};return u(r0,{title:"Create scoped token",onClose:t,children:[u("div",{className:"space-y-3",children:[r(ts,{label:"On behalf of user",children:r("select",{value:s,onChange:w=>a(w.target.value),className:"w-full rounded border border-border bg-background px-2 py-1.5 text-xs focus:outline-none focus:ring-1 focus:ring-primary",children:e.map(w=>r("option",{value:w.id,children:w.username},w.id))})}),r(ts,{label:"Name",children:r("input",{value:i,onChange:w=>l(w.target.value),placeholder:"cloudflare-tunnel-route",className:"w-full rounded border border-border bg-background px-2 py-1.5 text-xs focus:outline-none focus:ring-1 focus:ring-primary"})}),r(ts,{label:"Scopes",hint:"Each scope picks a concrete surface. The token can access ONLY what's listed.",children:u("div",{className:"space-y-1.5",children:[c.map((w,y)=>r(j8,{scope:w,addons:m,integrations:h,onChange:N=>g(y,N),onRemove:c.length>1?()=>d(N=>N.filter((k,S)=>S!==y)):void 0},y)),u("button",{onClick:()=>d(w=>[...w,{type:"addon",target:""}]),className:"inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] text-foreground-subtle hover:text-foreground hover:bg-foreground-subtle/10",children:[r(Ot,{className:"h-3 w-3"}),"Add scope"]})]})}),r(ts,{label:"Expires in (days)",hint:"Leave blank for non-expiring.",children:r("input",{type:"number",min:1,value:f,onChange:w=>p(w.target.value),placeholder:"30",className:"w-full rounded border border-border bg-background px-2 py-1.5 text-xs focus:outline-none focus:ring-1 focus:ring-primary"})})]}),u(o0,{children:[r("button",{onClick:t,className:"rounded px-3 py-1.5 text-xs text-foreground-subtle border border-border hover:text-foreground",children:"Cancel"}),u("button",{onClick:v,disabled:!x,className:"inline-flex items-center gap-1.5 rounded bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50",children:[o?r(Pe,{className:"h-3.5 w-3.5 animate-spin"}):r(xr,{className:"h-3.5 w-3.5"}),"Issue token"]})]})]})}function j8({scope:e,addons:t,integrations:n,onChange:o,onRemove:s}){const a=t.map(l=>({id:l.manifest.id})),i=()=>{switch(e.type){case"addon":return u("select",{value:e.target,onChange:l=>o({target:l.target.value}),className:"flex-1 rounded border border-border bg-background px-2 py-1.5 text-xs font-mono focus:outline-none focus:ring-1 focus:ring-primary",children:[r("option",{value:"",children:"— pick addon —"}),a.map(l=>r("option",{value:l.id,children:l.id},l.id))]});case"integration":return u("select",{value:e.target,onChange:l=>o({target:l.target.value}),className:"flex-1 rounded border border-border bg-background px-2 py-1.5 text-xs focus:outline-none focus:ring-1 focus:ring-primary",children:[r("option",{value:"",children:"— pick integration —"}),n.map(l=>u("option",{value:l.addonId,children:[l.name," (",l.addonId,")"]},l.id))]});case"capability":return u("select",{value:e.target,onChange:l=>o({target:l.target.value}),className:"flex-1 rounded border border-border bg-background px-2 py-1.5 text-xs font-mono focus:outline-none focus:ring-1 focus:ring-primary",children:[r("option",{value:"",children:"— pick capability —"}),Object.values(aw).sort().map(l=>r("option",{value:l,children:l},l))]});case"route-prefix":return r("input",{value:e.target,onChange:l=>o({target:l.target.value}),placeholder:"/api/cloudflare",className:"flex-1 rounded border border-border bg-background px-2 py-1.5 text-xs font-mono focus:outline-none focus:ring-1 focus:ring-primary"})}};return u("div",{className:"flex items-center gap-1.5",children:[u("select",{value:e.type,onChange:l=>o({type:l.target.value}),className:"rounded border border-border bg-background px-2 py-1.5 text-xs focus:outline-none focus:ring-1 focus:ring-primary",children:[r("option",{value:"addon",children:"addon"}),r("option",{value:"integration",children:"integration"}),r("option",{value:"capability",children:"capability"}),r("option",{value:"route-prefix",children:"route-prefix"})]}),i(),s&&r("button",{onClick:s,className:"rounded p-1 text-foreground-subtle hover:text-danger hover:bg-danger/10",title:"Remove scope",children:r(qe,{className:"h-3 w-3"})})]})}function H8({token:e,label:t,onClose:n}){const[o,s]=$(!1),a=async()=>{try{await navigator.clipboard.writeText(e),s(!0)}catch{}};return u(r0,{title:`Token: ${t}`,onClose:n,children:[u("div",{className:"space-y-3",children:[r("div",{className:"rounded border border-warning/30 bg-warning/10 px-3 py-2 text-xs text-warning",children:"Copy this token now. Once you close this dialog the secret cannot be displayed again."}),r("div",{className:"rounded border border-border bg-background p-2 font-mono text-[11px] break-all select-all",children:e})]}),u(o0,{children:[u("button",{onClick:()=>{a()},className:"inline-flex items-center gap-1.5 rounded bg-surface border border-border px-3 py-1.5 text-xs font-medium text-foreground hover:bg-primary/5 hover:border-primary/30",children:[o?r(Ct,{className:"h-3.5 w-3.5 text-primary"}):r(MD,{className:"h-3.5 w-3.5"}),o?"Copied":"Copy"]}),r("button",{onClick:n,className:"rounded bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90",children:"Done"})]})]})}function r0({title:e,onClose:t,children:n}){return r("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-background/80 backdrop-blur-sm",onClick:t,children:u("div",{className:"w-full max-w-md rounded-xl border border-border bg-surface shadow-2xl",onClick:o=>o.stopPropagation(),children:[u("div",{className:"flex items-start justify-between border-b border-border px-4 py-3",children:[r("h2",{className:"text-sm font-semibold text-foreground",children:e}),r("button",{onClick:t,className:"text-foreground-subtle hover:text-foreground",children:r(qe,{className:"h-4 w-4"})})]}),r("div",{className:"p-4",children:n})]})})}function o0({children:e}){return r("div",{className:"flex justify-end gap-2 border-t border-border px-4 py-3",children:e})}function ts({label:e,hint:t,children:n}){return u("div",{className:"space-y-1",children:[r("label",{className:"text-[10px] text-foreground-subtle uppercase tracking-wide",children:e}),n,t&&r("p",{className:"text-[10px] text-foreground-subtle",children:t})]})}const V8={local:"Local (username + password)",oidc:"OpenID Connect",saml:"SAML 2.0",ldap:"LDAP / Active Directory",other:"Custom"},yp={local:"bg-foreground-subtle/10 text-foreground",oidc:"bg-blue-500/15 text-blue-700 dark:text-blue-300",saml:"bg-purple-500/15 text-purple-700 dark:text-purple-300",ldap:"bg-amber-500/15 text-amber-700 dark:text-amber-300",other:"bg-slate-500/15 text-slate-700 dark:text-slate-300"};function q8(){const e=uc(),t=e.data??[];return r(It,{icon:xr,title:"Authentication",subtitle:"Login providers exposed to the admin UI. Local username + password is always available; OIDC / SAML / LDAP can be added by installing a provider addon.",actions:r(Kt,{to:"/system/addons",children:r(ze,{variant:"primary",size:"sm",children:"Add provider"})}),children:e.isLoading?r(Ge,{children:r("div",{className:"p-6 text-sm text-foreground-subtle",children:"Loading providers…"})}):t.length===0?r(Ge,{children:r(ko,{title:"No authentication providers registered",description:"Local auth should always be available — if this list is empty, the local-auth builtin failed to register. Check the Addons page for load errors."})}):r(Ge,{children:r("div",{className:"divide-y divide-border",children:t.map(n=>u("div",{className:"flex items-center gap-4 p-4",children:[r("div",{className:"h-10 w-10 rounded-lg bg-primary/10 text-primary flex items-center justify-center shrink-0",children:r(xr,{className:"h-5 w-5"})}),u("div",{className:"flex-1 min-w-0",children:[u("div",{className:"flex items-center gap-2",children:[r("span",{className:"font-semibold text-foreground",children:n.displayName}),r("span",{className:`text-[10px] rounded-full px-2 py-0.5 font-medium ${yp[n.kind]??yp.other}`,children:V8[n.kind]??n.kind}),!n.enabled&&r("span",{className:"text-[10px] rounded-full px-2 py-0.5 font-medium bg-red-500/15 text-red-700 dark:text-red-300",children:"Disabled"})]}),u("div",{className:"text-xs text-foreground-subtle mt-1 flex items-center gap-3",children:[r("span",{className:"font-mono",children:n.addonId}),n.hasCredentialFlow&&r("span",{children:"· username + password"}),n.hasRedirectFlow&&r("span",{children:"· redirect (SSO)"})]}),n.status&&r("div",{className:"text-xs text-foreground-subtle mt-1",children:n.status})]}),u(Kt,{to:`/system/addons?addon=${encodeURIComponent(n.addonId)}`,className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[r(wt,{className:"h-3.5 w-3.5"}),"Configure",r(Zx,{className:"h-3.5 w-3.5"})]})]},n.addonId))})})})}function Q8(){return r("div",{className:"flex flex-col",children:r("div",{className:"px-6 pt-6",children:r(td,{tabs:[{id:"users",label:"Users",icon:xy,content:r(_8,{})},{id:"api-keys",label:"Tokens",icon:ay,content:r(R8,{})},{id:"authentication",label:"Authentication",icon:xr,content:r(q8,{})}]})})})}function nd({addonId:e,defaultActivity:t,showActivity:n=!0,maxHeight:o="max-h-64",defaultTab:s}){const a=t??(s==="events"?"events":"logs"),[i,l]=$(a);return u("div",{className:"flex flex-col gap-4",children:[r(Rr,{nodeId:"hub",addonIds:[e],level:"global"}),n&&u("div",{className:"rounded-lg border border-border bg-surface overflow-hidden",children:[u("div",{className:"flex items-center justify-between px-3 py-2 border-b border-border bg-surface-hover/20",children:[r("span",{className:"text-[11px] font-semibold text-foreground-subtle uppercase tracking-wide",children:"Activity"}),u("div",{className:"flex items-center gap-1",children:[r(vp,{kind:"logs",active:i==="logs",onClick:()=>l("logs")}),r(vp,{kind:"events",active:i==="events",onClick:()=>l("events")})]})]}),i==="logs"?r(Wt,{addonId:e,maxHeight:o,showFilters:!1}):r(nr,{addonId:e,category:"addon.*",maxHeight:o})]})]})}function vp({kind:e,active:t,onClick:n}){return u("button",{onClick:n,className:`inline-flex items-center gap-1 rounded px-2 py-0.5 text-[11px] font-medium transition-colors ${t?"bg-primary/10 text-primary":"text-foreground-subtle hover:text-foreground hover:bg-surface-hover"}`,children:[r(e==="logs"?Xe:Ao,{className:"h-3 w-3"}),e==="logs"?"Logs":"Events"]})}const U8={"cloudflare-tunnel":"Cloudflare Tunnel",ngrok:"ngrok",tailscale:"Tailscale",other:"Custom"};function K8(){const e=ke(),t=qb(void 0,{refetchInterval:5e3}),n=t.data??[],[o,s]=$(null),a=()=>{e.invalidateQueries({queryKey:[["remoteAccess"]]}),s(null)},i=Qb({onSuccess:a,onError:()=>s(null)}),l=Ub({onSuccess:a,onError:()=>s(null)});return r(It,{icon:br,title:"Remote Access",subtitle:"Public-facing tunnels that expose this hub to the internet (Cloudflare Tunnel, ngrok, …). Settings, Logs and Events are docked under every provider.",actions:r(Kt,{to:"/system/addons",children:r(ze,{variant:"primary",size:"sm",children:"Add tunnel"})}),children:t.isLoading?r(Ge,{children:r("div",{className:"p-6 text-sm text-foreground-subtle",children:"Loading providers…"})}):n.length===0?r(Ge,{children:r(ko,{title:"No remote-access providers installed",description:"Install a tunnel addon (e.g. @camstack/addon-cloudflare-tunnel) to expose this hub publicly.",action:r(Kt,{to:"/system/addons",children:r(ze,{variant:"primary",size:"sm",children:"Browse addons"})})})}):r("div",{className:"flex flex-col gap-4",children:n.map(c=>{const d=o===c.addonId;return u(Ge,{children:[u("div",{className:"flex items-center gap-4 p-4 border-b border-border",children:[r("div",{className:`h-10 w-10 rounded-lg flex items-center justify-center shrink-0 ${c.connected?"bg-emerald-500/15 text-emerald-700 dark:text-emerald-300":"bg-foreground-subtle/15 text-foreground-subtle"}`,children:r(br,{className:"h-5 w-5"})}),u("div",{className:"flex-1 min-w-0",children:[u("div",{className:"flex items-center gap-2 flex-wrap",children:[r("span",{className:"font-semibold text-foreground",children:c.displayName}),r("span",{className:"text-[10px] rounded-full px-2 py-0.5 font-medium bg-blue-500/15 text-blue-700 dark:text-blue-300",children:U8[c.kind]??c.kind}),r("span",{className:`text-[10px] rounded-full px-2 py-0.5 font-medium ${c.connected?"bg-emerald-500/15 text-emerald-700 dark:text-emerald-300":"bg-foreground-subtle/15 text-foreground-subtle"}`,children:c.connected?"Connected":"Disconnected"})]}),r("div",{className:"text-xs text-foreground-subtle mt-1 font-mono",children:c.addonId}),c.endpoint&&u("div",{className:"text-xs text-emerald-700 dark:text-emerald-300 mt-1 flex items-center gap-1",children:[r(Gc,{className:"h-3 w-3"}),r("a",{href:c.endpoint.url,target:"_blank",rel:"noopener noreferrer",className:"hover:underline break-all",children:c.endpoint.url})]}),c.error&&r("div",{className:"text-xs text-danger mt-1",children:c.error})]}),r("div",{className:"flex items-center gap-1 shrink-0",children:c.connected?u(ze,{size:"sm",variant:"secondary",disabled:d,onClick:()=>{s(c.addonId),l.mutate({addonId:c.addonId})},children:[d?r(Pe,{className:"h-3 w-3 animate-spin"}):r(Eo,{className:"h-3 w-3"}),"Stop"]}):u(ze,{size:"sm",variant:"primary",disabled:d,onClick:()=>{s(c.addonId),i.mutate({addonId:c.addonId})},children:[d?r(Pe,{className:"h-3 w-3 animate-spin"}):r(va,{className:"h-3 w-3"}),"Start"]})})]}),r("div",{className:"p-4",children:r(nd,{addonId:c.addonId,maxHeight:"max-h-72"})})]},c.addonId)})})})}const G8={cloudflare:"Cloudflare TURN",coturn:"coturn (self-hosted)",twilio:"Twilio NTS",other:"Custom"};function W8(){const e=ke(),t=Zb(void 0,{refetchInterval:3e4}),n=Xb(),o=t.data??[],s=n.data??[],[a,i]=$(null),l=Jb({onSuccess:()=>{e.invalidateQueries({queryKey:[["turnOrchestrator"]]}),i(null)},onError:()=>i(null)});return r(It,{icon:an,title:"TURN Servers",subtitle:"ICE servers used for WebRTC NAT traversal. Multiple providers can coexist — the WebRTC layer concatenates servers from all enabled providers per session.",actions:r(Kt,{to:"/system/addons",children:r(ze,{variant:"primary",size:"sm",children:"Add provider"})}),children:t.isLoading?r(Ge,{children:r("div",{className:"p-6 text-sm text-foreground-subtle",children:"Loading providers…"})}):o.length===0?r(Ge,{children:r(ko,{title:"No TURN providers installed",description:"Install a TURN addon (e.g. @camstack/addon-cloudflare-turn) to enable WebRTC behind restrictive NATs.",action:r(Kt,{to:"/system/addons",children:r(ze,{variant:"primary",size:"sm",children:"Browse addons"})})})}):u("div",{className:"flex flex-col gap-4",children:[o.map(c=>{const d=a===c.addonId;return u(Ge,{children:[u("div",{className:"flex items-center gap-4 p-4 border-b border-border",children:[r("div",{className:`h-10 w-10 rounded-lg flex items-center justify-center shrink-0 ${c.error?"bg-danger/15 text-danger":c.enabled?"bg-violet-500/15 text-violet-700 dark:text-violet-300":"bg-foreground-subtle/15 text-foreground-subtle"}`,children:r(an,{className:"h-5 w-5"})}),u("div",{className:"flex-1 min-w-0",children:[u("div",{className:"flex items-center gap-2 flex-wrap",children:[r("span",{className:"font-semibold text-foreground",children:c.displayName}),r("span",{className:"text-[10px] rounded-full px-2 py-0.5 font-medium bg-violet-500/15 text-violet-700 dark:text-violet-300",children:G8[c.kind]??c.kind}),r("span",{className:`text-[10px] rounded-full px-2 py-0.5 font-medium ${c.enabled?"bg-emerald-500/15 text-emerald-700 dark:text-emerald-300":"bg-foreground-subtle/15 text-foreground-subtle"}`,children:c.enabled?"Enabled":"Disabled"})]}),u("div",{className:"text-xs text-foreground-subtle mt-1 flex items-center gap-3",children:[r("span",{className:"font-mono",children:c.addonId}),u("span",{children:["· ",c.serverCount," server",c.serverCount===1?"":"s"]})]}),c.error&&r("div",{className:"text-xs text-danger mt-1",children:c.error})]}),r("div",{className:"flex items-center gap-1 shrink-0",children:c.enabled?u(ze,{size:"sm",variant:"secondary",disabled:d,onClick:()=>{i(c.addonId),l.mutate({addonId:c.addonId,enabled:!1})},children:[d?r(Pe,{className:"h-3 w-3 animate-spin"}):r(Eo,{className:"h-3 w-3"}),"Disable"]}):u(ze,{size:"sm",variant:"primary",disabled:d,onClick:()=>{i(c.addonId),l.mutate({addonId:c.addonId,enabled:!0})},children:[d?r(Pe,{className:"h-3 w-3 animate-spin"}):r(va,{className:"h-3 w-3"}),"Enable"]})})]}),r("div",{className:"p-4",children:r(nd,{addonId:c.addonId,maxHeight:"max-h-72"})})]},c.addonId)}),u(Ge,{children:[u("div",{className:"px-4 py-3 border-b border-border flex items-center justify-between",children:[u("div",{children:[r("div",{className:"text-sm font-semibold",children:"Combined ICE server list"}),r("div",{className:"text-xs text-foreground-subtle",children:"What the WebRTC layer fetches per-session."})]}),r(ze,{size:"sm",variant:"secondary",onClick:()=>n.refetch(),disabled:n.isFetching,children:"Refresh"})]}),r("div",{className:"p-4",children:s.length===0?r("div",{className:"text-xs text-foreground-subtle",children:"No servers from enabled providers."}):r("ul",{className:"space-y-1 font-mono text-xs",children:s.map((c,d)=>{const f=Array.isArray(c.urls)?c.urls.join(", "):c.urls;return u("li",{className:"text-foreground",children:[f,c.username&&u("span",{className:"text-foreground-subtle",children:[" (user: ",c.username,")"]})]},d)})})})]})]})})}const Y8={lan:an,wifi:jn,docker:ba,vpn:ly,loopback:ln,other:ln},Z8={lan:"LAN",wifi:"Wi-Fi",docker:"Docker",vpn:"VPN",loopback:"Loopback",other:"Other"},X8=["lan","wifi","vpn","docker","other","loopback"];function J8(e){const{interfaces:t,disabled:n,hideLoopback:o,ipv4Only:s,emptyMessage:a}=e,i=Q(()=>t.filter(f=>!(o&&f.kind==="loopback"||s&&f.family!=="IPv4")),[t,o,s]),l=Q(()=>{const f=new Map;for(const p of i){const m=f.get(p.kind)??[];m.push(p),f.set(p.kind,m)}return X8.filter(p=>f.has(p)).map(p=>({kind:p,items:f.get(p)}))},[i]),c=f=>e.mode==="single"?e.value===f:e.value.includes(f),d=f=>{if(n||f.kind==="loopback")return;if(e.mode==="single"){e.onChange(e.value===f.address?null:f.address);return}const p=new Set(e.value);p.has(f.address)?p.delete(f.address):p.add(f.address),e.onChange([...p])};return i.length===0?r("div",{className:"text-xs text-foreground-subtle italic",children:a??"No addresses available."}):r("div",{className:"flex flex-col gap-3",children:l.map(({kind:f,items:p})=>{const m=Y8[f]??ln;return u("div",{className:"rounded-md border border-border overflow-hidden",children:[u("div",{className:"flex items-center gap-2 px-3 py-1.5 bg-surface-hover/30 border-b border-border",children:[r(m,{className:"h-3.5 w-3.5 text-foreground-subtle"}),r("span",{className:"text-[11px] font-semibold uppercase tracking-wide text-foreground-subtle",children:Z8[f]??f}),u("span",{className:"text-[10px] text-foreground-subtle",children:["· ",p.length]})]}),r("ul",{className:"divide-y divide-border",children:p.map(h=>{const g=c(h.address),b=h.kind==="loopback",x=!h.plausible&&!b;return u("li",{className:`flex items-center gap-3 px-3 py-2 ${b?"opacity-60 cursor-not-allowed":n?"opacity-60":x?"cursor-pointer hover:bg-surface-hover/30 bg-amber-500/[0.04]":"cursor-pointer hover:bg-surface-hover/30"}`,onClick:()=>d(h),children:[r("span",{className:`flex items-center justify-center h-4 w-4 rounded ${e.mode==="single"?"rounded-full":"rounded"} border ${g?"border-primary bg-primary text-primary-foreground":"border-border bg-surface"}`,children:g&&r(Ct,{className:"h-3 w-3"})}),u("div",{className:`flex-1 min-w-0 ${x?"text-foreground-subtle":""}`,children:[u("div",{className:"flex items-center gap-2 flex-wrap",children:[r("span",{className:`font-mono text-xs font-semibold ${x?"text-foreground-subtle":"text-foreground"}`,children:h.name}),r("span",{className:"text-[10px] rounded px-1.5 py-0.5 bg-foreground-subtle/10 text-foreground-subtle font-mono",children:h.family}),h.preferred&&r("span",{className:"text-[10px] rounded-full px-2 py-0.5 font-medium bg-primary/15 text-primary",children:"Auto-preferred"}),b&&r("span",{className:"text-[10px] rounded-full px-2 py-0.5 font-medium bg-foreground-subtle/15 text-foreground-subtle",children:"Always included"}),x&&u("span",{className:"inline-flex items-center gap-1 text-[10px] rounded-full px-2 py-0.5 font-medium bg-amber-500/15 text-amber-700 dark:text-amber-300",title:h.plausibleReason||void 0,children:[r(xt,{className:"h-2.5 w-2.5"}),"Unlikely usable"]})]}),u("div",{className:"text-xs text-foreground-subtle mt-0.5 font-mono break-all",children:[h.address,h.cidr&&h.cidr!==h.address?` (${h.cidr})`:""]})]})]},`${h.name}-${h.family}-${h.address}`)})})]},f)})})}const wp={"lan-ipv4":"bg-emerald-500/15 text-emerald-700 dark:text-emerald-300","lan-ipv6":"bg-violet-500/15 text-violet-700 dark:text-violet-300",public:"bg-blue-500/15 text-blue-700 dark:text-blue-300",loopback:"bg-foreground-subtle/15 text-foreground-subtle"};function e9(){const e=ke(),t=Le(),n=Hg(void 0,{refetchInterval:3e4}),o=qg(void 0),s=Qg({onSuccess:()=>{e.invalidateQueries({queryKey:[["localNetwork"]]})}}),a=Ug({onSuccess:S=>{p(S.addresses),e.invalidateQueries({queryKey:[["localNetwork"]]})}}),i=Q(()=>n.data?.interfaces??[],[n.data]),l=typeof window<"u"?Number(window.location.port)||(window.location.protocol==="https:"?443:80):4e3,c=typeof window<"u"&&window.location.protocol==="https:"?"https":"http",d=Vg({port:l,scheme:c},{refetchInterval:3e4}),[f,p]=$([]),[m,h]=$(!1);Y(()=>{!m&&o.data&&(p(o.data.addresses),h(!0))},[o.data,m]);const g=o.data?.addresses??[],b=Q(()=>{if(f.length!==g.length)return!0;const S=[...f].sort(),M=[...g].sort();return S.some((P,I)=>P!==M[I])},[f,g]),x=()=>{s.mutate({addresses:[...f]})},v=()=>{p(g)},w=()=>{p([])},y=()=>{n.refetch(),d.refetch(),o.refetch()},N=async()=>{try{const S=await t.raceConnectionEndpoints({perCandidateTimeoutMs:1500});console.info("[network-addresses] race result",S)}catch(S){console.warn("[network-addresses] race failed",S)}},k=d.data?.endpoints??[];return r(It,{icon:an,title:"Network Addresses",subtitle:"Pick the local addresses SDK clients should race for the fastest path to this hub. Empty selection (auto) lets every non-loopback / non-link-local interface participate.",actions:u("div",{className:"flex items-center gap-2",children:[u(ze,{size:"sm",variant:"secondary",onClick:y,disabled:n.isLoading,children:[r(pt,{className:`h-3 w-3 ${n.isLoading?"animate-spin":""}`}),"Refresh"]}),r(ze,{size:"sm",variant:"secondary",onClick:N,children:"Probe race"})]}),children:u("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:[u(Ge,{children:[u("div",{className:"px-4 py-3 border-b border-border flex items-center justify-between",children:[u("div",{children:[r("div",{className:"text-sm font-semibold",children:"Allowed addresses"}),r("div",{className:"text-xs text-foreground-subtle",children:f.length===0?"Auto — every non-loopback / non-link-local interface participates.":`${f.length} pinned`})]}),u("div",{className:"flex items-center gap-1",children:[u(ze,{size:"sm",variant:"secondary",onClick:()=>a.mutate(void 0),disabled:a.isPending||s.isPending,title:"Re-run the auto-detection heuristic + overwrite the current allowlist with the best matches.",children:[r(eT,{className:"h-3 w-3"}),a.isPending?"Detecting…":"Best match"]}),u(ze,{size:"sm",variant:"secondary",onClick:w,disabled:f.length===0||s.isPending,children:[r(my,{className:"h-3 w-3"}),"Clear"]}),b&&r(ze,{size:"sm",variant:"secondary",onClick:v,disabled:s.isPending,children:"Discard"}),u(ze,{size:"sm",variant:"primary",onClick:x,disabled:!b||s.isPending,children:[r(FL,{className:"h-3 w-3"}),s.isPending?"Saving…":"Save"]})]})]}),r("div",{className:"p-4",children:r(J8,{mode:"multiple",interfaces:i,value:f,onChange:p,disabled:s.isPending,emptyMessage:n.isLoading?"Loading interfaces…":"No interfaces detected."})})]}),u(Ge,{children:[u("div",{className:"px-4 py-3 border-b border-border",children:[r("div",{className:"text-sm font-semibold",children:"Connection endpoints — priority order"}),r("div",{className:"text-xs text-foreground-subtle",children:"Live preview of the ranked candidate list the SDK would race against. Updates with each Save."})]}),r("div",{className:"p-4",children:k.length===0?r("div",{className:"text-xs text-foreground-subtle italic",children:d.isLoading?"Loading…":"No endpoints available."}):r("ul",{className:"space-y-1 text-xs",children:k.map(S=>u("li",{className:`flex items-center gap-2 flex-wrap ${S.plausible?"":"opacity-80"}`,children:[r("span",{className:"font-mono text-[10px] w-10 text-foreground-subtle",children:String(S.priority).padStart(4,"0")}),r("span",{className:`text-[10px] rounded-full px-2 py-0.5 font-medium ${wp[S.kind]??wp.loopback}`,children:S.kind}),S.interfaceKind!=="lan"&&S.interfaceKind!=="public"&&r("span",{className:"text-[10px] rounded px-1.5 py-0.5 bg-foreground-subtle/10 text-foreground-subtle font-medium uppercase",children:S.interfaceKind}),!S.plausible&&S.interfaceKind!=="loopback"&&u("span",{className:"inline-flex items-center gap-1 text-[10px] rounded-full px-2 py-0.5 font-medium bg-amber-500/15 text-amber-700 dark:text-amber-300",title:S.plausibleReason||void 0,children:[r(xt,{className:"h-2.5 w-2.5"}),"Unlikely usable"]}),r("span",{className:`font-mono break-all ${S.plausible?"text-foreground":"text-foreground-subtle"}`,children:S.baseUrl}),u("span",{className:"text-foreground-subtle",children:["— ",S.label]})]},`${S.priority}-${S.baseUrl}`))})})]})]})})}const t9={tailscale:"Tailscale",headscale:"Headscale",zerotier:"ZeroTier",other:"Custom"},n9={mesh:"bg-violet-500/15 text-violet-700 dark:text-violet-300",public:"bg-blue-500/15 text-blue-700 dark:text-blue-300"};function r9(){const e=ke(),t=Kg(void 0,{refetchInterval:5e3}),n=t.data??[],[o,s]=$(null),[a,i]=$({}),[l,c]=$({}),d=()=>{e.invalidateQueries({queryKey:[["meshOrchestrator"]]}),s(null)},f=Gg({onSuccess:d,onError:()=>s(null)}),p=Wg({onSuccess:d,onError:()=>s(null)});return r(It,{icon:ba,title:"Mesh Networks",subtitle:"Private VPN meshes that connect CamStack to your other devices (Tailscale, Headscale, …). Each provider can also expose this hub publicly via its ingress (Tailscale Funnel).",actions:r(Kt,{to:"/system/addons",children:r(ze,{variant:"primary",size:"sm",children:"Add mesh"})}),children:t.isLoading?r(Ge,{children:r("div",{className:"p-6 text-sm text-foreground-subtle",children:"Loading providers…"})}):n.length===0?r(Ge,{children:r(ko,{title:"No mesh-network providers installed",description:"Install a mesh addon (e.g. @camstack/addon-tailscale) to join this hub into a private VPN mesh.",action:r(Kt,{to:"/system/addons",children:r(ze,{variant:"primary",size:"sm",children:"Browse addons"})})})}):r("div",{className:"flex flex-col gap-4",children:n.map(m=>{const h=o===m.addonId,g=a[m.addonId]??"",b=l[m.addonId]??"",x=g.trim().length>=8;return u(Ge,{children:[u("div",{className:"flex items-start gap-4 p-4 border-b border-border",children:[r("div",{className:`h-10 w-10 rounded-lg flex items-center justify-center shrink-0 ${m.joined?"bg-emerald-500/15 text-emerald-700 dark:text-emerald-300":"bg-foreground-subtle/15 text-foreground-subtle"}`,children:r(an,{className:"h-5 w-5"})}),u("div",{className:"flex-1 min-w-0",children:[u("div",{className:"flex items-center gap-2 flex-wrap",children:[r("span",{className:"font-semibold text-foreground",children:m.displayName}),r("span",{className:"text-[10px] rounded-full px-2 py-0.5 font-medium bg-blue-500/15 text-blue-700 dark:text-blue-300",children:t9[m.kind]??m.kind}),r("span",{className:`text-[10px] rounded-full px-2 py-0.5 font-medium ${m.joined?"bg-emerald-500/15 text-emerald-700 dark:text-emerald-300":"bg-foreground-subtle/15 text-foreground-subtle"}`,children:m.joined?"Joined":"Not joined"}),m.joined&&u("span",{className:"text-[10px] rounded-full px-2 py-0.5 font-medium bg-foreground-subtle/15 text-foreground-subtle",children:[m.peerCount," peer",m.peerCount===1?"":"s"]})]}),r("div",{className:"text-xs text-foreground-subtle mt-1 font-mono",children:m.addonId}),m.joined&&u("div",{className:"mt-2 grid grid-cols-1 sm:grid-cols-2 gap-x-4 gap-y-1 text-xs",children:[m.meshIp&&u("div",{className:"flex items-center gap-1.5",children:[r("span",{className:"text-foreground-subtle",children:"Mesh IP:"}),r("span",{className:"font-mono text-foreground",children:m.meshIp})]}),m.magicDnsHostname&&u("div",{className:"flex items-center gap-1.5",children:[r("span",{className:"text-foreground-subtle",children:"MagicDNS:"}),r("span",{className:"font-mono text-foreground break-all",children:m.magicDnsHostname})]})]}),m.joined&&m.endpoints.length>0&&u("div",{className:"mt-3 flex flex-col gap-1",children:[r("div",{className:"text-[11px] font-semibold text-foreground-subtle uppercase tracking-wide",children:"Endpoints"}),m.endpoints.map(v=>u("div",{className:"flex items-center gap-2 text-xs",children:[u("span",{className:`text-[10px] rounded-full px-2 py-0.5 font-medium ${n9[v.scope]??"bg-foreground-subtle/15 text-foreground-subtle"}`,children:[v.scope==="public"?r(br,{className:"inline h-2.5 w-2.5 mr-0.5"}):null,v.label]}),u("a",{href:v.url,target:"_blank",rel:"noopener noreferrer",className:"text-emerald-700 dark:text-emerald-300 hover:underline break-all flex items-center gap-1",children:[r(Gc,{className:"h-3 w-3 shrink-0"}),v.url]})]},v.id))]}),m.error&&r("div",{className:"text-xs text-danger mt-2",children:m.error})]}),r("div",{className:"flex flex-col items-end gap-2 shrink-0",children:m.joined?u(ze,{size:"sm",variant:"secondary",disabled:h,onClick:()=>{s(m.addonId),p.mutate({addonId:m.addonId})},children:[h?r(Pe,{className:"h-3 w-3 animate-spin"}):r(cy,{className:"h-3 w-3"}),"Leave"]}):u("div",{className:"flex flex-col gap-1.5 items-stretch w-64",children:[r("input",{type:"password",autoComplete:"off",placeholder:"Auth key (tskey-auth-…)",value:g,onChange:v=>i(w=>({...w,[m.addonId]:v.target.value})),className:"rounded-md border border-border bg-surface px-2 py-1 text-xs font-mono text-foreground placeholder:text-foreground-subtle focus:outline-none focus:ring-1 focus:ring-primary"}),r("input",{type:"text",placeholder:"Hostname (optional)",value:b,onChange:v=>c(w=>({...w,[m.addonId]:v.target.value})),className:"rounded-md border border-border bg-surface px-2 py-1 text-xs font-mono text-foreground placeholder:text-foreground-subtle focus:outline-none focus:ring-1 focus:ring-primary"}),u(ze,{size:"sm",variant:"primary",disabled:h||!x,onClick:()=>{s(m.addonId),f.mutate({addonId:m.addonId,authKey:g.trim(),hostname:b.trim()?b.trim():void 0})},children:[h?r(Pe,{className:"h-3 w-3 animate-spin"}):r(iL,{className:"h-3 w-3"}),"Join"]})]})})]}),r("div",{className:"p-4",children:r(nd,{addonId:m.addonId,maxHeight:"max-h-72"})})]},m.addonId)})})})}function o9(){return r("div",{className:"flex flex-col",children:r("div",{className:"px-6 pt-6",children:r(td,{tabs:[{id:"addresses",label:"Network Addresses",icon:ln,content:r(e9,{})},{id:"remote-access",label:"Remote Access",icon:br,content:r(K8,{})},{id:"mesh",label:"Mesh Networks",icon:ba,content:r(r9,{})},{id:"turn",label:"TURN Servers",icon:an,content:r(W8,{})}]})})})}function s9(e){const t=e.basePath;if(typeof t=="string"&&t.length>0)return t;const n=Object.keys(e);return n.length===0?"":n.join(", ")}function a9({location:e,onEdit:t,onDelete:n,onSetDefault:o}){const s=s9(e.config);return u("div",{className:"flex items-center gap-3 px-3 py-2 border-t border-border first:border-t-0 hover:bg-primary/5",children:[u("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:[r("div",{className:"w-[88px] shrink-0",children:e.isDefault?u("span",{className:"inline-flex items-center gap-0.5 rounded bg-primary/10 border border-primary/20 px-1.5 py-0.5 text-[10px] font-semibold text-primary uppercase tracking-wide",title:"Default location for this type",children:[r(oi,{className:"h-2.5 w-2.5 fill-primary"}),"Default"]}):u("button",{onClick:()=>o(e),className:"inline-flex items-center gap-0.5 rounded border border-border px-1.5 py-0.5 text-[10px] font-medium text-foreground-subtle hover:text-foreground hover:bg-primary/10 hover:border-primary/30 uppercase tracking-wide",title:"Promote to default for this type",children:[r(oi,{className:"h-2.5 w-2.5"}),"Set default"]})}),r("span",{className:"text-[10px] uppercase tracking-wide text-foreground-subtle bg-background border border-border rounded px-1.5 py-0.5 font-mono",children:e.providerId}),e.isSystem&&r("span",{className:"text-[10px] uppercase tracking-wide text-foreground-subtle bg-background border border-border rounded px-1.5 py-0.5",title:"System-managed location — cannot be deleted; edit config to relocate",children:"system"}),u("div",{className:"min-w-0",children:[r("div",{className:"text-xs font-medium text-foreground truncate",children:e.displayName}),s&&r("div",{className:"text-[10px] text-foreground-subtle truncate font-mono",children:s})]})]}),u("div",{className:"flex items-center gap-1 shrink-0",children:[!e.isDefault&&u("button",{onClick:()=>o(e),className:"inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] font-medium text-foreground-subtle border border-border hover:text-foreground hover:bg-primary/10",title:"Set as default for this type",children:[r(oi,{className:"h-3 w-3"}),"Set default"]}),u("button",{onClick:()=>t(e),className:"inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] font-medium text-foreground-subtle border border-border hover:text-foreground hover:bg-primary/10",children:[r(Po,{className:"h-3 w-3"}),"Edit"]}),!e.isSystem&&ps[e.type]!=="singleton"&&r("button",{onClick:()=>n(e),className:"inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] font-medium text-danger hover:bg-danger/10",title:"Delete location",children:r(We,{className:"h-3 w-3"})})]})]})}function i9({type:e,displayName:t,description:n,locations:o,onAdd:s,onEdit:a,onDelete:i,onSetDefault:l}){const c=Q(()=>{const d=[...o];return d.sort((f,p)=>f.isDefault!==p.isDefault?f.isDefault?-1:1:f.displayName.localeCompare(p.displayName)),d},[o]);return u("div",{className:"rounded-lg border border-border bg-surface",children:[u("div",{className:"flex items-start justify-between border-b border-border px-3 py-2",children:[u("div",{className:"space-y-0.5",children:[u("div",{className:"flex items-center gap-2",children:[r("span",{className:"text-sm font-semibold text-foreground capitalize",children:t}),r("span",{className:"text-[10px] uppercase tracking-wide text-foreground-subtle bg-background border border-border rounded px-1.5 py-0.5 font-mono",children:e})]}),n&&r("p",{className:"text-[11px] text-foreground-subtle",children:n}),ps[e]==="singleton"&&r("p",{className:"text-[10px] text-foreground-subtle italic",children:"Singleton — one location per type. Edit the existing entry; it can't be split."})]}),ps[e]==="multi"&&u("button",{onClick:()=>s(e),className:"inline-flex items-center gap-1 rounded bg-primary px-2 py-1 text-[11px] font-medium text-primary-foreground hover:bg-primary/90",children:[r(Ot,{className:"h-3 w-3"}),"Add"]})]}),c.length===0?r("div",{className:"px-3 py-4 text-center text-[11px] text-foreground-subtle italic",children:ps[e]==="multi"?'No location registered. Click "Add" to register one.':"No location registered yet — should be auto-seeded at next boot."}):r("div",{children:c.map(d=>r(a9,{location:d,onEdit:a,onDelete:i,onSetDefault:l},d.id))})]})}function l9(e){const t=e.trim().toLowerCase();return t.length===0?"":t.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Np(e,t){const n=l9(t),o=n.length>0?n:"default";return`${e}:${o}`}function s0({initialType:e,onClose:t,onCreated:n}){const o=ke(),s=Le().trpcClient,[a,i]=$("picker"),[l,c]=$(e),[d,f]=$(null),[p,m]=$({}),[h,g]=$(""),[b,x]=$(null),[v,w]=$(!1),[y,N]=$(null),[k,S]=$(!1),M=Nc(),P=Q(()=>{const D=M.data;return Array.isArray(D)?D.filter(R=>R.supportedLocationTypes.includes(l)):[]},[M.data,l]),I=M.isLoading,F=da({onSuccess:()=>{o.invalidateQueries({queryKey:[["storage","listLocations"]]}),n()}}),E=Q(()=>b!==null&&b.length>0?b:Np(l,h),[l,h,b]),B=async()=>{if(d){S(!0),N(null);try{const R=await(L=>s.storage.testConfig.query(L))({providerId:d.providerId,config:p});N(R)}catch(D){N({ok:!1,error:D instanceof Error?D.message:String(D)})}finally{S(!1)}}},O=()=>{d&&F.mutate({id:E,type:l,displayName:h.trim(),providerId:d.providerId,config:p,isDefault:v})},A={picker:"Add Location — Pick provider",config:`Add Location — ${d?.displayName??""}`,naming:"Add Location — Name & defaults"};return r("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-background/80 backdrop-blur-sm",onClick:t,children:u("div",{className:"w-full max-w-md rounded-xl border border-border bg-surface shadow-2xl",onClick:D=>D.stopPropagation(),children:[u("div",{className:"flex items-start justify-between border-b border-border px-4 py-3",children:[u("div",{className:"space-y-0.5",children:[r("h2",{className:"text-sm font-semibold text-foreground",children:A[a]}),u("p",{className:"text-xs text-foreground-subtle",children:["Type: ",r("span",{className:"font-mono",children:l})]})]}),r("button",{onClick:t,className:"text-foreground-subtle hover:text-foreground",children:r(qe,{className:"h-4 w-4"})})]}),a==="picker"&&u("div",{className:"p-4 space-y-2",children:[I&&r("div",{className:"text-xs text-foreground-subtle animate-pulse",children:"Loading providers…"}),!I&&P.length===0&&u("div",{className:"rounded border border-border bg-background px-3 py-4 text-center text-xs text-foreground-subtle",children:['No storage-provider supports type "',l,'". Install a compatible addon (e.g. ',r("code",{className:"font-mono",children:"remote-storage"}),") to enable it."]}),P.map(D=>u("button",{onClick:()=>{f(D),i("config")},className:"flex w-full items-center gap-3 rounded-lg border border-border bg-background p-3 text-left hover:border-primary/40 hover:bg-primary/5 transition-colors",children:[u("div",{className:"flex-1 min-w-0",children:[r("p",{className:"text-xs font-semibold text-foreground",children:D.displayName}),r("p",{className:"text-[10px] text-foreground-subtle font-mono mt-0.5 truncate",children:D.providerId})]}),r(Mt,{className:"h-4 w-4 text-foreground-subtle flex-shrink-0"})]},D.providerId))]}),a==="config"&&d&&u("div",{className:"p-4 space-y-3 max-h-[60vh] overflow-y-auto",children:[r(Nn,{schema:d.configSchema,values:p,onChange:m}),y&&r("div",{className:`rounded border px-3 py-2 text-[11px] ${y.ok?"border-success/30 bg-success/5 text-success":"border-danger/30 bg-danger/5 text-danger"}`,children:y.ok?"Connection OK.":`Test failed: ${y.error??"unknown error"}`}),u("div",{className:"flex items-center justify-between pt-1",children:[r("button",{onClick:()=>i("picker"),className:"rounded px-3 py-1.5 text-xs text-foreground-subtle border border-border hover:text-foreground",children:"Back"}),u("div",{className:"flex items-center gap-2",children:[r("button",{onClick:()=>{B()},disabled:k,className:"rounded border border-border px-3 py-1.5 text-xs text-foreground hover:bg-primary/10 disabled:opacity-50",children:k?"Testing…":"Test connection"}),r("button",{onClick:()=>i("naming"),className:"rounded bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90",children:"Next"})]})]})]}),a==="naming"&&d&&u("div",{className:"p-4 space-y-3",children:[u("div",{className:"space-y-1",children:[r("label",{className:"text-[10px] uppercase tracking-wide text-foreground-subtle",children:"Display name"}),r("input",{type:"text",value:h,onChange:D=>g(D.target.value),placeholder:`${l} on ${d.displayName}`,className:"w-full rounded border border-border bg-background px-2 py-1.5 text-xs text-foreground focus:outline-none focus:ring-1 focus:ring-primary"})]}),u("div",{className:"space-y-1",children:[u("label",{className:"text-[10px] uppercase tracking-wide text-foreground-subtle",children:["Id ",r("span",{className:"lowercase tracking-normal text-foreground-subtle",children:"— auto-derived; override if needed"})]}),r("input",{type:"text",value:E,onChange:D=>x(D.target.value),placeholder:Np(l,h),className:"w-full rounded border border-border bg-background px-2 py-1.5 text-xs text-foreground font-mono focus:outline-none focus:ring-1 focus:ring-primary"}),u("p",{className:"text-[10px] text-foreground-subtle",children:["Format: ",r("code",{className:"font-mono",children:"<type>:<slug>"}),". Lowercase letters, digits, and hyphens only."]})]}),u("label",{className:"flex items-start gap-2 rounded border border-border bg-background px-3 py-2 cursor-pointer hover:bg-primary/5",children:[r("input",{type:"checkbox",checked:v,onChange:D=>w(D.target.checked),className:"accent-primary mt-0.5"}),u("div",{className:"space-y-0.5",children:[u("div",{className:"text-xs font-medium text-foreground",children:['Mark as default for type "',l,'"']}),u("div",{className:"text-[10px] text-foreground-subtle",children:["Setting this as default will demote the current default for this type. References like"," ",u("code",{className:"font-mono",children:['"',l,'"']})," resolve to whichever location is the default."]})]})]}),F.isError&&r("div",{className:"rounded border border-danger/30 bg-danger/5 text-danger px-3 py-2 text-[11px]",children:F.error instanceof Error?F.error.message:String(F.error)}),u("div",{className:"flex items-center justify-between pt-1",children:[r("button",{onClick:()=>i("config"),className:"rounded px-3 py-1.5 text-xs text-foreground-subtle border border-border hover:text-foreground",children:"Back"}),u("div",{className:"flex items-center gap-2",children:[r("button",{onClick:()=>{c(e),f(null),m({}),g(""),x(null),w(!1),N(null),i("picker")},className:"rounded px-3 py-1.5 text-xs text-foreground-subtle border border-border hover:text-foreground",children:"Reset"}),u("button",{onClick:O,disabled:F.isPending||h.trim().length===0,className:"inline-flex items-center gap-1.5 rounded bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50",children:[F.isPending?r(Pe,{className:"h-3.5 w-3.5 animate-spin"}):null,F.isPending?"Saving…":"Save"]})]})]})]})]})})}function c9({location:e,onClose:t,onSaved:n}){const o=ke(),s=Le().trpcClient,[a,i]=$({...e.config}),[l,c]=$(e.displayName),[d,f]=$(null),[p,m]=$(!1),h=Nc(),g=Q(()=>{const w=h.data;return Array.isArray(w)?w.find(N=>N.providerId===e.providerId)??null:null},[h.data,e.providerId]),b=da({onSuccess:()=>{o.invalidateQueries({queryKey:[["storage","listLocations"]]}),n()}}),x=async()=>{m(!0),f(null);try{const y=await(N=>s.storage.testConfig.query(N))({providerId:e.providerId,config:a});f(y)}catch(w){f({ok:!1,error:w instanceof Error?w.message:String(w)})}finally{m(!1)}},v=()=>{b.mutate({id:e.id,type:e.type,providerId:e.providerId,isDefault:e.isDefault,displayName:l.trim(),config:a})};return r("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-background/80 backdrop-blur-sm",onClick:t,children:u("div",{className:"w-full max-w-md rounded-xl border border-border bg-surface shadow-2xl",onClick:w=>w.stopPropagation(),children:[u("div",{className:"flex items-start justify-between border-b border-border px-4 py-3",children:[u("div",{className:"space-y-0.5",children:[u("h2",{className:"text-sm font-semibold text-foreground",children:["Edit ",e.displayName]}),u("p",{className:"text-xs text-foreground-subtle",children:[r("span",{className:"font-mono",children:e.id})," · ",g?.displayName??e.providerId]})]}),r("button",{onClick:t,className:"text-foreground-subtle hover:text-foreground",children:r(qe,{className:"h-4 w-4"})})]}),u("div",{className:"p-4 space-y-3 max-h-[60vh] overflow-y-auto",children:[u("div",{className:"space-y-1",children:[r("label",{className:"text-[10px] uppercase tracking-wide text-foreground-subtle",children:"Display name"}),r("input",{type:"text",value:l,onChange:w=>c(w.target.value),className:"w-full rounded border border-border bg-background px-2 py-1.5 text-xs text-foreground focus:outline-none focus:ring-1 focus:ring-primary"})]}),g&&r(Nn,{schema:g.configSchema,values:a,onChange:i}),!g&&!h.isLoading&&u("div",{className:"rounded border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-[11px] text-amber-700 dark:text-amber-300",children:["Provider ",r("code",{className:"font-mono",children:e.providerId})," is no longer registered. Field schema unavailable; raw config is preserved on save."]}),d&&r("div",{className:`rounded border px-3 py-2 text-[11px] ${d.ok?"border-success/30 bg-success/5 text-success":"border-danger/30 bg-danger/5 text-danger"}`,children:d.ok?"Connection OK.":`Test failed: ${d.error??"unknown error"}`}),b.isError&&r("div",{className:"rounded border border-danger/30 bg-danger/5 text-danger px-3 py-2 text-[11px]",children:b.error instanceof Error?b.error.message:String(b.error)})]}),u("div",{className:"flex items-center justify-between gap-2 border-t border-border px-4 py-3",children:[r("button",{onClick:t,className:"rounded px-3 py-1.5 text-xs text-foreground-subtle border border-border hover:text-foreground",children:"Cancel"}),u("div",{className:"flex items-center gap-2",children:[r("button",{onClick:()=>{x()},disabled:p||!g,className:"rounded border border-border px-3 py-1.5 text-xs text-foreground hover:bg-primary/10 disabled:opacity-50",children:p?"Testing…":"Test connection"}),u("button",{onClick:v,disabled:b.isPending||l.trim().length===0,className:"inline-flex items-center gap-1.5 rounded bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50",children:[b.isPending?r(Pe,{className:"h-3.5 w-3.5 animate-spin"}):null,b.isPending?"Saving…":"Save"]})]})]})]})})}const d9={data:"Data",media:"Media",recordings:"Recordings","recordings-high":"Recordings (High)","recordings-low":"Recordings (Low)","recordings-clips":"Recordings (Clips)","event-images":"Event Images",models:"Models","addons-data":"Addons Data",cache:"Cache",logs:"Logs",backups:"Backups"},u9={backups:"Snapshot archives. Default landing for `backup-orchestrator`.",recordings:"Continuous recordings (combined high + low + clips when no slot is specified).","recordings-high":"High-quality continuous recordings.","recordings-low":"Low-quality continuous recordings.","recordings-clips":"Event clips (motion / detection triggers).","event-images":"Detection snapshots, thumbnails, and crops.",models:"ML model files. Read by inference-engine addons.",logs:"Long-term log archives."};function p9(){const e=ke(),t=rt(),{data:n,isLoading:o,isError:s}=Kb({}),[a,i]=$(null),[l,c]=$(null),d=Gb({onSuccess:()=>{e.invalidateQueries({queryKey:[["storage","listLocations"]]})}}),f=da({onSuccess:()=>{e.invalidateQueries({queryKey:[["storage","listLocations"]]})}}),p=g=>{g.isDefault||f.mutate({id:g.id,type:g.type,providerId:g.providerId,displayName:g.displayName,config:g.config,isDefault:!0})},m=async g=>{if(g.isDefault){await t({title:"Cannot delete default location",message:`"${g.displayName}" is the default for type "${g.type}". Mark another location as default first, then delete this one.`,confirmLabel:"OK",variant:"warning"});return}await t({title:`Delete location "${g.displayName}"?`,message:"This removes the location record. Files on disk are not deleted; the underlying directory or remote path stays untouched.",confirmLabel:"Delete",variant:"danger"})&&d.mutate({id:g.id})},h=Q(()=>{const g=new Map;for(const b of Ed)g.set(b,[]);for(const b of n??[]){const x=g.get(b.type);x?x.push(b):g.set(b.type,[b])}return g},[n]);return u(It,{icon:lo,title:"Storage Locations",subtitle:u(ve,{children:["Register where each kind of data lives. Each type can have multiple locations — one is the default, the rest are addressable by their fully-qualified id (",r("code",{className:"font-mono",children:"<type>:<slug>"}),")."]}),children:[o&&r("div",{className:"text-xs text-foreground-subtle animate-pulse",children:"Loading locations…"}),s&&r("div",{className:"text-xs text-danger",children:"Failed to load storage locations."}),!o&&!s&&r("div",{className:"space-y-3",children:Ed.map(g=>r(i9,{type:g,displayName:d9[g],description:u9[g],locations:h.get(g)??[],onAdd:b=>i(b),onEdit:b=>c(b),onDelete:b=>{m(b)},onSetDefault:b=>p(b)},g))}),a!==null&&r(s0,{initialType:a,onClose:()=>i(null),onCreated:()=>{e.invalidateQueries({queryKey:[["storage","listLocations"]]}),i(null)}}),l!==null&&r(c9,{location:l,onClose:()=>c(null),onSaved:()=>{e.invalidateQueries({queryKey:[["storage","listLocations"]]}),c(null)}})]})}const f9=[["backup","listDestinations"]],m9=["backup","listArchives"];function h9({destinationId:e,restoreSupported:t,onOpenRestoreWizard:n}){const o=ke(),s=rt(),{data:a,isLoading:i,isError:l}=fc({destinationId:e}),c=a??[],d=pg({onSuccess:()=>{o.invalidateQueries({queryKey:[[...m9]]}),o.invalidateQueries({queryKey:f9})}}),f=q(async b=>{await s({title:"Delete this archive?",message:`Permanently deletes "${b.label??b.id}" and frees ${Nt(b.sizeBytes)}.`,confirmLabel:"Delete",variant:"danger"})&&d.mutate({destinationId:e,backupId:b.id})},[s,e,d]),[p,m]=$(null),h=q(async b=>{m(b.id);try{const x=localStorage.getItem("camstack_admin_token"),v={};x&&(v.Authorization=`Bearer ${x}`);const w=await fetch(g9(e,b.id),{headers:v});if(!w.ok)throw new Error(`download failed: ${w.status} ${w.statusText}`);const y=await w.blob(),N=URL.createObjectURL(y),k=document.createElement("a");k.href=N,k.download=`${b.label??b.id}.tar.gz`,document.body.appendChild(k),k.click(),k.remove(),URL.revokeObjectURL(N)}finally{m(null)}},[e]),g=Q(()=>[...c].sort((b,x)=>x.createdAt-b.createdAt),[c]);return i?r("div",{className:"text-xs text-foreground-subtle animate-pulse py-2",children:"Loading archives…"}):l?r("div",{className:"text-xs text-danger py-2",children:"Failed to read manifest for this destination"}):g.length===0?r("div",{className:"text-xs text-foreground-subtle italic py-2",children:"No archives at this destination yet."}):r("div",{className:"rounded border border-border bg-surface overflow-x-auto",children:u("table",{className:"w-full text-xs min-w-[640px]",children:[r("thead",{children:u("tr",{className:"text-foreground-subtle bg-background/30",children:[r("th",{className:"text-left px-3 py-1.5 font-medium",children:"When"}),r("th",{className:"text-left px-3 py-1.5 font-medium",children:"Label"}),r("th",{className:"text-left px-3 py-1.5 font-medium",children:"Includes"}),r("th",{className:"text-right px-3 py-1.5 font-medium",children:"Size"}),r("th",{className:"text-right px-3 py-1.5 font-medium w-52",children:"Actions"})]})}),r("tbody",{children:g.map(b=>u("tr",{className:"border-t border-border hover:bg-primary/5",children:[r("td",{className:"px-3 py-1.5 text-foreground tabular-nums",children:b9(b.createdAt)}),r("td",{className:"px-3 py-1.5 text-foreground",children:b.label??r("span",{className:"text-foreground-subtle italic",children:"—"})}),r("td",{className:"px-3 py-1.5 text-foreground-subtle",children:b.locations.join(", ")}),r("td",{className:"px-3 py-1.5 text-foreground text-right tabular-nums",children:Nt(b.sizeBytes)}),r("td",{className:"px-3 py-1.5",children:u("div",{className:"flex items-center justify-end gap-1",children:[u("button",{onClick:()=>{h(b)},disabled:p===b.id,className:"inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] font-medium text-foreground-subtle hover:text-foreground hover:bg-primary/10 disabled:opacity-50",title:"Download archive",children:[p===b.id?r(Pe,{className:"h-3 w-3 animate-spin"}):r(wn,{className:"h-3 w-3"}),"Download"]}),t&&n&&u("button",{onClick:()=>n({destinationId:e,archiveId:b.id}),className:"inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] font-medium text-primary hover:bg-primary/10",title:"Restore from this archive",children:[r(bt,{className:"h-3 w-3"}),"Restore"]}),r("button",{onClick:()=>{f(b)},disabled:d.isPending,className:"inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] font-medium text-danger hover:bg-danger/10 disabled:opacity-50",title:"Delete archive",children:d.isPending?r(Pe,{className:"h-3 w-3 animate-spin"}):r(We,{className:"h-3 w-3"})})]})})]},b.id))})]})})}function g9(e,t){return`/api/backup/download/${encodeURIComponent(e)}/${encodeURIComponent(t)}`}function b9(e){return new Date(e).toLocaleString(void 0,{day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit"})}const a0=[{id:"manual",label:"Manual only",cron:""},{id:"hourly",label:"Every hour",cron:"0 * * * *",description:"On the hour"},{id:"every-3h",label:"Every 3 hours",cron:"0 */3 * * *",description:"00:00, 03:00, 06:00, 09:00 …"},{id:"every-6h",label:"Every 6 hours",cron:"0 */6 * * *",description:"00:00, 06:00, 12:00, 18:00"},{id:"daily-3am",label:"Daily at 03:00",cron:"0 3 * * *",description:"Every night at 3 AM"},{id:"weekly-sun",label:"Weekly Sunday 03:00",cron:"0 3 * * 0",description:"Sunday morning at 3 AM"}];function x9(e){const t=e.trim();for(const n of a0)if(n.cron===t)return n.id;return"custom"}function y9({value:e,onChange:t,previewCount:n=5,disabled:o=!1}){const s=x9(e),[a,i]=$(s==="custom");Y(()=>{s!=="custom"&&i(!1)},[s]);const l=N9(e,250),c=mg({cron:l,count:n},{enabled:l.trim().length>0}),d=c.data??null,f=m=>{i(!1),t(m.cron)},p=a||s==="custom";return u("div",{className:"space-y-3",children:[u("div",{className:"space-y-1",children:[r("div",{className:"text-[10px] uppercase tracking-wide text-foreground-subtle",children:"Schedule preset"}),u("div",{className:"flex flex-wrap gap-1.5",children:[a0.map(m=>{const h=!a&&s===m.id;return r("button",{type:"button",onClick:()=>f(m),disabled:o,className:"rounded border px-2 py-1 text-[11px] transition-colors disabled:opacity-50 "+(h?"border-primary bg-primary/10 text-primary":"border-border bg-background text-foreground-subtle hover:bg-primary/5 hover:text-foreground"),title:m.description??m.label,children:m.label},m.id)}),r("button",{type:"button",onClick:()=>{i(!0),e.trim().length===0&&t("0 3 * * *")},disabled:o,className:"rounded border px-2 py-1 text-[11px] transition-colors disabled:opacity-50 "+(p?"border-primary bg-primary/10 text-primary":"border-border bg-background text-foreground-subtle hover:bg-primary/5 hover:text-foreground"),children:"Custom…"})]})]}),p&&u("div",{className:"space-y-1",children:[r("div",{className:"text-[10px] uppercase tracking-wide text-foreground-subtle",children:"Cron expression (5-field POSIX)"}),r("input",{type:"text",value:e,onChange:m=>t(m.target.value),disabled:o,placeholder:"0 3 * * *",spellCheck:!1,className:"w-full rounded border border-border bg-background px-2 py-1.5 text-xs font-mono text-foreground placeholder:text-foreground-subtle focus:outline-none focus:ring-1 focus:ring-primary"}),u("p",{className:"text-[10px] text-foreground-subtle",children:["Format: ",r("span",{className:"font-mono",children:"minute hour day-of-month month day-of-week"})," · all times server-local"]})]}),r(v9,{cron:l,preview:d,loading:c.isFetching})]})}function v9({cron:e,preview:t,loading:n}){return n&&t===null?u("div",{className:"flex items-center gap-2 rounded border border-border bg-background/40 px-3 py-2 text-[11px] text-foreground-subtle",children:[r(Pe,{className:"h-3 w-3 animate-spin"}),"Validating…"]}):t===null?null:t.ok?t.nextRuns.length===0?r("div",{className:"rounded border border-border bg-background/40 px-3 py-2 text-[11px] text-foreground-subtle",children:"No future runs match this expression."}):u("div",{className:"space-y-1",children:[r("div",{className:"text-[10px] uppercase tracking-wide text-foreground-subtle",children:"Next runs"}),r("ul",{className:"rounded border border-border bg-background/40 divide-y divide-border",children:t.nextRuns.map((o,s)=>u("li",{className:"flex items-center justify-between px-3 py-1.5 text-[11px]",children:[r("span",{className:"text-foreground tabular-nums",children:new Date(o).toLocaleString()}),r("span",{className:"text-foreground-subtle text-[10px] tabular-nums",children:w9(o)})]},`${o}-${s}`))})]}):r("div",{className:"rounded border border-danger/40 bg-danger/10 px-3 py-2 text-[11px] text-danger",children:t.error??"Invalid cron expression"})}function w9(e){const t=e-Date.now();if(t<=0)return"now";const n=Math.floor(t/1e3);if(n<60)return`in ${n}s`;const o=Math.floor(n/60);if(o<60)return`in ${o}m`;const s=Math.floor(o/60);return s<24?`in ${s}h`:`in ${Math.floor(s/24)}d`}function N9(e,t){const[n,o]=$(e),s=Q(()=>e,[e]);return Y(()=>{const a=setTimeout(()=>o(s),t);return()=>clearTimeout(a)},[s,t]),n}const k9=[["backup","listDestinations"]];function S9({onCreateAt:e,onOpenRestoreWizard:t}){const{data:n,isLoading:o,isError:s}=pc(),a=n??[],[i,l]=$(null),c=f=>{l(p=>p===f?null:f)},d=P9();return o?r("div",{className:"text-xs text-foreground-subtle animate-pulse",children:"Loading destinations…"}):s?r("div",{className:"text-xs text-danger",children:"Failed to load destinations"}):a.length===0?r("div",{className:"rounded-lg border border-border bg-surface px-4 py-8 text-center",children:r("p",{className:"text-xs text-foreground-subtle",children:"No `backups`-typed storage locations registered. Add one in Settings → Storage to begin."})}):r("div",{className:"rounded-lg border border-border bg-surface overflow-x-auto",children:u("table",{className:"w-full text-xs min-w-[720px]",children:[r("thead",{children:u("tr",{className:"text-foreground-subtle border-b border-border bg-background/40",children:[r("th",{className:"text-left px-3 py-2 font-medium w-6"}),r("th",{className:"text-left px-3 py-2 font-medium",children:"Destination"}),r("th",{className:"text-left px-3 py-2 font-medium w-20",children:"Enabled"}),r("th",{className:"text-left px-3 py-2 font-medium w-28",children:"Retention"}),r("th",{className:"text-left px-3 py-2 font-medium w-56",children:"Schedule"}),r("th",{className:"text-left px-3 py-2 font-medium w-44",children:"Last success"}),r("th",{className:"text-right px-3 py-2 font-medium w-44",children:"Actions"})]})}),r("tbody",{children:a.map(f=>{const p=d.get(f.id);return r(C9,{row:f,isOpen:i===f.id,onToggle:()=>c(f.id),onCreateAt:e,liveLastSuccessAt:p?.at,liveLastSuccessSizeBytes:p?.sizeBytes,...t?{onOpenRestoreWizard:t}:{}},f.id)})})]})})}function C9({row:e,isOpen:t,onToggle:n,onCreateAt:o,onOpenRestoreWizard:s,liveLastSuccessAt:a,liveLastSuccessSizeBytes:i}){const l=ke(),c=fg({onSuccess:()=>{l.invalidateQueries({queryKey:k9})}}),[d,f]=$(String(e.retentionCount));Y(()=>{f(String(e.retentionCount))},[e.retentionCount]);const[p,m]=$(!1),h=q(x=>{c.mutate({locationId:e.id,enabled:x,retentionCount:e.retentionCount,...e.label!==void 0?{label:e.label}:{},...e.cron!==void 0?{cron:e.cron}:{}})},[c,e.id,e.retentionCount,e.label,e.cron]),g=q(()=>{const x=Number.parseInt(d,10);if(Number.isNaN(x)||x<1){f(String(e.retentionCount));return}x!==e.retentionCount&&c.mutate({locationId:e.id,enabled:e.enabled,retentionCount:x,...e.label!==void 0?{label:e.label}:{},...e.cron!==void 0?{cron:e.cron}:{}})},[c,d,e.id,e.enabled,e.retentionCount,e.label,e.cron]),b=q(x=>{c.mutate({locationId:e.id,enabled:e.enabled,retentionCount:e.retentionCount,...e.label!==void 0?{label:e.label}:{},cron:x},{onSuccess:()=>{m(!1)}})},[c,e.id,e.enabled,e.retentionCount,e.label]);return u(ve,{children:[u("tr",{className:"border-t border-border first:border-t-0 hover:bg-primary/5",children:[r("td",{className:"px-2 py-2",children:r("button",{onClick:n,className:"inline-flex items-center justify-center rounded p-1 text-foreground-subtle hover:bg-primary/10 hover:text-foreground",title:t?"Hide archives":"Show archives",children:t?r(Rt,{className:"h-3.5 w-3.5"}):r(Mt,{className:"h-3.5 w-3.5"})})}),r("td",{className:"px-3 py-2",children:u("button",{onClick:n,className:"text-left hover:underline focus:outline-none",title:"View archives",children:[r("div",{className:"text-foreground font-medium",children:e.displayName}),u("div",{className:"flex items-center gap-1.5 mt-0.5",children:[r("span",{className:"text-[10px] uppercase tracking-wide text-foreground-subtle bg-background border border-border rounded px-1.5 py-0.5",children:e.kind}),r("span",{className:"text-[10px] text-foreground-subtle font-mono",children:e.id})]})]})}),r("td",{className:"px-3 py-2",children:r("label",{className:"inline-flex items-center cursor-pointer",children:r("input",{type:"checkbox",className:"accent-primary",checked:e.enabled,disabled:c.isPending,onChange:x=>h(x.target.checked)})})}),r("td",{className:"px-3 py-2",children:r("input",{type:"number",min:1,max:1e3,value:d,disabled:c.isPending,onChange:x=>f(x.target.value),onBlur:g,onKeyDown:x=>{x.key==="Enter"&&x.target.blur(),x.key==="Escape"&&f(String(e.retentionCount))},className:"w-16 rounded border border-border bg-background px-2 py-1 text-xs text-foreground focus:outline-none focus:ring-1 focus:ring-primary"})}),r("td",{className:"px-3 py-2",children:r(M9,{cron:e.cron,nextRunAt:e.nextRunAt,onEdit:()=>m(!0),disabled:c.isPending})}),r("td",{className:"px-3 py-2 text-foreground-subtle",children:(()=>{const x=E9(a,e.lastSuccessAt),v=x===a?i:e.lastSuccessSizeBytes;return x!==void 0?r($9,{at:x,sizeBytes:v}):r("span",{className:"italic",children:"Never"})})()}),r("td",{className:"px-3 py-2",children:r("div",{className:"flex items-center justify-end gap-1.5",children:e.triggerSupported&&u("button",{onClick:()=>o(e),className:"inline-flex items-center gap-1 rounded bg-primary px-2 py-1 text-[11px] font-medium text-primary-foreground hover:bg-primary/90",children:[r(Ot,{className:"h-3 w-3"}),"Create here"]})})})]}),t&&r("tr",{className:"border-t border-border bg-background/30",children:r("td",{colSpan:7,className:"px-4 py-3",children:r(h9,{destinationId:e.id,restoreSupported:e.restoreSupported,...s?{onOpenRestoreWizard:s}:{}})})}),p&&r(A9,{destinationName:e.displayName,currentCron:e.cron??"",onSave:b,onClose:()=>m(!1),saving:c.isPending,saveError:c.error instanceof Error?c.error.message:null})]})}function M9({cron:e,nextRunAt:t,onEdit:n,disabled:o}){const s=typeof e=="string"&&e.trim().length>0;return u("button",{type:"button",onClick:n,disabled:o,className:"group flex flex-col items-start gap-0.5 text-left rounded px-1.5 py-1 -mx-1.5 hover:bg-primary/5 disabled:opacity-50",title:"Edit schedule",children:[u("div",{className:"flex items-center gap-1.5",children:[r(aD,{className:"h-3 w-3 text-foreground-subtle group-hover:text-foreground"}),r("span",{className:s?"font-mono text-foreground":"italic text-foreground-subtle",children:s?e:"Manual"})]}),s&&t!==void 0&&u("span",{className:"text-[10px] text-foreground-subtle tabular-nums",children:["next ",I9(t)]})]})}function I9(e){const t=e-Date.now();if(t<=0)return"imminent";const n=Math.floor(t/1e3);if(n<60)return`in ${n}s`;const o=Math.floor(n/60);if(o<60)return`in ${o}m`;const s=Math.floor(o/60);return s<24?`in ${s}h`:`in ${Math.floor(s/24)}d`}function A9({destinationName:e,currentCron:t,onSave:n,onClose:o,saving:s,saveError:a}){const[i,l]=$(t);return r("tr",{children:r("td",{colSpan:7,className:"p-0",children:r("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-background/80 backdrop-blur-sm",onClick:o,children:u("div",{className:"w-full max-w-lg rounded-xl border border-border bg-surface shadow-2xl",onClick:c=>c.stopPropagation(),children:[u("div",{className:"flex items-start justify-between border-b border-border px-4 py-3",children:[u("div",{className:"space-y-0.5",children:[r("h2",{className:"text-sm font-semibold text-foreground",children:"Schedule"}),u("p",{className:"text-xs text-foreground-subtle",children:["→ ",e]})]}),r("button",{onClick:o,className:"text-foreground-subtle hover:text-foreground",title:"Close",children:r(qe,{className:"h-4 w-4"})})]}),u("div",{className:"p-4",children:[r(y9,{value:i,onChange:l,disabled:s}),a!==null&&r("div",{className:"mt-3 rounded border border-danger/40 bg-danger/10 px-3 py-2 text-[11px] text-danger",children:a})]}),u("div",{className:"flex justify-end gap-2 border-t border-border px-4 py-3",children:[r("button",{onClick:o,disabled:s,className:"rounded px-3 py-1.5 text-xs text-foreground-subtle border border-border hover:text-foreground disabled:opacity-50",children:"Cancel"}),r("button",{onClick:()=>n(i.trim()),disabled:s||i.trim()===t.trim(),className:"inline-flex items-center gap-1.5 rounded bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50",children:s?"Saving…":"Save"})]})]})})})})}function P9(){const{map:e}=ec(Ne.BackupCompleted,t=>t.destinationId);return Q(()=>{const t=new Map;for(const[n,o]of e)t.set(n,{at:Date.now(),sizeBytes:o.sizeMB*1024*1024});return t},[e])}function E9(e,t){return e===void 0?t:t===void 0||e>t?e:t}function $9({at:e,sizeBytes:t}){const n=_9(e),o=Q(()=>new Date(e).toLocaleString(),[e]);return u("span",{title:o,className:"text-foreground tabular-nums",children:[n,t!==void 0&&u("span",{className:"ml-1 text-foreground-subtle",children:["· ",Nt(t)]})]})}function _9(e){const[,t]=$(0);return Y(()=>{const n=setInterval(()=>t(o=>o+1),3e4);return()=>clearInterval(n)},[]),D9(e)}function D9(e){const t=Math.max(0,Date.now()-e),n=Math.floor(t/1e3);if(n<60)return`${n}s ago`;const o=Math.floor(n/60);if(o<60)return`${o}m ago`;const s=Math.floor(o/60);if(s<24)return`${s}h ago`;const a=Math.floor(s/24);if(a<30)return`${a}d ago`;const i=Math.floor(a/30);return i<12?`${i}mo ago`:`${Math.floor(a/365)}y ago`}const L9=[["backup","list"]];function T9({initialDestinationId:e,initialArchiveId:t,onClose:n,onScheduled:o}){const s=ke(),[a,i]=$(e&&t?2:1),[l,c]=$(e),[d,f]=$(t),[p,m]=$(new Set),{data:h}=pc(),g=h??[],{data:b,isLoading:x}=fc({destinationId:l??""},{enabled:!!l}),v=b??[];Y(()=>{if(l!==void 0)return;const F=g.filter(E=>E.restoreSupported);F.length===1&&c(F[0].id)},[l,g]);const{data:w}=dg({destinationId:l??"",backupId:d??""},{enabled:!!l&&!!d}),y=Q(()=>w?.locations??[],[w]);Y(()=>{y.length!==0&&m(F=>F.size===0?new Set(y):F)},[y]);const N=ug({onSuccess:()=>{s.invalidateQueries({queryKey:L9}),o(),n()}}),k=F=>{m(E=>{const B=new Set(E);return B.has(F)?B.delete(F):B.add(F),B})},S=!!l&&!!d,M=p.size>0,P=S&&M&&!N.isPending,I=()=>{!l||!d||N.mutate({destinationId:l,backupId:d,locations:[...p]})};return r("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-background/80 backdrop-blur-sm",onClick:n,children:u("div",{className:"w-full max-w-md rounded-xl border border-border bg-surface shadow-2xl",onClick:F=>F.stopPropagation(),children:[u("div",{className:"flex items-start justify-between border-b border-border px-4 py-3",children:[u("div",{className:"space-y-0.5",children:[r("h2",{className:"text-sm font-semibold text-foreground",children:"Restore Backup"}),u("p",{className:"text-xs text-foreground-subtle",children:["Step ",a," of 3 — ",a===1?"pick source":a===2?"pick locations":"confirm"]})]}),r("button",{onClick:n,className:"text-foreground-subtle hover:text-foreground",children:r(qe,{className:"h-4 w-4"})})]}),a===1&&r(R9,{destinations:g,destinationId:l,onPickDestination:F=>{c(F),f(void 0),m(new Set)},archives:v,archivesLoading:x,archiveId:d,onPickArchive:f}),a===2&&r(O9,{locations:y,picked:p,onToggle:k}),a===3&&r(z9,{destinationName:g.find(F=>F.id===l)?.displayName??l??"",archive:v.find(F=>F.id===d),picked:[...p]}),u("div",{className:"flex justify-between gap-2 border-t border-border px-4 py-3",children:[r("div",{children:a>1&&u("button",{onClick:()=>i(F=>F===3?2:1),className:"inline-flex items-center gap-1 rounded px-3 py-1.5 text-xs text-foreground-subtle border border-border hover:text-foreground",children:[r(Yx,{className:"h-3 w-3"}),"Back"]})}),u("div",{className:"flex items-center gap-2",children:[r("button",{onClick:n,className:"rounded px-3 py-1.5 text-xs text-foreground-subtle border border-border hover:text-foreground",children:"Cancel"}),a<3?u("button",{disabled:a===1&&!S||a===2&&!M,onClick:()=>i(F=>F===1?2:3),className:"inline-flex items-center gap-1 rounded bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50",children:["Next",r(Zx,{className:"h-3 w-3"})]}):u("button",{onClick:I,disabled:!P,className:"inline-flex items-center gap-1.5 rounded bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50",children:[N.isPending?r(Pe,{className:"h-3.5 w-3.5 animate-spin"}):r(bt,{className:"h-3.5 w-3.5"}),"Schedule Restore"]})]})]})]})})}function R9({destinations:e,destinationId:t,onPickDestination:n,archives:o,archivesLoading:s,archiveId:a,onPickArchive:i}){const l=e.filter(c=>c.restoreSupported);return u("div",{className:"p-4 space-y-3",children:[u("div",{className:"space-y-1.5",children:[r("label",{className:"text-[10px] text-foreground-subtle uppercase tracking-wide",children:"Destination"}),u("select",{value:t??"",onChange:c=>n(c.target.value),className:"w-full rounded border border-border bg-background px-2 py-1.5 text-xs text-foreground focus:outline-none focus:ring-1 focus:ring-primary",children:[r("option",{value:"",disabled:!0,children:"Select destination…"}),l.map(c=>u("option",{value:c.id,children:[c.displayName," (",c.kind,")"]},c.id))]})]}),u("div",{className:"space-y-1.5",children:[r("label",{className:"text-[10px] text-foreground-subtle uppercase tracking-wide",children:"Archive"}),!t&&r("div",{className:"text-xs text-foreground-subtle italic",children:"Pick a destination first."}),t&&s&&r("div",{className:"text-xs text-foreground-subtle animate-pulse",children:"Reading archives…"}),t&&!s&&o.length===0&&r("div",{className:"text-xs text-foreground-subtle italic",children:"No archives available at this destination."}),t&&o.length>0&&r("div",{className:"rounded border border-border bg-background divide-y divide-border max-h-64 overflow-y-auto",children:o.map(c=>{const d=a===c.id;return u("label",{className:`flex items-center justify-between px-3 py-2 text-xs cursor-pointer ${d?"bg-primary/10":"hover:bg-primary/5"}`,children:[u("div",{className:"flex items-center gap-2",children:[r("input",{type:"radio",name:"archive",checked:d,onChange:()=>i(c.id),className:"accent-primary"}),u("div",{children:[r("div",{className:"font-medium text-foreground",children:c.label??c.id}),r("div",{className:"text-[10px] text-foreground-subtle",children:new Date(c.createdAt).toLocaleString()})]})]}),r("span",{className:"text-[10px] text-foreground-subtle tabular-nums",children:Nt(c.sizeBytes)})]},c.id)})})]})]})}function O9({locations:e,picked:t,onToggle:n}){return e.length===0?r("div",{className:"p-4",children:r("div",{className:"text-xs text-foreground-subtle",children:"Loading archive manifest… If this persists, the archive may predate manifests — restoring will apply everything in the tarball."})}):u("div",{className:"p-4 space-y-3",children:[r("div",{className:"rounded border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-[11px] text-amber-700 dark:text-amber-300",children:"Selected entries will overwrite live data on the next server restart. Unchecked entries stay current."}),u("div",{className:"space-y-1.5",children:[r("label",{className:"text-[10px] text-foreground-subtle uppercase tracking-wide",children:"Apply"}),r("div",{className:"rounded border border-border bg-background divide-y divide-border max-h-64 overflow-y-auto",children:e.map(o=>u("label",{className:"flex items-center gap-2 px-3 py-2 text-xs hover:bg-primary/5 cursor-pointer",children:[r("input",{type:"checkbox",checked:t.has(o),onChange:()=>n(o),className:"accent-primary"}),r("span",{className:"font-mono text-foreground",children:o}),r("span",{className:"ml-auto text-[10px] text-foreground-subtle",children:F9(o)})]},o))})]})]})}function z9({destinationName:e,archive:t,picked:n}){return u("div",{className:"p-4 space-y-3 text-xs",children:[r("div",{className:"rounded border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-amber-700 dark:text-amber-300",children:"Restore is applied at next server boot. Active connections will drop when you restart."}),u("dl",{className:"space-y-1.5",children:[r(ns,{term:"Destination",value:e}),r(ns,{term:"Archive",value:t?.label??t?.id??"—"}),t&&r(ns,{term:"Created",value:`${new Date(t.createdAt).toLocaleString()} · ${Nt(t.sizeBytes)}`}),r(ns,{term:"Locations",value:n.length>0?n.join(", "):"— (full archive)"})]})]})}function ns({term:e,value:t}){return u("div",{className:"flex justify-between gap-3",children:[r("dt",{className:"text-foreground-subtle",children:e}),r("dd",{className:"text-foreground font-mono text-right truncate",children:t})]})}const B9={db:"Database",addons:"Addon configs","addons-data":"Addon data",tls:"TLS certificates",cache:"Cache",data:"Top-level data"};function F9(e){return B9[e]??""}const j9=[["backup","list"]],H9=[["backup","listLocations"]];function V9(){const e=ke(),t=rt(),{data:n}=cg(),o=lg({onSuccess:()=>{e.invalidateQueries({queryKey:j9}),e.invalidateQueries({queryKey:[["backup","listDestinations"]]}),e.invalidateQueries({queryKey:[["backup","listArchives"]]})}}),s=Uh(),[a,i]=$(null),[l,c]=$(null),[d,f]=$(!1),[p,m]=$(!1),[h,g]=$(!1),b=async()=>{await t({title:"Restart server now?",message:"Active connections will drop and the apply-backup hook will run before boot.",confirmLabel:"Restart",variant:"warning"})&&s.mutate({confirm:!0})};return u(It,{icon:Uc,title:"Backup & Restore",subtitle:"Schedule + per-destination retention live in the orchestrator. Each `backups` storage location is a destination.",actions:u(ve,{children:[u("button",{onClick:()=>g(!0),className:"inline-flex items-center gap-1.5 rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90",children:[r(Ot,{className:"h-3.5 w-3.5"}),"Add destination"]}),u("button",{onClick:()=>f(!0),className:"inline-flex items-center gap-1.5 rounded-lg bg-surface border border-border px-3 py-1.5 text-xs font-medium text-foreground hover:bg-primary/5 hover:border-primary/30",children:[r(bt,{className:"h-3.5 w-3.5"}),"Restore…"]})]}),children:[p&&r("div",{className:"rounded-lg border border-amber-500/30 bg-amber-500/10 px-3 py-2.5 text-xs text-amber-700 dark:text-amber-300",children:u("div",{className:"flex items-center justify-between gap-3",children:[u("div",{className:"flex items-center gap-2",children:[r(bt,{className:"h-3.5 w-3.5"}),r("span",{children:"Restore scheduled. Restart the server to apply."})]}),u("button",{onClick:()=>{b()},disabled:s.isPending,className:"inline-flex items-center gap-1.5 rounded bg-amber-500/20 px-2 py-1 font-medium text-amber-800 dark:text-amber-200 hover:bg-amber-500/30 disabled:opacity-50",children:[s.isPending?r(Pe,{className:"h-3.5 w-3.5 animate-spin"}):r(bt,{className:"h-3.5 w-3.5"}),"Restart Now"]})]})}),r(S9,{onCreateAt:x=>i(x),onOpenRestoreWizard:x=>c(x)}),a&&r(q9,{destination:a,locations:n??[],onClose:()=>i(null),onSubmit:(x,v)=>{o.mutate({destinations:[a.id],locations:x,label:v||void 0},{onSuccess:()=>{i(null),e.invalidateQueries({queryKey:H9})}})},submitting:o.isPending}),(l||d)&&r(T9,{...l?{initialDestinationId:l.destinationId,initialArchiveId:l.archiveId}:{},onClose:()=>{c(null),f(!1)},onScheduled:()=>m(!0)}),h&&r(s0,{initialType:"backups",onClose:()=>g(!1),onCreated:()=>{g(!1),e.invalidateQueries({queryKey:[["backup","listDestinations"]]})}})]})}function q9({destination:e,locations:t,onClose:n,onSubmit:o,submitting:s}){const a=t.filter(p=>p.present),[i,l]=$(""),[c,d]=$(()=>new Set(a.map(p=>p.name))),f=p=>{d(m=>{const h=new Set(m);return h.has(p)?h.delete(p):h.add(p),h})};return r("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-background/80 backdrop-blur-sm",onClick:n,children:u("div",{className:"w-full max-w-md rounded-xl border border-border bg-surface shadow-2xl",onClick:p=>p.stopPropagation(),children:[u("div",{className:"flex items-start justify-between border-b border-border px-4 py-3",children:[u("div",{className:"space-y-0.5",children:[r("h2",{className:"text-sm font-semibold text-foreground",children:"Create Backup"}),u("p",{className:"text-xs text-foreground-subtle",children:["→ ",e.displayName]})]}),r("button",{onClick:n,className:"text-foreground-subtle hover:text-foreground",children:r(qe,{className:"h-4 w-4"})})]}),u("div",{className:"p-4 space-y-3",children:[u("div",{className:"space-y-1",children:[r("label",{className:"text-[10px] text-foreground-subtle uppercase tracking-wide",children:"Label (optional)"}),r("input",{type:"text",value:i,onChange:p=>l(p.target.value),placeholder:"pre-upgrade",className:"w-full rounded border border-border bg-background px-2 py-1.5 text-xs text-foreground placeholder:text-foreground-subtle focus:outline-none focus:ring-1 focus:ring-primary"})]}),u("div",{className:"space-y-1.5",children:[r("label",{className:"text-[10px] text-foreground-subtle uppercase tracking-wide",children:"Include"}),u("div",{className:"rounded border border-border bg-background divide-y divide-border max-h-64 overflow-y-auto",children:[a.length===0&&r("div",{className:"px-3 py-2 text-xs text-foreground-subtle italic",children:"Nothing to back up."}),a.map(p=>u("label",{className:"flex items-center justify-between px-3 py-2 text-xs hover:bg-primary/5 cursor-pointer",children:[u("div",{className:"flex items-center gap-2",children:[r("input",{type:"checkbox",checked:c.has(p.name),onChange:()=>f(p.name),className:"accent-primary"}),r("span",{className:"font-mono text-foreground",children:p.name})]}),u("div",{className:"text-[10px] text-foreground-subtle tabular-nums",children:[Nt(p.sizeBytes)," · ",p.fileCount," files"]})]},p.name))]})]})]}),u("div",{className:"flex justify-end gap-2 border-t border-border px-4 py-3",children:[r("button",{onClick:n,className:"rounded px-3 py-1.5 text-xs text-foreground-subtle border border-border hover:text-foreground",children:"Cancel"}),u("button",{onClick:()=>o(Array.from(c),i.trim()),disabled:s||c.size===0,className:"inline-flex items-center gap-1.5 rounded bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50",children:[s?r(Pe,{className:"h-3.5 w-3.5 animate-spin"}):r(Uc,{className:"h-3.5 w-3.5"}),s?"Creating…":"Create"]})]})]})})}function Q9(){return r("div",{className:"flex flex-col",children:r("div",{className:"px-6 pt-6",children:r(td,{tabs:[{id:"storage",label:"Storage",icon:lo,content:r(p9,{})},{id:"backup",label:"Backup",icon:Uc,content:r(V9,{})}]})})})}function U9(){const{data:e,isLoading:t}=In(void 0,{staleTime:3e4}),n=(e??[]).find(s=>s.isHub&&s.isOnline),o=n?.addons.map(s=>s.id)??[];return u("div",{className:"flex flex-col h-full gap-4 p-4",children:[u("div",{className:"flex items-center gap-3",children:[r(wt,{className:"h-5 w-5 text-muted-foreground"}),r("h1",{className:"text-xl font-semibold",children:"Settings"}),n&&u("span",{className:"text-xs px-2 py-0.5 rounded-full bg-muted text-muted-foreground",children:["hub: ",n.name]})]}),t?r("div",{className:"flex items-center justify-center flex-1 text-muted-foreground text-sm",children:"Loading hub topology…"}):n?o.length===0?r("div",{className:"flex items-center justify-center flex-1 text-muted-foreground text-sm",children:"No addons installed on the hub yet."}):r("div",{className:"w-full",children:r(Rr,{nodeId:n.id,addonIds:o,level:"global"})}):u("div",{className:"flex flex-col items-center justify-center flex-1 text-muted-foreground text-sm gap-2",children:[r(wt,{className:"h-8 w-8 opacity-30"}),r("p",{children:"No online hub node found."}),r("p",{className:"text-xs",children:"Settings will appear once the hub is reachable."})]})]})}function K9(e){const t=new FormData;return t.append("file",e.file,e.file.name),t.append("nodeId",e.nodeId),e.addonId&&t.append("addonId",e.addonId),new Promise((n,o)=>{const s=new XMLHttpRequest;s.open("POST","/api/addons/upload"),e.token&&s.setRequestHeader("Authorization",`Bearer ${e.token}`),s.upload.addEventListener("progress",a=>{a.lengthComputable&&e.onProgress(Math.round(a.loaded/a.total*100))}),s.addEventListener("load",()=>{let a;try{a=JSON.parse(s.responseText)}catch{o(new Error(`HTTP ${s.status}`));return}s.status>=200&&s.status<300?n(a):o(new Error(a.error??`HTTP ${s.status}`))}),s.addEventListener("error",()=>o(new Error("Network error during upload"))),s.addEventListener("abort",()=>o(new Error("Upload aborted"))),s.send(t)})}function G9({nodeId:e,addons:t,isHub:n}){const o=ke(),s=rt(),[a,i]=$(null),[l,c]=$(null),[d,f]=$(!1),[p,m]=$(null),[h,g]=$(0),b=ne(null),x=ia(),v=Xg(),w=()=>{o.invalidateQueries({queryKey:[["nodes","topology"]]})},y=async M=>{i(M);try{await x.mutateAsync({nodeId:e,addonId:M}),w()}catch(P){console.error("Failed to restart addon:",P)}finally{i(null)}},N=async M=>{if(await s({title:"Uninstall addon",message:`Remove "${M}" from ${e}? The addon directory will be deleted on disk.`,confirmLabel:"Uninstall",variant:"danger"})){c(M);try{await v.mutateAsync({nodeId:e,addonId:M}),w()}catch(I){console.error("Failed to uninstall addon:",I)}finally{c(null)}}},S=u("div",{className:"flex items-center gap-2 mb-2",children:[r("input",{ref:b,type:"file",accept:".tgz,.tar.gz",className:"hidden",onChange:async M=>{const P=M.target.files?.[0];if(P){M.target.value="",m(null),f(!0),g(0);try{const I=localStorage.getItem("camstack_admin_token");await K9({file:P,nodeId:e,token:I,onProgress:g}),w()}catch(I){m(I instanceof Error?I.message:String(I))}finally{f(!1),g(0)}}}}),u("button",{onClick:()=>b.current?.click(),disabled:d,className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1 text-[11px] font-medium text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors disabled:opacity-50",children:[d?r(Pe,{className:"h-3 w-3 animate-spin"}):r(Xc,{className:"h-3 w-3"}),d?`Uploading… ${h}%`:"Upload addon (.tgz)"]}),d&&r("div",{className:"flex-1 h-1 rounded-full bg-muted overflow-hidden max-w-[140px]",children:r("div",{className:"h-full bg-primary transition-all",style:{width:`${h}%`}})}),p&&r("span",{className:"text-[10px] text-destructive",children:p})]});return t.length===0?u("div",{children:[S,r("div",{className:"py-4 text-xs text-muted-foreground text-center",children:"No addons on this node"})]}):u("div",{children:[S,u("table",{className:"w-full text-xs",children:[r("thead",{children:u("tr",{className:"text-muted-foreground text-left",children:[r("th",{className:"py-2 font-medium",children:"Addon"}),r("th",{className:"py-2 font-medium",children:"Capabilities"}),r("th",{className:"py-2 font-medium",children:"Status"}),r("th",{className:"py-2 font-medium w-16"})]})}),r("tbody",{children:t.map(M=>u("tr",{className:"border-t border-border/50",children:[r("td",{className:"py-2 font-medium",children:M.id}),r("td",{className:"py-2",children:r("div",{className:"flex flex-wrap gap-1",children:M.capabilities.length>0?M.capabilities.map(P=>r("span",{className:"text-[9px] px-1 py-0.5 rounded bg-blue-500/10 text-blue-400",children:P},P)):r("span",{className:"text-muted-foreground",children:"—"})})}),r("td",{className:"py-2",children:r("span",{className:`text-[10px] px-1.5 py-0.5 rounded-full ${M.status==="running"?"bg-success/10 text-success":M.status==="error"?"bg-destructive/10 text-destructive":"bg-muted text-muted-foreground"}`,children:M.status})}),r("td",{className:"py-2",children:u("div",{className:"flex items-center gap-1 justify-end",children:[r("button",{onClick:()=>y(M.id),disabled:a===M.id||l===M.id,className:"p-1 rounded hover:bg-muted text-muted-foreground hover:text-foreground transition-colors disabled:opacity-50",title:`Restart ${M.id}`,children:r(bt,{className:`h-3 w-3 ${a===M.id?"animate-spin":""}`})}),r("button",{onClick:()=>N(M.id),disabled:a===M.id||l===M.id,className:"p-1 rounded hover:bg-destructive/10 text-muted-foreground hover:text-destructive transition-colors disabled:opacity-50",title:`Uninstall ${M.id}`,children:l===M.id?r(Pe,{className:"h-3 w-3 animate-spin"}):r(We,{className:"h-3 w-3"})})]})})]},M.id))})]})]})}function W9(e){if(e<60)return`${e}s`;const t=Math.floor(e/60);if(t<60)return`${t}m`;const n=Math.floor(t/60);return n<24?`${n}h ${t%60}m`:`${Math.floor(n/24)}d ${n%24}h`}function Y9({state:e}){return r("span",{className:`text-[10px] px-1.5 py-0.5 rounded-full ${e==="running"?"bg-success/10 text-success":e==="crashed"?"bg-destructive/10 text-destructive":"bg-muted text-muted-foreground"}`,children:e})}const Z9=["trace","debug","info","warn","error"];function X9({proc:e,nodeId:t,defaultExpanded:n,activePanel:o,onTogglePanel:s}){const a=e.services??[],i=a.length===1,[l,c]=$(i||n),[d,f]=$(null),[p,m]=$("info"),h=e.name.includes("(core)"),g=ia(),b=Jg(),x=rb(),v=async N=>{f(N);try{await g.mutateAsync({nodeId:t,addonId:N})}catch(k){console.error("Failed to restart addon:",k)}finally{f(null)}},w=async()=>{f(e.name);try{await b.mutateAsync({nodeId:t,processName:e.name})}catch(N){console.error("Failed to restart process:",N)}finally{f(null)}},y=async N=>{const k=`${t}/${e.name}`;try{await x.mutateAsync({nodeId:k,level:N}),m(N)}catch(S){console.error("Failed to set log level:",S)}};return u("div",{className:"border border-border/50 rounded-lg overflow-hidden",children:[u("div",{role:i?void 0:"button",tabIndex:i?void 0:0,onClick:i?void 0:()=>c(!l),onKeyDown:i?void 0:N=>{(N.key==="Enter"||N.key===" ")&&c(!l)},className:`flex items-center gap-2 w-full px-3 py-2 bg-muted/20 transition-colors text-left select-none ${i?"":"hover:bg-muted/40 cursor-pointer"}`,children:[i?r("span",{className:"h-3 w-3 shrink-0"}):l?r(Rt,{className:"h-3 w-3 text-muted-foreground shrink-0"}):r(Mt,{className:"h-3 w-3 text-muted-foreground shrink-0"}),h?r(ln,{className:"h-3.5 w-3.5 text-primary shrink-0"}):r(ga,{className:"h-3.5 w-3.5 text-amber-500 shrink-0"}),r("span",{className:"text-xs font-semibold flex-1",children:e.name}),u("span",{className:"text-[10px] text-muted-foreground tabular-nums",children:["PID ",e.pid]}),r(Y9,{state:e.state}),u("span",{className:"text-[10px] text-muted-foreground tabular-nums",children:[e.cpuPercent,"% CPU"]}),r("span",{className:"text-[10px] text-muted-foreground tabular-nums",children:Nt(e.memoryRss)}),r("span",{className:"text-[10px] text-muted-foreground tabular-nums",children:W9(e.uptimeSeconds)}),!h&&u("div",{className:"flex items-center gap-1",onClick:N=>N.stopPropagation(),children:[u(Gm,{children:[r(Wm,{className:"text-[9px] px-1.5 py-0.5 rounded border border-border text-muted-foreground hover:text-foreground hover:bg-muted transition-colors font-mono",title:"Set log level",children:p}),r(Ym,{align:"end",className:"min-w-[70px] py-0.5",children:Z9.map(N=>r(Zm,{onClick:()=>y(N),className:`h-auto px-2 py-1 text-[10px] font-mono ${N===p?"text-primary font-semibold":""}`,children:N},N))})]}),r("button",{onClick:w,disabled:d===e.name,className:"p-1 rounded hover:bg-muted text-muted-foreground hover:text-foreground transition-colors disabled:opacity-50",title:"Restart process",children:r(bt,{className:`h-3 w-3 ${d===e.name?"animate-spin":""}`})})]})]}),l&&a.length>0&&r("div",{className:"divide-y divide-border/30",children:a.map(N=>u("div",{children:[u("div",{className:"flex items-center gap-2 px-3 py-1.5 pl-9 hover:bg-muted/10 transition-colors",children:[r("div",{className:`h-1.5 w-1.5 rounded-full shrink-0 ${N.status==="running"?"bg-success":"bg-muted-foreground/30"}`}),r("span",{className:"text-xs font-medium flex-1 min-w-0 truncate",children:N.addonId}),N.capabilities.length>0&&u("div",{className:"flex gap-1 flex-shrink-0",children:[N.capabilities.slice(0,3).map(k=>r("span",{className:"text-[9px] px-1 py-0.5 rounded bg-blue-500/10 text-blue-400 truncate max-w-[80px]",children:k},k)),N.capabilities.length>3&&u("span",{className:"text-[9px] text-muted-foreground",children:["+",N.capabilities.length-3]})]}),u("div",{className:"flex items-center gap-1 shrink-0",children:[r("button",{onClick:()=>s(N.addonId,"logs"),className:`p-0.5 rounded transition-colors ${o?.addonId===N.addonId&&o.type==="logs"?"bg-primary/10 text-primary":"hover:bg-muted text-muted-foreground hover:text-foreground"}`,title:`Show logs for ${N.addonId}`,children:r(Xe,{className:"h-3 w-3"})}),r("button",{onClick:()=>s(N.addonId,"events"),className:`p-0.5 rounded transition-colors ${o?.addonId===N.addonId&&o.type==="events"?"bg-primary/10 text-primary":"hover:bg-muted text-muted-foreground hover:text-foreground"}`,title:`Show events for ${N.addonId}`,children:r(Zc,{className:"h-3 w-3"})}),r("button",{onClick:()=>v(N.addonId),disabled:d===N.addonId,className:"p-0.5 rounded hover:bg-muted text-muted-foreground hover:text-foreground transition-colors disabled:opacity-50",title:`Restart ${N.addonId}`,children:r(bt,{className:`h-3 w-3 ${d===N.addonId?"animate-spin":""}`})})]})]}),o?.addonId===N.addonId&&o.type==="logs"&&r("div",{className:"border-t border-border/40 bg-muted/5",children:r(Wt,{addonId:N.addonId,agentId:t,maxHeight:"max-h-48",showFilters:!1,onClose:()=>s(N.addonId,"logs")})}),o?.addonId===N.addonId&&o.type==="events"&&r("div",{className:"border-t border-border/40 bg-muted/5",children:r(nr,{addonId:N.addonId,category:"addon.*",maxHeight:"max-h-48",onClose:()=>s(N.addonId,"events")})})]},N.addonId))}),l&&a.length===0&&r("div",{className:"px-3 py-2 pl-9 text-[10px] text-muted-foreground",children:"No services"})]})}function J9({nodeId:e,processes:t}){const[n,o]=$(null),s=(a,i)=>{o(l=>l?.addonId===a&&l.type===i?null:{addonId:a,type:i})};return t.length===0?r("div",{className:"py-4 text-xs text-muted-foreground text-center",children:"No processes on this node"}):r("div",{className:"space-y-2 py-1",children:t.map((a,i)=>r(X9,{proc:a,nodeId:e,defaultExpanded:i===0,activePanel:n,onTogglePanel:s},a.name))})}function e7(e){return e<60?`${e}s`:e<3600?`${Math.floor(e/60)}m ${e%60}s`:e<86400?`${Math.floor(e/3600)}h ${Math.floor(e%3600/60)}m`:`${Math.floor(e/86400)}d ${Math.floor(e%86400/3600)}h`}function t7(e,t=80){return e.length<=t?e:`…${e.slice(e.length-t+1)}`}function n7({nodeId:e}){const t=ke(),n=rt(),[o,s]=$("all"),a=Ar("metrics.node-processes-snapshot",k=>k.nodeId===e),{data:i}=Yg({nodeId:e},{staleTime:6e4}),l=a?.processes??i,c=Q(()=>l?[...l]:[],[l]),d=Q(()=>o==="ghost"?c.filter(k=>k.classification==="ghost"):c,[c,o]),f=Q(()=>{const k=c.filter(M=>M.classification==="ghost"),S=new Map;for(const M of k)S.has(M.ppid)||S.set(M.ppid,[]),S.get(M.ppid).push(M);return[...S.entries()].filter(([,M])=>M.length>1).map(([M,P])=>({ppid:M,children:P})).sort((M,P)=>P.children.length-M.children.length)},[c]),p=Zg({onSettled:()=>{t.invalidateQueries({queryKey:[["metricsProvider","listNodeProcesses"]]})}}),m=Q(()=>{const k=new Map;for(const S of c)k.set(S.pid,S.classification);return k},[c]),h=async(k,S)=>{if(k.classification==="root"||k.classification==="system")return;const M=k.classification==="ghost"?"ghost":k.addonId??"process",P=S?"SIGKILL":"SIGTERM";await n({title:`Send ${P}?`,message:`Target pid ${k.pid} (${M}) on node ${e}.`,confirmLabel:`Send ${P}`,variant:"danger"})&&p.mutate({nodeId:e,pid:k.pid,force:S})},g=async(k,S)=>{try{await p.mutateAsync({nodeId:e,pid:k,force:S})}catch{}},b=async k=>{const S=m.get(k.ppid);if(S==="root"||S==="system"){await n({title:"Cannot kill protected ancestor",message:S==="root"?`pid ${k.ppid} is the current node supervisor. Restart the node via the cluster page instead.`:`pid ${k.ppid} is a system ancestor (concurrently / vite / npm wrapper). Killing it would tear down the dev tree.`,confirmLabel:"OK",cancelLabel:"Close",variant:"warning"});return}await n({title:`Kill ghost parent + ${k.children.length} child(ren)?`,message:`SIGKILL parent pid ${k.ppid} and SIGTERM ${k.children.length} ghost child(ren) on node ${e}.`,confirmLabel:"Kill all",variant:"danger"})&&(await Promise.all([g(k.ppid,!0),...k.children.map(P=>g(P.pid,!1))]),t.invalidateQueries({queryKey:[["metricsProvider","listNodeProcesses"]]}))},x=async()=>{const k=c.filter(M=>M.classification==="ghost");k.length===0||!await n({title:`Kill all ${k.length} ghost process(es)?`,message:`SIGKILL ${k.length} ghost process(es) on node ${e}. This is irreversible.`,confirmLabel:"Kill all",variant:"danger"})||(await Promise.all(k.map(M=>g(M.pid,!0))),t.invalidateQueries({queryKey:[["metricsProvider","listNodeProcesses"]]}))},v=c.filter(k=>k.classification==="ghost").length,w=c.filter(k=>k.classification==="managed").length,y=c.filter(k=>k.classification==="root").length,N=c.filter(k=>k.classification==="system").length;return u("div",{className:"space-y-4",children:[u("div",{className:"flex items-start justify-between gap-4",children:[u("p",{className:"text-[11px] text-foreground-subtle",children:["ps"," scan + kernel `$process.list` cross-reference. Ghosts = camstack-shaped commands with no managed binding (usually orphaned to ppid=1). Refreshes every 10s."]}),u("button",{type:"button",onClick:()=>t.invalidateQueries({queryKey:[["metricsProvider","listNodeProcesses"]]}),className:"inline-flex items-center gap-1 rounded border border-border px-2 py-1 text-[11px] text-foreground hover:bg-surface-hover",children:[r(pt,{className:"h-3 w-3"})," Refresh"]})]}),u("div",{className:"grid grid-cols-4 gap-3",children:[u("div",{className:"rounded-lg border border-border p-3",children:[r("div",{className:"text-[10px] uppercase tracking-wider text-foreground-subtle",children:"Root"}),r("div",{className:"text-xl font-semibold text-foreground",children:y})]}),u("div",{className:"rounded-lg border border-border p-3",children:[r("div",{className:"text-[10px] uppercase tracking-wider text-foreground-subtle",children:"Managed"}),r("div",{className:"text-xl font-semibold text-foreground",children:w})]}),u("div",{className:"rounded-lg border border-border p-3",children:[r("div",{className:"text-[10px] uppercase tracking-wider text-foreground-subtle",children:"System"}),r("div",{className:"text-xl font-semibold text-foreground",children:N})]}),u("div",{className:`rounded-lg border p-3 ${v>0?"border-destructive/40 bg-destructive/5":"border-border"}`,children:[u("div",{className:"text-[10px] uppercase tracking-wider text-foreground-subtle flex items-center gap-1",children:[v>0&&r(Ko,{className:"h-3 w-3 text-destructive"})," Ghosts"]}),r("div",{className:`text-xl font-semibold ${v>0?"text-destructive":"text-foreground"}`,children:v})]})]}),f.length>0&&u("div",{className:"rounded-lg border border-amber-500/40 bg-amber-500/5 p-3",children:[u("div",{className:"flex items-center gap-1 text-[11px] font-semibold text-amber-400 mb-2",children:[r(xt,{className:"h-3 w-3"})," Recurring ghost parents (",f.length,")"]}),r("div",{className:"space-y-1.5",children:f.map(k=>u("div",{className:"text-[11px] text-foreground flex items-center justify-between gap-2",children:[u("div",{className:"flex items-center gap-2",children:[u("span",{className:"font-mono text-foreground-subtle",children:["ppid ",k.ppid]}),u("span",{children:["→ ",k.children.length," ghost(s)"]})]}),u("button",{type:"button",disabled:p.isPending,onClick:()=>{b(k)},className:"inline-flex items-center gap-1 rounded border border-amber-500/40 bg-amber-500/10 px-2 py-0.5 text-[10px] text-amber-400 hover:bg-amber-500/20 disabled:opacity-30",children:[r(Ko,{className:"h-3 w-3"})," Kill parent + ",k.children.length]})]},k.ppid))})]}),u("div",{className:"flex items-center justify-between gap-2 text-[11px]",children:[u("div",{className:"flex items-center gap-2",children:[r("span",{className:"text-foreground-subtle",children:"Filter:"}),u("button",{type:"button",className:`px-2 py-0.5 rounded ${o==="all"?"bg-primary text-primary-foreground":"border border-border text-foreground hover:bg-surface-hover"}`,onClick:()=>s("all"),children:["All (",c.length,")"]}),u("button",{type:"button",className:`px-2 py-0.5 rounded ${o==="ghost"?"bg-destructive text-destructive-foreground":"border border-border text-foreground hover:bg-surface-hover"}`,onClick:()=>s("ghost"),children:["Ghost only (",v,")"]})]}),v>0&&u("button",{type:"button",disabled:p.isPending,onClick:()=>{x()},className:"inline-flex items-center gap-1 rounded border border-destructive/40 bg-destructive/10 px-2 py-1 text-[11px] font-medium text-destructive hover:bg-destructive/20 disabled:opacity-30",children:[r(Ko,{className:"h-3 w-3"})," Kill all ",v," ghost(s)"]})]}),r("div",{className:"rounded-lg border border-border overflow-hidden",children:u("table",{className:"w-full text-xs",children:[r("thead",{className:"bg-surface",children:u("tr",{className:"text-foreground-subtle text-[10px] uppercase tracking-wider",children:[r("th",{className:"text-left px-3 py-2",children:"Class"}),r("th",{className:"text-right px-3 py-2",children:"PID"}),r("th",{className:"text-right px-3 py-2",children:"PPID"}),r("th",{className:"text-left px-3 py-2",children:"Addon"}),r("th",{className:"text-left px-3 py-2",children:"Command"}),r("th",{className:"text-right px-3 py-2",children:"CPU%"}),r("th",{className:"text-right px-3 py-2",children:"RSS"}),r("th",{className:"text-right px-3 py-2",children:"Uptime"}),r("th",{className:"w-44"})]})}),u("tbody",{children:[d.length===0&&r("tr",{children:r("td",{colSpan:9,className:"px-3 py-4 text-center text-foreground-subtle text-[11px]",children:o==="ghost"?"No ghost processes detected.":"Scanning…"})}),d.map(k=>u("tr",{className:`border-t border-border ${k.classification==="ghost"?"bg-destructive/5":""}`,children:[r("td",{className:"px-3 py-2",children:r("span",{className:`inline-block rounded-full px-1.5 py-0.5 text-[10px] font-medium ${k.classification==="ghost"?"bg-destructive/20 text-destructive":k.classification==="root"?"bg-sky-500/20 text-sky-400":k.classification==="system"?"bg-foreground-subtle/20 text-foreground-subtle":"bg-success/20 text-success"}`,children:k.classification})}),r("td",{className:"px-3 py-2 text-right font-mono text-foreground",children:k.pid}),u("td",{className:"px-3 py-2 text-right font-mono text-foreground-subtle",children:[k.ppid,k.orphaned?" ⚠":""]}),r("td",{className:"px-3 py-2 text-foreground-subtle text-[11px]",children:k.addonId??"—"}),r("td",{className:"px-3 py-2 font-mono text-[10px] text-foreground-subtle break-all",children:t7(k.command)}),r("td",{className:"px-3 py-2 text-right text-foreground",children:k.cpuPercent.toFixed(1)}),r("td",{className:"px-3 py-2 text-right text-foreground",children:Nt(k.memoryRssBytes)}),r("td",{className:"px-3 py-2 text-right text-foreground-subtle",children:e7(k.uptimeSec)}),r("td",{className:"px-3 py-2 text-right",children:u("div",{className:"inline-flex gap-1",children:[u("button",{type:"button",disabled:p.isPending||k.classification==="root"||k.classification==="system",onClick:()=>{h(k,!1)},title:"SIGTERM",className:"inline-flex items-center gap-1 px-1.5 py-0.5 rounded border border-border text-[10px] text-foreground hover:bg-surface-hover disabled:opacity-30",children:[r(We,{className:"h-3 w-3"})," Term"]}),u("button",{type:"button",disabled:p.isPending||k.classification==="root"||k.classification==="system",onClick:()=>{h(k,!0)},title:"SIGKILL",className:"inline-flex items-center gap-1 px-1.5 py-0.5 rounded border border-destructive/30 text-[10px] text-destructive hover:bg-destructive/10 disabled:opacity-30",children:[r(Ko,{className:"h-3 w-3"})," Kill"]})]})})]},k.pid))]})]})}),p.isError&&u("div",{className:"rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-[11px] text-destructive",children:["Kill failed: ",p.error instanceof Error?p.error.message:"unknown"]})]})}function r7({nodeId:e,addonIds:t}){return t.length===0?r("div",{className:"py-4 text-xs text-muted-foreground text-center",children:"No addons on this node"}):r("div",{className:"w-full py-2",children:r(Rr,{nodeId:e,addonIds:t,level:"global"})})}function o7({nodeId:e,addons:t}){const n=ke(),{data:o,isLoading:s}=hb({nodeId:e}),a=Q(()=>{const l=new Map;for(const c of t)for(const d of c.capabilities){const f=l.get(d)??[];f.push(c.id),l.set(d,f)}return[...l.entries()].sort(([c],[d])=>c.localeCompare(d)).map(([c,d])=>({capName:c,providers:d}))},[t]),i=gb({onSuccess:()=>{n.invalidateQueries({queryKey:[["pipelineOrchestrator","getCapabilityBindings"]]})}});return a.length===0?r("div",{className:"py-4 text-xs text-muted-foreground text-center",children:"No capabilities on this node"}):u("table",{className:"w-full text-xs",children:[r("thead",{children:u("tr",{className:"text-muted-foreground text-left",children:[r("th",{className:"py-2 font-medium w-1/2",children:"Capability"}),r("th",{className:"py-2 font-medium",children:"Bound provider"})]})}),r("tbody",{children:a.map(({capName:l,providers:c})=>{const f=o?.[l]??c[0]??"",p=c.length===1;return u("tr",{className:"border-t border-border/50",children:[r("td",{className:"py-2 font-medium",children:l}),r("td",{className:"py-2",children:r("select",{value:f,onChange:m=>i.mutate({nodeId:e,capName:l,addonId:m.target.value}),disabled:p||i.isPending||s,className:"w-full rounded-md border border-border bg-surface px-2 py-1 text-xs text-foreground focus:outline-none focus:ring-1 focus:ring-primary disabled:opacity-60",title:p?"Only one provider installed — choice becomes available once a second addon registers this capability":void 0,children:c.map(m=>r("option",{value:m,children:m},m))})})]},l)})})]})}function s7(e){if(e==null)return"—";const t=Math.floor(e/1e3),n=Math.floor(t/86400),o=Math.floor(t%86400/3600),s=Math.floor(t%3600/60);return n>0?`${n}d ${o}h ${s}m`:o>0?`${o}h ${s}m`:`${s}m`}function a7(e){const[t,n]=$(!1),[o,s]=$(e.name),a=ke(),i=tb({onSuccess:()=>{a.invalidateQueries({queryKey:[["nodes","topology"]]})}}),l=(e.localIps??[]).filter(p=>!p.includes(":")),c=(e.localIps??[]).filter(p=>p.includes(":")),d=async()=>{if(!o.trim()||o===e.name){n(!1);return}try{await i.mutateAsync({nodeId:e.nodeId,name:o.trim()}),n(!1)}catch(p){console.error("Rename failed:",p)}},f=[["Node ID",r("span",{className:"font-mono text-xs",children:e.nodeId})],["Display Name",t?u("div",{className:"flex items-center gap-1.5",children:[r("input",{type:"text",className:"flex-1 px-2 py-0.5 text-xs border border-border rounded bg-background focus:outline-none focus:ring-1 focus:ring-primary",value:o,onChange:p=>s(p.target.value),onKeyDown:p=>{p.key==="Enter"&&d(),p.key==="Escape"&&n(!1)},disabled:i.isPending,autoFocus:!0}),r("button",{onClick:()=>void d(),disabled:i.isPending,className:"p-0.5 text-success hover:bg-success/10 rounded",title:"Save",children:r(Ct,{className:"h-3.5 w-3.5"})}),r("button",{onClick:()=>n(!1),className:"p-0.5 text-muted-foreground hover:bg-muted rounded",title:"Cancel",children:r(qe,{className:"h-3.5 w-3.5"})})]}):u("div",{className:"flex items-center gap-1.5",children:[r("span",{className:"text-xs",children:e.name}),!e.isHub&&r("button",{onClick:()=>{s(e.name),n(!0)},className:"p-0.5 text-muted-foreground hover:text-primary rounded",title:"Rename",children:r(Po,{className:"h-3 w-3"})})]})],["Hostname",r("span",{className:"text-xs",children:e.hostname})],["Role",e.isHub?r("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-primary/10 text-primary font-medium",children:"Hub"}):r("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-muted text-muted-foreground font-medium",children:"Agent"})],["Platform",u("span",{className:"text-xs",children:[e.platform," / ",e.arch]})],["CPU",u("span",{className:"text-xs",children:[e.cpuModel??"—"," (",e.cpuCores," cores)"]})],["Memory",r("span",{className:"text-xs",children:e.memoryMB>0?`${(e.memoryMB/1024).toFixed(1)} GB`:"—"})],["Uptime",r("span",{className:"text-xs",children:s7(e.uptime)})],["Engines",e.engines.length>0?r("div",{className:"flex flex-wrap gap-1",children:e.engines.map(p=>r("span",{className:"text-[9px] px-1.5 py-0.5 rounded-full bg-purple-500/10 text-purple-400 font-medium",children:p},p))}):r("span",{className:"text-xs text-muted-foreground",children:"—"})]];return l.length>0&&f.push(["IPv4",r("div",{className:"flex flex-wrap gap-1.5",children:l.map((p,m)=>r("span",{className:"font-mono text-xs px-1.5 py-0.5 rounded bg-muted",children:p},`${p}-${m}`))})]),c.length>0&&f.push(["IPv6",r("div",{className:"flex flex-wrap gap-1.5",children:c.map((p,m)=>r("span",{className:"font-mono text-[10px] px-1.5 py-0.5 rounded bg-muted truncate max-w-[280px]",title:p,children:p},`${p}-${m}`))})]),r("div",{className:"py-2",children:r("table",{className:"w-full text-sm",children:r("tbody",{children:f.map(([p,m],h)=>u("tr",{className:h%2===0?"bg-muted/20":"",children:[r("td",{className:"py-1.5 px-2 text-xs font-medium text-muted-foreground w-28 align-top whitespace-nowrap",children:p}),r("td",{className:"py-1.5 px-2",children:m})]},p))})})})}function i7({node:e}){const[t,n]=$("info"),o=e.processes??[],s=e.addons.map(a=>a.id);return e.isOnline?u("div",{className:"border border-border rounded-xl overflow-hidden",children:[u("div",{className:"flex items-center gap-3 px-4 py-3 bg-muted/30 border-b border-border",children:[r("div",{className:"w-2.5 h-2.5 rounded-full bg-success"}),r("span",{className:"text-sm font-semibold",children:e.name}),u("span",{className:"text-xs text-muted-foreground",children:[e.cpuModel??e.platform," · ",e.memoryMB>0?`${Math.round(e.memoryMB/1024)}GB`:""," · ",e.arch]}),e.engines.map(a=>r("span",{className:"text-[9px] px-1.5 py-0.5 rounded-full bg-purple-500/10 text-purple-400 font-medium",children:a},a)),u("div",{className:"ml-auto flex gap-3 text-xs text-muted-foreground",children:[u("span",{className:"flex items-center gap-1",children:[r(ut,{className:"h-3 w-3"})," ",e.cpuPercent,"%"]}),u("span",{className:"flex items-center gap-1",children:[r(Wc,{className:"h-3 w-3"})," ",e.memoryPercent,"%"]})]})]}),r("div",{className:"flex border-b border-border px-4",children:["info","addons","forks","processes","settings","capabilities"].map(a=>r("button",{onClick:()=>n(a),className:`px-3 py-2 text-xs font-medium border-b-2 transition-colors ${t===a?"border-primary text-primary":"border-transparent text-muted-foreground hover:text-foreground"}`,children:a==="info"?"Info":a==="addons"?`Addons (${e.addons.length})`:a==="forks"?`Forks (${o.length})`:a==="processes"?"Processes":a==="settings"?"Settings":"Capabilities"},a))}),u("div",{className:"px-4 py-2",children:[t==="info"&&r(a7,{nodeId:e.id,name:e.name,hostname:e.hostname,platform:e.platform,arch:e.arch,cpuModel:e.cpuModel,cpuCores:e.cpuCores,memoryMB:e.memoryMB,engines:e.engines,isHub:e.isHub,uptime:e.uptime,localIps:e.localIps}),t==="addons"&&r(G9,{nodeId:e.id,addons:e.addons,isHub:e.isHub}),t==="forks"&&r(J9,{nodeId:e.id,processes:o}),t==="processes"&&r(n7,{nodeId:e.id}),t==="settings"&&r(r7,{nodeId:e.id,addonIds:s}),t==="capabilities"&&r(o7,{nodeId:e.id,addons:e.addons})]})]}):u("div",{className:"border border-border rounded-xl overflow-hidden opacity-60",children:[u("div",{className:"flex items-center gap-3 px-4 py-3 bg-muted/30",children:[r("div",{className:"w-2.5 h-2.5 rounded-full bg-destructive"}),r("span",{className:"text-sm font-semibold",children:e.name}),u("span",{className:"text-xs text-muted-foreground",children:[e.cpuModel??e.platform," · ",e.memoryMB>0?`${Math.round(e.memoryMB/1024)}GB`:""," · ",e.arch]}),e.engines.map(a=>r("span",{className:"text-[9px] px-1.5 py-0.5 rounded-full bg-purple-500/10 text-purple-400 font-medium",children:a},a)),r("span",{className:"ml-auto text-xs px-2 py-0.5 rounded-full bg-destructive/10 text-destructive",children:"offline"})]}),u("div",{className:"px-4 py-3 text-xs text-muted-foreground",children:[e.addons.length," addon",e.addons.length!==1?"s":""," assigned — will resume when node reconnects"]})]})}function l7({nodes:e}){const t=[...e].sort((n,o)=>n.isHub?-1:o.isHub?1:n.isOnline&&!o.isOnline?-1:!n.isOnline&&o.isOnline?1:n.name.localeCompare(o.name));return r("div",{className:"flex flex-col gap-4",children:t.map(n=>r(i7,{node:n},n.id))})}function Ue(e){if(typeof e=="string"||typeof e=="number")return""+e;let t="";if(Array.isArray(e))for(let n=0,o;n<e.length;n++)(o=Ue(e[n]))!==""&&(t+=(t&&" ")+o);else for(let n in e)e[n]&&(t+=(t&&" ")+n);return t}var c7={value:()=>{}};function Ca(){for(var e=0,t=arguments.length,n={},o;e<t;++e){if(!(o=arguments[e]+"")||o in n||/[\s.]/.test(o))throw new Error("illegal type: "+o);n[o]=[]}return new bs(n)}function bs(e){this._=e}function d7(e,t){return e.trim().split(/^|\s+/).map(function(n){var o="",s=n.indexOf(".");if(s>=0&&(o=n.slice(s+1),n=n.slice(0,s)),n&&!t.hasOwnProperty(n))throw new Error("unknown type: "+n);return{type:n,name:o}})}bs.prototype=Ca.prototype={constructor:bs,on:function(e,t){var n=this._,o=d7(e+"",n),s,a=-1,i=o.length;if(arguments.length<2){for(;++a<i;)if((s=(e=o[a]).type)&&(s=u7(n[s],e.name)))return s;return}if(t!=null&&typeof t!="function")throw new Error("invalid callback: "+t);for(;++a<i;)if(s=(e=o[a]).type)n[s]=kp(n[s],e.name,t);else if(t==null)for(s in n)n[s]=kp(n[s],e.name,null);return this},copy:function(){var e={},t=this._;for(var n in t)e[n]=t[n].slice();return new bs(e)},call:function(e,t){if((s=arguments.length-2)>0)for(var n=new Array(s),o=0,s,a;o<s;++o)n[o]=arguments[o+2];if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(a=this._[e],o=0,s=a.length;o<s;++o)a[o].value.apply(t,n)},apply:function(e,t,n){if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(var o=this._[e],s=0,a=o.length;s<a;++s)o[s].value.apply(t,n)}};function u7(e,t){for(var n=0,o=e.length,s;n<o;++n)if((s=e[n]).name===t)return s.value}function kp(e,t,n){for(var o=0,s=e.length;o<s;++o)if(e[o].name===t){e[o]=c7,e=e.slice(0,o).concat(e.slice(o+1));break}return n!=null&&e.push({name:t,value:n}),e}var fl="http://www.w3.org/1999/xhtml";const Sp={svg:"http://www.w3.org/2000/svg",xhtml:fl,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function Ma(e){var t=e+="",n=t.indexOf(":");return n>=0&&(t=e.slice(0,n))!=="xmlns"&&(e=e.slice(n+1)),Sp.hasOwnProperty(t)?{space:Sp[t],local:e}:e}function p7(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===fl&&t.documentElement.namespaceURI===fl?t.createElement(e):t.createElementNS(n,e)}}function f7(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function i0(e){var t=Ma(e);return(t.local?f7:p7)(t)}function m7(){}function rd(e){return e==null?m7:function(){return this.querySelector(e)}}function h7(e){typeof e!="function"&&(e=rd(e));for(var t=this._groups,n=t.length,o=new Array(n),s=0;s<n;++s)for(var a=t[s],i=a.length,l=o[s]=new Array(i),c,d,f=0;f<i;++f)(c=a[f])&&(d=e.call(c,c.__data__,f,a))&&("__data__"in c&&(d.__data__=c.__data__),l[f]=d);return new ft(o,this._parents)}function g7(e){return e==null?[]:Array.isArray(e)?e:Array.from(e)}function b7(){return[]}function l0(e){return e==null?b7:function(){return this.querySelectorAll(e)}}function x7(e){return function(){return g7(e.apply(this,arguments))}}function y7(e){typeof e=="function"?e=x7(e):e=l0(e);for(var t=this._groups,n=t.length,o=[],s=[],a=0;a<n;++a)for(var i=t[a],l=i.length,c,d=0;d<l;++d)(c=i[d])&&(o.push(e.call(c,c.__data__,d,i)),s.push(c));return new ft(o,s)}function c0(e){return function(){return this.matches(e)}}function d0(e){return function(t){return t.matches(e)}}var v7=Array.prototype.find;function w7(e){return function(){return v7.call(this.children,e)}}function N7(){return this.firstElementChild}function k7(e){return this.select(e==null?N7:w7(typeof e=="function"?e:d0(e)))}var S7=Array.prototype.filter;function C7(){return Array.from(this.children)}function M7(e){return function(){return S7.call(this.children,e)}}function I7(e){return this.selectAll(e==null?C7:M7(typeof e=="function"?e:d0(e)))}function A7(e){typeof e!="function"&&(e=c0(e));for(var t=this._groups,n=t.length,o=new Array(n),s=0;s<n;++s)for(var a=t[s],i=a.length,l=o[s]=[],c,d=0;d<i;++d)(c=a[d])&&e.call(c,c.__data__,d,a)&&l.push(c);return new ft(o,this._parents)}function u0(e){return new Array(e.length)}function P7(){return new ft(this._enter||this._groups.map(u0),this._parents)}function zs(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}zs.prototype={constructor:zs,appendChild:function(e){return this._parent.insertBefore(e,this._next)},insertBefore:function(e,t){return this._parent.insertBefore(e,t)},querySelector:function(e){return this._parent.querySelector(e)},querySelectorAll:function(e){return this._parent.querySelectorAll(e)}};function E7(e){return function(){return e}}function $7(e,t,n,o,s,a){for(var i=0,l,c=t.length,d=a.length;i<d;++i)(l=t[i])?(l.__data__=a[i],o[i]=l):n[i]=new zs(e,a[i]);for(;i<c;++i)(l=t[i])&&(s[i]=l)}function _7(e,t,n,o,s,a,i){var l,c,d=new Map,f=t.length,p=a.length,m=new Array(f),h;for(l=0;l<f;++l)(c=t[l])&&(m[l]=h=i.call(c,c.__data__,l,t)+"",d.has(h)?s[l]=c:d.set(h,c));for(l=0;l<p;++l)h=i.call(e,a[l],l,a)+"",(c=d.get(h))?(o[l]=c,c.__data__=a[l],d.delete(h)):n[l]=new zs(e,a[l]);for(l=0;l<f;++l)(c=t[l])&&d.get(m[l])===c&&(s[l]=c)}function D7(e){return e.__data__}function L7(e,t){if(!arguments.length)return Array.from(this,D7);var n=t?_7:$7,o=this._parents,s=this._groups;typeof e!="function"&&(e=E7(e));for(var a=s.length,i=new Array(a),l=new Array(a),c=new Array(a),d=0;d<a;++d){var f=o[d],p=s[d],m=p.length,h=T7(e.call(f,f&&f.__data__,d,o)),g=h.length,b=l[d]=new Array(g),x=i[d]=new Array(g),v=c[d]=new Array(m);n(f,p,b,x,v,h,t);for(var w=0,y=0,N,k;w<g;++w)if(N=b[w]){for(w>=y&&(y=w+1);!(k=x[y])&&++y<g;);N._next=k||null}}return i=new ft(i,o),i._enter=l,i._exit=c,i}function T7(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function R7(){return new ft(this._exit||this._groups.map(u0),this._parents)}function O7(e,t,n){var o=this.enter(),s=this,a=this.exit();return typeof e=="function"?(o=e(o),o&&(o=o.selection())):o=o.append(e+""),t!=null&&(s=t(s),s&&(s=s.selection())),n==null?a.remove():n(a),o&&s?o.merge(s).order():s}function z7(e){for(var t=e.selection?e.selection():e,n=this._groups,o=t._groups,s=n.length,a=o.length,i=Math.min(s,a),l=new Array(s),c=0;c<i;++c)for(var d=n[c],f=o[c],p=d.length,m=l[c]=new Array(p),h,g=0;g<p;++g)(h=d[g]||f[g])&&(m[g]=h);for(;c<s;++c)l[c]=n[c];return new ft(l,this._parents)}function B7(){for(var e=this._groups,t=-1,n=e.length;++t<n;)for(var o=e[t],s=o.length-1,a=o[s],i;--s>=0;)(i=o[s])&&(a&&i.compareDocumentPosition(a)^4&&a.parentNode.insertBefore(i,a),a=i);return this}function F7(e){e||(e=j7);function t(p,m){return p&&m?e(p.__data__,m.__data__):!p-!m}for(var n=this._groups,o=n.length,s=new Array(o),a=0;a<o;++a){for(var i=n[a],l=i.length,c=s[a]=new Array(l),d,f=0;f<l;++f)(d=i[f])&&(c[f]=d);c.sort(t)}return new ft(s,this._parents).order()}function j7(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function H7(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function V7(){return Array.from(this)}function q7(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var o=e[t],s=0,a=o.length;s<a;++s){var i=o[s];if(i)return i}return null}function Q7(){let e=0;for(const t of this)++e;return e}function U7(){return!this.node()}function K7(e){for(var t=this._groups,n=0,o=t.length;n<o;++n)for(var s=t[n],a=0,i=s.length,l;a<i;++a)(l=s[a])&&e.call(l,l.__data__,a,s);return this}function G7(e){return function(){this.removeAttribute(e)}}function W7(e){return function(){this.removeAttributeNS(e.space,e.local)}}function Y7(e,t){return function(){this.setAttribute(e,t)}}function Z7(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function X7(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttribute(e):this.setAttribute(e,n)}}function J7(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttributeNS(e.space,e.local):this.setAttributeNS(e.space,e.local,n)}}function ez(e,t){var n=Ma(e);if(arguments.length<2){var o=this.node();return n.local?o.getAttributeNS(n.space,n.local):o.getAttribute(n)}return this.each((t==null?n.local?W7:G7:typeof t=="function"?n.local?J7:X7:n.local?Z7:Y7)(n,t))}function p0(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function tz(e){return function(){this.style.removeProperty(e)}}function nz(e,t,n){return function(){this.style.setProperty(e,t,n)}}function rz(e,t,n){return function(){var o=t.apply(this,arguments);o==null?this.style.removeProperty(e):this.style.setProperty(e,o,n)}}function oz(e,t,n){return arguments.length>1?this.each((t==null?tz:typeof t=="function"?rz:nz)(e,t,n??"")):vr(this.node(),e)}function vr(e,t){return e.style.getPropertyValue(t)||p0(e).getComputedStyle(e,null).getPropertyValue(t)}function sz(e){return function(){delete this[e]}}function az(e,t){return function(){this[e]=t}}function iz(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function lz(e,t){return arguments.length>1?this.each((t==null?sz:typeof t=="function"?iz:az)(e,t)):this.node()[e]}function f0(e){return e.trim().split(/^|\s+/)}function od(e){return e.classList||new m0(e)}function m0(e){this._node=e,this._names=f0(e.getAttribute("class")||"")}m0.prototype={add:function(e){var t=this._names.indexOf(e);t<0&&(this._names.push(e),this._node.setAttribute("class",this._names.join(" ")))},remove:function(e){var t=this._names.indexOf(e);t>=0&&(this._names.splice(t,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(e){return this._names.indexOf(e)>=0}};function h0(e,t){for(var n=od(e),o=-1,s=t.length;++o<s;)n.add(t[o])}function g0(e,t){for(var n=od(e),o=-1,s=t.length;++o<s;)n.remove(t[o])}function cz(e){return function(){h0(this,e)}}function dz(e){return function(){g0(this,e)}}function uz(e,t){return function(){(t.apply(this,arguments)?h0:g0)(this,e)}}function pz(e,t){var n=f0(e+"");if(arguments.length<2){for(var o=od(this.node()),s=-1,a=n.length;++s<a;)if(!o.contains(n[s]))return!1;return!0}return this.each((typeof t=="function"?uz:t?cz:dz)(n,t))}function fz(){this.textContent=""}function mz(e){return function(){this.textContent=e}}function hz(e){return function(){var t=e.apply(this,arguments);this.textContent=t??""}}function gz(e){return arguments.length?this.each(e==null?fz:(typeof e=="function"?hz:mz)(e)):this.node().textContent}function bz(){this.innerHTML=""}function xz(e){return function(){this.innerHTML=e}}function yz(e){return function(){var t=e.apply(this,arguments);this.innerHTML=t??""}}function vz(e){return arguments.length?this.each(e==null?bz:(typeof e=="function"?yz:xz)(e)):this.node().innerHTML}function wz(){this.nextSibling&&this.parentNode.appendChild(this)}function Nz(){return this.each(wz)}function kz(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function Sz(){return this.each(kz)}function Cz(e){var t=typeof e=="function"?e:i0(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})}function Mz(){return null}function Iz(e,t){var n=typeof e=="function"?e:i0(e),o=t==null?Mz:typeof t=="function"?t:rd(t);return this.select(function(){return this.insertBefore(n.apply(this,arguments),o.apply(this,arguments)||null)})}function Az(){var e=this.parentNode;e&&e.removeChild(this)}function Pz(){return this.each(Az)}function Ez(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function $z(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function _z(e){return this.select(e?$z:Ez)}function Dz(e){return arguments.length?this.property("__data__",e):this.node().__data__}function Lz(e){return function(t){e.call(this,t,this.__data__)}}function Tz(e){return e.trim().split(/^|\s+/).map(function(t){var n="",o=t.indexOf(".");return o>=0&&(n=t.slice(o+1),t=t.slice(0,o)),{type:t,name:n}})}function Rz(e){return function(){var t=this.__on;if(t){for(var n=0,o=-1,s=t.length,a;n<s;++n)a=t[n],(!e.type||a.type===e.type)&&a.name===e.name?this.removeEventListener(a.type,a.listener,a.options):t[++o]=a;++o?t.length=o:delete this.__on}}}function Oz(e,t,n){return function(){var o=this.__on,s,a=Lz(t);if(o){for(var i=0,l=o.length;i<l;++i)if((s=o[i]).type===e.type&&s.name===e.name){this.removeEventListener(s.type,s.listener,s.options),this.addEventListener(s.type,s.listener=a,s.options=n),s.value=t;return}}this.addEventListener(e.type,a,n),s={type:e.type,name:e.name,value:t,listener:a,options:n},o?o.push(s):this.__on=[s]}}function zz(e,t,n){var o=Tz(e+""),s,a=o.length,i;if(arguments.length<2){var l=this.node().__on;if(l){for(var c=0,d=l.length,f;c<d;++c)for(s=0,f=l[c];s<a;++s)if((i=o[s]).type===f.type&&i.name===f.name)return f.value}return}for(l=t?Oz:Rz,s=0;s<a;++s)this.each(l(o[s],t,n));return this}function b0(e,t,n){var o=p0(e),s=o.CustomEvent;typeof s=="function"?s=new s(t,n):(s=o.document.createEvent("Event"),n?(s.initEvent(t,n.bubbles,n.cancelable),s.detail=n.detail):s.initEvent(t,!1,!1)),e.dispatchEvent(s)}function Bz(e,t){return function(){return b0(this,e,t)}}function Fz(e,t){return function(){return b0(this,e,t.apply(this,arguments))}}function jz(e,t){return this.each((typeof t=="function"?Fz:Bz)(e,t))}function*Hz(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var o=e[t],s=0,a=o.length,i;s<a;++s)(i=o[s])&&(yield i)}var x0=[null];function ft(e,t){this._groups=e,this._parents=t}function $o(){return new ft([[document.documentElement]],x0)}function Vz(){return this}ft.prototype=$o.prototype={constructor:ft,select:h7,selectAll:y7,selectChild:k7,selectChildren:I7,filter:A7,data:L7,enter:P7,exit:R7,join:O7,merge:z7,selection:Vz,order:B7,sort:F7,call:H7,nodes:V7,node:q7,size:Q7,empty:U7,each:K7,attr:ez,style:oz,property:lz,classed:pz,text:gz,html:vz,raise:Nz,lower:Sz,append:Cz,insert:Iz,remove:Pz,clone:_z,datum:Dz,on:zz,dispatch:jz,[Symbol.iterator]:Hz};function lt(e){return typeof e=="string"?new ft([[document.querySelector(e)]],[document.documentElement]):new ft([[e]],x0)}function qz(e){let t;for(;t=e.sourceEvent;)e=t;return e}function Pt(e,t){if(e=qz(e),t===void 0&&(t=e.currentTarget),t){var n=t.ownerSVGElement||t;if(n.createSVGPoint){var o=n.createSVGPoint();return o.x=e.clientX,o.y=e.clientY,o=o.matrixTransform(t.getScreenCTM().inverse()),[o.x,o.y]}if(t.getBoundingClientRect){var s=t.getBoundingClientRect();return[e.clientX-s.left-t.clientLeft,e.clientY-s.top-t.clientTop]}}return[e.pageX,e.pageY]}const Qz={passive:!1},uo={capture:!0,passive:!1};function ki(e){e.stopImmediatePropagation()}function ur(e){e.preventDefault(),e.stopImmediatePropagation()}function y0(e){var t=e.document.documentElement,n=lt(e).on("dragstart.drag",ur,uo);"onselectstart"in t?n.on("selectstart.drag",ur,uo):(t.__noselect=t.style.MozUserSelect,t.style.MozUserSelect="none")}function v0(e,t){var n=e.document.documentElement,o=lt(e).on("dragstart.drag",null);t&&(o.on("click.drag",ur,uo),setTimeout(function(){o.on("click.drag",null)},0)),"onselectstart"in n?o.on("selectstart.drag",null):(n.style.MozUserSelect=n.__noselect,delete n.__noselect)}const rs=e=>()=>e;function ml(e,{sourceEvent:t,subject:n,target:o,identifier:s,active:a,x:i,y:l,dx:c,dy:d,dispatch:f}){Object.defineProperties(this,{type:{value:e,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},subject:{value:n,enumerable:!0,configurable:!0},target:{value:o,enumerable:!0,configurable:!0},identifier:{value:s,enumerable:!0,configurable:!0},active:{value:a,enumerable:!0,configurable:!0},x:{value:i,enumerable:!0,configurable:!0},y:{value:l,enumerable:!0,configurable:!0},dx:{value:c,enumerable:!0,configurable:!0},dy:{value:d,enumerable:!0,configurable:!0},_:{value:f}})}ml.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};function Uz(e){return!e.ctrlKey&&!e.button}function Kz(){return this.parentNode}function Gz(e,t){return t??{x:e.x,y:e.y}}function Wz(){return navigator.maxTouchPoints||"ontouchstart"in this}function w0(){var e=Uz,t=Kz,n=Gz,o=Wz,s={},a=Ca("start","drag","end"),i=0,l,c,d,f,p=0;function m(N){N.on("mousedown.drag",h).filter(o).on("touchstart.drag",x).on("touchmove.drag",v,Qz).on("touchend.drag touchcancel.drag",w).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function h(N,k){if(!(f||!e.call(this,N,k))){var S=y(this,t.call(this,N,k),N,k,"mouse");S&&(lt(N.view).on("mousemove.drag",g,uo).on("mouseup.drag",b,uo),y0(N.view),ki(N),d=!1,l=N.clientX,c=N.clientY,S("start",N))}}function g(N){if(ur(N),!d){var k=N.clientX-l,S=N.clientY-c;d=k*k+S*S>p}s.mouse("drag",N)}function b(N){lt(N.view).on("mousemove.drag mouseup.drag",null),v0(N.view,d),ur(N),s.mouse("end",N)}function x(N,k){if(e.call(this,N,k)){var S=N.changedTouches,M=t.call(this,N,k),P=S.length,I,F;for(I=0;I<P;++I)(F=y(this,M,N,k,S[I].identifier,S[I]))&&(ki(N),F("start",N,S[I]))}}function v(N){var k=N.changedTouches,S=k.length,M,P;for(M=0;M<S;++M)(P=s[k[M].identifier])&&(ur(N),P("drag",N,k[M]))}function w(N){var k=N.changedTouches,S=k.length,M,P;for(f&&clearTimeout(f),f=setTimeout(function(){f=null},500),M=0;M<S;++M)(P=s[k[M].identifier])&&(ki(N),P("end",N,k[M]))}function y(N,k,S,M,P,I){var F=a.copy(),E=Pt(I||S,k),B,O,A;if((A=n.call(N,new ml("beforestart",{sourceEvent:S,target:m,identifier:P,active:i,x:E[0],y:E[1],dx:0,dy:0,dispatch:F}),M))!=null)return B=A.x-E[0]||0,O=A.y-E[1]||0,function D(_,R,L){var z=E,j;switch(_){case"start":s[P]=D,j=i++;break;case"end":delete s[P],--i;case"drag":E=Pt(L||R,k),j=i;break}F.call(_,N,new ml(_,{sourceEvent:R,subject:A,target:m,identifier:P,active:j,x:E[0]+B,y:E[1]+O,dx:E[0]-z[0],dy:E[1]-z[1],dispatch:F}),M)}}return m.filter=function(N){return arguments.length?(e=typeof N=="function"?N:rs(!!N),m):e},m.container=function(N){return arguments.length?(t=typeof N=="function"?N:rs(N),m):t},m.subject=function(N){return arguments.length?(n=typeof N=="function"?N:rs(N),m):n},m.touchable=function(N){return arguments.length?(o=typeof N=="function"?N:rs(!!N),m):o},m.on=function(){var N=a.on.apply(a,arguments);return N===a?m:N},m.clickDistance=function(N){return arguments.length?(p=(N=+N)*N,m):Math.sqrt(p)},m}function sd(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function N0(e,t){var n=Object.create(e.prototype);for(var o in t)n[o]=t[o];return n}function _o(){}var po=.7,Bs=1/po,pr="\\s*([+-]?\\d+)\\s*",fo="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",Ut="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",Yz=/^#([0-9a-f]{3,8})$/,Zz=new RegExp(`^rgb\\(${pr},${pr},${pr}\\)$`),Xz=new RegExp(`^rgb\\(${Ut},${Ut},${Ut}\\)$`),Jz=new RegExp(`^rgba\\(${pr},${pr},${pr},${fo}\\)$`),eB=new RegExp(`^rgba\\(${Ut},${Ut},${Ut},${fo}\\)$`),tB=new RegExp(`^hsl\\(${fo},${Ut},${Ut}\\)$`),nB=new RegExp(`^hsla\\(${fo},${Ut},${Ut},${fo}\\)$`),Cp={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074};sd(_o,Vn,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:Mp,formatHex:Mp,formatHex8:rB,formatHsl:oB,formatRgb:Ip,toString:Ip});function Mp(){return this.rgb().formatHex()}function rB(){return this.rgb().formatHex8()}function oB(){return k0(this).formatHsl()}function Ip(){return this.rgb().formatRgb()}function Vn(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=Yz.exec(e))?(n=t[1].length,t=parseInt(t[1],16),n===6?Ap(t):n===3?new nt(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?os(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?os(t>>12&15|t>>8&240,t>>8&15|t>>4&240,t>>4&15|t&240,((t&15)<<4|t&15)/255):null):(t=Zz.exec(e))?new nt(t[1],t[2],t[3],1):(t=Xz.exec(e))?new nt(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=Jz.exec(e))?os(t[1],t[2],t[3],t[4]):(t=eB.exec(e))?os(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=tB.exec(e))?$p(t[1],t[2]/100,t[3]/100,1):(t=nB.exec(e))?$p(t[1],t[2]/100,t[3]/100,t[4]):Cp.hasOwnProperty(e)?Ap(Cp[e]):e==="transparent"?new nt(NaN,NaN,NaN,0):null}function Ap(e){return new nt(e>>16&255,e>>8&255,e&255,1)}function os(e,t,n,o){return o<=0&&(e=t=n=NaN),new nt(e,t,n,o)}function sB(e){return e instanceof _o||(e=Vn(e)),e?(e=e.rgb(),new nt(e.r,e.g,e.b,e.opacity)):new nt}function hl(e,t,n,o){return arguments.length===1?sB(e):new nt(e,t,n,o??1)}function nt(e,t,n,o){this.r=+e,this.g=+t,this.b=+n,this.opacity=+o}sd(nt,hl,N0(_o,{brighter(e){return e=e==null?Bs:Math.pow(Bs,e),new nt(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?po:Math.pow(po,e),new nt(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new nt(zn(this.r),zn(this.g),zn(this.b),Fs(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:Pp,formatHex:Pp,formatHex8:aB,formatRgb:Ep,toString:Ep}));function Pp(){return`#${Tn(this.r)}${Tn(this.g)}${Tn(this.b)}`}function aB(){return`#${Tn(this.r)}${Tn(this.g)}${Tn(this.b)}${Tn((isNaN(this.opacity)?1:this.opacity)*255)}`}function Ep(){const e=Fs(this.opacity);return`${e===1?"rgb(":"rgba("}${zn(this.r)}, ${zn(this.g)}, ${zn(this.b)}${e===1?")":`, ${e})`}`}function Fs(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function zn(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function Tn(e){return e=zn(e),(e<16?"0":"")+e.toString(16)}function $p(e,t,n,o){return o<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new Et(e,t,n,o)}function k0(e){if(e instanceof Et)return new Et(e.h,e.s,e.l,e.opacity);if(e instanceof _o||(e=Vn(e)),!e)return new Et;if(e instanceof Et)return e;e=e.rgb();var t=e.r/255,n=e.g/255,o=e.b/255,s=Math.min(t,n,o),a=Math.max(t,n,o),i=NaN,l=a-s,c=(a+s)/2;return l?(t===a?i=(n-o)/l+(n<o)*6:n===a?i=(o-t)/l+2:i=(t-n)/l+4,l/=c<.5?a+s:2-a-s,i*=60):l=c>0&&c<1?0:i,new Et(i,l,c,e.opacity)}function iB(e,t,n,o){return arguments.length===1?k0(e):new Et(e,t,n,o??1)}function Et(e,t,n,o){this.h=+e,this.s=+t,this.l=+n,this.opacity=+o}sd(Et,iB,N0(_o,{brighter(e){return e=e==null?Bs:Math.pow(Bs,e),new Et(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?po:Math.pow(po,e),new Et(this.h,this.s,this.l*e,this.opacity)},rgb(){var e=this.h%360+(this.h<0)*360,t=isNaN(e)||isNaN(this.s)?0:this.s,n=this.l,o=n+(n<.5?n:1-n)*t,s=2*n-o;return new nt(Si(e>=240?e-240:e+120,s,o),Si(e,s,o),Si(e<120?e+240:e-120,s,o),this.opacity)},clamp(){return new Et(_p(this.h),ss(this.s),ss(this.l),Fs(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){const e=Fs(this.opacity);return`${e===1?"hsl(":"hsla("}${_p(this.h)}, ${ss(this.s)*100}%, ${ss(this.l)*100}%${e===1?")":`, ${e})`}`}}));function _p(e){return e=(e||0)%360,e<0?e+360:e}function ss(e){return Math.max(0,Math.min(1,e||0))}function Si(e,t,n){return(e<60?t+(n-t)*e/60:e<180?n:e<240?t+(n-t)*(240-e)/60:t)*255}const ad=e=>()=>e;function lB(e,t){return function(n){return e+n*t}}function cB(e,t,n){return e=Math.pow(e,n),t=Math.pow(t,n)-e,n=1/n,function(o){return Math.pow(e+o*t,n)}}function dB(e){return(e=+e)==1?S0:function(t,n){return n-t?cB(t,n,e):ad(isNaN(t)?n:t)}}function S0(e,t){var n=t-e;return n?lB(e,n):ad(isNaN(e)?t:e)}const js=(function e(t){var n=dB(t);function o(s,a){var i=n((s=hl(s)).r,(a=hl(a)).r),l=n(s.g,a.g),c=n(s.b,a.b),d=S0(s.opacity,a.opacity);return function(f){return s.r=i(f),s.g=l(f),s.b=c(f),s.opacity=d(f),s+""}}return o.gamma=e,o})(1);function uB(e,t){t||(t=[]);var n=e?Math.min(t.length,e.length):0,o=t.slice(),s;return function(a){for(s=0;s<n;++s)o[s]=e[s]*(1-a)+t[s]*a;return o}}function pB(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function fB(e,t){var n=t?t.length:0,o=e?Math.min(n,e.length):0,s=new Array(o),a=new Array(n),i;for(i=0;i<o;++i)s[i]=no(e[i],t[i]);for(;i<n;++i)a[i]=t[i];return function(l){for(i=0;i<o;++i)a[i]=s[i](l);return a}}function mB(e,t){var n=new Date;return e=+e,t=+t,function(o){return n.setTime(e*(1-o)+t*o),n}}function Vt(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}function hB(e,t){var n={},o={},s;(e===null||typeof e!="object")&&(e={}),(t===null||typeof t!="object")&&(t={});for(s in t)s in e?n[s]=no(e[s],t[s]):o[s]=t[s];return function(a){for(s in n)o[s]=n[s](a);return o}}var gl=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,Ci=new RegExp(gl.source,"g");function gB(e){return function(){return e}}function bB(e){return function(t){return e(t)+""}}function C0(e,t){var n=gl.lastIndex=Ci.lastIndex=0,o,s,a,i=-1,l=[],c=[];for(e=e+"",t=t+"";(o=gl.exec(e))&&(s=Ci.exec(t));)(a=s.index)>n&&(a=t.slice(n,a),l[i]?l[i]+=a:l[++i]=a),(o=o[0])===(s=s[0])?l[i]?l[i]+=s:l[++i]=s:(l[++i]=null,c.push({i,x:Vt(o,s)})),n=Ci.lastIndex;return n<t.length&&(a=t.slice(n),l[i]?l[i]+=a:l[++i]=a),l.length<2?c[0]?bB(c[0].x):gB(t):(t=c.length,function(d){for(var f=0,p;f<t;++f)l[(p=c[f]).i]=p.x(d);return l.join("")})}function no(e,t){var n=typeof t,o;return t==null||n==="boolean"?ad(t):(n==="number"?Vt:n==="string"?(o=Vn(t))?(t=o,js):C0:t instanceof Vn?js:t instanceof Date?mB:pB(t)?uB:Array.isArray(t)?fB:typeof t.valueOf!="function"&&typeof t.toString!="function"||isNaN(t)?hB:Vt)(e,t)}var Dp=180/Math.PI,bl={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function M0(e,t,n,o,s,a){var i,l,c;return(i=Math.sqrt(e*e+t*t))&&(e/=i,t/=i),(c=e*n+t*o)&&(n-=e*c,o-=t*c),(l=Math.sqrt(n*n+o*o))&&(n/=l,o/=l,c/=l),e*o<t*n&&(e=-e,t=-t,c=-c,i=-i),{translateX:s,translateY:a,rotate:Math.atan2(t,e)*Dp,skewX:Math.atan(c)*Dp,scaleX:i,scaleY:l}}var as;function xB(e){const t=new(typeof DOMMatrix=="function"?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?bl:M0(t.a,t.b,t.c,t.d,t.e,t.f)}function yB(e){return e==null||(as||(as=document.createElementNS("http://www.w3.org/2000/svg","g")),as.setAttribute("transform",e),!(e=as.transform.baseVal.consolidate()))?bl:(e=e.matrix,M0(e.a,e.b,e.c,e.d,e.e,e.f))}function I0(e,t,n,o){function s(d){return d.length?d.pop()+" ":""}function a(d,f,p,m,h,g){if(d!==p||f!==m){var b=h.push("translate(",null,t,null,n);g.push({i:b-4,x:Vt(d,p)},{i:b-2,x:Vt(f,m)})}else(p||m)&&h.push("translate("+p+t+m+n)}function i(d,f,p,m){d!==f?(d-f>180?f+=360:f-d>180&&(d+=360),m.push({i:p.push(s(p)+"rotate(",null,o)-2,x:Vt(d,f)})):f&&p.push(s(p)+"rotate("+f+o)}function l(d,f,p,m){d!==f?m.push({i:p.push(s(p)+"skewX(",null,o)-2,x:Vt(d,f)}):f&&p.push(s(p)+"skewX("+f+o)}function c(d,f,p,m,h,g){if(d!==p||f!==m){var b=h.push(s(h)+"scale(",null,",",null,")");g.push({i:b-4,x:Vt(d,p)},{i:b-2,x:Vt(f,m)})}else(p!==1||m!==1)&&h.push(s(h)+"scale("+p+","+m+")")}return function(d,f){var p=[],m=[];return d=e(d),f=e(f),a(d.translateX,d.translateY,f.translateX,f.translateY,p,m),i(d.rotate,f.rotate,p,m),l(d.skewX,f.skewX,p,m),c(d.scaleX,d.scaleY,f.scaleX,f.scaleY,p,m),d=f=null,function(h){for(var g=-1,b=m.length,x;++g<b;)p[(x=m[g]).i]=x.x(h);return p.join("")}}}var vB=I0(xB,"px, ","px)","deg)"),wB=I0(yB,", ",")",")"),NB=1e-12;function Lp(e){return((e=Math.exp(e))+1/e)/2}function kB(e){return((e=Math.exp(e))-1/e)/2}function SB(e){return((e=Math.exp(2*e))-1)/(e+1)}const xs=(function e(t,n,o){function s(a,i){var l=a[0],c=a[1],d=a[2],f=i[0],p=i[1],m=i[2],h=f-l,g=p-c,b=h*h+g*g,x,v;if(b<NB)v=Math.log(m/d)/t,x=function(M){return[l+M*h,c+M*g,d*Math.exp(t*M*v)]};else{var w=Math.sqrt(b),y=(m*m-d*d+o*b)/(2*d*n*w),N=(m*m-d*d-o*b)/(2*m*n*w),k=Math.log(Math.sqrt(y*y+1)-y),S=Math.log(Math.sqrt(N*N+1)-N);v=(S-k)/t,x=function(M){var P=M*v,I=Lp(k),F=d/(n*w)*(I*SB(t*P+k)-kB(k));return[l+F*h,c+F*g,d*I/Lp(t*P+k)]}}return x.duration=v*1e3*t/Math.SQRT2,x}return s.rho=function(a){var i=Math.max(.001,+a),l=i*i,c=l*l;return e(i,l,c)},s})(Math.SQRT2,2,4);var wr=0,Kr=0,Vr=0,A0=1e3,Hs,Gr,Vs=0,qn=0,Ia=0,mo=typeof performance=="object"&&performance.now?performance:Date,P0=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function id(){return qn||(P0(CB),qn=mo.now()+Ia)}function CB(){qn=0}function qs(){this._call=this._time=this._next=null}qs.prototype=E0.prototype={constructor:qs,restart:function(e,t,n){if(typeof e!="function")throw new TypeError("callback is not a function");n=(n==null?id():+n)+(t==null?0:+t),!this._next&&Gr!==this&&(Gr?Gr._next=this:Hs=this,Gr=this),this._call=e,this._time=n,xl()},stop:function(){this._call&&(this._call=null,this._time=1/0,xl())}};function E0(e,t,n){var o=new qs;return o.restart(e,t,n),o}function MB(){id(),++wr;for(var e=Hs,t;e;)(t=qn-e._time)>=0&&e._call.call(void 0,t),e=e._next;--wr}function Tp(){qn=(Vs=mo.now())+Ia,wr=Kr=0;try{MB()}finally{wr=0,AB(),qn=0}}function IB(){var e=mo.now(),t=e-Vs;t>A0&&(Ia-=t,Vs=e)}function AB(){for(var e,t=Hs,n,o=1/0;t;)t._call?(o>t._time&&(o=t._time),e=t,t=t._next):(n=t._next,t._next=null,t=e?e._next=n:Hs=n);Gr=e,xl(o)}function xl(e){if(!wr){Kr&&(Kr=clearTimeout(Kr));var t=e-qn;t>24?(e<1/0&&(Kr=setTimeout(Tp,e-mo.now()-Ia)),Vr&&(Vr=clearInterval(Vr))):(Vr||(Vs=mo.now(),Vr=setInterval(IB,A0)),wr=1,P0(Tp))}}function Rp(e,t,n){var o=new qs;return t=t==null?0:+t,o.restart(s=>{o.stop(),e(s+t)},t,n),o}var PB=Ca("start","end","cancel","interrupt"),EB=[],$0=0,Op=1,yl=2,ys=3,zp=4,vl=5,vs=6;function Aa(e,t,n,o,s,a){var i=e.__transition;if(!i)e.__transition={};else if(n in i)return;$B(e,n,{name:t,index:o,group:s,on:PB,tween:EB,time:a.time,delay:a.delay,duration:a.duration,ease:a.ease,timer:null,state:$0})}function ld(e,t){var n=Bt(e,t);if(n.state>$0)throw new Error("too late; already scheduled");return n}function Yt(e,t){var n=Bt(e,t);if(n.state>ys)throw new Error("too late; already running");return n}function Bt(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw new Error("transition not found");return n}function $B(e,t,n){var o=e.__transition,s;o[t]=n,n.timer=E0(a,0,n.time);function a(d){n.state=Op,n.timer.restart(i,n.delay,n.time),n.delay<=d&&i(d-n.delay)}function i(d){var f,p,m,h;if(n.state!==Op)return c();for(f in o)if(h=o[f],h.name===n.name){if(h.state===ys)return Rp(i);h.state===zp?(h.state=vs,h.timer.stop(),h.on.call("interrupt",e,e.__data__,h.index,h.group),delete o[f]):+f<t&&(h.state=vs,h.timer.stop(),h.on.call("cancel",e,e.__data__,h.index,h.group),delete o[f])}if(Rp(function(){n.state===ys&&(n.state=zp,n.timer.restart(l,n.delay,n.time),l(d))}),n.state=yl,n.on.call("start",e,e.__data__,n.index,n.group),n.state===yl){for(n.state=ys,s=new Array(m=n.tween.length),f=0,p=-1;f<m;++f)(h=n.tween[f].value.call(e,e.__data__,n.index,n.group))&&(s[++p]=h);s.length=p+1}}function l(d){for(var f=d<n.duration?n.ease.call(null,d/n.duration):(n.timer.restart(c),n.state=vl,1),p=-1,m=s.length;++p<m;)s[p].call(e,f);n.state===vl&&(n.on.call("end",e,e.__data__,n.index,n.group),c())}function c(){n.state=vs,n.timer.stop(),delete o[t];for(var d in o)return;delete e.__transition}}function ws(e,t){var n=e.__transition,o,s,a=!0,i;if(n){t=t==null?null:t+"";for(i in n){if((o=n[i]).name!==t){a=!1;continue}s=o.state>yl&&o.state<vl,o.state=vs,o.timer.stop(),o.on.call(s?"interrupt":"cancel",e,e.__data__,o.index,o.group),delete n[i]}a&&delete e.__transition}}function _B(e){return this.each(function(){ws(this,e)})}function DB(e,t){var n,o;return function(){var s=Yt(this,e),a=s.tween;if(a!==n){o=n=a;for(var i=0,l=o.length;i<l;++i)if(o[i].name===t){o=o.slice(),o.splice(i,1);break}}s.tween=o}}function LB(e,t,n){var o,s;if(typeof n!="function")throw new Error;return function(){var a=Yt(this,e),i=a.tween;if(i!==o){s=(o=i).slice();for(var l={name:t,value:n},c=0,d=s.length;c<d;++c)if(s[c].name===t){s[c]=l;break}c===d&&s.push(l)}a.tween=s}}function TB(e,t){var n=this._id;if(e+="",arguments.length<2){for(var o=Bt(this.node(),n).tween,s=0,a=o.length,i;s<a;++s)if((i=o[s]).name===e)return i.value;return null}return this.each((t==null?DB:LB)(n,e,t))}function cd(e,t,n){var o=e._id;return e.each(function(){var s=Yt(this,o);(s.value||(s.value={}))[t]=n.apply(this,arguments)}),function(s){return Bt(s,o).value[t]}}function _0(e,t){var n;return(typeof t=="number"?Vt:t instanceof Vn?js:(n=Vn(t))?(t=n,js):C0)(e,t)}function RB(e){return function(){this.removeAttribute(e)}}function OB(e){return function(){this.removeAttributeNS(e.space,e.local)}}function zB(e,t,n){var o,s=n+"",a;return function(){var i=this.getAttribute(e);return i===s?null:i===o?a:a=t(o=i,n)}}function BB(e,t,n){var o,s=n+"",a;return function(){var i=this.getAttributeNS(e.space,e.local);return i===s?null:i===o?a:a=t(o=i,n)}}function FB(e,t,n){var o,s,a;return function(){var i,l=n(this),c;return l==null?void this.removeAttribute(e):(i=this.getAttribute(e),c=l+"",i===c?null:i===o&&c===s?a:(s=c,a=t(o=i,l)))}}function jB(e,t,n){var o,s,a;return function(){var i,l=n(this),c;return l==null?void this.removeAttributeNS(e.space,e.local):(i=this.getAttributeNS(e.space,e.local),c=l+"",i===c?null:i===o&&c===s?a:(s=c,a=t(o=i,l)))}}function HB(e,t){var n=Ma(e),o=n==="transform"?wB:_0;return this.attrTween(e,typeof t=="function"?(n.local?jB:FB)(n,o,cd(this,"attr."+e,t)):t==null?(n.local?OB:RB)(n):(n.local?BB:zB)(n,o,t))}function VB(e,t){return function(n){this.setAttribute(e,t.call(this,n))}}function qB(e,t){return function(n){this.setAttributeNS(e.space,e.local,t.call(this,n))}}function QB(e,t){var n,o;function s(){var a=t.apply(this,arguments);return a!==o&&(n=(o=a)&&qB(e,a)),n}return s._value=t,s}function UB(e,t){var n,o;function s(){var a=t.apply(this,arguments);return a!==o&&(n=(o=a)&&VB(e,a)),n}return s._value=t,s}function KB(e,t){var n="attr."+e;if(arguments.length<2)return(n=this.tween(n))&&n._value;if(t==null)return this.tween(n,null);if(typeof t!="function")throw new Error;var o=Ma(e);return this.tween(n,(o.local?QB:UB)(o,t))}function GB(e,t){return function(){ld(this,e).delay=+t.apply(this,arguments)}}function WB(e,t){return t=+t,function(){ld(this,e).delay=t}}function YB(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?GB:WB)(t,e)):Bt(this.node(),t).delay}function ZB(e,t){return function(){Yt(this,e).duration=+t.apply(this,arguments)}}function XB(e,t){return t=+t,function(){Yt(this,e).duration=t}}function JB(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?ZB:XB)(t,e)):Bt(this.node(),t).duration}function eF(e,t){if(typeof t!="function")throw new Error;return function(){Yt(this,e).ease=t}}function tF(e){var t=this._id;return arguments.length?this.each(eF(t,e)):Bt(this.node(),t).ease}function nF(e,t){return function(){var n=t.apply(this,arguments);if(typeof n!="function")throw new Error;Yt(this,e).ease=n}}function rF(e){if(typeof e!="function")throw new Error;return this.each(nF(this._id,e))}function oF(e){typeof e!="function"&&(e=c0(e));for(var t=this._groups,n=t.length,o=new Array(n),s=0;s<n;++s)for(var a=t[s],i=a.length,l=o[s]=[],c,d=0;d<i;++d)(c=a[d])&&e.call(c,c.__data__,d,a)&&l.push(c);return new dn(o,this._parents,this._name,this._id)}function sF(e){if(e._id!==this._id)throw new Error;for(var t=this._groups,n=e._groups,o=t.length,s=n.length,a=Math.min(o,s),i=new Array(o),l=0;l<a;++l)for(var c=t[l],d=n[l],f=c.length,p=i[l]=new Array(f),m,h=0;h<f;++h)(m=c[h]||d[h])&&(p[h]=m);for(;l<o;++l)i[l]=t[l];return new dn(i,this._parents,this._name,this._id)}function aF(e){return(e+"").trim().split(/^|\s+/).every(function(t){var n=t.indexOf(".");return n>=0&&(t=t.slice(0,n)),!t||t==="start"})}function iF(e,t,n){var o,s,a=aF(t)?ld:Yt;return function(){var i=a(this,e),l=i.on;l!==o&&(s=(o=l).copy()).on(t,n),i.on=s}}function lF(e,t){var n=this._id;return arguments.length<2?Bt(this.node(),n).on.on(e):this.each(iF(n,e,t))}function cF(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function dF(){return this.on("end.remove",cF(this._id))}function uF(e){var t=this._name,n=this._id;typeof e!="function"&&(e=rd(e));for(var o=this._groups,s=o.length,a=new Array(s),i=0;i<s;++i)for(var l=o[i],c=l.length,d=a[i]=new Array(c),f,p,m=0;m<c;++m)(f=l[m])&&(p=e.call(f,f.__data__,m,l))&&("__data__"in f&&(p.__data__=f.__data__),d[m]=p,Aa(d[m],t,n,m,d,Bt(f,n)));return new dn(a,this._parents,t,n)}function pF(e){var t=this._name,n=this._id;typeof e!="function"&&(e=l0(e));for(var o=this._groups,s=o.length,a=[],i=[],l=0;l<s;++l)for(var c=o[l],d=c.length,f,p=0;p<d;++p)if(f=c[p]){for(var m=e.call(f,f.__data__,p,c),h,g=Bt(f,n),b=0,x=m.length;b<x;++b)(h=m[b])&&Aa(h,t,n,b,m,g);a.push(m),i.push(f)}return new dn(a,i,t,n)}var fF=$o.prototype.constructor;function mF(){return new fF(this._groups,this._parents)}function hF(e,t){var n,o,s;return function(){var a=vr(this,e),i=(this.style.removeProperty(e),vr(this,e));return a===i?null:a===n&&i===o?s:s=t(n=a,o=i)}}function D0(e){return function(){this.style.removeProperty(e)}}function gF(e,t,n){var o,s=n+"",a;return function(){var i=vr(this,e);return i===s?null:i===o?a:a=t(o=i,n)}}function bF(e,t,n){var o,s,a;return function(){var i=vr(this,e),l=n(this),c=l+"";return l==null&&(c=l=(this.style.removeProperty(e),vr(this,e))),i===c?null:i===o&&c===s?a:(s=c,a=t(o=i,l))}}function xF(e,t){var n,o,s,a="style."+t,i="end."+a,l;return function(){var c=Yt(this,e),d=c.on,f=c.value[a]==null?l||(l=D0(t)):void 0;(d!==n||s!==f)&&(o=(n=d).copy()).on(i,s=f),c.on=o}}function yF(e,t,n){var o=(e+="")=="transform"?vB:_0;return t==null?this.styleTween(e,hF(e,o)).on("end.style."+e,D0(e)):typeof t=="function"?this.styleTween(e,bF(e,o,cd(this,"style."+e,t))).each(xF(this._id,e)):this.styleTween(e,gF(e,o,t),n).on("end.style."+e,null)}function vF(e,t,n){return function(o){this.style.setProperty(e,t.call(this,o),n)}}function wF(e,t,n){var o,s;function a(){var i=t.apply(this,arguments);return i!==s&&(o=(s=i)&&vF(e,i,n)),o}return a._value=t,a}function NF(e,t,n){var o="style."+(e+="");if(arguments.length<2)return(o=this.tween(o))&&o._value;if(t==null)return this.tween(o,null);if(typeof t!="function")throw new Error;return this.tween(o,wF(e,t,n??""))}function kF(e){return function(){this.textContent=e}}function SF(e){return function(){var t=e(this);this.textContent=t??""}}function CF(e){return this.tween("text",typeof e=="function"?SF(cd(this,"text",e)):kF(e==null?"":e+""))}function MF(e){return function(t){this.textContent=e.call(this,t)}}function IF(e){var t,n;function o(){var s=e.apply(this,arguments);return s!==n&&(t=(n=s)&&MF(s)),t}return o._value=e,o}function AF(e){var t="text";if(arguments.length<1)return(t=this.tween(t))&&t._value;if(e==null)return this.tween(t,null);if(typeof e!="function")throw new Error;return this.tween(t,IF(e))}function PF(){for(var e=this._name,t=this._id,n=L0(),o=this._groups,s=o.length,a=0;a<s;++a)for(var i=o[a],l=i.length,c,d=0;d<l;++d)if(c=i[d]){var f=Bt(c,t);Aa(c,e,n,d,i,{time:f.time+f.delay+f.duration,delay:0,duration:f.duration,ease:f.ease})}return new dn(o,this._parents,e,n)}function EF(){var e,t,n=this,o=n._id,s=n.size();return new Promise(function(a,i){var l={value:i},c={value:function(){--s===0&&a()}};n.each(function(){var d=Yt(this,o),f=d.on;f!==e&&(t=(e=f).copy(),t._.cancel.push(l),t._.interrupt.push(l),t._.end.push(c)),d.on=t}),s===0&&a()})}var $F=0;function dn(e,t,n,o){this._groups=e,this._parents=t,this._name=n,this._id=o}function L0(){return++$F}var Jt=$o.prototype;dn.prototype={constructor:dn,select:uF,selectAll:pF,selectChild:Jt.selectChild,selectChildren:Jt.selectChildren,filter:oF,merge:sF,selection:mF,transition:PF,call:Jt.call,nodes:Jt.nodes,node:Jt.node,size:Jt.size,empty:Jt.empty,each:Jt.each,on:lF,attr:HB,attrTween:KB,style:yF,styleTween:NF,text:CF,textTween:AF,remove:dF,tween:TB,delay:YB,duration:JB,ease:tF,easeVarying:rF,end:EF,[Symbol.iterator]:Jt[Symbol.iterator]};function _F(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}var DF={time:null,delay:0,duration:250,ease:_F};function LF(e,t){for(var n;!(n=e.__transition)||!(n=n[t]);)if(!(e=e.parentNode))throw new Error(`transition ${t} not found`);return n}function TF(e){var t,n;e instanceof dn?(t=e._id,e=e._name):(t=L0(),(n=DF).time=id(),e=e==null?null:e+"");for(var o=this._groups,s=o.length,a=0;a<s;++a)for(var i=o[a],l=i.length,c,d=0;d<l;++d)(c=i[d])&&Aa(c,e,t,d,i,n||LF(c,t));return new dn(o,this._parents,e,t)}$o.prototype.interrupt=_B;$o.prototype.transition=TF;const is=e=>()=>e;function RF(e,{sourceEvent:t,target:n,transform:o,dispatch:s}){Object.defineProperties(this,{type:{value:e,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},target:{value:n,enumerable:!0,configurable:!0},transform:{value:o,enumerable:!0,configurable:!0},_:{value:s}})}function nn(e,t,n){this.k=e,this.x=t,this.y=n}nn.prototype={constructor:nn,scale:function(e){return e===1?this:new nn(this.k*e,this.x,this.y)},translate:function(e,t){return e===0&t===0?this:new nn(this.k,this.x+this.k*e,this.y+this.k*t)},apply:function(e){return[e[0]*this.k+this.x,e[1]*this.k+this.y]},applyX:function(e){return e*this.k+this.x},applyY:function(e){return e*this.k+this.y},invert:function(e){return[(e[0]-this.x)/this.k,(e[1]-this.y)/this.k]},invertX:function(e){return(e-this.x)/this.k},invertY:function(e){return(e-this.y)/this.k},rescaleX:function(e){return e.copy().domain(e.range().map(this.invertX,this).map(e.invert,e))},rescaleY:function(e){return e.copy().domain(e.range().map(this.invertY,this).map(e.invert,e))},toString:function(){return"translate("+this.x+","+this.y+") scale("+this.k+")"}};var Pa=new nn(1,0,0);T0.prototype=nn.prototype;function T0(e){for(;!e.__zoom;)if(!(e=e.parentNode))return Pa;return e.__zoom}function Mi(e){e.stopImmediatePropagation()}function qr(e){e.preventDefault(),e.stopImmediatePropagation()}function OF(e){return(!e.ctrlKey||e.type==="wheel")&&!e.button}function zF(){var e=this;return e instanceof SVGElement?(e=e.ownerSVGElement||e,e.hasAttribute("viewBox")?(e=e.viewBox.baseVal,[[e.x,e.y],[e.x+e.width,e.y+e.height]]):[[0,0],[e.width.baseVal.value,e.height.baseVal.value]]):[[0,0],[e.clientWidth,e.clientHeight]]}function Bp(){return this.__zoom||Pa}function BF(e){return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function FF(){return navigator.maxTouchPoints||"ontouchstart"in this}function jF(e,t,n){var o=e.invertX(t[0][0])-n[0][0],s=e.invertX(t[1][0])-n[1][0],a=e.invertY(t[0][1])-n[0][1],i=e.invertY(t[1][1])-n[1][1];return e.translate(s>o?(o+s)/2:Math.min(0,o)||Math.max(0,s),i>a?(a+i)/2:Math.min(0,a)||Math.max(0,i))}function R0(){var e=OF,t=zF,n=jF,o=BF,s=FF,a=[0,1/0],i=[[-1/0,-1/0],[1/0,1/0]],l=250,c=xs,d=Ca("start","zoom","end"),f,p,m,h=500,g=150,b=0,x=10;function v(A){A.property("__zoom",Bp).on("wheel.zoom",P,{passive:!1}).on("mousedown.zoom",I).on("dblclick.zoom",F).filter(s).on("touchstart.zoom",E).on("touchmove.zoom",B).on("touchend.zoom touchcancel.zoom",O).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}v.transform=function(A,D,_,R){var L=A.selection?A.selection():A;L.property("__zoom",Bp),A!==L?k(A,D,_,R):L.interrupt().each(function(){S(this,arguments).event(R).start().zoom(null,typeof D=="function"?D.apply(this,arguments):D).end()})},v.scaleBy=function(A,D,_,R){v.scaleTo(A,function(){var L=this.__zoom.k,z=typeof D=="function"?D.apply(this,arguments):D;return L*z},_,R)},v.scaleTo=function(A,D,_,R){v.transform(A,function(){var L=t.apply(this,arguments),z=this.__zoom,j=_==null?N(L):typeof _=="function"?_.apply(this,arguments):_,H=z.invert(j),T=typeof D=="function"?D.apply(this,arguments):D;return n(y(w(z,T),j,H),L,i)},_,R)},v.translateBy=function(A,D,_,R){v.transform(A,function(){return n(this.__zoom.translate(typeof D=="function"?D.apply(this,arguments):D,typeof _=="function"?_.apply(this,arguments):_),t.apply(this,arguments),i)},null,R)},v.translateTo=function(A,D,_,R,L){v.transform(A,function(){var z=t.apply(this,arguments),j=this.__zoom,H=R==null?N(z):typeof R=="function"?R.apply(this,arguments):R;return n(Pa.translate(H[0],H[1]).scale(j.k).translate(typeof D=="function"?-D.apply(this,arguments):-D,typeof _=="function"?-_.apply(this,arguments):-_),z,i)},R,L)};function w(A,D){return D=Math.max(a[0],Math.min(a[1],D)),D===A.k?A:new nn(D,A.x,A.y)}function y(A,D,_){var R=D[0]-_[0]*A.k,L=D[1]-_[1]*A.k;return R===A.x&&L===A.y?A:new nn(A.k,R,L)}function N(A){return[(+A[0][0]+ +A[1][0])/2,(+A[0][1]+ +A[1][1])/2]}function k(A,D,_,R){A.on("start.zoom",function(){S(this,arguments).event(R).start()}).on("interrupt.zoom end.zoom",function(){S(this,arguments).event(R).end()}).tween("zoom",function(){var L=this,z=arguments,j=S(L,z).event(R),H=t.apply(L,z),T=_==null?N(H):typeof _=="function"?_.apply(L,z):_,W=Math.max(H[1][0]-H[0][0],H[1][1]-H[0][1]),G=L.__zoom,ee=typeof D=="function"?D.apply(L,z):D,se=c(G.invert(T).concat(W/G.k),ee.invert(T).concat(W/ee.k));return function(te){if(te===1)te=ee;else{var X=se(te),re=W/X[2];te=new nn(re,T[0]-X[0]*re,T[1]-X[1]*re)}j.zoom(null,te)}})}function S(A,D,_){return!_&&A.__zooming||new M(A,D)}function M(A,D){this.that=A,this.args=D,this.active=0,this.sourceEvent=null,this.extent=t.apply(A,D),this.taps=0}M.prototype={event:function(A){return A&&(this.sourceEvent=A),this},start:function(){return++this.active===1&&(this.that.__zooming=this,this.emit("start")),this},zoom:function(A,D){return this.mouse&&A!=="mouse"&&(this.mouse[1]=D.invert(this.mouse[0])),this.touch0&&A!=="touch"&&(this.touch0[1]=D.invert(this.touch0[0])),this.touch1&&A!=="touch"&&(this.touch1[1]=D.invert(this.touch1[0])),this.that.__zoom=D,this.emit("zoom"),this},end:function(){return--this.active===0&&(delete this.that.__zooming,this.emit("end")),this},emit:function(A){var D=lt(this.that).datum();d.call(A,this.that,new RF(A,{sourceEvent:this.sourceEvent,target:v,transform:this.that.__zoom,dispatch:d}),D)}};function P(A,...D){if(!e.apply(this,arguments))return;var _=S(this,D).event(A),R=this.__zoom,L=Math.max(a[0],Math.min(a[1],R.k*Math.pow(2,o.apply(this,arguments)))),z=Pt(A);if(_.wheel)(_.mouse[0][0]!==z[0]||_.mouse[0][1]!==z[1])&&(_.mouse[1]=R.invert(_.mouse[0]=z)),clearTimeout(_.wheel);else{if(R.k===L)return;_.mouse=[z,R.invert(z)],ws(this),_.start()}qr(A),_.wheel=setTimeout(j,g),_.zoom("mouse",n(y(w(R,L),_.mouse[0],_.mouse[1]),_.extent,i));function j(){_.wheel=null,_.end()}}function I(A,...D){if(m||!e.apply(this,arguments))return;var _=A.currentTarget,R=S(this,D,!0).event(A),L=lt(A.view).on("mousemove.zoom",T,!0).on("mouseup.zoom",W,!0),z=Pt(A,_),j=A.clientX,H=A.clientY;y0(A.view),Mi(A),R.mouse=[z,this.__zoom.invert(z)],ws(this),R.start();function T(G){if(qr(G),!R.moved){var ee=G.clientX-j,se=G.clientY-H;R.moved=ee*ee+se*se>b}R.event(G).zoom("mouse",n(y(R.that.__zoom,R.mouse[0]=Pt(G,_),R.mouse[1]),R.extent,i))}function W(G){L.on("mousemove.zoom mouseup.zoom",null),v0(G.view,R.moved),qr(G),R.event(G).end()}}function F(A,...D){if(e.apply(this,arguments)){var _=this.__zoom,R=Pt(A.changedTouches?A.changedTouches[0]:A,this),L=_.invert(R),z=_.k*(A.shiftKey?.5:2),j=n(y(w(_,z),R,L),t.apply(this,D),i);qr(A),l>0?lt(this).transition().duration(l).call(k,j,R,A):lt(this).call(v.transform,j,R,A)}}function E(A,...D){if(e.apply(this,arguments)){var _=A.touches,R=_.length,L=S(this,D,A.changedTouches.length===R).event(A),z,j,H,T;for(Mi(A),j=0;j<R;++j)H=_[j],T=Pt(H,this),T=[T,this.__zoom.invert(T),H.identifier],L.touch0?!L.touch1&&L.touch0[2]!==T[2]&&(L.touch1=T,L.taps=0):(L.touch0=T,z=!0,L.taps=1+!!f);f&&(f=clearTimeout(f)),z&&(L.taps<2&&(p=T[0],f=setTimeout(function(){f=null},h)),ws(this),L.start())}}function B(A,...D){if(this.__zooming){var _=S(this,D).event(A),R=A.changedTouches,L=R.length,z,j,H,T;for(qr(A),z=0;z<L;++z)j=R[z],H=Pt(j,this),_.touch0&&_.touch0[2]===j.identifier?_.touch0[0]=H:_.touch1&&_.touch1[2]===j.identifier&&(_.touch1[0]=H);if(j=_.that.__zoom,_.touch1){var W=_.touch0[0],G=_.touch0[1],ee=_.touch1[0],se=_.touch1[1],te=(te=ee[0]-W[0])*te+(te=ee[1]-W[1])*te,X=(X=se[0]-G[0])*X+(X=se[1]-G[1])*X;j=w(j,Math.sqrt(te/X)),H=[(W[0]+ee[0])/2,(W[1]+ee[1])/2],T=[(G[0]+se[0])/2,(G[1]+se[1])/2]}else if(_.touch0)H=_.touch0[0],T=_.touch0[1];else return;_.zoom("touch",n(y(j,H,T),_.extent,i))}}function O(A,...D){if(this.__zooming){var _=S(this,D).event(A),R=A.changedTouches,L=R.length,z,j;for(Mi(A),m&&clearTimeout(m),m=setTimeout(function(){m=null},h),z=0;z<L;++z)j=R[z],_.touch0&&_.touch0[2]===j.identifier?delete _.touch0:_.touch1&&_.touch1[2]===j.identifier&&delete _.touch1;if(_.touch1&&!_.touch0&&(_.touch0=_.touch1,delete _.touch1),_.touch0)_.touch0[1]=this.__zoom.invert(_.touch0[0]);else if(_.end(),_.taps===2&&(j=Pt(j,this),Math.hypot(p[0]-j[0],p[1]-j[1])<x)){var H=lt(this).on("dblclick.zoom");H&&H.apply(this,arguments)}}}return v.wheelDelta=function(A){return arguments.length?(o=typeof A=="function"?A:is(+A),v):o},v.filter=function(A){return arguments.length?(e=typeof A=="function"?A:is(!!A),v):e},v.touchable=function(A){return arguments.length?(s=typeof A=="function"?A:is(!!A),v):s},v.extent=function(A){return arguments.length?(t=typeof A=="function"?A:is([[+A[0][0],+A[0][1]],[+A[1][0],+A[1][1]]]),v):t},v.scaleExtent=function(A){return arguments.length?(a[0]=+A[0],a[1]=+A[1],v):[a[0],a[1]]},v.translateExtent=function(A){return arguments.length?(i[0][0]=+A[0][0],i[1][0]=+A[1][0],i[0][1]=+A[0][1],i[1][1]=+A[1][1],v):[[i[0][0],i[0][1]],[i[1][0],i[1][1]]]},v.constrain=function(A){return arguments.length?(n=A,v):n},v.duration=function(A){return arguments.length?(l=+A,v):l},v.interpolate=function(A){return arguments.length?(c=A,v):c},v.on=function(){var A=d.on.apply(d,arguments);return A===d?v:A},v.clickDistance=function(A){return arguments.length?(b=(A=+A)*A,v):Math.sqrt(b)},v.tapDistance=function(A){return arguments.length?(x=+A,v):x},v}const Gt={error001:()=>"[React Flow]: Seems like you have not used zustand provider as an ancestor. Help: https://reactflow.dev/error#001",error002:()=>"It looks like you've created a new nodeTypes or edgeTypes object. If this wasn't on purpose please define the nodeTypes/edgeTypes outside of the component or memoize them.",error003:e=>`Node type "${e}" not found. Using fallback type "default".`,error004:()=>"The React Flow parent container needs a width and a height to render the graph.",error005:()=>"Only child nodes can use a parent extent.",error006:()=>"Can't create edge. An edge needs a source and a target.",error007:e=>`The old edge with id=${e} does not exist.`,error009:e=>`Marker type "${e}" doesn't exist.`,error008:(e,{id:t,sourceHandle:n,targetHandle:o})=>`Couldn't create edge for ${e} handle id: "${e==="source"?n:o}", edge id: ${t}.`,error010:()=>"Handle: No node id found. Make sure to only use a Handle inside a custom Node.",error011:e=>`Edge type "${e}" not found. Using fallback type "default".`,error012:e=>`Node with id "${e}" does not exist, it may have been removed. This can happen when a node is deleted before the "onNodeClick" handler is called.`,error013:(e="react")=>`It seems that you haven't loaded the styles. Please import '@xyflow/${e}/dist/style.css' or base.css to make sure everything is working properly.`,error014:()=>"useNodeConnections: No node ID found. Call useNodeConnections inside a custom Node or provide a node ID.",error015:()=>"It seems that you are trying to drag a node that is not initialized. Please use onNodesChange as explained in the docs."},ho=[[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY],[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]],O0=["Enter"," ","Escape"],z0={"node.a11yDescription.default":"Press enter or space to select a node. Press delete to remove it and escape to cancel.","node.a11yDescription.keyboardDisabled":"Press enter or space to select a node. You can then use the arrow keys to move the node around. Press delete to remove it and escape to cancel.","node.a11yDescription.ariaLiveMessage":({direction:e,x:t,y:n})=>`Moved selected node ${e}. New position, x: ${t}, y: ${n}`,"edge.a11yDescription.default":"Press enter or space to select an edge. You can then press delete to remove it or escape to cancel.","controls.ariaLabel":"Control Panel","controls.zoomIn.ariaLabel":"Zoom In","controls.zoomOut.ariaLabel":"Zoom Out","controls.fitView.ariaLabel":"Fit View","controls.interactive.ariaLabel":"Toggle Interactivity","minimap.ariaLabel":"Mini Map","handle.ariaLabel":"Handle"};var Nr;(function(e){e.Strict="strict",e.Loose="loose"})(Nr||(Nr={}));var Bn;(function(e){e.Free="free",e.Vertical="vertical",e.Horizontal="horizontal"})(Bn||(Bn={}));var go;(function(e){e.Partial="partial",e.Full="full"})(go||(go={}));const B0={inProgress:!1,isValid:null,from:null,fromHandle:null,fromPosition:null,fromNode:null,to:null,toHandle:null,toPosition:null,toNode:null,pointer:null};var xn;(function(e){e.Bezier="default",e.Straight="straight",e.Step="step",e.SmoothStep="smoothstep",e.SimpleBezier="simplebezier"})(xn||(xn={}));var Qs;(function(e){e.Arrow="arrow",e.ArrowClosed="arrowclosed"})(Qs||(Qs={}));var we;(function(e){e.Left="left",e.Top="top",e.Right="right",e.Bottom="bottom"})(we||(we={}));const Fp={[we.Left]:we.Right,[we.Right]:we.Left,[we.Top]:we.Bottom,[we.Bottom]:we.Top};function F0(e){return e===null?null:e?"valid":"invalid"}const j0=e=>"id"in e&&"source"in e&&"target"in e,HF=e=>"id"in e&&"position"in e&&!("source"in e)&&!("target"in e),dd=e=>"id"in e&&"internals"in e&&!("source"in e)&&!("target"in e),Do=(e,t=[0,0])=>{const{width:n,height:o}=fn(e),s=e.origin??t,a=n*s[0],i=o*s[1];return{x:e.position.x-a,y:e.position.y-i}},VF=(e,t={nodeOrigin:[0,0]})=>{if(e.length===0)return{x:0,y:0,width:0,height:0};const n=e.reduce((o,s)=>{const a=typeof s=="string";let i=!t.nodeLookup&&!a?s:void 0;t.nodeLookup&&(i=a?t.nodeLookup.get(s):dd(s)?s:t.nodeLookup.get(s.id));const l=i?Us(i,t.nodeOrigin):{x:0,y:0,x2:0,y2:0};return Ea(o,l)},{x:1/0,y:1/0,x2:-1/0,y2:-1/0});return $a(n)},Lo=(e,t={})=>{let n={x:1/0,y:1/0,x2:-1/0,y2:-1/0},o=!1;return e.forEach(s=>{(t.filter===void 0||t.filter(s))&&(n=Ea(n,Us(s)),o=!0)}),o?$a(n):{x:0,y:0,width:0,height:0}},ud=(e,t,[n,o,s]=[0,0,1],a=!1,i=!1)=>{const l={...Ro(t,[n,o,s]),width:t.width/s,height:t.height/s},c=[];for(const d of e.values()){const{measured:f,selectable:p=!0,hidden:m=!1}=d;if(i&&!p||m)continue;const h=f.width??d.width??d.initialWidth??null,g=f.height??d.height??d.initialHeight??null,b=bo(l,Sr(d)),x=(h??0)*(g??0),v=a&&b>0;(!d.internals.handleBounds||v||b>=x||d.dragging)&&c.push(d)}return c},qF=(e,t)=>{const n=new Set;return e.forEach(o=>{n.add(o.id)}),t.filter(o=>n.has(o.source)||n.has(o.target))};function QF(e,t){const n=new Map,o=t?.nodes?new Set(t.nodes.map(s=>s.id)):null;return e.forEach(s=>{s.measured.width&&s.measured.height&&(t?.includeHiddenNodes||!s.hidden)&&(!o||o.has(s.id))&&n.set(s.id,s)}),n}async function UF({nodes:e,width:t,height:n,panZoom:o,minZoom:s,maxZoom:a},i){if(e.size===0)return Promise.resolve(!0);const l=QF(e,i),c=Lo(l),d=pd(c,t,n,i?.minZoom??s,i?.maxZoom??a,i?.padding??.1);return await o.setViewport(d,{duration:i?.duration,ease:i?.ease,interpolate:i?.interpolate}),Promise.resolve(!0)}function H0({nodeId:e,nextPosition:t,nodeLookup:n,nodeOrigin:o=[0,0],nodeExtent:s,onError:a}){const i=n.get(e),l=i.parentId?n.get(i.parentId):void 0,{x:c,y:d}=l?l.internals.positionAbsolute:{x:0,y:0},f=i.origin??o;let p=i.extent||s;if(i.extent==="parent"&&!i.expandParent)if(!l)a?.("005",Gt.error005());else{const h=l.measured.width,g=l.measured.height;h&&g&&(p=[[c,d],[c+h,d+g]])}else l&&Cr(i.extent)&&(p=[[i.extent[0][0]+c,i.extent[0][1]+d],[i.extent[1][0]+c,i.extent[1][1]+d]]);const m=Cr(p)?Qn(t,p,i.measured):t;return(i.measured.width===void 0||i.measured.height===void 0)&&a?.("015",Gt.error015()),{position:{x:m.x-c+(i.measured.width??0)*f[0],y:m.y-d+(i.measured.height??0)*f[1]},positionAbsolute:m}}async function KF({nodesToRemove:e=[],edgesToRemove:t=[],nodes:n,edges:o,onBeforeDelete:s}){const a=new Set(e.map(m=>m.id)),i=[];for(const m of n){if(m.deletable===!1)continue;const h=a.has(m.id),g=!h&&m.parentId&&i.find(b=>b.id===m.parentId);(h||g)&&i.push(m)}const l=new Set(t.map(m=>m.id)),c=o.filter(m=>m.deletable!==!1),f=qF(i,c);for(const m of c)l.has(m.id)&&!f.find(g=>g.id===m.id)&&f.push(m);if(!s)return{edges:f,nodes:i};const p=await s({nodes:i,edges:f});return typeof p=="boolean"?p?{edges:f,nodes:i}:{edges:[],nodes:[]}:p}const kr=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),Qn=(e={x:0,y:0},t,n)=>({x:kr(e.x,t[0][0],t[1][0]-(n?.width??0)),y:kr(e.y,t[0][1],t[1][1]-(n?.height??0))});function V0(e,t,n){const{width:o,height:s}=fn(n),{x:a,y:i}=n.internals.positionAbsolute;return Qn(e,[[a,i],[a+o,i+s]],t)}const jp=(e,t,n)=>e<t?kr(Math.abs(e-t),1,t)/t:e>n?-kr(Math.abs(e-n),1,t)/t:0,q0=(e,t,n=15,o=40)=>{const s=jp(e.x,o,t.width-o)*n,a=jp(e.y,o,t.height-o)*n;return[s,a]},Ea=(e,t)=>({x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),x2:Math.max(e.x2,t.x2),y2:Math.max(e.y2,t.y2)}),wl=({x:e,y:t,width:n,height:o})=>({x:e,y:t,x2:e+n,y2:t+o}),$a=({x:e,y:t,x2:n,y2:o})=>({x:e,y:t,width:n-e,height:o-t}),Sr=(e,t=[0,0])=>{const{x:n,y:o}=dd(e)?e.internals.positionAbsolute:Do(e,t);return{x:n,y:o,width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}},Us=(e,t=[0,0])=>{const{x:n,y:o}=dd(e)?e.internals.positionAbsolute:Do(e,t);return{x:n,y:o,x2:n+(e.measured?.width??e.width??e.initialWidth??0),y2:o+(e.measured?.height??e.height??e.initialHeight??0)}},Q0=(e,t)=>$a(Ea(wl(e),wl(t))),bo=(e,t)=>{const n=Math.max(0,Math.min(e.x+e.width,t.x+t.width)-Math.max(e.x,t.x)),o=Math.max(0,Math.min(e.y+e.height,t.y+t.height)-Math.max(e.y,t.y));return Math.ceil(n*o)},Hp=e=>$t(e.width)&&$t(e.height)&&$t(e.x)&&$t(e.y),$t=e=>!isNaN(e)&&isFinite(e),GF=(e,t)=>{},To=(e,t=[1,1])=>({x:t[0]*Math.round(e.x/t[0]),y:t[1]*Math.round(e.y/t[1])}),Ro=({x:e,y:t},[n,o,s],a=!1,i=[1,1])=>{const l={x:(e-n)/s,y:(t-o)/s};return a?To(l,i):l},Ks=({x:e,y:t},[n,o,s])=>({x:e*s+n,y:t*s+o});function or(e,t){if(typeof e=="number")return Math.floor((t-t/(1+e))*.5);if(typeof e=="string"&&e.endsWith("px")){const n=parseFloat(e);if(!Number.isNaN(n))return Math.floor(n)}if(typeof e=="string"&&e.endsWith("%")){const n=parseFloat(e);if(!Number.isNaN(n))return Math.floor(t*n*.01)}return console.error(`[React Flow] The padding value "${e}" is invalid. Please provide a number or a string with a valid unit (px or %).`),0}function WF(e,t,n){if(typeof e=="string"||typeof e=="number"){const o=or(e,n),s=or(e,t);return{top:o,right:s,bottom:o,left:s,x:s*2,y:o*2}}if(typeof e=="object"){const o=or(e.top??e.y??0,n),s=or(e.bottom??e.y??0,n),a=or(e.left??e.x??0,t),i=or(e.right??e.x??0,t);return{top:o,right:i,bottom:s,left:a,x:a+i,y:o+s}}return{top:0,right:0,bottom:0,left:0,x:0,y:0}}function YF(e,t,n,o,s,a){const{x:i,y:l}=Ks(e,[t,n,o]),{x:c,y:d}=Ks({x:e.x+e.width,y:e.y+e.height},[t,n,o]),f=s-c,p=a-d;return{left:Math.floor(i),top:Math.floor(l),right:Math.floor(f),bottom:Math.floor(p)}}const pd=(e,t,n,o,s,a)=>{const i=WF(a,t,n),l=(t-i.x)/e.width,c=(n-i.y)/e.height,d=Math.min(l,c),f=kr(d,o,s),p=e.x+e.width/2,m=e.y+e.height/2,h=t/2-p*f,g=n/2-m*f,b=YF(e,h,g,f,t,n),x={left:Math.min(b.left-i.left,0),top:Math.min(b.top-i.top,0),right:Math.min(b.right-i.right,0),bottom:Math.min(b.bottom-i.bottom,0)};return{x:h-x.left+x.right,y:g-x.top+x.bottom,zoom:f}},xo=()=>typeof navigator<"u"&&navigator?.userAgent?.indexOf("Mac")>=0;function Cr(e){return e!=null&&e!=="parent"}function fn(e){return{width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}}function U0(e){return(e.measured?.width??e.width??e.initialWidth)!==void 0&&(e.measured?.height??e.height??e.initialHeight)!==void 0}function K0(e,t={width:0,height:0},n,o,s){const a={...e},i=o.get(n);if(i){const l=i.origin||s;a.x+=i.internals.positionAbsolute.x-(t.width??0)*l[0],a.y+=i.internals.positionAbsolute.y-(t.height??0)*l[1]}return a}function Vp(e,t){if(e.size!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;return!0}function ZF(){let e,t;return{promise:new Promise((o,s)=>{e=o,t=s}),resolve:e,reject:t}}function XF(e){return{...z0,...e||{}}}function ro(e,{snapGrid:t=[0,0],snapToGrid:n=!1,transform:o,containerBounds:s}){const{x:a,y:i}=_t(e),l=Ro({x:a-(s?.left??0),y:i-(s?.top??0)},o),{x:c,y:d}=n?To(l,t):l;return{xSnapped:c,ySnapped:d,...l}}const fd=e=>({width:e.offsetWidth,height:e.offsetHeight}),G0=e=>e?.getRootNode?.()||window?.document,JF=["INPUT","SELECT","TEXTAREA"];function W0(e){const t=e.composedPath?.()?.[0]||e.target;return t?.nodeType!==1?!1:JF.includes(t.nodeName)||t.hasAttribute("contenteditable")||!!t.closest(".nokey")}const Y0=e=>"clientX"in e,_t=(e,t)=>{const n=Y0(e),o=n?e.clientX:e.touches?.[0].clientX,s=n?e.clientY:e.touches?.[0].clientY;return{x:o-(t?.left??0),y:s-(t?.top??0)}},qp=(e,t,n,o,s)=>{const a=t.querySelectorAll(`.${e}`);return!a||!a.length?null:Array.from(a).map(i=>{const l=i.getBoundingClientRect();return{id:i.getAttribute("data-handleid"),type:e,nodeId:s,position:i.getAttribute("data-handlepos"),x:(l.left-n.left)/o,y:(l.top-n.top)/o,...fd(i)}})};function Z0({sourceX:e,sourceY:t,targetX:n,targetY:o,sourceControlX:s,sourceControlY:a,targetControlX:i,targetControlY:l}){const c=e*.125+s*.375+i*.375+n*.125,d=t*.125+a*.375+l*.375+o*.125,f=Math.abs(c-e),p=Math.abs(d-t);return[c,d,f,p]}function ls(e,t){return e>=0?.5*e:t*25*Math.sqrt(-e)}function Qp({pos:e,x1:t,y1:n,x2:o,y2:s,c:a}){switch(e){case we.Left:return[t-ls(t-o,a),n];case we.Right:return[t+ls(o-t,a),n];case we.Top:return[t,n-ls(n-s,a)];case we.Bottom:return[t,n+ls(s-n,a)]}}function X0({sourceX:e,sourceY:t,sourcePosition:n=we.Bottom,targetX:o,targetY:s,targetPosition:a=we.Top,curvature:i=.25}){const[l,c]=Qp({pos:n,x1:e,y1:t,x2:o,y2:s,c:i}),[d,f]=Qp({pos:a,x1:o,y1:s,x2:e,y2:t,c:i}),[p,m,h,g]=Z0({sourceX:e,sourceY:t,targetX:o,targetY:s,sourceControlX:l,sourceControlY:c,targetControlX:d,targetControlY:f});return[`M${e},${t} C${l},${c} ${d},${f} ${o},${s}`,p,m,h,g]}function J0({sourceX:e,sourceY:t,targetX:n,targetY:o}){const s=Math.abs(n-e)/2,a=n<e?n+s:n-s,i=Math.abs(o-t)/2,l=o<t?o+i:o-i;return[a,l,s,i]}function ej({sourceNode:e,targetNode:t,selected:n=!1,zIndex:o=0,elevateOnSelect:s=!1,zIndexMode:a="basic"}){if(a==="manual")return o;const i=s&&n?o+1e3:o,l=Math.max(e.parentId||s&&e.selected?e.internals.z:0,t.parentId||s&&t.selected?t.internals.z:0);return i+l}function tj({sourceNode:e,targetNode:t,width:n,height:o,transform:s}){const a=Ea(Us(e),Us(t));a.x===a.x2&&(a.x2+=1),a.y===a.y2&&(a.y2+=1);const i={x:-s[0]/s[2],y:-s[1]/s[2],width:n/s[2],height:o/s[2]};return bo(i,$a(a))>0}const nj=({source:e,sourceHandle:t,target:n,targetHandle:o})=>`xy-edge__${e}${t||""}-${n}${o||""}`,rj=(e,t)=>t.some(n=>n.source===e.source&&n.target===e.target&&(n.sourceHandle===e.sourceHandle||!n.sourceHandle&&!e.sourceHandle)&&(n.targetHandle===e.targetHandle||!n.targetHandle&&!e.targetHandle)),oj=(e,t,n={})=>{if(!e.source||!e.target)return t;const o=n.getEdgeId||nj;let s;return j0(e)?s={...e}:s={...e,id:o(e)},rj(s,t)?t:(s.sourceHandle===null&&delete s.sourceHandle,s.targetHandle===null&&delete s.targetHandle,t.concat(s))};function ev({sourceX:e,sourceY:t,targetX:n,targetY:o}){const[s,a,i,l]=J0({sourceX:e,sourceY:t,targetX:n,targetY:o});return[`M ${e},${t}L ${n},${o}`,s,a,i,l]}const Up={[we.Left]:{x:-1,y:0},[we.Right]:{x:1,y:0},[we.Top]:{x:0,y:-1},[we.Bottom]:{x:0,y:1}},sj=({source:e,sourcePosition:t=we.Bottom,target:n})=>t===we.Left||t===we.Right?e.x<n.x?{x:1,y:0}:{x:-1,y:0}:e.y<n.y?{x:0,y:1}:{x:0,y:-1},Kp=(e,t)=>Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2));function aj({source:e,sourcePosition:t=we.Bottom,target:n,targetPosition:o=we.Top,center:s,offset:a,stepPosition:i}){const l=Up[t],c=Up[o],d={x:e.x+l.x*a,y:e.y+l.y*a},f={x:n.x+c.x*a,y:n.y+c.y*a},p=sj({source:d,sourcePosition:t,target:f}),m=p.x!==0?"x":"y",h=p[m];let g=[],b,x;const v={x:0,y:0},w={x:0,y:0},[,,y,N]=J0({sourceX:e.x,sourceY:e.y,targetX:n.x,targetY:n.y});if(l[m]*c[m]===-1){m==="x"?(b=s.x??d.x+(f.x-d.x)*i,x=s.y??(d.y+f.y)/2):(b=s.x??(d.x+f.x)/2,x=s.y??d.y+(f.y-d.y)*i);const P=[{x:b,y:d.y},{x:b,y:f.y}],I=[{x:d.x,y:x},{x:f.x,y:x}];l[m]===h?g=m==="x"?P:I:g=m==="x"?I:P}else{const P=[{x:d.x,y:f.y}],I=[{x:f.x,y:d.y}];if(m==="x"?g=l.x===h?I:P:g=l.y===h?P:I,t===o){const A=Math.abs(e[m]-n[m]);if(A<=a){const D=Math.min(a-1,a-A);l[m]===h?v[m]=(d[m]>e[m]?-1:1)*D:w[m]=(f[m]>n[m]?-1:1)*D}}if(t!==o){const A=m==="x"?"y":"x",D=l[m]===c[A],_=d[A]>f[A],R=d[A]<f[A];(l[m]===1&&(!D&&_||D&&R)||l[m]!==1&&(!D&&R||D&&_))&&(g=m==="x"?P:I)}const F={x:d.x+v.x,y:d.y+v.y},E={x:f.x+w.x,y:f.y+w.y},B=Math.max(Math.abs(F.x-g[0].x),Math.abs(E.x-g[0].x)),O=Math.max(Math.abs(F.y-g[0].y),Math.abs(E.y-g[0].y));B>=O?(b=(F.x+E.x)/2,x=g[0].y):(b=g[0].x,x=(F.y+E.y)/2)}const k={x:d.x+v.x,y:d.y+v.y},S={x:f.x+w.x,y:f.y+w.y};return[[e,...k.x!==g[0].x||k.y!==g[0].y?[k]:[],...g,...S.x!==g[g.length-1].x||S.y!==g[g.length-1].y?[S]:[],n],b,x,y,N]}function ij(e,t,n,o){const s=Math.min(Kp(e,t)/2,Kp(t,n)/2,o),{x:a,y:i}=t;if(e.x===a&&a===n.x||e.y===i&&i===n.y)return`L${a} ${i}`;if(e.y===i){const d=e.x<n.x?-1:1,f=e.y<n.y?1:-1;return`L ${a+s*d},${i}Q ${a},${i} ${a},${i+s*f}`}const l=e.x<n.x?1:-1,c=e.y<n.y?-1:1;return`L ${a},${i+s*c}Q ${a},${i} ${a+s*l},${i}`}function Nl({sourceX:e,sourceY:t,sourcePosition:n=we.Bottom,targetX:o,targetY:s,targetPosition:a=we.Top,borderRadius:i=5,centerX:l,centerY:c,offset:d=20,stepPosition:f=.5}){const[p,m,h,g,b]=aj({source:{x:e,y:t},sourcePosition:n,target:{x:o,y:s},targetPosition:a,center:{x:l,y:c},offset:d,stepPosition:f});let x=`M${p[0].x} ${p[0].y}`;for(let v=1;v<p.length-1;v++)x+=ij(p[v-1],p[v],p[v+1],i);return x+=`L${p[p.length-1].x} ${p[p.length-1].y}`,[x,m,h,g,b]}function Gp(e){return e&&!!(e.internals.handleBounds||e.handles?.length)&&!!(e.measured.width||e.width||e.initialWidth)}function lj(e){const{sourceNode:t,targetNode:n}=e;if(!Gp(t)||!Gp(n))return null;const o=t.internals.handleBounds||Wp(t.handles),s=n.internals.handleBounds||Wp(n.handles),a=Yp(o?.source??[],e.sourceHandle),i=Yp(e.connectionMode===Nr.Strict?s?.target??[]:(s?.target??[]).concat(s?.source??[]),e.targetHandle);if(!a||!i)return e.onError?.("008",Gt.error008(a?"target":"source",{id:e.id,sourceHandle:e.sourceHandle,targetHandle:e.targetHandle})),null;const l=a?.position||we.Bottom,c=i?.position||we.Top,d=Un(t,a,l),f=Un(n,i,c);return{sourceX:d.x,sourceY:d.y,targetX:f.x,targetY:f.y,sourcePosition:l,targetPosition:c}}function Wp(e){if(!e)return null;const t=[],n=[];for(const o of e)o.width=o.width??1,o.height=o.height??1,o.type==="source"?t.push(o):o.type==="target"&&n.push(o);return{source:t,target:n}}function Un(e,t,n=we.Left,o=!1){const s=(t?.x??0)+e.internals.positionAbsolute.x,a=(t?.y??0)+e.internals.positionAbsolute.y,{width:i,height:l}=t??fn(e);if(o)return{x:s+i/2,y:a+l/2};switch(t?.position??n){case we.Top:return{x:s+i/2,y:a};case we.Right:return{x:s+i,y:a+l/2};case we.Bottom:return{x:s+i/2,y:a+l};case we.Left:return{x:s,y:a+l/2}}}function Yp(e,t){return e&&(t?e.find(n=>n.id===t):e[0])||null}function kl(e,t){return e?typeof e=="string"?e:`${t?`${t}__`:""}${Object.keys(e).sort().map(o=>`${o}=${e[o]}`).join("&")}`:""}function cj(e,{id:t,defaultColor:n,defaultMarkerStart:o,defaultMarkerEnd:s}){const a=new Set;return e.reduce((i,l)=>([l.markerStart||o,l.markerEnd||s].forEach(c=>{if(c&&typeof c=="object"){const d=kl(c,t);a.has(d)||(i.push({id:d,color:c.color||n,...c}),a.add(d))}}),i),[]).sort((i,l)=>i.id.localeCompare(l.id))}const tv=1e3,dj=10,md={nodeOrigin:[0,0],nodeExtent:ho,elevateNodesOnSelect:!0,zIndexMode:"basic",defaults:{}},uj={...md,checkEquality:!0};function hd(e,t){const n={...e};for(const o in t)t[o]!==void 0&&(n[o]=t[o]);return n}function pj(e,t,n){const o=hd(md,n);for(const s of e.values())if(s.parentId)bd(s,e,t,o);else{const a=Do(s,o.nodeOrigin),i=Cr(s.extent)?s.extent:o.nodeExtent,l=Qn(a,i,fn(s));s.internals.positionAbsolute=l}}function fj(e,t){if(!e.handles)return e.measured?t?.internals.handleBounds:void 0;const n=[],o=[];for(const s of e.handles){const a={id:s.id,width:s.width??1,height:s.height??1,nodeId:e.id,x:s.x,y:s.y,position:s.position,type:s.type};s.type==="source"?n.push(a):s.type==="target"&&o.push(a)}return{source:n,target:o}}function gd(e){return e==="manual"}function Sl(e,t,n,o={}){const s=hd(uj,o),a={i:0},i=new Map(t),l=s?.elevateNodesOnSelect&&!gd(s.zIndexMode)?tv:0;let c=e.length>0,d=!1;t.clear(),n.clear();for(const f of e){let p=i.get(f.id);if(s.checkEquality&&f===p?.internals.userNode)t.set(f.id,p);else{const m=Do(f,s.nodeOrigin),h=Cr(f.extent)?f.extent:s.nodeExtent,g=Qn(m,h,fn(f));p={...s.defaults,...f,measured:{width:f.measured?.width,height:f.measured?.height},internals:{positionAbsolute:g,handleBounds:fj(f,p),z:nv(f,l,s.zIndexMode),userNode:f}},t.set(f.id,p)}(p.measured===void 0||p.measured.width===void 0||p.measured.height===void 0)&&!p.hidden&&(c=!1),f.parentId&&bd(p,t,n,o,a),d||=f.selected??!1}return{nodesInitialized:c,hasSelectedNodes:d}}function mj(e,t){if(!e.parentId)return;const n=t.get(e.parentId);n?n.set(e.id,e):t.set(e.parentId,new Map([[e.id,e]]))}function bd(e,t,n,o,s){const{elevateNodesOnSelect:a,nodeOrigin:i,nodeExtent:l,zIndexMode:c}=hd(md,o),d=e.parentId,f=t.get(d);if(!f){console.warn(`Parent node ${d} not found. Please make sure that parent nodes are in front of their child nodes in the nodes array.`);return}mj(e,n),s&&!f.parentId&&f.internals.rootParentIndex===void 0&&c==="auto"&&(f.internals.rootParentIndex=++s.i,f.internals.z=f.internals.z+s.i*dj),s&&f.internals.rootParentIndex!==void 0&&(s.i=f.internals.rootParentIndex);const p=a&&!gd(c)?tv:0,{x:m,y:h,z:g}=hj(e,f,i,l,p,c),{positionAbsolute:b}=e.internals,x=m!==b.x||h!==b.y;(x||g!==e.internals.z)&&t.set(e.id,{...e,internals:{...e.internals,positionAbsolute:x?{x:m,y:h}:b,z:g}})}function nv(e,t,n){const o=$t(e.zIndex)?e.zIndex:0;return gd(n)?o:o+(e.selected?t:0)}function hj(e,t,n,o,s,a){const{x:i,y:l}=t.internals.positionAbsolute,c=fn(e),d=Do(e,n),f=Cr(e.extent)?Qn(d,e.extent,c):d;let p=Qn({x:i+f.x,y:l+f.y},o,c);e.extent==="parent"&&(p=V0(p,c,t));const m=nv(e,s,a),h=t.internals.z??0;return{x:p.x,y:p.y,z:h>=m?h+1:m}}function xd(e,t,n,o=[0,0]){const s=[],a=new Map;for(const i of e){const l=t.get(i.parentId);if(!l)continue;const c=a.get(i.parentId)?.expandedRect??Sr(l),d=Q0(c,i.rect);a.set(i.parentId,{expandedRect:d,parent:l})}return a.size>0&&a.forEach(({expandedRect:i,parent:l},c)=>{const d=l.internals.positionAbsolute,f=fn(l),p=l.origin??o,m=i.x<d.x?Math.round(Math.abs(d.x-i.x)):0,h=i.y<d.y?Math.round(Math.abs(d.y-i.y)):0,g=Math.max(f.width,Math.round(i.width)),b=Math.max(f.height,Math.round(i.height)),x=(g-f.width)*p[0],v=(b-f.height)*p[1];(m>0||h>0||x||v)&&(s.push({id:c,type:"position",position:{x:l.position.x-m+x,y:l.position.y-h+v}}),n.get(c)?.forEach(w=>{e.some(y=>y.id===w.id)||s.push({id:w.id,type:"position",position:{x:w.position.x+m,y:w.position.y+h}})})),(f.width<i.width||f.height<i.height||m||h)&&s.push({id:c,type:"dimensions",setAttributes:!0,dimensions:{width:g+(m?p[0]*m-x:0),height:b+(h?p[1]*h-v:0)}})}),s}function gj(e,t,n,o,s,a,i){const l=o?.querySelector(".xyflow__viewport");let c=!1;if(!l)return{changes:[],updatedInternals:c};const d=[],f=window.getComputedStyle(l),{m22:p}=new window.DOMMatrixReadOnly(f.transform),m=[];for(const h of e.values()){const g=t.get(h.id);if(!g)continue;if(g.hidden){t.set(g.id,{...g,internals:{...g.internals,handleBounds:void 0}}),c=!0;continue}const b=fd(h.nodeElement),x=g.measured.width!==b.width||g.measured.height!==b.height;if(!!(b.width&&b.height&&(x||!g.internals.handleBounds||h.force))){const w=h.nodeElement.getBoundingClientRect(),y=Cr(g.extent)?g.extent:a;let{positionAbsolute:N}=g.internals;g.parentId&&g.extent==="parent"?N=V0(N,b,t.get(g.parentId)):y&&(N=Qn(N,y,b));const k={...g,measured:b,internals:{...g.internals,positionAbsolute:N,handleBounds:{source:qp("source",h.nodeElement,w,p,g.id),target:qp("target",h.nodeElement,w,p,g.id)}}};t.set(g.id,k),g.parentId&&bd(k,t,n,{nodeOrigin:s,zIndexMode:i}),c=!0,x&&(d.push({id:g.id,type:"dimensions",dimensions:b}),g.expandParent&&g.parentId&&m.push({id:g.id,parentId:g.parentId,rect:Sr(k,s)}))}}if(m.length>0){const h=xd(m,t,n,s);d.push(...h)}return{changes:d,updatedInternals:c}}async function bj({delta:e,panZoom:t,transform:n,translateExtent:o,width:s,height:a}){if(!t||!e.x&&!e.y)return Promise.resolve(!1);const i=await t.setViewportConstrained({x:n[0]+e.x,y:n[1]+e.y,zoom:n[2]},[[0,0],[s,a]],o),l=!!i&&(i.x!==n[0]||i.y!==n[1]||i.k!==n[2]);return Promise.resolve(l)}function Zp(e,t,n,o,s,a){let i=s;const l=o.get(i)||new Map;o.set(i,l.set(n,t)),i=`${s}-${e}`;const c=o.get(i)||new Map;if(o.set(i,c.set(n,t)),a){i=`${s}-${e}-${a}`;const d=o.get(i)||new Map;o.set(i,d.set(n,t))}}function rv(e,t,n){e.clear(),t.clear();for(const o of n){const{source:s,target:a,sourceHandle:i=null,targetHandle:l=null}=o,c={edgeId:o.id,source:s,target:a,sourceHandle:i,targetHandle:l},d=`${s}-${i}--${a}-${l}`,f=`${a}-${l}--${s}-${i}`;Zp("source",c,f,e,s,i),Zp("target",c,d,e,a,l),t.set(o.id,o)}}function ov(e,t){if(!e.parentId)return!1;const n=t.get(e.parentId);return n?n.selected?!0:ov(n,t):!1}function Xp(e,t,n){let o=e;do{if(o?.matches?.(t))return!0;if(o===n)return!1;o=o?.parentElement}while(o);return!1}function xj(e,t,n,o){const s=new Map;for(const[a,i]of e)if((i.selected||i.id===o)&&(!i.parentId||!ov(i,e))&&(i.draggable||t&&typeof i.draggable>"u")){const l=e.get(a);l&&s.set(a,{id:a,position:l.position||{x:0,y:0},distance:{x:n.x-l.internals.positionAbsolute.x,y:n.y-l.internals.positionAbsolute.y},extent:l.extent,parentId:l.parentId,origin:l.origin,expandParent:l.expandParent,internals:{positionAbsolute:l.internals.positionAbsolute||{x:0,y:0}},measured:{width:l.measured.width??0,height:l.measured.height??0}})}return s}function Ii({nodeId:e,dragItems:t,nodeLookup:n,dragging:o=!0}){const s=[];for(const[i,l]of t){const c=n.get(i)?.internals.userNode;c&&s.push({...c,position:l.position,dragging:o})}if(!e)return[s[0],s];const a=n.get(e)?.internals.userNode;return[a?{...a,position:t.get(e)?.position||a.position,dragging:o}:s[0],s]}function yj({dragItems:e,snapGrid:t,x:n,y:o}){const s=e.values().next().value;if(!s)return null;const a={x:n-s.distance.x,y:o-s.distance.y},i=To(a,t);return{x:i.x-a.x,y:i.y-a.y}}function vj({onNodeMouseDown:e,getStoreItems:t,onDragStart:n,onDrag:o,onDragStop:s}){let a={x:null,y:null},i=0,l=new Map,c=!1,d={x:0,y:0},f=null,p=!1,m=null,h=!1,g=!1,b=null;function x({noDragClassName:w,handleSelector:y,domNode:N,isSelectable:k,nodeId:S,nodeClickDistance:M=0}){m=lt(N);function P({x:B,y:O}){const{nodeLookup:A,nodeExtent:D,snapGrid:_,snapToGrid:R,nodeOrigin:L,onNodeDrag:z,onSelectionDrag:j,onError:H,updateNodePositions:T}=t();a={x:B,y:O};let W=!1;const G=l.size>1,ee=G&&D?wl(Lo(l)):null,se=G&&R?yj({dragItems:l,snapGrid:_,x:B,y:O}):null;for(const[te,X]of l){if(!A.has(te))continue;let re={x:B-X.distance.x,y:O-X.distance.y};R&&(re=se?{x:Math.round(re.x+se.x),y:Math.round(re.y+se.y)}:To(re,_));let ge=null;if(G&&D&&!X.extent&&ee){const{positionAbsolute:J}=X.internals,ae=J.x-ee.x+D[0][0],fe=J.x+X.measured.width-ee.x2+D[1][0],he=J.y-ee.y+D[0][1],V=J.y+X.measured.height-ee.y2+D[1][1];ge=[[ae,he],[fe,V]]}const{position:Z,positionAbsolute:U}=H0({nodeId:te,nextPosition:re,nodeLookup:A,nodeExtent:ge||D,nodeOrigin:L,onError:H});W=W||X.position.x!==Z.x||X.position.y!==Z.y,X.position=Z,X.internals.positionAbsolute=U}if(g=g||W,!!W&&(T(l,!0),b&&(o||z||!S&&j))){const[te,X]=Ii({nodeId:S,dragItems:l,nodeLookup:A});o?.(b,l,te,X),z?.(b,te,X),S||j?.(b,X)}}async function I(){if(!f)return;const{transform:B,panBy:O,autoPanSpeed:A,autoPanOnNodeDrag:D}=t();if(!D){c=!1,cancelAnimationFrame(i);return}const[_,R]=q0(d,f,A);(_!==0||R!==0)&&(a.x=(a.x??0)-_/B[2],a.y=(a.y??0)-R/B[2],await O({x:_,y:R})&&P(a)),i=requestAnimationFrame(I)}function F(B){const{nodeLookup:O,multiSelectionActive:A,nodesDraggable:D,transform:_,snapGrid:R,snapToGrid:L,selectNodesOnDrag:z,onNodeDragStart:j,onSelectionDragStart:H,unselectNodesAndEdges:T}=t();p=!0,(!z||!k)&&!A&&S&&(O.get(S)?.selected||T()),k&&z&&S&&e?.(S);const W=ro(B.sourceEvent,{transform:_,snapGrid:R,snapToGrid:L,containerBounds:f});if(a=W,l=xj(O,D,W,S),l.size>0&&(n||j||!S&&H)){const[G,ee]=Ii({nodeId:S,dragItems:l,nodeLookup:O});n?.(B.sourceEvent,l,G,ee),j?.(B.sourceEvent,G,ee),S||H?.(B.sourceEvent,ee)}}const E=w0().clickDistance(M).on("start",B=>{const{domNode:O,nodeDragThreshold:A,transform:D,snapGrid:_,snapToGrid:R}=t();f=O?.getBoundingClientRect()||null,h=!1,g=!1,b=B.sourceEvent,A===0&&F(B),a=ro(B.sourceEvent,{transform:D,snapGrid:_,snapToGrid:R,containerBounds:f}),d=_t(B.sourceEvent,f)}).on("drag",B=>{const{autoPanOnNodeDrag:O,transform:A,snapGrid:D,snapToGrid:_,nodeDragThreshold:R,nodeLookup:L}=t(),z=ro(B.sourceEvent,{transform:A,snapGrid:D,snapToGrid:_,containerBounds:f});if(b=B.sourceEvent,(B.sourceEvent.type==="touchmove"&&B.sourceEvent.touches.length>1||S&&!L.has(S))&&(h=!0),!h){if(!c&&O&&p&&(c=!0,I()),!p){const j=_t(B.sourceEvent,f),H=j.x-d.x,T=j.y-d.y;Math.sqrt(H*H+T*T)>R&&F(B)}(a.x!==z.xSnapped||a.y!==z.ySnapped)&&l&&p&&(d=_t(B.sourceEvent,f),P(z))}}).on("end",B=>{if(!(!p||h)&&(c=!1,p=!1,cancelAnimationFrame(i),l.size>0)){const{nodeLookup:O,updateNodePositions:A,onNodeDragStop:D,onSelectionDragStop:_}=t();if(g&&(A(l,!1),g=!1),s||D||!S&&_){const[R,L]=Ii({nodeId:S,dragItems:l,nodeLookup:O,dragging:!1});s?.(B.sourceEvent,l,R,L),D?.(B.sourceEvent,R,L),S||_?.(B.sourceEvent,L)}}}).filter(B=>{const O=B.target;return!B.button&&(!w||!Xp(O,`.${w}`,N))&&(!y||Xp(O,y,N))});m.call(E)}function v(){m?.on(".drag",null)}return{update:x,destroy:v}}function wj(e,t,n){const o=[],s={x:e.x-n,y:e.y-n,width:n*2,height:n*2};for(const a of t.values())bo(s,Sr(a))>0&&o.push(a);return o}const Nj=250;function kj(e,t,n,o){let s=[],a=1/0;const i=wj(e,n,t+Nj);for(const l of i){const c=[...l.internals.handleBounds?.source??[],...l.internals.handleBounds?.target??[]];for(const d of c){if(o.nodeId===d.nodeId&&o.type===d.type&&o.id===d.id)continue;const{x:f,y:p}=Un(l,d,d.position,!0),m=Math.sqrt(Math.pow(f-e.x,2)+Math.pow(p-e.y,2));m>t||(m<a?(s=[{...d,x:f,y:p}],a=m):m===a&&s.push({...d,x:f,y:p}))}}if(!s.length)return null;if(s.length>1){const l=o.type==="source"?"target":"source";return s.find(c=>c.type===l)??s[0]}return s[0]}function sv(e,t,n,o,s,a=!1){const i=o.get(e);if(!i)return null;const l=s==="strict"?i.internals.handleBounds?.[t]:[...i.internals.handleBounds?.source??[],...i.internals.handleBounds?.target??[]],c=(n?l?.find(d=>d.id===n):l?.[0])??null;return c&&a?{...c,...Un(i,c,c.position,!0)}:c}function av(e,t){return e||(t?.classList.contains("target")?"target":t?.classList.contains("source")?"source":null)}function Sj(e,t){let n=null;return t?n=!0:e&&!t&&(n=!1),n}const iv=()=>!0;function Cj(e,{connectionMode:t,connectionRadius:n,handleId:o,nodeId:s,edgeUpdaterType:a,isTarget:i,domNode:l,nodeLookup:c,lib:d,autoPanOnConnect:f,flowId:p,panBy:m,cancelConnection:h,onConnectStart:g,onConnect:b,onConnectEnd:x,isValidConnection:v=iv,onReconnectEnd:w,updateConnection:y,getTransform:N,getFromHandle:k,autoPanSpeed:S,dragThreshold:M=1,handleDomNode:P}){const I=G0(e.target);let F=0,E;const{x:B,y:O}=_t(e),A=av(a,P),D=l?.getBoundingClientRect();let _=!1;if(!D||!A)return;const R=sv(s,A,o,c,t);if(!R)return;let L=_t(e,D),z=!1,j=null,H=!1,T=null;function W(){if(!f||!D)return;const[Z,U]=q0(L,D,S);m({x:Z,y:U}),F=requestAnimationFrame(W)}const G={...R,nodeId:s,type:A,position:R.position},ee=c.get(s);let te={inProgress:!0,isValid:null,from:Un(ee,G,we.Left,!0),fromHandle:G,fromPosition:G.position,fromNode:ee,to:L,toHandle:null,toPosition:Fp[G.position],toNode:null,pointer:L};function X(){_=!0,y(te),g?.(e,{nodeId:s,handleId:o,handleType:A})}M===0&&X();function re(Z){if(!_){const{x:V,y:ie}=_t(Z),ue=V-B,de=ie-O;if(!(ue*ue+de*de>M*M))return;X()}if(!k()||!G){ge(Z);return}const U=N();L=_t(Z,D),E=kj(Ro(L,U,!1,[1,1]),n,c,G),z||(W(),z=!0);const J=lv(Z,{handle:E,connectionMode:t,fromNodeId:s,fromHandleId:o,fromType:i?"target":"source",isValidConnection:v,doc:I,lib:d,flowId:p,nodeLookup:c});T=J.handleDomNode,j=J.connection,H=Sj(!!E,J.isValid);const ae=c.get(s),fe=ae?Un(ae,G,we.Left,!0):te.from,he={...te,from:fe,isValid:H,to:J.toHandle&&H?Ks({x:J.toHandle.x,y:J.toHandle.y},U):L,toHandle:J.toHandle,toPosition:H&&J.toHandle?J.toHandle.position:Fp[G.position],toNode:J.toHandle?c.get(J.toHandle.nodeId):null,pointer:L};y(he),te=he}function ge(Z){if(!("touches"in Z&&Z.touches.length>0)){if(_){(E||T)&&j&&H&&b?.(j);const{inProgress:U,...J}=te,ae={...J,toPosition:te.toHandle?te.toPosition:null};x?.(Z,ae),a&&w?.(Z,ae)}h(),cancelAnimationFrame(F),z=!1,H=!1,j=null,T=null,I.removeEventListener("mousemove",re),I.removeEventListener("mouseup",ge),I.removeEventListener("touchmove",re),I.removeEventListener("touchend",ge)}}I.addEventListener("mousemove",re),I.addEventListener("mouseup",ge),I.addEventListener("touchmove",re),I.addEventListener("touchend",ge)}function lv(e,{handle:t,connectionMode:n,fromNodeId:o,fromHandleId:s,fromType:a,doc:i,lib:l,flowId:c,isValidConnection:d=iv,nodeLookup:f}){const p=a==="target",m=t?i.querySelector(`.${l}-flow__handle[data-id="${c}-${t?.nodeId}-${t?.id}-${t?.type}"]`):null,{x:h,y:g}=_t(e),b=i.elementFromPoint(h,g),x=b?.classList.contains(`${l}-flow__handle`)?b:m,v={handleDomNode:x,isValid:!1,connection:null,toHandle:null};if(x){const w=av(void 0,x),y=x.getAttribute("data-nodeid"),N=x.getAttribute("data-handleid"),k=x.classList.contains("connectable"),S=x.classList.contains("connectableend");if(!y||!w)return v;const M={source:p?y:o,sourceHandle:p?N:s,target:p?o:y,targetHandle:p?s:N};v.connection=M;const I=k&&S&&(n===Nr.Strict?p&&w==="source"||!p&&w==="target":y!==o||N!==s);v.isValid=I&&d(M),v.toHandle=sv(y,w,N,f,n,!0)}return v}const Cl={onPointerDown:Cj,isValid:lv};function Mj({domNode:e,panZoom:t,getTransform:n,getViewScale:o}){const s=lt(e);function a({translateExtent:l,width:c,height:d,zoomStep:f=1,pannable:p=!0,zoomable:m=!0,inversePan:h=!1}){const g=y=>{if(y.sourceEvent.type!=="wheel"||!t)return;const N=n(),k=y.sourceEvent.ctrlKey&&xo()?10:1,S=-y.sourceEvent.deltaY*(y.sourceEvent.deltaMode===1?.05:y.sourceEvent.deltaMode?1:.002)*f,M=N[2]*Math.pow(2,S*k);t.scaleTo(M)};let b=[0,0];const x=y=>{(y.sourceEvent.type==="mousedown"||y.sourceEvent.type==="touchstart")&&(b=[y.sourceEvent.clientX??y.sourceEvent.touches[0].clientX,y.sourceEvent.clientY??y.sourceEvent.touches[0].clientY])},v=y=>{const N=n();if(y.sourceEvent.type!=="mousemove"&&y.sourceEvent.type!=="touchmove"||!t)return;const k=[y.sourceEvent.clientX??y.sourceEvent.touches[0].clientX,y.sourceEvent.clientY??y.sourceEvent.touches[0].clientY],S=[k[0]-b[0],k[1]-b[1]];b=k;const M=o()*Math.max(N[2],Math.log(N[2]))*(h?-1:1),P={x:N[0]-S[0]*M,y:N[1]-S[1]*M},I=[[0,0],[c,d]];t.setViewportConstrained({x:P.x,y:P.y,zoom:N[2]},I,l)},w=R0().on("start",x).on("zoom",p?v:null).on("zoom.wheel",m?g:null);s.call(w,{})}function i(){s.on("zoom",null)}return{update:a,destroy:i,pointer:Pt}}const _a=e=>({x:e.x,y:e.y,zoom:e.k}),Ai=({x:e,y:t,zoom:n})=>Pa.translate(e,t).scale(n),ar=(e,t)=>e.target.closest(`.${t}`),cv=(e,t)=>t===2&&Array.isArray(e)&&e.includes(2),Ij=e=>((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2,Pi=(e,t=0,n=Ij,o=()=>{})=>{const s=typeof t=="number"&&t>0;return s||o(),s?e.transition().duration(t).ease(n).on("end",o):e},dv=e=>{const t=e.ctrlKey&&xo()?10:1;return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*t};function Aj({zoomPanValues:e,noWheelClassName:t,d3Selection:n,d3Zoom:o,panOnScrollMode:s,panOnScrollSpeed:a,zoomOnPinch:i,onPanZoomStart:l,onPanZoom:c,onPanZoomEnd:d}){return f=>{if(ar(f,t))return f.ctrlKey&&f.preventDefault(),!1;f.preventDefault(),f.stopImmediatePropagation();const p=n.property("__zoom").k||1;if(f.ctrlKey&&i){const x=Pt(f),v=dv(f),w=p*Math.pow(2,v);o.scaleTo(n,w,x,f);return}const m=f.deltaMode===1?20:1;let h=s===Bn.Vertical?0:f.deltaX*m,g=s===Bn.Horizontal?0:f.deltaY*m;!xo()&&f.shiftKey&&s!==Bn.Vertical&&(h=f.deltaY*m,g=0),o.translateBy(n,-(h/p)*a,-(g/p)*a,{internal:!0});const b=_a(n.property("__zoom"));clearTimeout(e.panScrollTimeout),e.isPanScrolling?(c?.(f,b),e.panScrollTimeout=setTimeout(()=>{d?.(f,b),e.isPanScrolling=!1},150)):(e.isPanScrolling=!0,l?.(f,b))}}function Pj({noWheelClassName:e,preventScrolling:t,d3ZoomHandler:n}){return function(o,s){const a=o.type==="wheel",i=!t&&a&&!o.ctrlKey,l=ar(o,e);if(o.ctrlKey&&a&&l&&o.preventDefault(),i||l)return null;o.preventDefault(),n.call(this,o,s)}}function Ej({zoomPanValues:e,onDraggingChange:t,onPanZoomStart:n}){return o=>{if(o.sourceEvent?.internal)return;const s=_a(o.transform);e.mouseButton=o.sourceEvent?.button||0,e.isZoomingOrPanning=!0,e.prevViewport=s,o.sourceEvent?.type==="mousedown"&&t(!0),n&&n?.(o.sourceEvent,s)}}function $j({zoomPanValues:e,panOnDrag:t,onPaneContextMenu:n,onTransformChange:o,onPanZoom:s}){return a=>{e.usedRightMouseButton=!!(n&&cv(t,e.mouseButton??0)),a.sourceEvent?.sync||o([a.transform.x,a.transform.y,a.transform.k]),s&&!a.sourceEvent?.internal&&s?.(a.sourceEvent,_a(a.transform))}}function _j({zoomPanValues:e,panOnDrag:t,panOnScroll:n,onDraggingChange:o,onPanZoomEnd:s,onPaneContextMenu:a}){return i=>{if(!i.sourceEvent?.internal&&(e.isZoomingOrPanning=!1,a&&cv(t,e.mouseButton??0)&&!e.usedRightMouseButton&&i.sourceEvent&&a(i.sourceEvent),e.usedRightMouseButton=!1,o(!1),s)){const l=_a(i.transform);e.prevViewport=l,clearTimeout(e.timerId),e.timerId=setTimeout(()=>{s?.(i.sourceEvent,l)},n?150:0)}}}function Dj({zoomActivationKeyPressed:e,zoomOnScroll:t,zoomOnPinch:n,panOnDrag:o,panOnScroll:s,zoomOnDoubleClick:a,userSelectionActive:i,noWheelClassName:l,noPanClassName:c,lib:d,connectionInProgress:f}){return p=>{const m=e||t,h=n&&p.ctrlKey,g=p.type==="wheel";if(p.button===1&&p.type==="mousedown"&&(ar(p,`${d}-flow__node`)||ar(p,`${d}-flow__edge`)))return!0;if(!o&&!m&&!s&&!a&&!n||i||f&&!g||ar(p,l)&&g||ar(p,c)&&(!g||s&&g&&!e)||!n&&p.ctrlKey&&g)return!1;if(!n&&p.type==="touchstart"&&p.touches?.length>1)return p.preventDefault(),!1;if(!m&&!s&&!h&&g||!o&&(p.type==="mousedown"||p.type==="touchstart")||Array.isArray(o)&&!o.includes(p.button)&&p.type==="mousedown")return!1;const b=Array.isArray(o)&&o.includes(p.button)||!p.button||p.button<=1;return(!p.ctrlKey||g)&&b}}function Lj({domNode:e,minZoom:t,maxZoom:n,translateExtent:o,viewport:s,onPanZoom:a,onPanZoomStart:i,onPanZoomEnd:l,onDraggingChange:c}){const d={isZoomingOrPanning:!1,usedRightMouseButton:!1,prevViewport:{},mouseButton:0,timerId:void 0,panScrollTimeout:void 0,isPanScrolling:!1},f=e.getBoundingClientRect(),p=R0().scaleExtent([t,n]).translateExtent(o),m=lt(e).call(p);w({x:s.x,y:s.y,zoom:kr(s.zoom,t,n)},[[0,0],[f.width,f.height]],o);const h=m.on("wheel.zoom"),g=m.on("dblclick.zoom");p.wheelDelta(dv);function b(E,B){return m?new Promise(O=>{p?.interpolate(B?.interpolate==="linear"?no:xs).transform(Pi(m,B?.duration,B?.ease,()=>O(!0)),E)}):Promise.resolve(!1)}function x({noWheelClassName:E,noPanClassName:B,onPaneContextMenu:O,userSelectionActive:A,panOnScroll:D,panOnDrag:_,panOnScrollMode:R,panOnScrollSpeed:L,preventScrolling:z,zoomOnPinch:j,zoomOnScroll:H,zoomOnDoubleClick:T,zoomActivationKeyPressed:W,lib:G,onTransformChange:ee,connectionInProgress:se,paneClickDistance:te,selectionOnDrag:X}){A&&!d.isZoomingOrPanning&&v();const re=D&&!W&&!A;p.clickDistance(X?1/0:!$t(te)||te<0?0:te);const ge=re?Aj({zoomPanValues:d,noWheelClassName:E,d3Selection:m,d3Zoom:p,panOnScrollMode:R,panOnScrollSpeed:L,zoomOnPinch:j,onPanZoomStart:i,onPanZoom:a,onPanZoomEnd:l}):Pj({noWheelClassName:E,preventScrolling:z,d3ZoomHandler:h});if(m.on("wheel.zoom",ge,{passive:!1}),!A){const U=Ej({zoomPanValues:d,onDraggingChange:c,onPanZoomStart:i});p.on("start",U);const J=$j({zoomPanValues:d,panOnDrag:_,onPaneContextMenu:!!O,onPanZoom:a,onTransformChange:ee});p.on("zoom",J);const ae=_j({zoomPanValues:d,panOnDrag:_,panOnScroll:D,onPaneContextMenu:O,onPanZoomEnd:l,onDraggingChange:c});p.on("end",ae)}const Z=Dj({zoomActivationKeyPressed:W,panOnDrag:_,zoomOnScroll:H,panOnScroll:D,zoomOnDoubleClick:T,zoomOnPinch:j,userSelectionActive:A,noPanClassName:B,noWheelClassName:E,lib:G,connectionInProgress:se});p.filter(Z),T?m.on("dblclick.zoom",g):m.on("dblclick.zoom",null)}function v(){p.on("zoom",null)}async function w(E,B,O){const A=Ai(E),D=p?.constrain()(A,B,O);return D&&await b(D),new Promise(_=>_(D))}async function y(E,B){const O=Ai(E);return await b(O,B),new Promise(A=>A(O))}function N(E){if(m){const B=Ai(E),O=m.property("__zoom");(O.k!==E.zoom||O.x!==E.x||O.y!==E.y)&&p?.transform(m,B,null,{sync:!0})}}function k(){const E=m?T0(m.node()):{x:0,y:0,k:1};return{x:E.x,y:E.y,zoom:E.k}}function S(E,B){return m?new Promise(O=>{p?.interpolate(B?.interpolate==="linear"?no:xs).scaleTo(Pi(m,B?.duration,B?.ease,()=>O(!0)),E)}):Promise.resolve(!1)}function M(E,B){return m?new Promise(O=>{p?.interpolate(B?.interpolate==="linear"?no:xs).scaleBy(Pi(m,B?.duration,B?.ease,()=>O(!0)),E)}):Promise.resolve(!1)}function P(E){p?.scaleExtent(E)}function I(E){p?.translateExtent(E)}function F(E){const B=!$t(E)||E<0?0:E;p?.clickDistance(B)}return{update:x,destroy:v,setViewport:y,setViewportConstrained:w,getViewport:k,scaleTo:S,scaleBy:M,setScaleExtent:P,setTranslateExtent:I,syncViewport:N,setClickDistance:F}}var Mr;(function(e){e.Line="line",e.Handle="handle"})(Mr||(Mr={}));function Tj({width:e,prevWidth:t,height:n,prevHeight:o,affectsX:s,affectsY:a}){const i=e-t,l=n-o,c=[i>0?1:i<0?-1:0,l>0?1:l<0?-1:0];return i&&s&&(c[0]=c[0]*-1),l&&a&&(c[1]=c[1]*-1),c}function Jp(e){const t=e.includes("right")||e.includes("left"),n=e.includes("bottom")||e.includes("top"),o=e.includes("left"),s=e.includes("top");return{isHorizontal:t,isVertical:n,affectsX:o,affectsY:s}}function gn(e,t){return Math.max(0,t-e)}function bn(e,t){return Math.max(0,e-t)}function cs(e,t,n){return Math.max(0,t-e,e-n)}function ef(e,t){return e?!t:t}function Rj(e,t,n,o,s,a,i,l){let{affectsX:c,affectsY:d}=t;const{isHorizontal:f,isVertical:p}=t,m=f&&p,{xSnapped:h,ySnapped:g}=n,{minWidth:b,maxWidth:x,minHeight:v,maxHeight:w}=o,{x:y,y:N,width:k,height:S,aspectRatio:M}=e;let P=Math.floor(f?h-e.pointerX:0),I=Math.floor(p?g-e.pointerY:0);const F=k+(c?-P:P),E=S+(d?-I:I),B=-a[0]*k,O=-a[1]*S;let A=cs(F,b,x),D=cs(E,v,w);if(i){let L=0,z=0;c&&P<0?L=gn(y+P+B,i[0][0]):!c&&P>0&&(L=bn(y+F+B,i[1][0])),d&&I<0?z=gn(N+I+O,i[0][1]):!d&&I>0&&(z=bn(N+E+O,i[1][1])),A=Math.max(A,L),D=Math.max(D,z)}if(l){let L=0,z=0;c&&P>0?L=bn(y+P,l[0][0]):!c&&P<0&&(L=gn(y+F,l[1][0])),d&&I>0?z=bn(N+I,l[0][1]):!d&&I<0&&(z=gn(N+E,l[1][1])),A=Math.max(A,L),D=Math.max(D,z)}if(s){if(f){const L=cs(F/M,v,w)*M;if(A=Math.max(A,L),i){let z=0;!c&&!d||c&&!d&&m?z=bn(N+O+F/M,i[1][1])*M:z=gn(N+O+(c?P:-P)/M,i[0][1])*M,A=Math.max(A,z)}if(l){let z=0;!c&&!d||c&&!d&&m?z=gn(N+F/M,l[1][1])*M:z=bn(N+(c?P:-P)/M,l[0][1])*M,A=Math.max(A,z)}}if(p){const L=cs(E*M,b,x)/M;if(D=Math.max(D,L),i){let z=0;!c&&!d||d&&!c&&m?z=bn(y+E*M+B,i[1][0])/M:z=gn(y+(d?I:-I)*M+B,i[0][0])/M,D=Math.max(D,z)}if(l){let z=0;!c&&!d||d&&!c&&m?z=gn(y+E*M,l[1][0])/M:z=bn(y+(d?I:-I)*M,l[0][0])/M,D=Math.max(D,z)}}}I=I+(I<0?D:-D),P=P+(P<0?A:-A),s&&(m?F>E*M?I=(ef(c,d)?-P:P)/M:P=(ef(c,d)?-I:I)*M:f?(I=P/M,d=c):(P=I*M,c=d));const _=c?y+P:y,R=d?N+I:N;return{width:k+(c?-P:P),height:S+(d?-I:I),x:a[0]*P*(c?-1:1)+_,y:a[1]*I*(d?-1:1)+R}}const uv={width:0,height:0,x:0,y:0},Oj={...uv,pointerX:0,pointerY:0,aspectRatio:1};function zj(e){return[[0,0],[e.measured.width,e.measured.height]]}function Bj(e,t,n){const o=t.position.x+e.position.x,s=t.position.y+e.position.y,a=e.measured.width??0,i=e.measured.height??0,l=n[0]*a,c=n[1]*i;return[[o-l,s-c],[o+a-l,s+i-c]]}function Fj({domNode:e,nodeId:t,getStoreItems:n,onChange:o,onEnd:s}){const a=lt(e);let i={controlDirection:Jp("bottom-right"),boundaries:{minWidth:0,minHeight:0,maxWidth:Number.MAX_VALUE,maxHeight:Number.MAX_VALUE},resizeDirection:void 0,keepAspectRatio:!1};function l({controlPosition:d,boundaries:f,keepAspectRatio:p,resizeDirection:m,onResizeStart:h,onResize:g,onResizeEnd:b,shouldResize:x}){let v={...uv},w={...Oj};i={boundaries:f,resizeDirection:m,keepAspectRatio:p,controlDirection:Jp(d)};let y,N=null,k=[],S,M,P,I=!1;const F=w0().on("start",E=>{const{nodeLookup:B,transform:O,snapGrid:A,snapToGrid:D,nodeOrigin:_,paneDomNode:R}=n();if(y=B.get(t),!y)return;N=R?.getBoundingClientRect()??null;const{xSnapped:L,ySnapped:z}=ro(E.sourceEvent,{transform:O,snapGrid:A,snapToGrid:D,containerBounds:N});v={width:y.measured.width??0,height:y.measured.height??0,x:y.position.x??0,y:y.position.y??0},w={...v,pointerX:L,pointerY:z,aspectRatio:v.width/v.height},S=void 0,y.parentId&&(y.extent==="parent"||y.expandParent)&&(S=B.get(y.parentId),M=S&&y.extent==="parent"?zj(S):void 0),k=[],P=void 0;for(const[j,H]of B)if(H.parentId===t&&(k.push({id:j,position:{...H.position},extent:H.extent}),H.extent==="parent"||H.expandParent)){const T=Bj(H,y,H.origin??_);P?P=[[Math.min(T[0][0],P[0][0]),Math.min(T[0][1],P[0][1])],[Math.max(T[1][0],P[1][0]),Math.max(T[1][1],P[1][1])]]:P=T}h?.(E,{...v})}).on("drag",E=>{const{transform:B,snapGrid:O,snapToGrid:A,nodeOrigin:D}=n(),_=ro(E.sourceEvent,{transform:B,snapGrid:O,snapToGrid:A,containerBounds:N}),R=[];if(!y)return;const{x:L,y:z,width:j,height:H}=v,T={},W=y.origin??D,{width:G,height:ee,x:se,y:te}=Rj(w,i.controlDirection,_,i.boundaries,i.keepAspectRatio,W,M,P),X=G!==j,re=ee!==H,ge=se!==L&&X,Z=te!==z&&re;if(!ge&&!Z&&!X&&!re)return;if((ge||Z||W[0]===1||W[1]===1)&&(T.x=ge?se:v.x,T.y=Z?te:v.y,v.x=T.x,v.y=T.y,k.length>0)){const fe=se-L,he=te-z;for(const V of k)V.position={x:V.position.x-fe+W[0]*(G-j),y:V.position.y-he+W[1]*(ee-H)},R.push(V)}if((X||re)&&(T.width=X&&(!i.resizeDirection||i.resizeDirection==="horizontal")?G:v.width,T.height=re&&(!i.resizeDirection||i.resizeDirection==="vertical")?ee:v.height,v.width=T.width,v.height=T.height),S&&y.expandParent){const fe=W[0]*(T.width??0);T.x&&T.x<fe&&(v.x=fe,w.x=w.x-(T.x-fe));const he=W[1]*(T.height??0);T.y&&T.y<he&&(v.y=he,w.y=w.y-(T.y-he))}const U=Tj({width:v.width,prevWidth:j,height:v.height,prevHeight:H,affectsX:i.controlDirection.affectsX,affectsY:i.controlDirection.affectsY}),J={...v,direction:U};x?.(E,J)!==!1&&(I=!0,g?.(E,J),o(T,R))}).on("end",E=>{I&&(b?.(E,{...v}),s?.({...v}),I=!1)});a.call(F)}function c(){a.on(".drag",null)}return{update:l,destroy:c}}var pv={exports:{}},fv={};/**
|
|
1084
|
+
`);return r(AO,{scope:{type:"device",deviceId:e},greeting:t,className:"h-full border-0 rounded-none"})}function LO({deviceId:e}){const t=Le(),n=Number.isFinite(e),o=Lc(t.trpcClient,n?e:0,{enabled:n}),{data:s}=q6(n?e:0);if(!n)return u("div",{className:"flex items-center justify-center h-full text-[11px] text-foreground-subtle italic",children:["Device #",e," not loaded."]});const a=(s?.features??[]).includes(Rn.PtzAutotrack);return u("div",{className:"flex flex-col h-full overflow-y-auto",children:[r($c,{controls:o,mode:"panel"}),a&&r(EO,{deviceId:e})]})}function TO({deviceId:e}){return Number.isFinite(e)?r("div",{className:"flex flex-col h-full overflow-y-auto",children:r(nr,{deviceId:e,limit:50,maxHeight:"max-h-full"})}):u("div",{className:"flex items-center justify-center h-full text-[11px] text-foreground-subtle italic",children:["Device #",e," not loaded."]})}function RO({deviceId:e}){return Number.isFinite(e)?r("div",{className:"flex flex-col h-full overflow-y-auto",children:r(Ec,{deviceId:e,limit:50,maxHeight:"max-h-full"})}):u("div",{className:"flex items-center justify-center h-full text-[11px] text-foreground-subtle italic",children:["Device #",e," not loaded."]})}function OO({parentDeviceId:e}){const{t}=zt(),n=et(),o=Le(),{data:s,isLoading:a,isError:i}=Fy(e);if(a)return r("div",{className:"rounded-lg border border-border bg-surface p-3",children:r("p",{className:"text-[10px] text-foreground-subtle",children:t("common.loading",{defaultValue:"Loading…"})})});if(i)return r("div",{className:"rounded-lg border border-border bg-surface p-3",children:r("p",{className:"text-[10px] text-warning",children:t("integrations.childrenLoadError",{defaultValue:"Failed to load children"})})});const l=s??[];if(l.length===0)return null;const c=l.some(p=>!!p.role),d=l.some(p=>!p.role),f=c&&!d?t("device.accessories",{defaultValue:"Accessories"}):!c&&d?t("device.adoptedDevices",{defaultValue:"Adopted devices"}):t("device.children",{defaultValue:"Children"});return u("div",{className:"rounded-lg border border-border bg-surface p-3",children:[r("div",{className:"text-[10px] font-semibold uppercase tracking-wide text-foreground-subtle mb-1.5",children:f}),r("div",{className:"space-y-1",children:l.map(p=>r(so,{trpc:o.trpcClient,device:p,variant:"minimal",onNavigate:m=>n(`/devices/${String(m)}`)},p.id))})]})}function wi(e){return e<1e3?`${e.toFixed(0)} kbps`:`${(e/1e3).toFixed(1)} Mbps`}function zO({device:e}){const t=et(),n=typeof e.id=="number"?e.id:null,o=String(e.type??""),s=o===at.Camera,a=o===at.Hub,i=e.features??[],{data:l}=bc({deviceId:n??0},{enabled:n!==null&&s,refetchInterval:5e3}),c=l?.streams??{},d=Object.entries(c),f=i.includes(Rn.DoorbellButton),p=Tc(f?{deviceId:n??void 0,historyLimit:10}:void 0),m=p.latest?Date.now()-p.latest.timestamp<3e4:!1;return u("div",{className:"space-y-5",children:[a&&n!==null&&r(Cx,{deviceId:n,onOpenChild:h=>t(`/devices/${h}`)}),s&&n!==null&&r(it,{widgetId:"pipeline-orchestrator/pipeline-quick-stats",host:"device-tab",deviceId:n}),f&&r(_c,{history:p.history,latestIsFresh:m}),s&&n!==null&&r(it,{widgetId:"stream-broker/stream-broker-panel",host:"device-tab",deviceId:n}),s&&d.length>0&&u("div",{className:"@container rounded-lg border border-border bg-surface overflow-hidden",style:{containerType:"inline-size"},children:[r("div",{className:"border-b border-border px-4 py-2",children:r("h2",{className:"text-xs font-semibold text-foreground uppercase tracking-wider",children:"Stream Network"})}),r("div",{className:"divide-y divide-border",children:d.map(([h,g])=>u("div",{className:"px-4 py-2.5",children:[u("div",{className:"flex items-center gap-2 mb-2",children:[r(jn,{className:"h-3 w-3 text-foreground-subtle"}),r("span",{className:"text-[11px] font-medium text-foreground",children:h})]}),u("div",{className:"grid grid-cols-2 @[640px]:grid-cols-4 gap-2",children:[r(Jo,{label:"Nominal",value:wi(g.nominalBitrateKbps??0)}),r(Jo,{label:"Observed",value:wi(g.observedBitrateKbps??0)}),r(Jo,{label:"Peak",value:wi(g.peakBitrateKbps??0)}),r(Jo,{label:"Packet Loss",value:`${(g.packetLossPercent??0).toFixed(2)}%`,warning:(g.packetLossPercent??0)>1})]})]},h))})]}),r(ky,{})]})}function Jo({label:e,value:t,warning:n}){return u("div",{children:[r("p",{className:"text-[10px] text-foreground-subtle",children:e}),r("p",{className:`text-xs font-medium ${n?"text-warning":"text-foreground"}`,children:t})]})}function BO({schema:e,values:t,pendingKeys:n,onChange:o,onAction:s,onSave:a,onDiscard:i,disabled:l}){const c=e.tabs??[],d=Q(()=>{const k=new Map;for(const S of e.sections){const M=S.tab??"general",P=k.get(M)??[];P.push(S),k.set(M,P)}return k},[e.sections]),f=new Set(c.map(k=>k.id)),p=[...c,...[...d.keys()].filter(k=>!f.has(k)).map(k=>({id:k,label:k,icon:"wrench",order:100}))],m=p[0]?.id??"general",[h,g]=$(m),b=d.get(h)??[],v={sections:b.length<=1?b.length===1?[{...b[0],title:""}]:b:b.every(S=>!S.title)?[{...b[0],title:"",fields:b.flatMap(S=>S.fields)}]:b},w=r(qy,{pendingCount:n.length,onSave:()=>a(n),onDiscard:()=>i(n),saving:l});if(p.length<=1)return u("div",{className:"flex flex-col gap-3",children:[r(Nn,{schema:e,values:t,onChange:o,onAction:s,disabled:l}),w]});const y=new Map,N=new Map;for(const[k,S]of d){y.set(k,S.length);const M=new Set,P=F=>{for(const E of F)if("key"in E&&typeof E.key=="string"&&M.add(E.key),E.type==="group")P(E.fields);else if(E.type==="sub-tabs")for(const B of E.tabs)P(B.fields)};for(const F of S)P(F.fields);const I=n.filter(F=>M.has(F)).length;I>0&&N.set(k,I)}return u("div",{className:"flex flex-col gap-3",children:[r(Qy,{tabs:p.map(k=>({id:k.id,label:k.label})),activeId:h,onChange:g,countByTab:y,pendingByTab:N}),r(Nn,{schema:v,values:t,onChange:o,onAction:s,disabled:l}),w]})}const fp={viewer:10,admin:20,super_admin:30};function FO(e,t){if(!t)return!0;const n=fp[t];return n===void 0?!0:(e?fp[e]??0:0)>=n}function jO(e){if(!e)return null;const n={sections:[...e.sections].sort((o,s)=>{const a=o.tab??"general",i=s.tab??"general";return a!==i?a.localeCompare(i):(o.order??0)-(s.order??0)})};return e.tabs?{...n,tabs:e.tabs}:n}function Gy(e){return e.type==="separator"||e.type==="info"||e.type==="button"||e.type==="widget"||e.type==="addon-action-button"}function Wy(e){return e.key}function HO(e){if(!Gy(e))return e.value}function Yy(e){return Gy(e)?null:e}function Ts(e,t){for(const n of e)if(t(n),n.type==="group")Ts(n.fields,t);else if(n.type==="sub-tabs")for(const o of n.tabs)Ts(o.fields,t)}function VO(e){if(!e)return{};const t={};for(const n of e.sections)Ts(n.fields,o=>{const s=Wy(o);s!==null&&(t[s]=HO(o))});return t}function mp(e,t){if(!e)return null;let n=null;for(const o of e.sections)if(Ts(o.fields,s=>{if(n!==null||Wy(s)!==t)return;const a=Yy(s);a&&a.writerCapName&&a.writerAddonId&&(n={capName:a.writerCapName,addonId:a.writerAddonId})}),n!==null)break;return n}function qO(e){return{...e,fields:e.fields.map(Zy)}}function Zy(e){return e.type==="separator"||e.type==="info"||e.type==="button"||e.type==="object-array"?e:{...e,readonlyField:!0}}function QO(e,t){return e&&{...e,sections:e.sections.map(n=>({...n,fields:n.fields.map(o=>{const s=Yy(o);return s?FO(t,s.minRole)?o:Zy(o):o})}))}}function Xy({deviceId:e,sectionFilter:t}){const n=ke(),{user:o}=Tr(),s=o?.role,a=ne(!1),{data:i,isLoading:l}=mc({deviceId:e},{refetchInterval:()=>a.current?!1:2500,staleTime:6e4,enabled:Number.isFinite(e)}),{data:c}=Fn({deviceId:e},{staleTime:6e4,enabled:Number.isFinite(e)}),d=i?.settings??null,f=i?.live??null,p=Q(()=>{if(!d&&!f)return null;const B=d?.sections??[],O=(f?.sections??[]).map(qO),A=[...B,...O],D=t?A.filter(t):A.filter(z=>z.location!=="top-tab");if(D.length===0)return null;const _=new Set;for(const z of D)_.add(z.tab??"general");const L=[...d?.tabs??[],...(f?.tabs??[]).filter(z=>!(d?.tabs??[]).some(j=>j.id===z.id))].filter(z=>_.has(z.id));return L.length>0?{tabs:L,sections:D}:{sections:D}},[d,f,t]),m=Q(()=>jO(p),[p]),h=Q(()=>QO(m,s),[m,s]),g=Q(()=>VO(h),[h]),b=Wb(),x=gc(),v=Ag({onSuccess:()=>{n.invalidateQueries({queryKey:[["deviceManager","getDeviceAggregate"]]})}}),w={isPending:v.isPending,mutate:B=>{v.mutate({deviceId:e,changes:[...B]})}},y=q(B=>{const O=Object.entries(B).map(([A,D])=>{const _=mp(h,A);return _?{writerCapName:_.capName,writerAddonId:_.addonId,key:A,value:D}:null}).filter(A=>A!==null);O.length>0&&w.mutate(O)},[h,w]),N=q(B=>{const O=Object.entries(B).map(([A,D])=>{const _=mp(h,A);return _?{writerCapName:_.capName,writerAddonId:_.addonId,key:A,value:D}:null}).filter(A=>A!==null);O.length>0&&w.mutate(O)},[h,w]),k=Uy({schema:h,serverValues:g,onImmediateSave:y,onDeferredSave:N}),{values:S,pendingKeys:M,handleChange:P,handleSave:I,handleDiscard:F}=k;if(a.current=k.editingPaused,l)return u("div",{className:"flex items-center justify-center py-12 text-foreground-subtle",children:[r(Pe,{className:"h-4 w-4 animate-spin mr-2"}),r("span",{className:"text-xs",children:"Loading device aggregate…"})]});if(!h||h.sections.length===0)return r("div",{className:"text-xs text-foreground-subtle italic py-4 text-center",children:"No aggregate contributions for this device."});async function E(B,O,A){if(B==="regenerate-rtsp-token"){const D=["rtspUrl:","regenerateToken:"].find(L=>O.startsWith(L));if(!D)throw new Error(`regenerate-rtsp-token: unrecognised key "${O}" (expected "rtspUrl:<streamId>" or "regenerateToken:<streamId>")`);const _=O.slice(D.length);if(!_)throw new Error(`regenerate-rtsp-token: key "${O}" has no streamId after prefix`);const R=`${e}/${_}`;await b.mutateAsync({brokerId:R}),n.invalidateQueries({queryKey:[["deviceManager","getDeviceAggregate"]]});return}if(B==="test-probe"){if(!c)return{status:"error",error:"Device metadata not loaded yet"};try{return await x.mutateAsync({addonId:c.addonId,type:c.type,key:O,value:A})}catch(D){return{status:"error",error:D instanceof Error?D.message:String(D)}}}if(B==="refresh-driver-data"){await v.mutateAsync({deviceId:e,changes:[{writerCapName:"device-manager",writerAddonId:"device-manager",key:O,value:Date.now()}]});return}throw new Error(`[device-aggregate] unknown action "${B}"`)}return r(BO,{schema:h,values:S,pendingKeys:M,onChange:P,onAction:E,onSave:I,onDiscard:F,disabled:w.isPending})}function UO({deviceId:e}){return r(Xy,{deviceId:e})}const Jy=6e4,ul=60*Jy,hp=24*ul;function Sa(e){if(e==null||e<=0)return"—";const t=Date.now()-e;return t<0||t<3e4?"just now":t<ul?`${String(Math.floor(t/Jy))}m ago`:t<hp?`${String(Math.floor(t/ul))}h ago`:`${String(Math.floor(t/hp))}d ago`}function KO(e,t=new Date){const n=new Date(e);return n.getFullYear()===t.getFullYear()&&n.getMonth()===t.getMonth()&&n.getDate()===t.getDate()}function e0({dev:e,busy:t,setBusy:n}){const o=e?.motionTrigger,s=on(e?.state.motionTrigger),[a,i]=$(!1);if(!o)return null;const l=s?.enabled===!0,c=s!==void 0,d=async()=>{if(t||!c)return;const p=!l;n(!0),i(!0);try{await o.setMotionTrigger({enabled:p})}finally{n(!1),i(!1)}};return u("button",{type:"button",onClick:()=>{d()},disabled:t||!c,title:c?l?"Disable trigger on motion":"Enable trigger on motion":"Awaiting state…","aria-pressed":l,className:`inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-[11px] font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50 ${l?"border-primary/50 bg-primary/15 text-primary":"border-border bg-surface text-foreground-subtle hover:text-foreground"}`,children:[r(Io,{className:"h-3 w-3"}),r("span",{children:a?l?"Disabling…":"Enabling…":c?l?"On motion: on":"On motion: off":"On motion: …"})]})}function t0({deviceId:e,deviceName:t,useSiren:n=!1}){const o=Le(),s=kt(o.trpcClient,e),a=on(s?.state.switch),[i,l]=$(!1),c=a?.on??!1,d=a?.lastChangedAt??null,f=a!==void 0,p=n?Ao:fy,m=async()=>{if(!(i||!f||!s?.switch)){l(!0);try{await s.switch.setState({on:!c})}finally{l(!1)}}};return u("div",{className:"flex h-full w-full flex-col items-center justify-center gap-3 p-4",children:[r("button",{type:"button",onClick:()=>{m()},disabled:i||!f||!s?.switch,title:f?c?`Turn off ${t}`:`Turn on ${t}`:"Awaiting state…","aria-pressed":c,className:`flex h-24 w-24 items-center justify-center rounded-full border-2 transition-all disabled:cursor-not-allowed disabled:opacity-50 ${c?"border-success bg-success/20 text-success shadow-lg shadow-success/20":"border-border bg-surface text-foreground-subtle hover:border-foreground-subtle hover:text-foreground"}`,children:r(p,{className:"h-10 w-10"})}),r(e0,{dev:s,busy:i,setBusy:l}),u("div",{className:"text-center",children:[r("div",{className:`text-sm font-semibold ${c?"text-success":"text-foreground-subtle"}`,children:f?c?"On":"Off":"Unknown"}),r("div",{className:"text-[10px] text-foreground-subtle mt-0.5",children:f?`Changed ${Sa(d)}`:"Awaiting state…"})]})]})}function GO({deviceId:e,deviceName:t}){const n=Le(),o=kt(n.trpcClient,e),s=on(o?.state.switch),a=on(o?.state.brightness),i=s?.on??!1,l=s?.lastChangedAt??null,c=s!==void 0,d=a!==void 0,f=o?.brightness!==void 0,[p,m]=$(!1),[h,g]=$(a?.percentage??0);Y(()=>{a?.percentage!==void 0&&g(a.percentage)},[a?.percentage]);const b=async()=>{if(!(p||!c||!o?.switch)){m(!0);try{await o.switch.setState({on:!i})}finally{m(!1)}}},x=async()=>{if(!(p||!d||!o?.brightness)){m(!0);try{await o.brightness.setBrightness({percentage:h})}finally{m(!1)}}};return u("div",{className:"flex h-full w-full flex-col items-center justify-center gap-3 p-4",children:[r("button",{type:"button",onClick:()=>{b()},disabled:p||!c||!o?.switch,title:c?i?`Turn off ${t}`:`Turn on ${t}`:"Awaiting state…","aria-pressed":i,className:`flex h-20 w-20 items-center justify-center rounded-full border-2 transition-all disabled:cursor-not-allowed disabled:opacity-50 ${i?"border-warning bg-warning/20 text-warning shadow-lg shadow-warning/30":"border-border bg-surface text-foreground-subtle hover:border-foreground-subtle hover:text-foreground"}`,children:r(rL,{className:"h-9 w-9"})}),f?u("div",{className:"flex w-full max-w-xs flex-col items-center gap-1",children:[r("input",{type:"range",min:0,max:100,step:1,value:h,disabled:p||!i||!d,onChange:v=>g(Number(v.currentTarget.value)),onPointerUp:()=>{x()},onKeyUp:v=>{v.key==="Enter"&&x()},"aria-label":"Brightness",className:"w-full accent-warning disabled:cursor-not-allowed disabled:opacity-50"}),r("div",{className:"text-[10px] text-foreground-subtle tabular-nums",children:d?`${String(h)}%`:"Brightness unavailable"})]}):null,r(e0,{dev:o,busy:p,setBusy:m}),u("div",{className:"text-center",children:[r("div",{className:`text-sm font-semibold ${i?"text-warning":"text-foreground-subtle"}`,children:c?i?"On":"Off":"Unknown"}),r("div",{className:"text-[10px] text-foreground-subtle mt-0.5",children:c?`Changed ${Sa(l)}`:"Awaiting state…"})]})]})}function WO({deviceId:e}){const t=Le(),n=kt(t.trpcClient,e),o=on(n?.state.motion),s=o?.detected??!1,a=o?.lastDetectedAt??null,i=o!==void 0;return u("div",{className:"flex h-full w-full flex-col items-center justify-center gap-3 p-4",children:[r("div",{className:`flex h-24 w-24 items-center justify-center rounded-full border-2 transition-all ${s?"border-danger bg-danger/20 text-danger shadow-lg shadow-danger/30 animate-pulse":"border-border bg-surface text-foreground-subtle"}`,"aria-live":"polite",title:s?"Motion detected":"Idle",children:s?r(LL,{className:"h-10 w-10"}):r(Io,{className:"h-10 w-10"})}),u("div",{className:"text-center",children:[r("div",{className:`text-sm font-semibold ${s?"text-danger":"text-foreground-subtle"}`,children:i?s?"Triggered":"Idle":"Unknown"}),r("div",{className:"text-[10px] text-foreground-subtle mt-0.5",children:i?`Last trip ${Sa(a)}`:"Awaiting state…"})]})]})}function YO({deviceId:e}){const t=Le(),n=kt(t.trpcClient,e),o=on(n?.state.doorbell),s=o?.lastPressedAt??null,a=o!==void 0,i=s!==null&&Date.now()-s<6e4,[l,c]=$(0),[d,f]=$(null);return Y(()=>{s===null||s===d||(f(s),KO(s)&&c(p=>p+1))},[s,d]),u("div",{className:"flex h-full w-full flex-col items-center justify-center gap-3 p-4",children:[r("div",{className:`flex h-24 w-24 items-center justify-center rounded-full border-2 transition-all ${i?"border-primary bg-primary/20 text-primary shadow-lg shadow-primary/30 animate-pulse":"border-border bg-surface text-foreground-subtle"}`,"aria-live":"polite",title:i?"Just pressed":"Idle",children:r(Ao,{className:"h-10 w-10"})}),u("div",{className:"text-center",children:[r("div",{className:`text-sm font-semibold ${i?"text-primary":"text-foreground-subtle"}`,children:a?`Last press ${Sa(s)}`:"Unknown"}),r("div",{className:"text-[10px] text-foreground-subtle mt-0.5 tabular-nums",children:a?`${String(l)} ring${l===1?"":"s"} today`:"Awaiting state…"})]})]})}function ZO({deviceName:e,deviceType:t,provider:n,isOnline:o,features:s}){return u("div",{className:"flex h-full w-full flex-col items-center justify-center gap-3 rounded-lg border border-dashed border-border bg-surface p-6 text-center",children:[r(cn,{type:n,size:"lg"}),u("div",{children:[r("div",{className:"text-sm font-semibold text-foreground",children:e}),r("div",{className:"text-[10px] text-foreground-subtle uppercase tracking-wider mt-0.5",children:t})]}),u("div",{className:"flex items-center gap-2 flex-wrap justify-center",children:[r(ka,{status:o?"online":"offline"}),s.length>0&&r(wa,{capabilities:s})]}),r("div",{className:"text-[10px] text-foreground-subtle italic max-w-xs mt-1",children:"No live view for this device type. Use the Config tab or the shortcut row to interact."})]})}function XO({deviceId:e}){const t=ke(),n=gg({deviceId:e},{refetchInterval:1e4,retry:!1}),o=bg({onSuccess:()=>{t.invalidateQueries({queryKey:[["deviceDiscovery","listDiscovered"]]}),t.invalidateQueries({queryKey:[["deviceDiscovery","getStatus"]]})}}),s=Q(()=>JO(n.data??[]),[n.data]);return u("div",{className:"flex h-full w-full flex-col gap-3 p-3 sm:p-4",children:[u("div",{className:"flex flex-wrap items-stretch gap-2 sm:gap-3",children:[r(Ni,{label:"Discovered",value:s.total,icon:r(an,{className:"h-3.5 w-3.5"})}),r(Ni,{label:"Adopted",value:s.adopted,accent:"success"}),r(Ni,{label:"Available",value:s.available,accent:s.available>0?"primary":void 0}),u("button",{type:"button",onClick:()=>{o.mutateAsync({deviceId:e}).catch(()=>{})},disabled:o.isPending,className:"inline-flex items-center justify-center gap-1.5 rounded-lg border border-border px-3 py-2 text-xs font-medium text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors disabled:opacity-50 self-stretch shrink-0",children:[o.isPending?r(Pe,{className:"h-3.5 w-3.5 animate-spin"}):r(pt,{className:"h-3.5 w-3.5"}),r("span",{className:"hidden sm:inline",children:"Discover"})]})]}),u("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 text-[11px] text-foreground-subtle border-t border-border-subtle pt-2",children:[r(es,{icon:r(jn,{className:"h-3 w-3 text-emerald-500"}),label:`${s.online} online`}),r(es,{icon:r(dy,{className:"h-3 w-3 text-amber-500"}),label:`${s.sleeping} sleeping`}),r(es,{icon:r(vy,{className:"h-3 w-3 text-destructive"}),label:`${s.offline} offline`}),s.unknown>0?r(es,{icon:r(ND,{className:"h-3 w-3 text-foreground-subtle"}),label:`${s.unknown} unknown`}):null]})]})}function JO(e){const t={total:e.length,adopted:0,available:0,online:0,sleeping:0,offline:0,unknown:0};for(const n of e)n.alreadyAdopted?t.adopted+=1:t.available+=1,t[n.status]+=1;return t}function Ni({label:e,value:t,icon:n,accent:o}){return u("div",{className:`flex flex-1 basis-[140px] min-w-0 flex-col gap-1 rounded-lg border px-2 py-1.5 sm:px-3 sm:py-2 ${o==="success"?"bg-emerald-500/10 border-emerald-500/30 text-emerald-500":o==="primary"?"bg-primary/10 border-primary/30 text-primary":"bg-surface-hover border-border text-foreground"}`,children:[u("div",{className:"flex items-center gap-1.5 text-[10px] uppercase tracking-wider opacity-70 truncate",children:[n,r("span",{className:"truncate",children:e})]}),r("div",{className:"text-xl sm:text-2xl font-semibold tabular-nums leading-none",children:t})]})}function es({icon:e,label:t}){return u("span",{className:"inline-flex items-center gap-1",children:[e,r("span",{children:t})]})}const e8=e=>r(t0,{...e,useSiren:!0}),t8={[at.Switch]:t0,[at.Siren]:e8,[at.Light]:GO,[at.Sensor]:WO,[at.Button]:YO,[at.Hub]:XO};function n8(e){const t=t8[e.deviceType]??ZO;return r(t,{...e})}function ed(e){if(e<60)return`${Math.round(e)}s`;const t=Math.floor(e/60),n=Math.round(e%60);if(t<60)return n>0?`${t}m ${n}s`:`${t}m`;const o=Math.floor(t/60),s=t%60;return s>0?`${o}h ${s}m`:`${o}h`}function Rs(e){return new Date(e).toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit",second:"2-digit"})}function Os(e){return e.toISOString().slice(0,10)}function r8(e,t){return Os(e)===Os(t)}function Ur(e){const t=new Date(e);return t.setHours(0,0,0,0),t}function o8(e){const t=new Date(e);return t.setHours(23,59,59,999),t}function At({className:e=""}){return r("div",{className:`animate-pulse rounded bg-foreground-subtle/10 ${e}`})}function Dn(){return u("div",{className:"flex items-center gap-3 px-4 py-3",children:[r(At,{className:"h-4 w-4"}),r(At,{className:"h-3 w-24"}),r(At,{className:"h-3 w-16 ml-auto"})]})}function jr({children:e,actions:t}){return u("div",{className:"border-b border-border px-4 py-2.5 flex items-center justify-between",children:[r("h2",{className:"text-xs font-semibold text-foreground uppercase tracking-wider",children:e}),t]})}function gp({icon:e,label:t,value:n}){return u("div",{className:"flex items-center gap-2",children:[r(e,{className:"h-3.5 w-3.5 text-foreground-subtle flex-shrink-0"}),u("div",{className:"min-w-0",children:[r("p",{className:"text-[10px] text-foreground-subtle leading-tight",children:t}),r("p",{className:"text-xs font-medium text-foreground leading-tight",children:n})]})]})}function s8({segments:e,selectedDate:t}){const n=Ur(t).getTime(),o=1440*60*1e3,s=Array.from({length:25},(a,i)=>i);return u("div",{className:"space-y-1",children:[r("div",{className:"flex justify-between px-0.5",children:s.filter(a=>a%3===0).map(a=>r("span",{className:"text-[9px] text-foreground-subtle font-mono",children:String(a).padStart(2,"0")},a))}),u("div",{className:"relative h-6 rounded bg-background border border-border overflow-hidden",children:[e.map(a=>{const i=new Date(a.startTime).getTime()-n,l=new Date(a.endTime).getTime()-n,c=Math.max(0,i/o*100),d=Math.min(100-c,(l-i)/o*100);return d<=0?null:r("div",{className:"absolute top-0 bottom-0 bg-primary/60 hover:bg-primary/80 transition-colors",style:{left:`${c}%`,width:`${Math.max(d,.3)}%`},title:`${Rs(a.startTime)} - ${Rs(a.endTime)} (${ed(a.duration)})`},a.id)}),s.slice(1,-1).map(a=>r("div",{className:"absolute top-0 bottom-0 w-px bg-border/50",style:{left:`${a/24*100}%`}},a))]})]})}function a8({segment:e,selected:t,onToggle:n,onPlay:o,onDownload:s,onDelete:a}){return u("div",{className:`flex items-center gap-3 px-4 py-2 border-b border-border last:border-b-0 hover:bg-background/50 transition-colors ${t?"bg-primary/5":""}`,children:[r("button",{onClick:n,className:"flex-shrink-0 text-foreground-subtle hover:text-foreground",children:t?r(gy,{className:"h-4 w-4 text-primary"}):r(Eo,{className:"h-4 w-4"})}),u("div",{className:"flex-1 min-w-0",children:[u("p",{className:"text-xs font-mono text-foreground",children:[Rs(e.startTime)," - ",Rs(e.endTime)]}),u("p",{className:"text-[10px] text-foreground-subtle",children:[ed(e.duration),e.sizeBytes!=null&&` · ${Nt(e.sizeBytes)}`]})]}),u("div",{className:"flex items-center gap-1 flex-shrink-0",children:[r("button",{onClick:o,title:"Play",className:"p-1 rounded hover:bg-foreground-subtle/10 text-foreground-subtle hover:text-foreground transition-colors",children:r(va,{className:"h-3.5 w-3.5"})}),r("button",{onClick:s,title:"Download",className:"p-1 rounded hover:bg-foreground-subtle/10 text-foreground-subtle hover:text-foreground transition-colors",children:r(wn,{className:"h-3.5 w-3.5"})}),r("button",{onClick:a,title:"Delete",className:"p-1 rounded hover:bg-danger/10 text-foreground-subtle hover:text-danger transition-colors",children:r(We,{className:"h-3.5 w-3.5"})})]})]})}function i8({deviceId:e}){const t=ke(),[n,o]=$(()=>Ur(new Date)),[s,a]=$(new Set),i=Hb({deviceId:e},{refetchInterval:5e3}),l=Bb({deviceId:e}),c=l.data?.streams[0]?.streamId??"stream0",d=Fb({deviceId:e,streamId:c,startTime:Ur(n).getTime(),endTime:o8(n).getTime()}),f=jb({deviceId:e,streamId:c},{refetchInterval:3e4}),p=Vb({deviceId:e,dataCategory:"recording:main"}),m=q(()=>{t.invalidateQueries({queryKey:["recordingEngine","getPolicyStatus"]}),t.invalidateQueries({queryKey:["recordingEngine","getSegments"]}),t.invalidateQueries({queryKey:["recordingEngine","getStorageUsage"]})},[t]),h=Ob({onSuccess:m}),g={isPending:h.isPending,error:h.error,mutate:()=>{const _=l.data,R=_?{mode:_.mode,streams:_.streams,enabled:!0,preBufferSec:_.preBufferSec,postBufferSec:_.postBufferSec,scheduleRules:_.scheduleRules}:{mode:"continuous",streams:[{streamId:c,mode:"always"}],enabled:!0,preBufferSec:10,postBufferSec:5};h.mutate({deviceId:e,policy:R})}},b=zb({onSuccess:m}),x=i.data??void 0,v=l.data??void 0,w=d.data??[],y=f.data,N=p.data??void 0,k=(x?.enabled??!1)&&(x?.activeStreams??0)>0,S=g.isPending||b.isPending,M=r8(n,new Date),P=Q(()=>[...w].sort((_,R)=>new Date(R.startTime).getTime()-new Date(_.startTime).getTime()),[w]),I=Q(()=>w.reduce((_,R)=>_+(R.duration??0),0),[w]),F=Q(()=>w.reduce((_,R)=>_+(R.sizeBytes??0),0),[w]);function E(){k?b.mutate({deviceId:e}):g.mutate()}function B(){o(_=>{const R=new Date(_);return R.setDate(R.getDate()-1),Ur(R)}),a(new Set)}function O(){M||(o(_=>{const R=new Date(_);return R.setDate(R.getDate()+1),Ur(R)}),a(new Set))}function A(_){a(R=>{const L=new Set(R);return L.has(_)?L.delete(_):L.add(_),L})}function D(){s.size===P.length?a(new Set):a(new Set(P.map(_=>_.id)))}return i.isLoading&&l.isLoading?u("div",{className:"space-y-4",children:[u("div",{className:"rounded-lg border border-border bg-surface overflow-hidden",children:[r(jr,{children:"Recording Status"}),u("div",{className:"px-4 py-4 space-y-3",children:[r(At,{className:"h-10 w-full"}),r(At,{className:"h-4 w-48"})]})]}),u("div",{className:"rounded-lg border border-border bg-surface overflow-hidden",children:[r(jr,{children:"Segments"}),u("div",{className:"divide-y divide-border",children:[r(Dn,{}),r(Dn,{}),r(Dn,{})]})]})]}):u("div",{className:"space-y-4",children:[u("div",{className:"rounded-lg border border-border bg-surface overflow-hidden",children:[r(jr,{children:"Recording Status"}),u("div",{className:"px-4 py-4 flex items-center justify-between gap-4",children:[u("div",{className:"flex items-center gap-3 min-w-0",children:[r("div",{className:`flex items-center justify-center rounded-full p-2 flex-shrink-0 ${k?"bg-danger/10":"bg-foreground-subtle/10"}`,children:r(ty,{className:`h-5 w-5 ${k?"text-danger animate-pulse":"text-foreground-subtle"}`})}),u("div",{className:"min-w-0",children:[r("p",{className:`text-sm font-medium ${k?"text-danger":"text-foreground-subtle"}`,children:k?"Recording":"Not Recording"}),r("p",{className:"text-[11px] text-foreground-subtle mt-0.5 truncate",children:k&&x?`${x.mode} – ${x.activeStreams} stream(s)`:"No active recording session"})]})]}),r("button",{onClick:E,disabled:S,className:`inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-medium transition-colors flex-shrink-0 disabled:opacity-50 ${k?"bg-danger/10 text-danger hover:bg-danger/20":"bg-primary text-primary-foreground hover:bg-primary/90"}`,children:k?u(ve,{children:[r(Eo,{className:"h-3.5 w-3.5"}),S?"Stopping...":"Stop Recording"]}):u(ve,{children:[r(va,{className:"h-3.5 w-3.5"}),S?"Starting...":"Start Recording"]})})]}),k&&x&&u("div",{className:"border-t border-border px-4 py-2 flex items-center gap-2 text-[11px] text-foreground-subtle",children:[r(Zr,{className:"h-3.5 w-3.5 text-primary flex-shrink-0"}),u("span",{children:[x.activeStreams," active stream",x.activeStreams!==1?"s":""," · mode: ",x.mode]})]})]}),u("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[u("div",{className:"rounded-lg border border-border bg-surface overflow-hidden",children:[r(jr,{children:u("span",{className:"flex items-center gap-1.5",children:[r(wt,{className:"h-3.5 w-3.5"}),"Settings"]})}),l.isLoading?u("div",{className:"px-4 py-3 space-y-2",children:[r(At,{className:"h-3 w-32"}),r(At,{className:"h-3 w-40"}),r(At,{className:"h-3 w-28"})]}):u("div",{className:"divide-y divide-border",children:[r(Hr,{label:"Stream",value:c}),r(Hr,{label:"Pre-buffer",value:v?`${v.preBufferSec}s`:"N/A"}),r(Hr,{label:"Mode",value:v?.mode??"continuous"}),r(Hr,{label:"Retention",value:N?.retentionDays!=null?`${N.retentionDays} days`:"N/A"}),N?.retentionGb!=null&&r(Hr,{label:"Max Storage",value:`${N.retentionGb} GB`})]})]}),u("div",{className:"rounded-lg border border-border bg-surface overflow-hidden",children:[r(jr,{children:u("span",{className:"flex items-center gap-1.5",children:[r(lo,{className:"h-3.5 w-3.5"}),"Storage"]})}),f.isLoading?u("div",{className:"px-4 py-3 space-y-2",children:[r(At,{className:"h-3 w-28"}),r(At,{className:"h-3 w-36"}),r(At,{className:"h-3 w-24"})]}):f.error?u("div",{className:"px-4 py-4 flex items-center gap-2 text-xs text-danger",children:[r(xt,{className:"h-4 w-4"}),"Failed to load storage info"]}):u("div",{className:"px-4 py-3 grid grid-cols-2 gap-3",children:[r(gp,{icon:lo,label:"Total",value:y?.totalBytes!=null?Nt(y.totalBytes):"N/A"}),r(gp,{icon:Zr,label:"Segments",value:y?.segmentCount!=null?String(y.segmentCount):"N/A"})]})]})]}),u("div",{className:"rounded-lg border border-border bg-surface overflow-hidden",children:[u("div",{className:"border-b border-border px-4 py-2.5 flex items-center justify-between",children:[r("h2",{className:"text-xs font-semibold text-foreground uppercase tracking-wider",children:"Segment Browser"}),u("div",{className:"flex items-center gap-2",children:[r("button",{onClick:B,className:"p-1 rounded hover:bg-foreground-subtle/10 text-foreground-subtle hover:text-foreground transition-colors",children:r(Kc,{className:"h-4 w-4"})}),u("div",{className:"flex items-center gap-1.5 text-xs text-foreground font-medium",children:[r(Xx,{className:"h-3.5 w-3.5 text-foreground-subtle"}),M?"Today":Os(n)]}),r("button",{onClick:O,disabled:M,className:"p-1 rounded hover:bg-foreground-subtle/10 text-foreground-subtle hover:text-foreground transition-colors disabled:opacity-30 disabled:cursor-not-allowed",children:r(Mt,{className:"h-4 w-4"})})]})]}),u("div",{className:"px-4 py-3 border-b border-border",children:[r(s8,{segments:w,selectedDate:n}),u("div",{className:"flex items-center gap-4 mt-2 text-[10px] text-foreground-subtle",children:[u("span",{children:[w.length," segment",w.length!==1?"s":""]}),I>0&&u("span",{children:[ed(I)," recorded"]}),F>0&&r("span",{children:Nt(F)})]})]}),P.length>0&&u("div",{className:"border-b border-border px-4 py-2 flex items-center justify-between",children:[r("button",{onClick:D,className:"text-[11px] text-foreground-subtle hover:text-foreground transition-colors",children:s.size===P.length?"Deselect All":"Select All"}),s.size>0&&u("div",{className:"flex items-center gap-2",children:[u("span",{className:"text-[10px] text-foreground-subtle",children:[s.size," selected"]}),u("button",{className:"inline-flex items-center gap-1 rounded px-2 py-0.5 text-[10px] font-medium bg-foreground-subtle/10 text-foreground-subtle hover:text-foreground transition-colors",title:"Download selected",children:[r(wn,{className:"h-3 w-3"}),"Download"]}),u("button",{className:"inline-flex items-center gap-1 rounded px-2 py-0.5 text-[10px] font-medium bg-danger/10 text-danger hover:bg-danger/20 transition-colors",title:"Delete selected",children:[r(We,{className:"h-3 w-3"}),"Delete"]})]})]}),d.isLoading?u("div",{className:"divide-y divide-border",children:[r(Dn,{}),r(Dn,{}),r(Dn,{}),r(Dn,{})]}):P.length===0?u("div",{className:"flex flex-col items-center justify-center py-12 text-foreground-subtle",children:[r(Zr,{className:"h-8 w-8 mb-3 opacity-30"}),r("p",{className:"text-sm",children:"No recorded segments"}),r("p",{className:"text-xs mt-1 opacity-70",children:M?"Recorded clips will appear here as they are created":`No recordings found for ${Os(n)}`})]}):r("div",{className:"max-h-[400px] overflow-y-auto",children:P.map(_=>r(a8,{segment:_,selected:s.has(_.id),onToggle:()=>A(_.id),onPlay:()=>{},onDownload:()=>{},onDelete:()=>{}},_.id))})]}),i.error&&u("div",{className:"rounded-lg border border-danger/30 bg-danger/5 px-4 py-3 flex items-center gap-2 text-xs text-danger",children:[r(xt,{className:"h-4 w-4 flex-shrink-0"}),"Failed to load recording status. Will retry automatically."]}),(g.error||b.error)&&u("div",{className:"rounded-lg border border-danger/30 bg-danger/5 px-4 py-3 flex items-center gap-2 text-xs text-danger",children:[r(xt,{className:"h-4 w-4 flex-shrink-0"}),g.error?`Failed to start recording: ${g.error instanceof Error?g.error.message:"Unknown error"}`:`Failed to stop recording: ${b.error instanceof Error?b.error.message:"Unknown error"}`]})]})}function Hr({label:e,value:t}){return u("div",{className:"flex items-center justify-between px-4 py-2.5",children:[r("span",{className:"text-xs text-foreground-subtle",children:e}),r("span",{className:"text-xs font-medium text-foreground",children:t})]})}function l8({deviceId:e}){const t=ke(),n=Number.isFinite(e),{data:o}=Fn({deviceId:e},{enabled:n}),s=typeof o?.type=="string"?o.type:"camera";yt(["deviceManager","getBindings"],["capability.binding-changed"]);const{data:a,isLoading:i,isError:l,error:c}=Cg({deviceId:e},{staleTime:3e4,enabled:n}),{data:d}=Ig({deviceType:s},{staleTime:3e4,enabled:!!s}),f=Mg({onSuccess:()=>{t.invalidateQueries({queryKey:[["deviceManager","getBindings"]]})}});if(i)return r("div",{className:"p-4",children:r("div",{className:"h-20 rounded-lg border border-border bg-surface animate-pulse"})});if(l)return u("div",{className:"p-4 text-xs text-red-400",children:["Failed to load bindings: ",c instanceof Error?c.message:String(c)]});const p=new Map,m={};for(const b of d??[])m[b.capName]=b.wrappers;for(const b of a?.entries??[])p.set(b.capName,{...b,wrappers:m[b.capName]??[]});for(const b of d??[])p.has(b.capName)||p.set(b.capName,{capName:b.capName,kind:"unbound",providerAddonId:"",providerNodeId:"",nativeAddonId:"",wrappers:b.wrappers});const h=[...p.values()].sort((b,x)=>b.capName.localeCompare(x.capName));if(h.length===0)return u("div",{className:"flex flex-col items-center justify-center gap-2 p-8 text-foreground-subtle",children:[r(ba,{className:"h-8 w-8 opacity-40"}),r("p",{className:"text-xs",children:"No capability providers applicable to this device yet."}),r("p",{className:"text-[10px] opacity-60",children:"Native providers show up here as soon as the owning addon registers them."})]});const g=h.filter(b=>b.kind!=="unbound").length;return u("div",{className:"flex flex-col gap-3 p-1",children:[u("div",{className:"text-[11px] text-foreground-subtle",children:[r("span",{className:"font-medium text-foreground",children:g})," ","of ",h.length," capabilit",h.length===1?"y":"ies"," bound — rows marked ",r("em",{children:"unbound"})," have a wrapper available you can activate."]}),r("div",{className:"overflow-hidden rounded-lg border border-border bg-surface",children:u("table",{className:"w-full border-collapse text-[11px]",children:[r("thead",{children:u("tr",{className:"bg-surface-hover/50 text-left text-[10px] uppercase tracking-wide text-foreground-subtle",children:[r("th",{className:"px-3 py-2 font-medium",children:"Capability"}),r("th",{className:"px-3 py-2 font-medium",children:"Kind"}),r("th",{className:"px-3 py-2 font-medium",children:"Active Provider"}),r("th",{className:"px-3 py-2 font-medium",children:"Node"}),r("th",{className:"px-3 py-2 font-medium",children:"Native"}),r("th",{className:"px-3 py-2 font-medium",children:"Wrapper"})]})}),r("tbody",{children:h.map(b=>{const x=b.kind==="wrapped"?b.providerAddonId:null;return u("tr",{className:"border-t border-border align-middle",children:[r("td",{className:"px-3 py-2 font-mono text-foreground",children:b.capName}),r("td",{className:"px-3 py-2",children:r(c8,{kind:b.kind})}),r("td",{className:"px-3 py-2 font-mono text-foreground-subtle",children:b.providerAddonId||r("span",{className:"opacity-40",children:"—"})}),r("td",{className:"px-3 py-2",children:b.providerNodeId?r(d8,{nodeId:b.providerNodeId}):r("span",{className:"text-[10px] opacity-40",children:"—"})}),r("td",{className:"px-3 py-2 font-mono text-foreground-subtle",children:b.nativeAddonId||r("span",{className:"opacity-40",children:"—"})}),r("td",{className:"px-3 py-2",children:r(u8,{wrappers:b.wrappers,activeWrapperId:x,disabled:f.isPending,onPick:v=>{const w=x===v;f.mutate({deviceId:e,capName:b.capName,wrapperAddonId:v,active:!w})}})})]},b.capName)})})]})})]})}function c8({kind:e}){return e==="native"?u("span",{className:"inline-flex items-center gap-1 rounded-md border border-success/30 text-success bg-success/5 px-1.5 py-0.5 text-[10px] font-medium",children:[r(ln,{className:"h-3 w-3"}),"native"]}):e==="wrapped"?u("span",{className:"inline-flex items-center gap-1 rounded-md border border-primary/30 text-primary bg-primary/5 px-1.5 py-0.5 text-[10px] font-medium",children:[r(eL,{className:"h-3 w-3"}),"wrapped"]}):u("span",{className:"inline-flex items-center gap-1 rounded-md border border-border text-foreground-subtle/70 px-1.5 py-0.5 text-[10px] font-medium",children:[r(gL,{className:"h-3 w-3"}),"unbound"]})}function d8({nodeId:e}){return r("span",{className:`inline-flex items-center rounded-md border border-border px-1.5 py-0.5 font-mono text-[10px] ${e==="hub"?"text-foreground-subtle":"text-foreground"}`,children:e})}function u8({wrappers:e,activeWrapperId:t,disabled:n,onPick:o}){return e.length===0?r("span",{className:"text-[10px] opacity-40",children:"none available"}):r("div",{className:"flex flex-wrap gap-1",children:e.map(s=>{const a=s===t;return u("button",{disabled:n,onClick:()=>o(s),title:a?"Click to deactivate (revert to native)":`Activate wrapper ${s}`,className:`inline-flex items-center gap-1 rounded-md border px-1.5 py-0.5 font-mono text-[10px] transition-colors disabled:opacity-50 ${a?"border-primary/40 bg-primary/10 text-primary":"border-border text-foreground-subtle hover:text-foreground hover:bg-surface-hover"}`,children:[a?r(Ct,{className:"h-3 w-3"}):r(my,{className:"h-3 w-3"}),s]},s)})})}function p8(e,t){if(!e)return null;for(const n of e.slots)for(const o of n.addons)if(o.id===t)return o;return null}function f8(e,t,n){const o=e?.stepOverridesByAgent?.[t]?.[n];if(o)return o.enabled===!1?"off":(o.enabled===!0,"on");const s=e?.stepToggles?.[n];return s===!1?"off":s===!0?"on":"inherit"}function m8({agents:e,currentAgent:t,onPick:n}){const[o,s]=$(!1);return u("div",{className:"relative",children:[r("button",{type:"button",className:"px-3 py-1 text-xs border border-border rounded bg-surface hover:bg-muted",onClick:()=>s(a=>!a),children:"Mirror from ▾"}),o&&r("div",{className:"absolute top-full left-0 mt-1 min-w-[140px] bg-surface border border-border rounded shadow-lg z-10",children:e.filter(a=>a!==t).map(a=>r("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-muted",onClick:()=>{s(!1),n(a)},children:a},a))})]})}function h8({deviceId:e,refreshToken:t}){const n=ke(),[o,s]=$(null),[a,i]=$(null),[l,c]=$(null),[d,f]=$(null),p=vc({deviceId:e}),m=$r(),h=ca({deviceId:e}),g=mb(),b=Q(()=>{const D=h.data?.agentNodeId;if(D)return D;const _=g.data?.find(R=>R.online)?.nodeId;return _||"hub"},[h.data?.agentNodeId,g.data]),x=a??b,v=So({nodeId:x??""},{enabled:!!x}),w=Mb({onSuccess:()=>{n.invalidateQueries({queryKey:[["pipelineOrchestrator","getCameraSettings"]]}),c(null)}}),y=Q(()=>v.data?ta(v.data):[],[v.data]),N=Q(()=>{const D=p.data??null,_={};for(const R of m.data??[])for(const L of Object.keys(R.settings.addonDefaults)){const z=_[L]??[];z.push({agentNodeId:R.nodeId,state:f8(D,R.nodeId,L)}),_[L]=z}return _},[p.data,m.data]),k=o?p8(v.data??null,o):null,S=x?m.data?.find(D=>D.nodeId===x)??null:null,M=o&&S?S.settings.addonDefaults[o]??null:null,P=o&&x?p.data?.stepOverridesByAgent?.[x]?.[o]??null:null,I=v.data?.selectedEngine.format??"coreml",F=D=>{i(D),c(null),f(null)},E=D=>{s(D),c(null),f(null)},B=D=>{if(!x||!o||!v.data||!m.data)return;const _=m.data.find(z=>z.nodeId===D),R=m.data.find(z=>z.nodeId===x);if(!_||!R)return;const[L]=bm({source:{nodeId:_.nodeId,engine:{format:I},defaults:_.settings.addonDefaults},target:{nodeId:R.nodeId,engine:{format:I},defaults:R.settings.addonDefaults},catalog:v.data,addonIds:[o]});if(!L){f("no mirror result");return}if(L.outcome==="skip"){f(`skipped: ${L.reason??"no candidate"}`);return}c(L.patch),f(`${L.outcome} from ${D}`)},O=()=>{!x||!o||w.mutate({deviceId:e,agentNodeId:x,addonId:o,patch:l})},A=()=>{!x||!o||w.mutate({deviceId:e,agentNodeId:x,addonId:o,patch:null})};return m.isLoading||v.isLoading?r("div",{className:"text-xs text-foreground-subtle animate-pulse p-4",children:"Loading pipeline…"}):v.data?r("div",{className:"@container h-full",style:{containerType:"inline-size"},children:u("div",{className:"flex flex-col @[720px]:flex-row h-full",children:[r("aside",{className:"w-full @[720px]:w-[300px] @[720px]:flex-shrink-0 border-b @[720px]:border-b-0 @[720px]:border-r border-border overflow-y-auto max-h-[40vh] @[720px]:max-h-none",children:r(fh,{tree:y,selectedAddonId:o,onSelect:E,agentDots:N})}),r("section",{className:"flex-1 min-w-0 p-4 overflow-y-auto",children:!o||!k?r("div",{className:"text-sm text-foreground-subtle",children:"Select a step on the left to configure it for this camera."}):u("div",{className:"space-y-4",children:[u("div",{children:[r("div",{className:"text-[10px] uppercase tracking-widest text-foreground-subtle",children:"Selected step"}),r("div",{className:"text-base font-semibold",children:k.name})]}),u("div",{className:"flex items-end gap-3 flex-wrap",children:[u("div",{children:[r("div",{className:"text-[10px] uppercase tracking-widest text-foreground-subtle mb-1",children:"Agent"}),r("div",{className:"flex rounded border border-border overflow-hidden",children:(m.data??[]).map(D=>r("button",{type:"button",onClick:()=>F(D.nodeId),className:`px-3 py-1 text-xs ${x===D.nodeId?"bg-primary text-primary-foreground":"bg-surface hover:bg-muted"}`,children:D.nodeId},D.nodeId))})]}),r(m8,{agents:(m.data??[]).map(D=>D.nodeId),currentAgent:x,onPick:B}),d&&r("div",{className:"text-[10px] text-foreground-subtle",children:d})]}),M&&r(ra,{mode:"device",addon:k,agentDefault:M,agentNodeId:x??"",currentPatch:l??P,engineFormat:I,onChangePatch:c}),u("div",{className:"flex items-center justify-between gap-2 pt-4 border-t border-border",children:[r("button",{type:"button",className:"px-3 py-1 text-xs border border-border rounded bg-surface hover:bg-muted text-foreground-subtle",disabled:!P||w.isPending,onClick:A,children:"Clear override"}),u("div",{className:"flex items-center gap-2",children:[r("button",{type:"button",className:"px-3 py-1 text-xs border border-border rounded bg-surface hover:bg-muted",onClick:()=>c(null),children:"Reset draft"}),r("button",{type:"button",className:"px-3 py-1 text-xs bg-primary text-primary-foreground rounded disabled:opacity-50",disabled:!x||!o||w.isPending,onClick:O,children:w.isPending?"Saving…":"Save"})]})]})]})})]})}):r("div",{className:"text-xs text-foreground-subtle p-4",children:"Catalog unavailable."})}const g8=[{id:"overview",label:"Overview",cameraOnly:!1},{id:"config",label:"Config",cameraOnly:!1},{id:"pipeline",label:"Pipeline",cameraOnly:!0},{id:"bindings",label:"Bindings",cameraOnly:!0},{id:"recording",label:"Recording",cameraOnly:!0}];function b8(e){const t=e===at.Camera;return g8.filter(n=>t||!n.cameraOnly).map(({id:n,label:o})=>({id:n,label:o}))}const x8=[{id:"logs",icon:Xe,label:"Logs"},{id:"repl",icon:by,label:"REPL"},{id:"events",icon:Ao,label:"Events"},{id:"state",icon:ny,label:"State"},{id:"ptz",icon:wL,label:"PTZ",featureGate:Rn.PanTiltZoom}];function y8(){const e=zc(),t=Number(e.deviceId),n=Number.isFinite(t),o=et(),s=ke(),a=rt(),i=Le(),[l,c]=$("overview"),[d,f]=$("logs"),p="device-detail.left-col-width-px",[m,h]=$(()=>{if(typeof window>"u")return null;const de=window.localStorage.getItem(p),le=de?Number(de):NaN;return Number.isFinite(le)&&le>0?le:null}),g=ne(m);g.current=m;function b(de){de.preventDefault();const le=de.clientX,Se=de.currentTarget.previousElementSibling?.getBoundingClientRect().width??m??0,pe=280,Ie=Math.max(pe+50,Math.floor(window.innerWidth*.7)),Te=ot=>{const rr=Math.max(pe,Math.min(Ie,Se+(ot.clientX-le)));h(rr)},Ye=()=>{document.removeEventListener("mousemove",Te),document.removeEventListener("mouseup",Ye);const ot=g.current;if(ot!==null)try{window.localStorage.setItem(p,String(Math.round(ot)))}catch{}document.body.style.userSelect="",document.body.style.cursor=""};document.body.style.userSelect="none",document.body.style.cursor="col-resize",document.addEventListener("mousemove",Te),document.addEventListener("mouseup",Ye)}const{data:x,isLoading:v,isError:w}=Fn({deviceId:t},{enabled:n,refetchInterval:5e3,retry:1}),{data:y}=mc({deviceId:t},{enabled:n,staleTime:3e4}),N=Q(()=>{const de=y?.settings?.sections??[],le=y?.live?.sections??[],Se=[...de,...le],pe=new Set;for(const Ie of Se)Ie.location==="top-tab"&&Ie.tab&&pe.add(Ie.tab);return[...pe].map(Ie=>{const Te=_i[Ie];return{id:Ie,label:Te?.label??Ie,isAddonContrib:!0}})},[y]),k=x,S=String(k?.name??e.deviceId??"Device"),M=k?.online===!0,P=M?"online":"offline",I=String(k?.addonId??"rtsp"),F=k?.features??[],E=k?.type,B=E===at.Camera,O=typeof k?.parentDeviceId=="number"?k.parentDeviceId:null,{data:A}=Fn({deviceId:O??0},{enabled:O!==null,staleTime:3e4}),D=Xn(),_=Q(()=>[...b8(E),...N],[E,N]),{data:R}=Fy(n?t:0),L=(R??[]).length>0,z=Q(()=>x8.filter(({featureGate:de})=>!de||F.includes(de)),[F]),{data:j}=Dg({addonId:I},{enabled:!!I&&I!=="rtsp"}),H=Sg({onSuccess:()=>{s.invalidateQueries({queryKey:[["deviceManager"]]}),o(j?.id?`/integrations/${j.id}`:"/integrations")}}),T=Ng({onSuccess:()=>{s.invalidateQueries({queryKey:[["deviceManager"]]})}}),W=kg({onSuccess:()=>{s.invalidateQueries({queryKey:[["deviceManager"]]})}}),G=Rb(),ee=sa({onSuccess:()=>{s.invalidateQueries({queryKey:[["deviceManager"]]})}}),se=F.includes(Rn.Rebootable),te=F.includes(Rn.BatteryOperated),X=tc(i.trpcClient,te&&n?t:null),[re,ge]=$(!1),Z=kt(i.trpcClient,n?t:null),U=async()=>{if(!(re||!Z)){ge(!0);try{await Z.snapshot?.invalidateCache({});const de=await Z.snapshot?.getSnapshot({});if(!de)return;const le=`data:${de.contentType};base64,${de.base64}`,Se=de.contentType.includes("png")?"png":"jpg",pe=S.replace(/[^a-zA-Z0-9_.-]+/g,"_"),Ie=new Date().toISOString().replace(/[:.]/g,"-"),Te=document.createElement("a");Te.href=le,Te.download=`${pe}-${Ie}.${Se}`,document.body.appendChild(Te),Te.click(),document.body.removeChild(Te)}finally{ge(!1)}}},J=T.isPending||W.isPending,{data:ae}=ca({deviceId:t},{enabled:n,refetchInterval:1e4}),fe=ae?.agentNodeId??null,V=typeof fe=="string"&&fe.length>0&&!fe.startsWith("addon:")?fe:void 0,{data:ie}=wc({deviceId:t,...V?{nodeId:V}:{}},{enabled:n,refetchInterval:3e3,retry:!1});function ue(){if(!n)return null;switch(l){case"overview":return r(zO,{device:k??{}});case"config":return r(UO,{deviceId:t});case"pipeline":return r(h8,{deviceId:t,refreshToken:0});case"bindings":return r(l8,{deviceId:t});case"recording":return r(i8,{deviceId:t});default:{const de=l;return N.some(Se=>Se.id===de)?r(Xy,{deviceId:t,sectionFilter:Se=>Se.location==="top-tab"&&Se.tab===de}):null}}}return n?v?u("div",{className:"flex flex-col h-full",children:[u("div",{className:"border-b border-border bg-surface px-6 py-4",children:[r("div",{className:"h-4 w-48 rounded bg-surface-hover animate-pulse mb-3"}),r("div",{className:"h-8 w-64 rounded bg-surface-hover animate-pulse"})]}),r("div",{className:"flex-1 p-6",children:r("div",{className:"h-40 rounded-lg border border-border bg-surface animate-pulse"})})]}):w||!x?u("div",{className:"flex flex-col items-center justify-center h-full gap-3 text-foreground-subtle",children:[r("p",{className:"text-lg font-semibold text-foreground",children:"Device not found"}),u("p",{className:"text-xs",children:["No device with ID ",u("code",{className:"font-mono bg-surface px-1.5 py-0.5 rounded text-[11px]",children:["#",t]})]}),r("button",{onClick:()=>o("/integrations"),className:"mt-2 rounded-lg bg-primary px-4 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90 transition-colors",children:"Back to Integrations"})]}):u("div",{className:"absolute inset-0 flex flex-col overflow-hidden",children:[u("div",{className:"border-b border-border bg-surface px-6 py-3 flex-shrink-0",children:[r("div",{className:"mb-2",children:r(Wl,{items:[{label:"Integrations",onClick:()=>o("/integrations")},{label:j?.name??I,onClick:()=>j?.id&&o(`/integrations/${j.id}`)},{label:S}]})}),u("div",{className:"flex items-center gap-2 sm:gap-3",children:[r(cn,{type:I,size:"lg"}),u("div",{className:"min-w-0 flex-1",children:[u("div",{className:"flex items-center gap-2 flex-wrap",children:[r("h1",{className:"text-sm sm:text-base font-semibold text-foreground truncate",children:S}),r(ka,{status:P}),te&&r(rc,{status:X,variant:"full"})]}),O!==null&&A&&u("button",{type:"button",onClick:()=>o(`/devices/${O}`),className:"text-[10px] text-foreground-subtle hover:text-primary transition-colors mt-0.5 inline-flex items-center gap-1",title:`Open parent device ${A.name}`,children:[r("span",{children:"↑"}),r("span",{className:"truncate",children:String(A.name??`Device #${O}`)})]}),r("div",{className:"hidden md:flex items-center gap-3 mt-0.5 text-[10px] text-foreground-subtle",children:F.length>0&&r(wa,{capabilities:F})})]}),ie&&r("div",{className:"hidden lg:flex",children:r(v8,{metrics:ie})}),u("div",{className:"flex items-center gap-1 shrink-0",children:[u("button",{onClick:async()=>{await a({title:`Disable "${S}"?`,message:"The device will stop processing streams and events. You can re-enable it later.",confirmLabel:"Disable",variant:"danger"})&&W.mutate({deviceId:t})},disabled:J,title:"Disable device",className:"inline-flex items-center gap-1.5 rounded-lg px-2 sm:px-2.5 py-1.5 text-[11px] font-medium border transition-colors disabled:opacity-50 border-success/30 text-success hover:bg-success/10",children:[r(fy,{className:"h-3.5 w-3.5"}),r("span",{className:"hidden sm:inline",children:J?"Updating…":"Enabled"})]}),r("div",{className:"hidden sm:block h-5 w-px bg-border mx-1"}),r(Ix,{triggerClassName:"ml-1",items:[{id:"snapshot",label:"Take snapshot",description:"Fetch a fresh frame and download it.",icon:gr,disabled:re,onClick:()=>{U()}},{id:"reboot",label:"Reboot device",description:"Camera goes offline for ~30 seconds.",icon:bt,hidden:!se,disabled:G.isPending,danger:!0,onClick:async()=>{await a({title:`Reboot "${S}"?`,message:"The camera will go offline for around 30 seconds while the firmware reboots.",confirmLabel:"Reboot",variant:"danger"})&&G.mutate({deviceId:t})}},{id:"restart-addon",label:"Restart addon",description:`Bounces every device served by ${j?.name??I}.`,icon:pt,disabled:ee.isPending,danger:!0,onClick:async()=>{await a({title:`Restart "${j?.name??I}"?`,message:`Restarting the addon will briefly disconnect every device served by it (not just "${S}"). Streams will reconnect automatically.`,confirmLabel:"Restart",variant:"danger"})&&ee.mutate({addonId:I})}},{id:"delete",label:"Delete device",description:"Remove the device and all its settings.",icon:We,separatorBefore:!0,disabled:H.isPending,danger:!0,onClick:async()=>{await a({title:`Delete "${S}"?`,message:"This will remove the device and all its settings. This action cannot be undone.",confirmLabel:"Delete",variant:"danger"})&&H.mutate({deviceId:t})}}]})]})]})]}),r(jh,{deviceId:t,device:k??void 0,children:r(vx,{children:r(Px,{children:u("main",{className:D?"flex-1 overflow-y-auto flex flex-col":"flex-1 min-h-0 overflow-hidden flex flex-row",children:[u("div",{className:D?"flex flex-col bg-surface":`${m===null?"w-1/2 lg:w-1/3":""} flex-shrink-0 flex flex-col bg-surface min-h-0 overflow-hidden`,style:!D&&m!==null?{width:`${String(m)}px`}:void 0,children:[r("div",{className:`flex-shrink-0 border-b border-border-subtle ${B?"aspect-video bg-black":"bg-surface"}`,children:B?r($O,{deviceId:t,intercomAvailable:F.includes(Rn.TwoWayAudio)}):r(n8,{deviceId:t,deviceName:S,deviceType:E??"unknown",provider:I,isOnline:M,features:F})}),u("div",{className:D?"flex flex-col border-b border-border":"flex-1 min-h-0 flex flex-col overflow-hidden",children:[r("div",{className:"flex-shrink-0 border-b border-border-subtle px-2 py-1.5",children:r("div",{className:"flex gap-1 overflow-x-auto -mx-1 px-1 pb-0.5",children:z.map(({id:de,label:le,icon:Se})=>u("button",{onClick:()=>f(de),title:le,className:`flex items-center gap-1 rounded px-2 py-1 text-[10px] font-medium transition-colors flex-shrink-0 ${d===de?"bg-primary/15 text-primary":"text-foreground-subtle hover:text-foreground hover:bg-surface-hover"}`,children:[r(Se,{className:"h-3 w-3"}),le]},de))})}),u("div",{className:D?"h-72 overflow-hidden":"flex-1 min-h-0 overflow-hidden",children:[d==="logs"&&r(_O,{deviceId:t}),d==="repl"&&r(DO,{deviceId:t}),d==="events"&&r(TO,{deviceId:t}),d==="state"&&r(RO,{deviceId:t}),d==="ptz"&&r(LO,{deviceId:t})]})]})]}),!D&&r("div",{role:"separator","aria-orientation":"vertical",title:"Drag to resize",onMouseDown:b,className:"flex-shrink-0 w-1 cursor-col-resize bg-border hover:bg-primary/40 transition-colors group relative z-10",children:r("span",{className:"absolute inset-y-0 -left-1 -right-1"})}),u("div",{className:D?"flex flex-col":"flex-1 min-w-0 min-h-0 flex flex-col overflow-hidden",children:[r("div",{className:"flex-shrink-0 border-b border-border bg-surface px-4",children:r("div",{className:"flex flex-wrap items-center gap-0",children:_.map(de=>{const le=l===de.id;return u("button",{onClick:()=>c(de.id),className:`relative flex-shrink-0 px-3 py-2 text-xs font-medium transition-colors ${le?"text-primary":"text-foreground-subtle hover:text-foreground"}`,children:[de.label,le&&r("span",{className:"absolute bottom-0 left-0 right-0 h-0.5 rounded-full bg-primary"})]},de.id)})})}),u("div",{className:D?"p-3 flex flex-col gap-3":"flex-1 min-h-0 overflow-y-auto p-4 flex flex-col gap-3",children:[l==="overview"&&L&&r(OO,{parentDeviceId:t}),ue()]})]})]})})})})]}):u("div",{className:"flex flex-col items-center justify-center h-full gap-3 text-foreground-subtle",children:[r("p",{className:"text-lg font-semibold text-foreground",children:"Invalid device id"}),u("p",{className:"text-xs",children:["The URL segment ",r("code",{className:"font-mono bg-surface px-1.5 py-0.5 rounded text-[11px]",children:e.deviceId})," is not a number."]}),r("button",{onClick:()=>o("/integrations"),className:"mt-2 rounded-lg bg-primary px-4 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90 transition-colors",children:"Back to Integrations"})]})}function v8({metrics:e}){const t=e.phase??"idle",n=Wn(t);return u("div",{className:"flex items-center gap-3 flex-shrink-0",children:[u("div",{className:"flex items-center gap-1.5",children:[r("span",{className:`h-1.5 w-1.5 rounded-full ${n.dotClass}`}),r("span",{className:`text-[10px] font-medium ${n.textColor}`,children:n.label})]}),r("div",{className:"h-3 w-px bg-border"}),u("div",{className:"flex items-center gap-1 text-[10px] text-foreground-subtle",children:[r(Io,{className:"h-3 w-3"}),r("span",{className:"text-foreground tabular-nums",children:(e.actualFps??0).toFixed(1)}),r("span",{children:"fps"})]}),u("div",{className:"flex items-center gap-1 text-[10px] text-foreground-subtle",children:[r(ut,{className:"h-3 w-3"}),r("span",{className:"text-foreground tabular-nums",children:(e.avgInferenceTimeMs??0).toFixed(0)}),r("span",{children:"ms"})]}),(e.queueDepth??0)>0&&u("span",{className:"text-[10px] text-warning tabular-nums",children:["q:",e.queueDepth]})]})}function w8({packageName:e,currentVersion:t,onInstall:n,onClose:o}){const{data:s,isLoading:a}=Kh({name:e},{staleTime:3e5});return u("div",{className:"fixed z-50 w-72 rounded-lg border border-border bg-surface shadow-xl overflow-hidden",style:{top:"auto",bottom:"auto"},ref:i=>{if(!i)return;const l=i.parentElement?.getBoundingClientRect();if(!l)return;const c=window.innerHeight-l.bottom,d=l.top;c<280&&d>c?(i.style.bottom=`${window.innerHeight-l.top+4}px`,i.style.top="auto"):(i.style.top=`${l.bottom+4}px`,i.style.bottom="auto"),i.style.right=`${window.innerWidth-l.right}px`},onClick:i=>i.stopPropagation(),children:[u("div",{className:"flex items-center justify-between px-3 py-2 border-b border-border",children:[r("span",{className:"text-[10px] uppercase tracking-wide text-foreground-subtle font-medium",children:"Versions"}),r("button",{type:"button",onClick:o,className:"text-foreground-subtle hover:text-foreground",children:r(qe,{className:"h-3 w-3"})})]}),a&&u("div",{className:"flex items-center justify-center gap-2 py-6 text-[10px] text-foreground-subtle",children:[r(Pe,{className:"h-3.5 w-3.5 animate-spin"}),"Loading versions..."]}),s&&r("div",{className:"max-h-64 overflow-auto divide-y divide-border",children:s.map(i=>{const l=i.version===t,c=/-(alpha|beta|rc|dev|canary|next)/i.test(i.version);return u("div",{className:`flex items-center gap-2 px-3 py-2 text-[11px] ${l?"bg-primary/5":"hover:bg-surface-hover"} transition-colors`,children:[r("span",{className:`font-mono flex-1 ${l?"text-primary font-semibold":c?"text-amber-400":"text-foreground"}`,children:i.version}),i.distTags.map(d=>r("span",{className:`text-[9px] rounded-full px-1.5 py-0.5 font-medium ${d==="latest"?"bg-emerald-500/15 text-emerald-400":d==="beta"?"bg-amber-500/15 text-amber-400":"bg-gray-500/15 text-gray-400"}`,children:d},d)),i.deprecated&&r("span",{className:"text-[9px] text-red-400 line-through",children:"deprecated"}),r("span",{className:"text-[9px] text-foreground-subtle shrink-0",children:new Date(i.publishedAt).toLocaleDateString()}),l?r(Ct,{className:"h-3 w-3 text-primary shrink-0"}):r("button",{type:"button",onClick:()=>n(i.version),className:"shrink-0 rounded p-0.5 hover:bg-primary/20 text-foreground-subtle hover:text-primary transition-colors",title:`Install ${i.version}`,children:r(wn,{className:"h-3 w-3"})})]},i.version)})}),s&&s.length===0&&r("div",{className:"py-4 text-center text-[10px] text-foreground-subtle",children:"No versions found"})]})}function N8({isBundle:e,installSource:t}){return u("div",{className:"relative flex-shrink-0",children:[r("div",{className:`h-9 w-9 rounded-lg flex items-center justify-center ${e?"bg-indigo-500/20 text-indigo-700 dark:text-indigo-300":"bg-purple-500/20 text-purple-700 dark:text-purple-300"}`,children:e?r(uy,{className:"h-4 w-4"}):r($s,{className:"h-4 w-4"})}),t==="local"&&r("span",{className:"absolute -top-1.5 -left-1.5 text-[7px] font-bold leading-none bg-orange-500 text-white px-1 py-0.5 rounded -rotate-12 shadow-sm",children:"DEV"}),t==="npm"&&r("span",{className:"absolute -top-1 -left-1 w-4 h-4 rounded bg-[#cb3837] flex items-center justify-center -rotate-12 shadow-sm",children:r("svg",{viewBox:"0 0 780 250",className:"w-[11px] h-[11px]",children:r("path",{fill:"#fff",d:"M240 250h100V50h100v200h340V0H0v250z"})})}),t==="upload"&&r("span",{className:"absolute -top-1.5 -left-1.5 flex items-center justify-center h-4 w-4 rounded bg-cyan-500 -rotate-12 shadow-sm",children:r(Xc,{className:"h-2.5 w-2.5 text-white"})})]})}function k8({addonId:e}){const t=ke(),{data:n="inherit"}=Yh({addonId:e},{staleTime:3e4}),o=Zh({onSuccess:()=>{t.invalidateQueries({queryKey:[["addons","getAddonAutoUpdate"]]})}});return r("div",{className:"flex rounded-lg border border-border overflow-hidden text-[10px] font-medium",children:["inherit","off","latest","beta"].map(s=>r("button",{type:"button",onClick:a=>{a.stopPropagation(),o.mutate({addonId:e,channel:s})},disabled:o.isPending,className:`px-2.5 py-1 transition-colors capitalize ${n===s?s==="inherit"?"bg-gray-700/50 text-gray-700 dark:text-gray-300":s==="off"?"bg-gray-700 text-gray-700 dark:text-gray-300":s==="latest"?"bg-blue-500/20 text-blue-400":"bg-amber-500/20 text-amber-400":"bg-transparent text-foreground-subtle hover:bg-surface-hover"} ${s!=="inherit"?"border-l border-border":""}`,children:s},s))})}function pl({addon:e,agents:t=[],clusterStatus:n,hideVersion:o,availableUpdate:s,onUpdate:a,isUpdating:i,bundle:l}){const[c,d]=$(!1),[f,p]=$(!1),[m,h]=$(!1),[g,b]=$(!1),[x,v]=$(!1),[w,y]=$("logs"),N=ke(),k=rt(),{manifest:S}=e,M=e.installedOn??[],P=!l&&!S.protected&&S.removable!==!1,I=!!l,F=l?.displayName??S.name,E=l?.packageName??S.packageName,B=l?.version??S.packageVersion??S.version,O=l?.installSource??e.installSource,A=l?l.bundle?.description??l.addons[0]?.manifest.description:S.description;!l&&(S.components&&S.components.length>0||t.length>=2);const D=Hh({onSuccess:()=>{N.invalidateQueries({queryKey:[["addons"]]}),N.invalidateQueries({queryKey:[["addonPages"]]}),N.invalidateQueries({queryKey:[["capabilities"]]})}}),_=sa({onSuccess:()=>{N.invalidateQueries({queryKey:[["addons"]]})}}),R=lc({onSuccess:()=>{N.invalidateQueries({queryKey:[["addons"]]}),N.invalidateQueries({queryKey:[["addonPages"]]}),N.invalidateQueries({queryKey:[["capabilities"]]}),N.invalidateQueries({queryKey:[["integrations"]]})}}),L=Gh({onSuccess:()=>{N.invalidateQueries({queryKey:[["addons"]]}),N.invalidateQueries({queryKey:[["alerts"]]})}}),z=e.health,j=z?.phase==="failed"&&!z.inGracePeriod,H=j&&z?.nextRetryAt&&!z.retrying;return u("div",{className:`rounded-lg border bg-surface overflow-hidden ${j?"border-red-500/50":"border-border"}`,children:[j&&z&&u("div",{className:"bg-danger/10 border-b border-danger/30 px-4 py-2.5 flex items-start gap-2.5",children:[r(SL,{className:"h-4 w-4 text-danger shrink-0 mt-0.5"}),u("div",{className:"flex-1 min-w-0",children:[u("div",{className:"text-xs font-semibold text-danger",children:["Failed to load (attempt #",z.retryCount,")"]}),r("div",{className:"text-[11px] text-foreground mt-0.5 break-words font-mono",children:z.lastError?.message??"Unknown error"}),H&&z.nextRetryAt&&u("div",{className:"text-[10px] text-foreground-subtle mt-1",children:["Auto-retry at ",new Date(z.nextRetryAt).toLocaleTimeString()]})]}),u("button",{type:"button",disabled:L.isPending||z.retrying,onClick:T=>{T.stopPropagation(),L.mutate({packageName:E})},className:"inline-flex items-center gap-1.5 rounded-md px-2.5 py-1 text-[11px] font-semibold border border-red-400/40 bg-red-400/10 text-red-700 dark:text-red-300 hover:bg-red-400/20 disabled:opacity-50 disabled:cursor-not-allowed transition-colors shrink-0",title:"Reset retry counter and force immediate reload",children:[r(pt,{className:`h-3 w-3 ${L.isPending||z.retrying?"animate-spin":""}`}),"Retry now"]})]}),u("div",{className:"flex items-start gap-3 px-4 py-3",children:[r(N8,{isBundle:I||!!S.components&&S.components.length>1,installSource:O}),u("div",{className:"flex-1 min-w-0",children:[u("div",{className:"flex items-center gap-2",children:[r("span",{className:"text-sm font-semibold text-foreground truncate",children:F}),u("span",{className:"text-[10px] text-foreground-subtle font-mono shrink-0",children:["(",E,")"]}),I&&u("span",{className:"text-[10px] rounded-full bg-primary/10 text-primary px-2 py-0.5 font-medium shrink-0 inline-flex items-center gap-1",children:[r(uy,{className:"h-3 w-3"}),l.addons.length]})]}),A&&r("p",{className:"text-[10px] text-foreground-subtle mt-0.5 line-clamp-1",children:A}),!I&&e.process&&u("div",{className:"flex items-center gap-1.5 mt-1",children:[r("span",{className:`text-[9px] rounded-full px-1.5 py-0.5 font-medium ${e.process.mode==="forked"?"bg-blue-500/15 text-blue-400":"bg-gray-500/15 text-gray-400"}`,children:e.process.mode==="forked"?"forked":"in-process"}),e.process.pid!=null&&u("span",{className:"text-[9px] font-mono text-foreground-subtle",children:["PID ",e.process.pid]}),r("span",{className:`text-[9px] rounded-full px-1.5 py-0.5 font-medium ${e.process.state==="running"?"bg-emerald-500/15 text-emerald-400":e.process.state==="crashed"?"bg-red-500/15 text-red-400":"bg-gray-500/15 text-gray-400"}`,children:e.process.state})]})]}),!o&&u("div",{className:"relative inline-flex items-center gap-1.5 shrink-0 pt-0.5",children:[i?u("span",{className:"inline-flex items-center gap-1 rounded-md px-2 py-1 text-[10px] font-medium border border-blue-500/30 bg-blue-500/10 text-blue-400",children:[r(Pe,{className:"h-3 w-3 animate-spin"}),"Updating to ",s,"…"]}):s&&a?u("button",{type:"button",onClick:T=>{T.stopPropagation(),a()},className:"inline-flex items-center gap-1 rounded-md px-2 py-1 text-[10px] font-semibold border border-primary/40 bg-primary/10 text-primary hover:bg-primary/20 transition-colors animate-pulse",title:`Update to ${s}`,children:[r(wn,{className:"h-3 w-3"}),s]}):null,u("button",{type:"button",onClick:T=>{T.stopPropagation(),h(W=>!W)},className:["inline-flex items-center gap-1 rounded-md px-2 py-1 text-[10px] font-bold font-mono border transition-colors",O==="local"?"border-orange-500/30 bg-orange-500/10 text-orange-400 hover:bg-orange-500/20":s?"border-amber-500/30 bg-amber-500/10 text-amber-400 hover:bg-amber-500/20":"border-emerald-500/30 bg-emerald-500/10 text-emerald-400 hover:bg-emerald-500/20"].join(" "),title:s?`Current ${B} — newer ${s} available`:"View all versions",children:[B,r(Rt,{className:"h-3 w-3 opacity-50"})]}),m&&r(w8,{packageName:E,currentVersion:B,onInstall:T=>{h(!1),R.mutate({packageName:E,version:T})},onClose:()=>h(!1)})]})]}),!I&&u("div",{className:"flex items-center gap-1 px-4 py-1.5 border-t border-border/50 bg-surface-hover/20",children:[u("button",{type:"button",onClick:T=>{T.stopPropagation(),_.mutate({addonId:S.id})},disabled:_.isPending,className:"inline-flex items-center gap-1 rounded-md px-2 py-1 text-[10px] font-medium border border-border text-foreground-subtle hover:text-blue-400 hover:border-blue-500/30 hover:bg-blue-500/10 disabled:opacity-50 transition-colors",children:[r(pt,{className:`h-3 w-3 ${_.isPending?"animate-spin":""}`}),"Restart"]}),u("button",{type:"button",onClick:T=>{T.stopPropagation(),b(W=>!W)},className:`inline-flex items-center gap-1 rounded-md px-2 py-1 text-[10px] font-medium border transition-colors ${g?"border-primary/30 bg-primary/10 text-primary":"border-border text-foreground-subtle hover:text-foreground hover:border-primary/30 hover:bg-primary/10"}`,children:[r(Xe,{className:"h-3 w-3"}),"Logs"]}),!I&&u("button",{type:"button",onClick:T=>{T.stopPropagation(),v(!0)},className:`inline-flex items-center gap-1 rounded-md px-2 py-1 text-[10px] font-medium border transition-colors ${x?"border-primary/30 bg-primary/10 text-primary":"border-border text-foreground-subtle hover:text-foreground hover:border-primary/30 hover:bg-primary/10"}`,children:[r(wt,{className:"h-3 w-3"}),"Settings"]}),r("div",{className:"flex-1"}),P&&u("button",{type:"button",onClick:async T=>{T.stopPropagation(),await k({title:`Uninstall ${S.name}?`,message:"This will remove the addon package and all its data. This action cannot be undone.",confirmLabel:"Uninstall",variant:"danger"})&&D.mutate({packageName:S.packageName})},disabled:D.isPending,className:"inline-flex items-center gap-1 rounded-md px-2 py-1 text-[10px] font-medium border border-border text-foreground-subtle hover:text-red-400 hover:border-red-500/30 hover:bg-red-500/10 disabled:opacity-50 transition-colors",children:[r(We,{className:"h-3 w-3"}),D.isPending?"Removing...":"Uninstall"]})]}),n&&n.nodes.length>1&&!I&&u("div",{className:"border-t border-border px-4 py-2 bg-muted/10",children:[r("div",{className:"text-[10px] font-medium text-foreground-subtle mb-1.5",children:"Cluster Deployment"}),r("div",{className:"space-y-1",children:n.nodes.map(T=>u("div",{className:"flex items-center gap-2 text-[10px]",children:[r("div",{className:`h-1.5 w-1.5 rounded-full shrink-0 ${T.status==="offline"?"bg-muted-foreground/30":T.synced?"bg-success":"bg-amber-500"}`}),r("span",{className:"font-medium text-foreground min-w-[60px]",children:T.name}),r("span",{className:"font-mono text-foreground-subtle",children:T.version}),!T.synced&&T.status!=="offline"&&r("span",{className:"text-[9px] px-1 py-0.5 rounded bg-amber-500/10 text-amber-400 border border-amber-500/20",children:"outdated"}),T.status==="offline"&&r("span",{className:"text-[9px] px-1 py-0.5 rounded bg-muted text-muted-foreground",children:"offline"}),T.synced&&T.status!=="offline"&&r("span",{className:"text-[9px] text-success",children:"synced"})]},T.nodeId))})]}),g&&!I&&u("div",{className:"border-t border-border",children:[u("div",{className:"flex items-center px-4 py-1 bg-surface-hover/20 border-b border-border/50",children:[u("div",{className:"flex rounded border border-border overflow-hidden text-[9px]",children:[r("button",{type:"button",onClick:()=>y("logs"),className:`px-2 py-0.5 transition-colors ${w==="logs"?"bg-primary/10 text-primary":"text-foreground-subtle hover:bg-surface-hover"}`,children:"Logs"}),r("button",{type:"button",onClick:()=>y("events"),className:`px-2 py-0.5 border-l border-border transition-colors ${w==="events"?"bg-primary/10 text-primary":"text-foreground-subtle hover:bg-surface-hover"}`,children:"Events"})]}),r("div",{className:"flex-1"}),r("button",{type:"button",onClick:T=>{T.stopPropagation(),b(!1)},className:"text-foreground-subtle hover:text-foreground",children:r(qe,{className:"h-3.5 w-3.5"})})]}),w==="logs"&&r(Wt,{addonId:S.id,maxHeight:"max-h-64",showFilters:!1}),w==="events"&&r(nr,{addonId:S.id,category:"addon.*",maxHeight:"max-h-64"})]}),I&&u(ve,{children:[r("button",{type:"button",onClick:()=>d(T=>!T),className:"w-full flex items-center justify-center border-t border-border py-1 hover:bg-surface-hover/50 transition-colors",children:c?r(bD,{className:"h-3.5 w-3.5 text-foreground-subtle"}):r(Rt,{className:"h-3.5 w-3.5 text-foreground-subtle"})}),c&&r("div",{className:"border-t border-border px-3 py-2 space-y-2",children:l.addons.map(T=>r(pl,{addon:T,agents:t,hideVersion:!0},T.manifest.id))})]}),x&&!I&&r("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm p-4",onClick:()=>v(!1),children:u("div",{className:"w-full max-w-lg max-h-[80vh] rounded-xl border border-border bg-surface shadow-2xl flex flex-col overflow-hidden",onClick:T=>T.stopPropagation(),children:[u("div",{className:"flex items-center justify-between px-5 py-3 border-b border-border flex-shrink-0",children:[u("div",{className:"flex items-center gap-2",children:[r(wt,{className:"h-4 w-4 text-primary"}),u("h2",{className:"text-sm font-semibold text-foreground",children:[F," Settings"]})]}),r("button",{onClick:()=>v(!1),className:"text-foreground-subtle hover:text-foreground transition-colors p-1 rounded",children:r(qe,{className:"h-4 w-4"})})]}),u("div",{className:"flex-1 overflow-y-auto px-5 py-4 space-y-4",children:[r(Rr,{nodeId:"hub",addonIds:[S.id],level:"global"}),O==="npm"&&u("div",{children:[r("div",{className:"text-[10px] font-medium text-foreground-subtle uppercase tracking-wide mb-2",children:"Auto-Update"}),r(k8,{addonId:S.id})]}),S.components&&S.components.length>0&&u("div",{children:[u("div",{className:"text-[10px] font-medium text-foreground-subtle uppercase tracking-wide mb-2",children:["Components (",S.components.length,")"]}),r("div",{className:"flex flex-wrap gap-1",children:S.components.map(T=>r("span",{className:"text-[10px] rounded bg-background border border-border px-1.5 py-0.5 text-foreground-subtle font-mono",children:T},T))})]}),t.length>=2&&u("div",{children:[r("div",{className:"text-[10px] font-medium text-foreground-subtle uppercase tracking-wide mb-2",children:"Installed on"}),u("div",{className:"flex items-center gap-1.5 flex-wrap",children:[M.length===0&&r("span",{className:"text-[10px] text-foreground-subtle",children:"Hub (local)"}),M.map(T=>r("span",{className:"rounded-full bg-surface-hover border border-border px-2 py-0.5 text-[10px] text-foreground-subtle",children:T},T)),u("div",{className:"relative",children:[u("button",{type:"button",onClick:T=>{T.stopPropagation(),p(W=>!W)},className:"inline-flex items-center gap-1 rounded-full border border-dashed border-border px-2 py-0.5 text-[10px] text-foreground-subtle hover:text-foreground hover:border-primary transition-colors",title:"Install on more agents",children:[r(Ot,{className:"h-3 w-3"}),"Add agent"]}),f&&u("div",{className:"absolute left-0 top-full mt-1 z-10 min-w-[160px] rounded-md border border-border bg-surface shadow-lg overflow-hidden",children:[t.filter(T=>!T.isHub&&!M.includes(T.name)).map(T=>r("button",{type:"button",onClick:W=>{W.stopPropagation(),p(!1)},className:"w-full text-left px-3 py-1.5 text-[10px] text-foreground hover:bg-surface-hover transition-colors",children:T.name},T.id)),t.filter(T=>!T.isHub&&!M.includes(T.name)).length===0&&r("div",{className:"px-3 py-1.5 text-[10px] text-foreground-subtle",children:"No available agents"})]})]})]})]})]}),r("div",{className:"flex items-center justify-end px-5 py-3 border-t border-border flex-shrink-0",children:r("button",{type:"button",onClick:()=>v(!1),className:"rounded-lg border border-border px-3 py-1.5 text-xs font-medium text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors",children:"Close"})})]})})]})}const S8=".tgz,.tar.gz,.zip";function C8({onUploadSuccess:e}){const[t,n]=$(!1),o=ne(null),s=q(async i=>{n(!0);const l=new FormData;l.append("file",i);const c=localStorage.getItem("camstack_admin_token")??"";try{(await(await fetch("/api/addons/upload",{method:"POST",headers:{Authorization:`Bearer ${c}`},body:l})).json()).success&&e()}finally{n(!1)}},[e]),a=q(i=>{const l=i.target.files?.[0];l&&s(l),i.target.value=""},[s]);return u(ve,{children:[r("input",{ref:o,type:"file",accept:S8,onChange:a,className:"hidden"}),u("button",{type:"button",onClick:()=>o.current?.click(),disabled:t,className:"flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-md bg-surface hover:bg-surface-hover border border-border disabled:opacity-50 transition-colors",children:[t?r(Pe,{className:"w-3.5 h-3.5 animate-spin"}):r(Xc,{className:"w-3.5 h-3.5"}),t?"Uploading...":"Upload"]})]})}function M8(e,t){const n=e??"hub-only";return n==="any-node"?!0:n==="hub-only"?t:!t}function I8(e){const t=e;if(!t?.manifest)return null;const n={...t.manifest,name:t.manifest.name??t.manifest.id,version:t.manifest.version??"0.0.0",capabilities:t.manifest.capabilities??[]},o=t.process,s=o?{pid:o.pid,mode:o.mode==="forked"?"forked":"in-process",state:o.state??"unknown"}:void 0,a=t.health;return{manifest:n,enabled:!0,source:t.source,installSource:t.installSource,installedOn:[],...s?{process:s}:{},hasBackup:t.hasBackup,...a?{health:a}:{}}}function A8(e){const t=new Map,n=[];for(const s of e){const a=s.manifest.packageName;if(!a){n.push(s);continue}const i=t.get(a);if(i)i.addons.push(s);else{const l=s.manifest.bundle,c={packageName:a,displayName:l?.displayName??s.manifest.packageDisplayName??s.manifest.name,version:s.manifest.packageVersion,addons:[s],...s.installSource!==void 0?{installSource:s.installSource}:{},...l!==void 0?{bundle:l}:{}};t.set(a,c)}}const o=[];for(const s of t.values())s.bundle!==void 0||s.addons.length>=2?o.push({bundle:s,representative:s.addons[0]}):o.push(s.addons[0]);return o.push(...n),o}function Xt(e){return"bundle"in e}function P8({addons:e,clusterStatus:t,selectedNode:n,onRefresh:o,isRefreshing:s}){const a=ke(),[i,l]=$(""),c=Y1(i),[d,f]=$(!1),p=ne(null);Y(()=>{if(!d)return;const L=z=>{p.current&&!p.current.contains(z.target)&&f(!1)};return document.addEventListener("mousedown",L),()=>document.removeEventListener("mousedown",L)},[d]);const{data:m}=cc(void 0,{staleTime:5*6e4}),h=Q(()=>{const L=new Map;for(const z of m??[])L.set(z.name,z.latestVersion);return L},[m]),[g,b]=$(null),[x,v]=$(null),w=Ui({onMutate:L=>{b(L.name),v(null)},onSuccess:(L,z)=>{b(null);const j=L;if(j&&j.success===!1){v({name:z.name,message:j.error??"Update failed (no error message returned by server)"});return}a.invalidateQueries({queryKey:[["addons"]]}),a.invalidateQueries({queryKey:[["addons","listUpdates"]]})},onError:(L,z)=>{b(null),v({name:z.name,message:L instanceof Error?L.message:String(L)})}}),{data:y}=Wh(void 0,{staleTime:3e4}),N=Xh({onSuccess:()=>{a.invalidateQueries({queryKey:[["addons","getAutoUpdateSettings"]]})}}),{data:k,isFetching:S}=qh({query:c||void 0},{enabled:d,staleTime:6e4}),M=Ui(),P=async()=>{const L=m??[];for(const z of L)await M.mutateAsync({name:z.name,version:z.latestVersion});a.invalidateQueries({queryKey:[["addons"]]})},I=lc({onSuccess:()=>{a.invalidateQueries({queryKey:[["addons"]]}),a.invalidateQueries({queryKey:[["addonPages"]]}),a.invalidateQueries({queryKey:[["capabilities"]]}),a.invalidateQueries({queryKey:[["integrations"]]})}}),[F,E]=$("type"),[B,O]=$(()=>typeof window>"u"?"grouped":window.localStorage.getItem("camstack.addons.viewMode")==="flat"?"flat":"grouped"),A=L=>{O(L),typeof window<"u"&&window.localStorage.setItem("camstack.addons.viewMode",L)},D=Q(()=>n.isHub?e:e.filter(L=>{const z=L.manifest.execution;return M8(z?.placement,n.isHub)}),[e,n.isHub]),_=B==="flat"?D:A8(D),R=Q(()=>{const L=[..._];switch(F){case"type":L.sort((z,j)=>{const H=Xt(z)?0:1,T=Xt(j)?0:1;if(H!==T)return H-T;const W=Xt(z)?z.bundle.displayName:z.manifest.name,G=Xt(j)?j.bundle.displayName:j.manifest.name;return W.localeCompare(G)});break;case"name":L.sort((z,j)=>{const H=Xt(z)?z.bundle.displayName:z.manifest.name,T=Xt(j)?j.bundle.displayName:j.manifest.name;return H.localeCompare(T)});break;case"source":L.sort((z,j)=>{const H=Xt(z)?z.bundle.installSource??"":z.installSource??"",T=Xt(j)?j.bundle.installSource??"":j.installSource??"";return H.localeCompare(T)});break}return L},[_,F]);return u("div",{className:"space-y-4",children:[x&&r("div",{className:"rounded-md border border-danger/30 bg-danger/5 px-3 py-2 text-[11px]",children:u("div",{className:"flex items-start justify-between gap-3",children:[u("div",{className:"space-y-0.5",children:[u("div",{className:"font-medium text-danger",children:["Failed to update ",x.name]}),r("div",{className:"text-foreground-subtle font-mono",children:x.message})]}),r("button",{type:"button",onClick:()=>v(null),className:"text-foreground-subtle hover:text-foreground text-[10px]",children:"dismiss"})]})}),u("div",{className:"flex items-center gap-2 flex-wrap",children:[u("div",{className:"flex items-center gap-1.5",children:[r("span",{className:"text-[10px] text-foreground-subtle",children:"Sort:"}),u("select",{value:F,onChange:L=>E(L.target.value),className:"rounded-md border border-border bg-surface px-2 py-1.5 text-[11px] text-foreground focus:outline-none focus:border-primary/50",children:[r("option",{value:"type",children:"Bundles first"}),r("option",{value:"name",children:"Name"}),r("option",{value:"source",children:"Install source"})]})]}),u("div",{className:"flex items-center gap-1.5",children:[r("span",{className:"text-[10px] text-foreground-subtle",children:"View:"}),r("div",{className:"flex rounded-md border border-border overflow-hidden text-[10px] font-medium",children:["grouped","flat"].map(L=>r("button",{type:"button",onClick:()=>A(L),className:`px-2.5 py-1.5 transition-colors capitalize ${B===L?"bg-primary/10 text-primary":"bg-transparent text-foreground-subtle hover:bg-surface-hover"}`,title:L==="grouped"?"Group multi-addon packages into a bundle card":"Show every addon as its own card",children:L},L))})]}),u("div",{className:"flex items-center gap-1.5",children:[r(pt,{className:"h-3 w-3 text-foreground-subtle"}),r("span",{className:"text-[10px] text-foreground-subtle",children:"Auto-Update:"}),r("div",{className:"flex rounded-md border border-border overflow-hidden text-[10px] font-medium",children:["off","latest","beta"].map(L=>r("button",{type:"button",onClick:()=>N.mutate({channel:L}),disabled:N.isPending,className:`px-2.5 py-1.5 transition-colors capitalize ${y?.channel===L?L==="off"?"bg-gray-700 text-gray-200":L==="latest"?"bg-blue-500/20 text-blue-400":"bg-amber-500/20 text-amber-400":"bg-transparent text-foreground-subtle hover:bg-surface-hover"} ${L!=="off"?"border-l border-border":""}`,children:L},L))})]}),(m?.length??0)>0&&u("button",{type:"button",onClick:()=>void P(),disabled:M.isPending,className:"flex items-center gap-1.5 px-2.5 py-1.5 text-[11px] rounded-md bg-blue-500/10 text-blue-400 hover:bg-blue-500/20 border border-blue-500/30 disabled:opacity-50 transition-colors font-medium",children:[r(wn,{className:`w-3 h-3 ${M.isPending?"animate-bounce":""}`}),"Update All (",m.length,")"]}),u("button",{type:"button",onClick:o,disabled:s,className:"flex items-center gap-1.5 px-2.5 py-1.5 text-[11px] rounded-md bg-surface hover:bg-surface-hover border border-border disabled:opacity-50 transition-colors",children:[r(pt,{className:`w-3 h-3 ${s?"animate-spin":""}`}),"Refresh"]})]}),u("div",{className:"flex items-center gap-3",children:[u("div",{className:"relative flex-1 min-w-[200px]",ref:p,children:[r(hy,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-foreground-subtle"}),r("input",{type:"text",value:i,onChange:L=>{l(L.target.value),f(!0)},onFocus:()=>f(!0),placeholder:"Search addons on npm...",className:"w-full rounded-lg border border-border bg-background pl-9 pr-3 py-2 text-xs text-foreground placeholder:text-foreground-subtle focus:outline-none focus:ring-1 focus:ring-primary"}),S&&r(Pe,{className:"absolute right-2.5 top-1/2 -translate-y-1/2 h-3 w-3 text-foreground-subtle animate-spin"}),d&&k&&k.length>0&&u("div",{className:"absolute left-0 right-0 top-full mt-1 z-40 rounded-lg border border-border bg-surface shadow-xl overflow-hidden",children:[k.length>0&&u("div",{className:"px-3 py-1.5 text-[10px] uppercase tracking-wide text-foreground-subtle border-b border-border",children:["npm results (",k.length,")"]}),k&&k.length>0&&r("div",{className:"max-h-72 overflow-auto divide-y divide-border",children:k.map(L=>u("div",{className:"flex items-center gap-3 px-3 py-2 hover:bg-surface-hover transition-colors",children:[r("div",{className:"w-6 h-6 rounded-md bg-primary/10 flex items-center justify-center text-primary text-[9px] font-bold shrink-0",children:L.name.replace("@camstack/addon-","").charAt(0).toUpperCase()}),u("div",{className:"flex-1 min-w-0",children:[u("div",{className:"flex items-center gap-2",children:[r("span",{className:"text-[11px] font-semibold truncate",children:L.name}),u("span",{className:"text-[10px] text-foreground-subtle",children:["v",L.version]})]}),L.description&&r("div",{className:"text-[10px] text-foreground-subtle truncate",children:L.description})]}),L.installed?u("span",{className:"inline-flex items-center gap-1 px-2 py-1 text-[10px] font-medium rounded-md border border-emerald-500/30 bg-emerald-500/10 text-emerald-400 shrink-0",children:[r(Ct,{className:"h-3 w-3"}),L.installedVersion??"Installed"]}):u("button",{type:"button",onClick:()=>I.mutate({packageName:L.name}),disabled:I.isPending,className:"inline-flex items-center gap-1 px-2 py-1 text-[10px] font-medium rounded-md bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-50 transition-colors shrink-0",children:[I.isPending?r(Pe,{className:"h-3 w-3 animate-spin"}):r(wn,{className:"h-3 w-3"}),"Install"]})]},L.name))})]})]}),r(C8,{onUploadSuccess:()=>{a.invalidateQueries({queryKey:[["addons"]]}),o()}})]}),D.length===0&&r("div",{className:"text-xs text-foreground-subtle",children:e.length===0?"No addons installed":`No addons compatible with ${n.name} (placement filter active)`}),r("div",{className:"space-y-2",children:R.map(L=>{if(Xt(L)){const H=L.bundle.packageName,T=h.get(H);return r(pl,{addon:L.representative,clusterStatus:t?.[L.representative.manifest.id],bundle:L.bundle,availableUpdate:T,isUpdating:g===H,onUpdate:T?()=>w.mutate({name:H,version:T}):void 0},H)}const z=L.manifest.packageName,j=h.get(z);return r(pl,{addon:L,clusterStatus:t?.[L.manifest.id],availableUpdate:j,isUpdating:g===z,onUpdate:j?()=>w.mutate({name:L.manifest.packageName,version:j}):void 0},L.manifest.id)})})]})}function E8(){const e=ke(),{data:t,isLoading:n,isError:o}=oa(),{data:s}=nb(void 0,{staleTime:15e3}),{data:a}=In(void 0,{staleTime:3e4,refetchInterval:1e4}),i=Q(()=>{const x=new Map;x.set("hub",{id:"hub",name:"Hub",isHub:!0});for(const v of a??[]){const w=String(v.id??"");w&&x.set(w,{id:w,name:String(v.name??w),isHub:!!v.isHub})}return[...x.values()]},[a]),[l,c]=$("hub"),d=i.find(x=>x.id===l)??i[0],f=Qh(),p=Vh(),m=f.isPending||p.isPending,h=async()=>{await f.mutateAsync(),await p.mutateAsync(),e.invalidateQueries({queryKey:[["addons"]]})},g=ne(f);g.current=f,Y(()=>{g.current.mutate()},[]);const b=(t??[]).map(I8).filter(x=>x!==null);return u("div",{className:"p-6 space-y-5",children:[u("div",{className:"flex items-center justify-between gap-4 flex-wrap",children:[u("div",{children:[r("h1",{className:"text-lg font-semibold text-foreground",children:"Addons"}),r("p",{className:"text-xs text-foreground-subtle mt-0.5",children:"Manage installed addons and explore capability providers."})]}),u("div",{className:"flex items-center gap-3 flex-wrap",children:[r(gh,{selectedNodeId:l,onSelect:c}),!n&&!o&&u("span",{className:"text-[10px] rounded-full bg-primary/10 text-primary px-2 py-0.5 font-medium",children:[b.length," installed"]}),u("button",{type:"button",onClick:()=>void h(),disabled:m,className:"inline-flex items-center gap-1.5 px-2.5 py-1.5 text-[11px] rounded-md bg-surface hover:bg-surface-hover border border-border disabled:opacity-50 transition-colors",title:"Re-fetch addons + check npm for new versions",children:[r(pt,{className:`w-3 h-3 ${m?"animate-spin":""}`}),"Check for updates"]})]})]}),!d.isHub&&u("div",{className:"rounded-md border border-warning/30 bg-warning/5 px-3 py-2 text-[11px] text-foreground-subtle",children:["Showing only addons compatible with"," ",r("span",{className:"font-medium text-foreground",children:d.name})," ","— agents only run ",r("code",{className:"font-mono",children:"agent-only"})," and"," ",r("code",{className:"font-mono",children:"any-node"})," addons. Install / uninstall is hub-driven; agents auto-sync from the hub."]}),n&&r("div",{className:"text-xs text-foreground-subtle animate-pulse",children:"Loading…"}),o&&r("div",{className:"text-xs text-danger",children:"Failed to load addons"}),!n&&!o&&r(P8,{addons:b,clusterStatus:s,selectedNode:d,onRefresh:()=>void h(),isRefreshing:m})]})}function $8(){return r(It,{icon:Xe,title:"Logs",children:r("div",{className:"rounded-lg border border-border bg-surface overflow-hidden",children:r(Wt,{limit:500,maxHeight:"max-h-[calc(100vh-250px)]",showScope:!0,showFilters:!0})})})}function td({tabs:e,defaultTab:t}){const[n,o]=Qc(),s=n.get("tab"),a=t??e[0]?.id??"",i=e.some(d=>d.id===s)?s:a,l=e.find(d=>d.id===i)??e[0],c=d=>{const f=new URLSearchParams(n);f.set("tab",d),o(f,{replace:!0})};return u("div",{className:"space-y-3",children:[r("div",{className:"flex border-b border-border",children:e.map(d=>{const f=d.icon,p=d.id===i;return u("button",{onClick:()=>c(d.id),className:`flex items-center gap-1.5 px-3 py-2 text-xs font-medium border-b-2 transition-colors ${p?"border-primary text-primary":"border-transparent text-foreground-subtle hover:text-foreground"}`,children:[f&&r(f,{className:"h-3.5 w-3.5"}),d.label]},d.id)})}),r("div",{children:l?.content})]})}const bp={super_admin:"bg-danger/10 text-danger",admin:"bg-primary/10 text-primary",viewer:"bg-foreground-subtle/10 text-foreground-subtle"};function _8(){const e=ke(),[t,n]=$(!1),[o,s]=$(""),[a,i]=$(""),[l,c]=$("viewer"),[d,f]=$(null),{data:p,isLoading:m,isError:h}=kc(),g=rt(),b=()=>e.invalidateQueries({queryKey:[["userManagement","listUsers"]]}),x=ex({onSuccess:()=>{b(),n(!1),s(""),i(""),c("viewer"),f(null)},onError:I=>{f(I instanceof Error?I.message:"Failed to create user")}}),v=nx({onSuccess:b}),w=tx({onSuccess:b}),y=Sc({onSuccess:b}),N=p??[];async function k(I){await g({title:"Delete user",message:`Permanently delete user "${I.username}"? This cannot be undone — any active sessions will be revoked on next request.`,confirmLabel:"Delete",variant:"danger"})&&v.mutate({id:I.id})}async function S(I){const F=window.prompt(`New password for "${I.username}":`);if(!F)return;if(F.length<8){window.alert("Password must be at least 8 characters.");return}await g({title:"Reset password",message:`Reset the password for "${I.username}"? They will need to use the new password on their next login.`,confirmLabel:"Reset"})&&y.mutate({id:I.id,newPassword:F})}function M(I,F){F!==I.role&&w.mutate({id:I.id,role:F})}function P(I){return I?new Date(typeof I=="number"?I:String(I)).toLocaleDateString("en-GB",{day:"2-digit",month:"short",year:"numeric"}):"—"}return u(It,{icon:xy,title:"Users",actions:u("button",{onClick:()=>n(!0),className:"inline-flex items-center gap-1.5 rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground shadow-sm hover:bg-primary/90",children:[r(Ot,{className:"h-3.5 w-3.5"}),"Create User"]}),children:[t&&u("div",{className:"rounded-lg border border-border bg-surface p-4 space-y-3",children:[u("div",{className:"flex items-center justify-between",children:[r("span",{className:"text-xs font-medium text-foreground",children:"New User"}),r("button",{onClick:()=>n(!1),className:"text-foreground-subtle hover:text-foreground",children:r(qe,{className:"h-4 w-4"})})]}),u("div",{className:"grid grid-cols-3 gap-3",children:[u("div",{className:"space-y-1",children:[r("label",{className:"text-[10px] text-foreground-subtle uppercase tracking-wide",children:"Username"}),r("input",{type:"text",value:o,onChange:I=>s(I.target.value),placeholder:"john",className:"w-full rounded border border-border bg-background px-2 py-1.5 text-xs text-foreground placeholder:text-foreground-subtle focus:outline-none focus:ring-1 focus:ring-primary"})]}),u("div",{className:"space-y-1",children:[r("label",{className:"text-[10px] text-foreground-subtle uppercase tracking-wide",children:"Password"}),r("input",{type:"password",value:a,onChange:I=>i(I.target.value),placeholder:"••••••••",className:"w-full rounded border border-border bg-background px-2 py-1.5 text-xs text-foreground placeholder:text-foreground-subtle focus:outline-none focus:ring-1 focus:ring-primary"})]}),u("div",{className:"space-y-1",children:[r("label",{className:"text-[10px] text-foreground-subtle uppercase tracking-wide",children:"Role"}),u("select",{value:l,onChange:I=>c(I.target.value),className:"w-full rounded border border-border bg-background px-2 py-1.5 text-xs text-foreground focus:outline-none focus:ring-1 focus:ring-primary",children:[r("option",{value:"viewer",children:"Viewer"}),r("option",{value:"admin",children:"Admin"}),r("option",{value:"super_admin",children:"Super Admin"})]})]})]}),d&&r("p",{className:"text-[10px] text-danger",children:d}),u("div",{className:"flex justify-end gap-2",children:[r("button",{onClick:()=>n(!1),className:"rounded px-3 py-1.5 text-xs text-foreground-subtle border border-border hover:text-foreground",children:"Cancel"}),r("button",{onClick:()=>x.mutate({username:o,password:a,role:l}),disabled:x.isPending||!o||!a,className:"rounded bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50",children:x.isPending?"Creating...":"Create"})]})]}),m&&r("div",{className:"text-xs text-foreground-subtle animate-pulse",children:"Loading..."}),h&&r("div",{className:"text-xs text-danger",children:"Failed to load"}),!m&&!h&&N.length===0&&r("div",{className:"text-xs text-foreground-subtle",children:"No data"}),(()=>{const I=E=>v.isPending&&v.variables?.id===E.id||w.isPending&&w.variables?.id===E.id||y.isPending&&y.variables?.id===E.id;return r(uh,{columns:[{key:"username",header:"Username",render:E=>E.username},{key:"role",header:"Role",render:E=>{const B=E.role??"viewer",O=bp[B]??bp.viewer;return u("select",{value:B,onChange:A=>M(E,A.target.value),disabled:I(E),className:`rounded border border-border bg-background px-2 py-0.5 text-xs focus:outline-none focus:ring-1 focus:ring-primary disabled:opacity-50 ${O}`,title:"Change role",children:[r("option",{value:"viewer",children:"Viewer"}),r("option",{value:"admin",children:"Admin"}),r("option",{value:"super_admin",children:"Super Admin"})]})}},{key:"createdAt",header:"Created",render:E=>r("span",{className:"text-foreground-subtle",children:P(E.createdAt)})},{key:"actions",header:"Actions",align:"right",render:E=>{const B=I(E);return u("div",{className:"flex items-center justify-end gap-1",children:[u("button",{onClick:()=>S(E),disabled:B,className:"inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] text-foreground-subtle hover:bg-foreground-subtle/10 hover:text-foreground disabled:opacity-50",title:"Reset password",children:[r(YD,{className:"h-3 w-3"}),"Reset password"]}),u("button",{onClick:()=>k(E),disabled:B,className:"inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] text-danger hover:bg-danger/10 disabled:opacity-50",title:"Delete user",children:[B?r(Pe,{className:"h-3 w-3 animate-spin"}):r(We,{className:"h-3 w-3"}),"Delete"]})]})}}],rows:N,rowKey:E=>E.id,minWidthPx:560})})()]})}const D8={super_admin:"bg-danger/10 text-danger",admin:"bg-primary/10 text-primary",viewer:"bg-foreground-subtle/10 text-foreground-subtle",agent:"bg-warning/10 text-warning"};function to(e){if(!e)return"—";const t=new Date(e);return Number.isNaN(t.getTime())?"—":t.toLocaleString()}function L8(e){return e?e==="*"?"*":e.join(", "):""}function T8(e){return e.type==="integration"?{type:"addon",target:e.target}:{type:e.type,target:e.target}}function R8(){const e=ke(),t=rt(),{data:n,isLoading:o}=rx(),{data:s}=kc(),a=Q(()=>n??[],[n]),i=Q(()=>s??[],[s]),l=()=>e.invalidateQueries({queryKey:[["userManagement","listApiKeys"]]}),c=()=>e.invalidateQueries({queryKey:[["userManagement","listScopedTokens"]]}),[d,f]=$(!1),[p,m]=$(null),h=ox({onSuccess:l}),g=sx({onSuccess:({token:w,record:y})=>{c(),f(!1),m({token:w,label:y.name})}}),b=ax({onSuccess:c}),x=async(w,y)=>{await t({title:`Revoke "${y}"?`,message:"Any client using this token will lose access immediately. This cannot be undone.",confirmLabel:"Revoke",variant:"danger"})&&h.mutate({id:w})},v=async(w,y)=>{await t({title:`Revoke "${y}"?`,message:"The scoped token will be invalid on its next use.",confirmLabel:"Revoke",variant:"danger"})&&b.mutate({id:w})};return u(It,{icon:ay,title:"Tokens",subtitle:"Issue scoped tokens to grant a user a narrow surface — a specific addon, integration, route prefix, or capability. Every token MUST be scoped: revoking it has predictable blast radius.",actions:u("button",{onClick:()=>f(!0),className:"inline-flex items-center gap-1.5 rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50",disabled:i.length===0,title:i.length===0?"Create a user first":"Issue a scoped token",children:[r(xr,{className:"h-3.5 w-3.5"}),"New token"]}),children:[u(xp,{title:"Scoped tokens",subtitle:"Grouped per user",children:[i.length===0&&r(z8,{text:"No users yet — scoped tokens are issued on behalf of an existing user."}),i.map(w=>r(B8,{userId:w.id,username:w.username,onRevoke:(y,N)=>{v(y,N)},revokePending:b.isPending,revokeId:b.variables?.id},w.id))]}),a.length>0&&r(xp,{title:"Legacy API keys",subtitle:`${a.length} pre-existing — revoke only`,children:r(n0,{headers:["Label","Role","Prefix","Allowed providers","Created","Last used",""],rows:a.map(w=>{const y=w.role??"viewer",N=h.isPending&&h.variables?.id===w.id;return u("tr",{className:"hover:bg-primary/5",children:[r("td",{className:"px-3 py-2 text-foreground border-b border-border font-medium",children:w.label}),r("td",{className:"px-3 py-2 text-foreground border-b border-border",children:r("span",{className:`inline-block rounded px-2 py-0.5 text-[10px] uppercase tracking-wide ${D8[y]}`,children:y})}),u("td",{className:"px-3 py-2 text-foreground border-b border-border font-mono text-[11px]",children:[w.tokenPrefix,"…"]}),r("td",{className:"px-3 py-2 text-foreground border-b border-border text-foreground-subtle",children:L8(w.allowedProviders)||"all"}),r("td",{className:"px-3 py-2 text-foreground-subtle border-b border-border",children:to(w.createdAt)}),r("td",{className:"px-3 py-2 text-foreground-subtle border-b border-border",children:to(w.lastUsedAt)}),r("td",{className:"px-3 py-2 border-b border-border text-right",children:u("button",{onClick:()=>{x(w.id,w.label)},disabled:N,className:"inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] text-danger hover:bg-danger/10 disabled:opacity-50",title:"Revoke",children:[N?r(Pe,{className:"h-3 w-3 animate-spin"}):r(We,{className:"h-3 w-3"}),"Revoke"]})})]},w.id)})})}),o&&r(O8,{}),d&&r(F8,{users:i.map(w=>({id:w.id,username:w.username})),onClose:()=>f(!1),onSubmit:w=>g.mutate({name:w.name,scopes:w.scopes,...w.expiresAt!==void 0?{expiresAt:w.expiresAt}:{}}),submitting:g.isPending}),p&&r(H8,{token:p.token,label:p.label,onClose:()=>m(null)})]})}function xp({title:e,subtitle:t,children:n}){return u("div",{className:"space-y-2",children:[u("div",{className:"flex items-baseline justify-between",children:[r("h2",{className:"text-sm font-semibold text-foreground",children:e}),t&&r("span",{className:"text-[10px] text-foreground-subtle",children:t})]}),n]})}function O8(){return r("div",{className:"space-y-2",children:[1,2].map(e=>r("div",{className:"h-10 rounded border border-border bg-surface animate-pulse"},e))})}function z8({text:e}){return r("div",{className:"rounded border border-dashed border-border bg-surface px-3 py-4 text-xs text-foreground-subtle text-center",children:e})}function n0({headers:e,rows:t}){return r("div",{className:"rounded-lg border border-border bg-surface overflow-x-auto",children:u("table",{className:"w-full text-xs min-w-[640px]",children:[r("thead",{children:r("tr",{children:e.map((n,o)=>r("th",{className:`px-3 py-2 text-foreground-subtle font-medium bg-surface border-b border-border whitespace-nowrap ${o===e.length-1?"text-right":"text-left"}`,children:n},o))})}),r("tbody",{children:t})]})})}function B8({userId:e,username:t,onRevoke:n,revokePending:o,revokeId:s}){const{data:a,isLoading:i}=ix({userId:e}),l=a??[];return i||l.length===0?null:u("div",{className:"space-y-1.5",children:[r("div",{className:"text-[11px] font-medium text-foreground",children:t}),r(n0,{headers:["Name","Prefix","Scopes","Expires","Last used","Created",""],rows:l.map(c=>{const d=o&&s===c.id;return u("tr",{className:"hover:bg-primary/5",children:[r("td",{className:"px-3 py-2 text-foreground border-b border-border font-medium",children:c.name}),u("td",{className:"px-3 py-2 text-foreground border-b border-border font-mono text-[11px]",children:[c.tokenPrefix,"…"]}),r("td",{className:"px-3 py-2 text-foreground border-b border-border",children:r("div",{className:"flex flex-wrap gap-1",children:c.scopes.map((f,p)=>u("span",{className:"inline-block rounded bg-foreground-subtle/10 px-1.5 py-0.5 text-[10px] font-mono",children:[f.type,":",f.target]},p))})}),r("td",{className:"px-3 py-2 text-foreground-subtle border-b border-border",children:to(c.expiresAt)}),r("td",{className:"px-3 py-2 text-foreground-subtle border-b border-border",children:to(c.lastUsedAt)}),r("td",{className:"px-3 py-2 text-foreground-subtle border-b border-border",children:to(c.createdAt)}),r("td",{className:"px-3 py-2 border-b border-border text-right",children:u("button",{onClick:()=>n(c.id,c.name),disabled:d,className:"inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] text-danger hover:bg-danger/10 disabled:opacity-50",children:[d?r(Pe,{className:"h-3 w-3 animate-spin"}):r(We,{className:"h-3 w-3"}),"Revoke"]})})]},c.id)})})]})}function F8({users:e,onClose:t,onSubmit:n,submitting:o}){const[s,a]=$(e[0]?.id??""),[i,l]=$(""),[c,d]=$([{type:"addon",target:""}]),[f,p]=$(""),{data:m=[]}=oa(),{data:h=[]}=aa(),g=(w,y)=>{d(N=>N.map((k,S)=>{if(S!==w)return k;const M={...k,...y};return y.type!==void 0&&y.type!==k.type&&(M.target=""),M}))},b=c.filter(w=>w.target.trim().length>0).map(T8),x=s!==""&&i.trim().length>0&&b.length>0&&!o,v=()=>{const w=parseInt(f,10),y=Number.isFinite(w)&&w>0?Date.now()+w*864e5:void 0;n({userId:s,name:i.trim(),scopes:b,expiresAt:y})};return u(r0,{title:"Create scoped token",onClose:t,children:[u("div",{className:"space-y-3",children:[r(ts,{label:"On behalf of user",children:r("select",{value:s,onChange:w=>a(w.target.value),className:"w-full rounded border border-border bg-background px-2 py-1.5 text-xs focus:outline-none focus:ring-1 focus:ring-primary",children:e.map(w=>r("option",{value:w.id,children:w.username},w.id))})}),r(ts,{label:"Name",children:r("input",{value:i,onChange:w=>l(w.target.value),placeholder:"cloudflare-tunnel-route",className:"w-full rounded border border-border bg-background px-2 py-1.5 text-xs focus:outline-none focus:ring-1 focus:ring-primary"})}),r(ts,{label:"Scopes",hint:"Each scope picks a concrete surface. The token can access ONLY what's listed.",children:u("div",{className:"space-y-1.5",children:[c.map((w,y)=>r(j8,{scope:w,addons:m,integrations:h,onChange:N=>g(y,N),onRemove:c.length>1?()=>d(N=>N.filter((k,S)=>S!==y)):void 0},y)),u("button",{onClick:()=>d(w=>[...w,{type:"addon",target:""}]),className:"inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] text-foreground-subtle hover:text-foreground hover:bg-foreground-subtle/10",children:[r(Ot,{className:"h-3 w-3"}),"Add scope"]})]})}),r(ts,{label:"Expires in (days)",hint:"Leave blank for non-expiring.",children:r("input",{type:"number",min:1,value:f,onChange:w=>p(w.target.value),placeholder:"30",className:"w-full rounded border border-border bg-background px-2 py-1.5 text-xs focus:outline-none focus:ring-1 focus:ring-primary"})})]}),u(o0,{children:[r("button",{onClick:t,className:"rounded px-3 py-1.5 text-xs text-foreground-subtle border border-border hover:text-foreground",children:"Cancel"}),u("button",{onClick:v,disabled:!x,className:"inline-flex items-center gap-1.5 rounded bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50",children:[o?r(Pe,{className:"h-3.5 w-3.5 animate-spin"}):r(xr,{className:"h-3.5 w-3.5"}),"Issue token"]})]})]})}function j8({scope:e,addons:t,integrations:n,onChange:o,onRemove:s}){const a=t.map(l=>({id:l.manifest.id})),i=()=>{switch(e.type){case"addon":return u("select",{value:e.target,onChange:l=>o({target:l.target.value}),className:"flex-1 rounded border border-border bg-background px-2 py-1.5 text-xs font-mono focus:outline-none focus:ring-1 focus:ring-primary",children:[r("option",{value:"",children:"— pick addon —"}),a.map(l=>r("option",{value:l.id,children:l.id},l.id))]});case"integration":return u("select",{value:e.target,onChange:l=>o({target:l.target.value}),className:"flex-1 rounded border border-border bg-background px-2 py-1.5 text-xs focus:outline-none focus:ring-1 focus:ring-primary",children:[r("option",{value:"",children:"— pick integration —"}),n.map(l=>u("option",{value:l.addonId,children:[l.name," (",l.addonId,")"]},l.id))]});case"capability":return u("select",{value:e.target,onChange:l=>o({target:l.target.value}),className:"flex-1 rounded border border-border bg-background px-2 py-1.5 text-xs font-mono focus:outline-none focus:ring-1 focus:ring-primary",children:[r("option",{value:"",children:"— pick capability —"}),Object.values(aw).sort().map(l=>r("option",{value:l,children:l},l))]});case"route-prefix":return r("input",{value:e.target,onChange:l=>o({target:l.target.value}),placeholder:"/api/cloudflare",className:"flex-1 rounded border border-border bg-background px-2 py-1.5 text-xs font-mono focus:outline-none focus:ring-1 focus:ring-primary"})}};return u("div",{className:"flex items-center gap-1.5",children:[u("select",{value:e.type,onChange:l=>o({type:l.target.value}),className:"rounded border border-border bg-background px-2 py-1.5 text-xs focus:outline-none focus:ring-1 focus:ring-primary",children:[r("option",{value:"addon",children:"addon"}),r("option",{value:"integration",children:"integration"}),r("option",{value:"capability",children:"capability"}),r("option",{value:"route-prefix",children:"route-prefix"})]}),i(),s&&r("button",{onClick:s,className:"rounded p-1 text-foreground-subtle hover:text-danger hover:bg-danger/10",title:"Remove scope",children:r(qe,{className:"h-3 w-3"})})]})}function H8({token:e,label:t,onClose:n}){const[o,s]=$(!1),a=async()=>{try{await navigator.clipboard.writeText(e),s(!0)}catch{}};return u(r0,{title:`Token: ${t}`,onClose:n,children:[u("div",{className:"space-y-3",children:[r("div",{className:"rounded border border-warning/30 bg-warning/10 px-3 py-2 text-xs text-warning",children:"Copy this token now. Once you close this dialog the secret cannot be displayed again."}),r("div",{className:"rounded border border-border bg-background p-2 font-mono text-[11px] break-all select-all",children:e})]}),u(o0,{children:[u("button",{onClick:()=>{a()},className:"inline-flex items-center gap-1.5 rounded bg-surface border border-border px-3 py-1.5 text-xs font-medium text-foreground hover:bg-primary/5 hover:border-primary/30",children:[o?r(Ct,{className:"h-3.5 w-3.5 text-primary"}):r(MD,{className:"h-3.5 w-3.5"}),o?"Copied":"Copy"]}),r("button",{onClick:n,className:"rounded bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90",children:"Done"})]})]})}function r0({title:e,onClose:t,children:n}){return r("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-background/80 backdrop-blur-sm",onClick:t,children:u("div",{className:"w-full max-w-md rounded-xl border border-border bg-surface shadow-2xl",onClick:o=>o.stopPropagation(),children:[u("div",{className:"flex items-start justify-between border-b border-border px-4 py-3",children:[r("h2",{className:"text-sm font-semibold text-foreground",children:e}),r("button",{onClick:t,className:"text-foreground-subtle hover:text-foreground",children:r(qe,{className:"h-4 w-4"})})]}),r("div",{className:"p-4",children:n})]})})}function o0({children:e}){return r("div",{className:"flex justify-end gap-2 border-t border-border px-4 py-3",children:e})}function ts({label:e,hint:t,children:n}){return u("div",{className:"space-y-1",children:[r("label",{className:"text-[10px] text-foreground-subtle uppercase tracking-wide",children:e}),n,t&&r("p",{className:"text-[10px] text-foreground-subtle",children:t})]})}const V8={local:"Local (username + password)",oidc:"OpenID Connect",saml:"SAML 2.0",ldap:"LDAP / Active Directory",other:"Custom"},yp={local:"bg-foreground-subtle/10 text-foreground",oidc:"bg-blue-500/15 text-blue-700 dark:text-blue-300",saml:"bg-purple-500/15 text-purple-700 dark:text-purple-300",ldap:"bg-amber-500/15 text-amber-700 dark:text-amber-300",other:"bg-slate-500/15 text-slate-700 dark:text-slate-300"};function q8(){const e=uc(),t=e.data??[];return r(It,{icon:xr,title:"Authentication",subtitle:"Login providers exposed to the admin UI. Local username + password is always available; OIDC / SAML / LDAP can be added by installing a provider addon.",actions:r(Kt,{to:"/system/addons",children:r(ze,{variant:"primary",size:"sm",children:"Add provider"})}),children:e.isLoading?r(Ge,{children:r("div",{className:"p-6 text-sm text-foreground-subtle",children:"Loading providers…"})}):t.length===0?r(Ge,{children:r(ko,{title:"No authentication providers registered",description:"Local auth should always be available — if this list is empty, the local-auth builtin failed to register. Check the Addons page for load errors."})}):r(Ge,{children:r("div",{className:"divide-y divide-border",children:t.map(n=>u("div",{className:"flex items-center gap-4 p-4",children:[r("div",{className:"h-10 w-10 rounded-lg bg-primary/10 text-primary flex items-center justify-center shrink-0",children:r(xr,{className:"h-5 w-5"})}),u("div",{className:"flex-1 min-w-0",children:[u("div",{className:"flex items-center gap-2",children:[r("span",{className:"font-semibold text-foreground",children:n.displayName}),r("span",{className:`text-[10px] rounded-full px-2 py-0.5 font-medium ${yp[n.kind]??yp.other}`,children:V8[n.kind]??n.kind}),!n.enabled&&r("span",{className:"text-[10px] rounded-full px-2 py-0.5 font-medium bg-red-500/15 text-red-700 dark:text-red-300",children:"Disabled"})]}),u("div",{className:"text-xs text-foreground-subtle mt-1 flex items-center gap-3",children:[r("span",{className:"font-mono",children:n.addonId}),n.hasCredentialFlow&&r("span",{children:"· username + password"}),n.hasRedirectFlow&&r("span",{children:"· redirect (SSO)"})]}),n.status&&r("div",{className:"text-xs text-foreground-subtle mt-1",children:n.status})]}),u(Kt,{to:`/system/addons?addon=${encodeURIComponent(n.addonId)}`,className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[r(wt,{className:"h-3.5 w-3.5"}),"Configure",r(Zx,{className:"h-3.5 w-3.5"})]})]},n.addonId))})})})}function Q8(){return r("div",{className:"flex flex-col",children:r("div",{className:"px-6 pt-6",children:r(td,{tabs:[{id:"users",label:"Users",icon:xy,content:r(_8,{})},{id:"api-keys",label:"Tokens",icon:ay,content:r(R8,{})},{id:"authentication",label:"Authentication",icon:xr,content:r(q8,{})}]})})})}function nd({addonId:e,defaultActivity:t,showActivity:n=!0,maxHeight:o="max-h-64",defaultTab:s}){const a=t??(s==="events"?"events":"logs"),[i,l]=$(a);return u("div",{className:"flex flex-col gap-4",children:[r(Rr,{nodeId:"hub",addonIds:[e],level:"global"}),n&&u("div",{className:"rounded-lg border border-border bg-surface overflow-hidden",children:[u("div",{className:"flex items-center justify-between px-3 py-2 border-b border-border bg-surface-hover/20",children:[r("span",{className:"text-[11px] font-semibold text-foreground-subtle uppercase tracking-wide",children:"Activity"}),u("div",{className:"flex items-center gap-1",children:[r(vp,{kind:"logs",active:i==="logs",onClick:()=>l("logs")}),r(vp,{kind:"events",active:i==="events",onClick:()=>l("events")})]})]}),i==="logs"?r(Wt,{addonId:e,maxHeight:o,showFilters:!1}):r(nr,{addonId:e,category:"addon.*",maxHeight:o})]})]})}function vp({kind:e,active:t,onClick:n}){return u("button",{onClick:n,className:`inline-flex items-center gap-1 rounded px-2 py-0.5 text-[11px] font-medium transition-colors ${t?"bg-primary/10 text-primary":"text-foreground-subtle hover:text-foreground hover:bg-surface-hover"}`,children:[r(e==="logs"?Xe:Ao,{className:"h-3 w-3"}),e==="logs"?"Logs":"Events"]})}const U8={"cloudflare-tunnel":"Cloudflare Tunnel",ngrok:"ngrok",tailscale:"Tailscale",other:"Custom"};function K8(){const e=ke(),t=qb(void 0,{refetchInterval:5e3}),n=t.data??[],[o,s]=$(null),a=()=>{e.invalidateQueries({queryKey:[["remoteAccess"]]}),s(null)},i=Qb({onSuccess:a,onError:()=>s(null)}),l=Ub({onSuccess:a,onError:()=>s(null)});return r(It,{icon:br,title:"Remote Access",subtitle:"Public-facing tunnels that expose this hub to the internet (Cloudflare Tunnel, ngrok, …). Settings, Logs and Events are docked under every provider.",actions:r(Kt,{to:"/system/addons",children:r(ze,{variant:"primary",size:"sm",children:"Add tunnel"})}),children:t.isLoading?r(Ge,{children:r("div",{className:"p-6 text-sm text-foreground-subtle",children:"Loading providers…"})}):n.length===0?r(Ge,{children:r(ko,{title:"No remote-access providers installed",description:"Install a tunnel addon (e.g. @camstack/addon-cloudflare-tunnel) to expose this hub publicly.",action:r(Kt,{to:"/system/addons",children:r(ze,{variant:"primary",size:"sm",children:"Browse addons"})})})}):r("div",{className:"flex flex-col gap-4",children:n.map(c=>{const d=o===c.addonId;return u(Ge,{children:[u("div",{className:"flex items-center gap-4 p-4 border-b border-border",children:[r("div",{className:`h-10 w-10 rounded-lg flex items-center justify-center shrink-0 ${c.connected?"bg-emerald-500/15 text-emerald-700 dark:text-emerald-300":"bg-foreground-subtle/15 text-foreground-subtle"}`,children:r(br,{className:"h-5 w-5"})}),u("div",{className:"flex-1 min-w-0",children:[u("div",{className:"flex items-center gap-2 flex-wrap",children:[r("span",{className:"font-semibold text-foreground",children:c.displayName}),r("span",{className:"text-[10px] rounded-full px-2 py-0.5 font-medium bg-blue-500/15 text-blue-700 dark:text-blue-300",children:U8[c.kind]??c.kind}),r("span",{className:`text-[10px] rounded-full px-2 py-0.5 font-medium ${c.connected?"bg-emerald-500/15 text-emerald-700 dark:text-emerald-300":"bg-foreground-subtle/15 text-foreground-subtle"}`,children:c.connected?"Connected":"Disconnected"})]}),r("div",{className:"text-xs text-foreground-subtle mt-1 font-mono",children:c.addonId}),c.endpoint&&u("div",{className:"text-xs text-emerald-700 dark:text-emerald-300 mt-1 flex items-center gap-1",children:[r(Gc,{className:"h-3 w-3"}),r("a",{href:c.endpoint.url,target:"_blank",rel:"noopener noreferrer",className:"hover:underline break-all",children:c.endpoint.url})]}),c.error&&r("div",{className:"text-xs text-danger mt-1",children:c.error})]}),r("div",{className:"flex items-center gap-1 shrink-0",children:c.connected?u(ze,{size:"sm",variant:"secondary",disabled:d,onClick:()=>{s(c.addonId),l.mutate({addonId:c.addonId})},children:[d?r(Pe,{className:"h-3 w-3 animate-spin"}):r(Eo,{className:"h-3 w-3"}),"Stop"]}):u(ze,{size:"sm",variant:"primary",disabled:d,onClick:()=>{s(c.addonId),i.mutate({addonId:c.addonId})},children:[d?r(Pe,{className:"h-3 w-3 animate-spin"}):r(va,{className:"h-3 w-3"}),"Start"]})})]}),r("div",{className:"p-4",children:r(nd,{addonId:c.addonId,maxHeight:"max-h-72"})})]},c.addonId)})})})}const G8={cloudflare:"Cloudflare TURN",coturn:"coturn (self-hosted)",twilio:"Twilio NTS",other:"Custom"};function W8(){const e=ke(),t=Zb(void 0,{refetchInterval:3e4}),n=Xb(),o=t.data??[],s=n.data??[],[a,i]=$(null),l=Jb({onSuccess:()=>{e.invalidateQueries({queryKey:[["turnOrchestrator"]]}),i(null)},onError:()=>i(null)});return r(It,{icon:an,title:"TURN Servers",subtitle:"ICE servers used for WebRTC NAT traversal. Multiple providers can coexist — the WebRTC layer concatenates servers from all enabled providers per session.",actions:r(Kt,{to:"/system/addons",children:r(ze,{variant:"primary",size:"sm",children:"Add provider"})}),children:t.isLoading?r(Ge,{children:r("div",{className:"p-6 text-sm text-foreground-subtle",children:"Loading providers…"})}):o.length===0?r(Ge,{children:r(ko,{title:"No TURN providers installed",description:"Install a TURN addon (e.g. @camstack/addon-cloudflare-turn) to enable WebRTC behind restrictive NATs.",action:r(Kt,{to:"/system/addons",children:r(ze,{variant:"primary",size:"sm",children:"Browse addons"})})})}):u("div",{className:"flex flex-col gap-4",children:[o.map(c=>{const d=a===c.addonId;return u(Ge,{children:[u("div",{className:"flex items-center gap-4 p-4 border-b border-border",children:[r("div",{className:`h-10 w-10 rounded-lg flex items-center justify-center shrink-0 ${c.error?"bg-danger/15 text-danger":c.enabled?"bg-violet-500/15 text-violet-700 dark:text-violet-300":"bg-foreground-subtle/15 text-foreground-subtle"}`,children:r(an,{className:"h-5 w-5"})}),u("div",{className:"flex-1 min-w-0",children:[u("div",{className:"flex items-center gap-2 flex-wrap",children:[r("span",{className:"font-semibold text-foreground",children:c.displayName}),r("span",{className:"text-[10px] rounded-full px-2 py-0.5 font-medium bg-violet-500/15 text-violet-700 dark:text-violet-300",children:G8[c.kind]??c.kind}),r("span",{className:`text-[10px] rounded-full px-2 py-0.5 font-medium ${c.enabled?"bg-emerald-500/15 text-emerald-700 dark:text-emerald-300":"bg-foreground-subtle/15 text-foreground-subtle"}`,children:c.enabled?"Enabled":"Disabled"})]}),u("div",{className:"text-xs text-foreground-subtle mt-1 flex items-center gap-3",children:[r("span",{className:"font-mono",children:c.addonId}),u("span",{children:["· ",c.serverCount," server",c.serverCount===1?"":"s"]})]}),c.error&&r("div",{className:"text-xs text-danger mt-1",children:c.error})]}),r("div",{className:"flex items-center gap-1 shrink-0",children:c.enabled?u(ze,{size:"sm",variant:"secondary",disabled:d,onClick:()=>{i(c.addonId),l.mutate({addonId:c.addonId,enabled:!1})},children:[d?r(Pe,{className:"h-3 w-3 animate-spin"}):r(Eo,{className:"h-3 w-3"}),"Disable"]}):u(ze,{size:"sm",variant:"primary",disabled:d,onClick:()=>{i(c.addonId),l.mutate({addonId:c.addonId,enabled:!0})},children:[d?r(Pe,{className:"h-3 w-3 animate-spin"}):r(va,{className:"h-3 w-3"}),"Enable"]})})]}),c.urls.length>0&&u("div",{className:"px-4 py-3 border-b border-border",children:[u("div",{className:"text-[11px] font-semibold text-foreground-subtle uppercase tracking-wide mb-2",children:["Discovered ICE servers (",c.urls.length,")"]}),r("div",{className:"flex flex-wrap gap-1",children:c.urls.map(f=>r("span",{className:"inline-block rounded px-1.5 py-0.5 text-[10px] font-mono bg-foreground-subtle/10 text-foreground",children:f},f))})]}),r("div",{className:"p-4",children:r(nd,{addonId:c.addonId,maxHeight:"max-h-72"})})]},c.addonId)}),u(Ge,{children:[u("div",{className:"px-4 py-3 border-b border-border flex items-center justify-between",children:[u("div",{children:[r("div",{className:"text-sm font-semibold",children:"Combined ICE server list"}),r("div",{className:"text-xs text-foreground-subtle",children:"What the WebRTC layer fetches per-session."})]}),r(ze,{size:"sm",variant:"secondary",onClick:()=>n.refetch(),disabled:n.isFetching,children:"Refresh"})]}),r("div",{className:"p-4",children:s.length===0?r("div",{className:"text-xs text-foreground-subtle",children:"No servers from enabled providers."}):r("div",{className:"flex flex-col gap-3",children:s.map((c,d)=>{const f=Array.isArray(c.urls)?c.urls:[c.urls];return u("div",{className:"rounded border border-border bg-surface",children:[(c.username||c.credential)&&u("div",{className:"px-3 py-1.5 border-b border-border text-[10px] font-mono text-foreground-subtle flex items-center gap-3",children:[c.username&&u("span",{children:[r("span",{className:"text-foreground-subtle",children:"user:"})," ",r("span",{className:"text-foreground",children:c.username})]}),c.credential&&u("span",{title:c.credential,children:[r("span",{className:"text-foreground-subtle",children:"credential:"})," ",r("span",{className:"text-foreground",children:`${c.credential.slice(0,8)}…${c.credential.slice(-4)}`})]})]}),r("ul",{className:"divide-y divide-border",children:f.map(p=>r("li",{className:"px-3 py-1.5 font-mono text-xs text-foreground break-all",children:p},p))})]},d)})})})]})]})})}const Y8={lan:an,wifi:jn,docker:ba,vpn:ly,loopback:ln,other:ln},Z8={lan:"LAN",wifi:"Wi-Fi",docker:"Docker",vpn:"VPN",loopback:"Loopback",other:"Other"},X8=["lan","wifi","vpn","docker","other","loopback"];function J8(e){const{interfaces:t,disabled:n,hideLoopback:o,ipv4Only:s,emptyMessage:a}=e,i=Q(()=>t.filter(f=>!(o&&f.kind==="loopback"||s&&f.family!=="IPv4")),[t,o,s]),l=Q(()=>{const f=new Map;for(const p of i){const m=f.get(p.kind)??[];m.push(p),f.set(p.kind,m)}return X8.filter(p=>f.has(p)).map(p=>({kind:p,items:f.get(p)}))},[i]),c=f=>e.mode==="single"?e.value===f:e.value.includes(f),d=f=>{if(n||f.kind==="loopback")return;if(e.mode==="single"){e.onChange(e.value===f.address?null:f.address);return}const p=new Set(e.value);p.has(f.address)?p.delete(f.address):p.add(f.address),e.onChange([...p])};return i.length===0?r("div",{className:"text-xs text-foreground-subtle italic",children:a??"No addresses available."}):r("div",{className:"flex flex-col gap-3",children:l.map(({kind:f,items:p})=>{const m=Y8[f]??ln;return u("div",{className:"rounded-md border border-border overflow-hidden",children:[u("div",{className:"flex items-center gap-2 px-3 py-1.5 bg-surface-hover/30 border-b border-border",children:[r(m,{className:"h-3.5 w-3.5 text-foreground-subtle"}),r("span",{className:"text-[11px] font-semibold uppercase tracking-wide text-foreground-subtle",children:Z8[f]??f}),u("span",{className:"text-[10px] text-foreground-subtle",children:["· ",p.length]})]}),r("ul",{className:"divide-y divide-border",children:p.map(h=>{const g=c(h.address),b=h.kind==="loopback",x=!h.plausible&&!b;return u("li",{className:`flex items-center gap-3 px-3 py-2 ${b?"opacity-60 cursor-not-allowed":n?"opacity-60":x?"cursor-pointer hover:bg-surface-hover/30 bg-amber-500/[0.04]":"cursor-pointer hover:bg-surface-hover/30"}`,onClick:()=>d(h),children:[r("span",{className:`flex items-center justify-center h-4 w-4 rounded ${e.mode==="single"?"rounded-full":"rounded"} border ${g?"border-primary bg-primary text-primary-foreground":"border-border bg-surface"}`,children:g&&r(Ct,{className:"h-3 w-3"})}),u("div",{className:`flex-1 min-w-0 ${x?"text-foreground-subtle":""}`,children:[u("div",{className:"flex items-center gap-2 flex-wrap",children:[r("span",{className:`font-mono text-xs font-semibold ${x?"text-foreground-subtle":"text-foreground"}`,children:h.name}),r("span",{className:"text-[10px] rounded px-1.5 py-0.5 bg-foreground-subtle/10 text-foreground-subtle font-mono",children:h.family}),h.preferred&&r("span",{className:"text-[10px] rounded-full px-2 py-0.5 font-medium bg-primary/15 text-primary",children:"Auto-preferred"}),b&&r("span",{className:"text-[10px] rounded-full px-2 py-0.5 font-medium bg-foreground-subtle/15 text-foreground-subtle",children:"Always included"}),x&&u("span",{className:"inline-flex items-center gap-1 text-[10px] rounded-full px-2 py-0.5 font-medium bg-amber-500/15 text-amber-700 dark:text-amber-300",title:h.plausibleReason||void 0,children:[r(xt,{className:"h-2.5 w-2.5"}),"Unlikely usable"]})]}),u("div",{className:"text-xs text-foreground-subtle mt-0.5 font-mono break-all",children:[h.address,h.cidr&&h.cidr!==h.address?` (${h.cidr})`:""]})]})]},`${h.name}-${h.family}-${h.address}`)})})]},f)})})}const wp={"lan-ipv4":"bg-emerald-500/15 text-emerald-700 dark:text-emerald-300","lan-ipv6":"bg-violet-500/15 text-violet-700 dark:text-violet-300",public:"bg-blue-500/15 text-blue-700 dark:text-blue-300",loopback:"bg-foreground-subtle/15 text-foreground-subtle"};function e9(){const e=ke(),t=Le(),n=Hg(void 0,{refetchInterval:3e4}),o=qg(void 0),s=Qg({onSuccess:()=>{e.invalidateQueries({queryKey:[["localNetwork"]]})}}),a=Ug({onSuccess:S=>{p(S.addresses),e.invalidateQueries({queryKey:[["localNetwork"]]})}}),i=Q(()=>n.data?.interfaces??[],[n.data]),l=typeof window<"u"?Number(window.location.port)||(window.location.protocol==="https:"?443:80):4e3,c=typeof window<"u"&&window.location.protocol==="https:"?"https":"http",d=Vg({port:l,scheme:c},{refetchInterval:3e4}),[f,p]=$([]),[m,h]=$(!1);Y(()=>{!m&&o.data&&(p(o.data.addresses),h(!0))},[o.data,m]);const g=o.data?.addresses??[],b=Q(()=>{if(f.length!==g.length)return!0;const S=[...f].sort(),M=[...g].sort();return S.some((P,I)=>P!==M[I])},[f,g]),x=()=>{s.mutate({addresses:[...f]})},v=()=>{p(g)},w=()=>{p([])},y=()=>{n.refetch(),d.refetch(),o.refetch()},N=async()=>{try{const S=await t.raceConnectionEndpoints({perCandidateTimeoutMs:1500});console.info("[network-addresses] race result",S)}catch(S){console.warn("[network-addresses] race failed",S)}},k=d.data?.endpoints??[];return r(It,{icon:an,title:"Network Addresses",subtitle:"Pick the local addresses SDK clients should race for the fastest path to this hub. Empty selection (auto) lets every non-loopback / non-link-local interface participate.",actions:u("div",{className:"flex items-center gap-2",children:[u(ze,{size:"sm",variant:"secondary",onClick:y,disabled:n.isLoading,children:[r(pt,{className:`h-3 w-3 ${n.isLoading?"animate-spin":""}`}),"Refresh"]}),r(ze,{size:"sm",variant:"secondary",onClick:N,children:"Probe race"})]}),children:u("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:[u(Ge,{children:[u("div",{className:"px-4 py-3 border-b border-border flex items-center justify-between",children:[u("div",{children:[r("div",{className:"text-sm font-semibold",children:"Allowed addresses"}),r("div",{className:"text-xs text-foreground-subtle",children:f.length===0?"Auto — every non-loopback / non-link-local interface participates.":`${f.length} pinned`})]}),u("div",{className:"flex items-center gap-1",children:[u(ze,{size:"sm",variant:"secondary",onClick:()=>a.mutate(void 0),disabled:a.isPending||s.isPending,title:"Re-run the auto-detection heuristic + overwrite the current allowlist with the best matches.",children:[r(eT,{className:"h-3 w-3"}),a.isPending?"Detecting…":"Best match"]}),u(ze,{size:"sm",variant:"secondary",onClick:w,disabled:f.length===0||s.isPending,children:[r(my,{className:"h-3 w-3"}),"Clear"]}),b&&r(ze,{size:"sm",variant:"secondary",onClick:v,disabled:s.isPending,children:"Discard"}),u(ze,{size:"sm",variant:"primary",onClick:x,disabled:!b||s.isPending,children:[r(FL,{className:"h-3 w-3"}),s.isPending?"Saving…":"Save"]})]})]}),r("div",{className:"p-4",children:r(J8,{mode:"multiple",interfaces:i,value:f,onChange:p,disabled:s.isPending,emptyMessage:n.isLoading?"Loading interfaces…":"No interfaces detected."})})]}),u(Ge,{children:[u("div",{className:"px-4 py-3 border-b border-border",children:[r("div",{className:"text-sm font-semibold",children:"Connection endpoints — priority order"}),r("div",{className:"text-xs text-foreground-subtle",children:"Live preview of the ranked candidate list the SDK would race against. Updates with each Save."})]}),r("div",{className:"p-4",children:k.length===0?r("div",{className:"text-xs text-foreground-subtle italic",children:d.isLoading?"Loading…":"No endpoints available."}):r("ul",{className:"space-y-1 text-xs",children:k.map(S=>u("li",{className:`flex items-center gap-2 flex-wrap ${S.plausible?"":"opacity-80"}`,children:[r("span",{className:"font-mono text-[10px] w-10 text-foreground-subtle",children:String(S.priority).padStart(4,"0")}),r("span",{className:`text-[10px] rounded-full px-2 py-0.5 font-medium ${wp[S.kind]??wp.loopback}`,children:S.kind}),S.interfaceKind!=="lan"&&S.interfaceKind!=="public"&&r("span",{className:"text-[10px] rounded px-1.5 py-0.5 bg-foreground-subtle/10 text-foreground-subtle font-medium uppercase",children:S.interfaceKind}),!S.plausible&&S.interfaceKind!=="loopback"&&u("span",{className:"inline-flex items-center gap-1 text-[10px] rounded-full px-2 py-0.5 font-medium bg-amber-500/15 text-amber-700 dark:text-amber-300",title:S.plausibleReason||void 0,children:[r(xt,{className:"h-2.5 w-2.5"}),"Unlikely usable"]}),r("span",{className:`font-mono break-all ${S.plausible?"text-foreground":"text-foreground-subtle"}`,children:S.baseUrl}),u("span",{className:"text-foreground-subtle",children:["— ",S.label]})]},`${S.priority}-${S.baseUrl}`))})})]})]})})}const t9={tailscale:"Tailscale",headscale:"Headscale",zerotier:"ZeroTier",other:"Custom"},n9={mesh:"bg-violet-500/15 text-violet-700 dark:text-violet-300",public:"bg-blue-500/15 text-blue-700 dark:text-blue-300"};function r9(){const e=ke(),t=Kg(void 0,{refetchInterval:5e3}),n=t.data??[],[o,s]=$(null),[a,i]=$({}),[l,c]=$({}),d=()=>{e.invalidateQueries({queryKey:[["meshOrchestrator"]]}),s(null)},f=Gg({onSuccess:d,onError:()=>s(null)}),p=Wg({onSuccess:d,onError:()=>s(null)});return r(It,{icon:ba,title:"Mesh Networks",subtitle:"Private VPN meshes that connect CamStack to your other devices (Tailscale, Headscale, …). Each provider can also expose this hub publicly via its ingress (Tailscale Funnel).",actions:r(Kt,{to:"/system/addons",children:r(ze,{variant:"primary",size:"sm",children:"Add mesh"})}),children:t.isLoading?r(Ge,{children:r("div",{className:"p-6 text-sm text-foreground-subtle",children:"Loading providers…"})}):n.length===0?r(Ge,{children:r(ko,{title:"No mesh-network providers installed",description:"Install a mesh addon (e.g. @camstack/addon-tailscale) to join this hub into a private VPN mesh.",action:r(Kt,{to:"/system/addons",children:r(ze,{variant:"primary",size:"sm",children:"Browse addons"})})})}):r("div",{className:"flex flex-col gap-4",children:n.map(m=>{const h=o===m.addonId,g=a[m.addonId]??"",b=l[m.addonId]??"",x=g.trim().length>=8;return u(Ge,{children:[u("div",{className:"flex items-start gap-4 p-4 border-b border-border",children:[r("div",{className:`h-10 w-10 rounded-lg flex items-center justify-center shrink-0 ${m.joined?"bg-emerald-500/15 text-emerald-700 dark:text-emerald-300":"bg-foreground-subtle/15 text-foreground-subtle"}`,children:r(an,{className:"h-5 w-5"})}),u("div",{className:"flex-1 min-w-0",children:[u("div",{className:"flex items-center gap-2 flex-wrap",children:[r("span",{className:"font-semibold text-foreground",children:m.displayName}),r("span",{className:"text-[10px] rounded-full px-2 py-0.5 font-medium bg-blue-500/15 text-blue-700 dark:text-blue-300",children:t9[m.kind]??m.kind}),r("span",{className:`text-[10px] rounded-full px-2 py-0.5 font-medium ${m.joined?"bg-emerald-500/15 text-emerald-700 dark:text-emerald-300":"bg-foreground-subtle/15 text-foreground-subtle"}`,children:m.joined?"Joined":"Not joined"}),m.joined&&u("span",{className:"text-[10px] rounded-full px-2 py-0.5 font-medium bg-foreground-subtle/15 text-foreground-subtle",children:[m.peerCount," peer",m.peerCount===1?"":"s"]})]}),r("div",{className:"text-xs text-foreground-subtle mt-1 font-mono",children:m.addonId}),m.joined&&u("div",{className:"mt-2 grid grid-cols-1 sm:grid-cols-2 gap-x-4 gap-y-1 text-xs",children:[m.meshIp&&u("div",{className:"flex items-center gap-1.5",children:[r("span",{className:"text-foreground-subtle",children:"Mesh IP:"}),r("span",{className:"font-mono text-foreground",children:m.meshIp})]}),m.magicDnsHostname&&u("div",{className:"flex items-center gap-1.5",children:[r("span",{className:"text-foreground-subtle",children:"MagicDNS:"}),r("span",{className:"font-mono text-foreground break-all",children:m.magicDnsHostname})]})]}),m.joined&&m.endpoints.length>0&&u("div",{className:"mt-3 flex flex-col gap-1",children:[r("div",{className:"text-[11px] font-semibold text-foreground-subtle uppercase tracking-wide",children:"Endpoints"}),m.endpoints.map(v=>u("div",{className:"flex items-center gap-2 text-xs",children:[u("span",{className:`text-[10px] rounded-full px-2 py-0.5 font-medium ${n9[v.scope]??"bg-foreground-subtle/15 text-foreground-subtle"}`,children:[v.scope==="public"?r(br,{className:"inline h-2.5 w-2.5 mr-0.5"}):null,v.label]}),u("a",{href:v.url,target:"_blank",rel:"noopener noreferrer",className:"text-emerald-700 dark:text-emerald-300 hover:underline break-all flex items-center gap-1",children:[r(Gc,{className:"h-3 w-3 shrink-0"}),v.url]})]},v.id))]}),m.error&&r("div",{className:"text-xs text-danger mt-2",children:m.error})]}),r("div",{className:"flex flex-col items-end gap-2 shrink-0",children:m.joined?u(ze,{size:"sm",variant:"secondary",disabled:h,onClick:()=>{s(m.addonId),p.mutate({addonId:m.addonId})},children:[h?r(Pe,{className:"h-3 w-3 animate-spin"}):r(cy,{className:"h-3 w-3"}),"Leave"]}):u("div",{className:"flex flex-col gap-1.5 items-stretch w-64",children:[r("input",{type:"password",autoComplete:"off",placeholder:"Auth key (tskey-auth-…)",value:g,onChange:v=>i(w=>({...w,[m.addonId]:v.target.value})),className:"rounded-md border border-border bg-surface px-2 py-1 text-xs font-mono text-foreground placeholder:text-foreground-subtle focus:outline-none focus:ring-1 focus:ring-primary"}),r("input",{type:"text",placeholder:"Hostname (optional)",value:b,onChange:v=>c(w=>({...w,[m.addonId]:v.target.value})),className:"rounded-md border border-border bg-surface px-2 py-1 text-xs font-mono text-foreground placeholder:text-foreground-subtle focus:outline-none focus:ring-1 focus:ring-primary"}),u(ze,{size:"sm",variant:"primary",disabled:h||!x,onClick:()=>{s(m.addonId),f.mutate({addonId:m.addonId,authKey:g.trim(),hostname:b.trim()?b.trim():void 0})},children:[h?r(Pe,{className:"h-3 w-3 animate-spin"}):r(iL,{className:"h-3 w-3"}),"Join"]})]})})]}),r("div",{className:"p-4",children:r(nd,{addonId:m.addonId,maxHeight:"max-h-72"})})]},m.addonId)})})})}function o9(){return r("div",{className:"flex flex-col",children:r("div",{className:"px-6 pt-6",children:r(td,{tabs:[{id:"addresses",label:"Network Addresses",icon:ln,content:r(e9,{})},{id:"remote-access",label:"Remote Access",icon:br,content:r(K8,{})},{id:"mesh",label:"Mesh Networks",icon:ba,content:r(r9,{})},{id:"turn",label:"TURN Servers",icon:an,content:r(W8,{})}]})})})}function s9(e){const t=e.basePath;if(typeof t=="string"&&t.length>0)return t;const n=Object.keys(e);return n.length===0?"":n.join(", ")}function a9({location:e,onEdit:t,onDelete:n,onSetDefault:o}){const s=s9(e.config);return u("div",{className:"flex items-center gap-3 px-3 py-2 border-t border-border first:border-t-0 hover:bg-primary/5",children:[u("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:[r("div",{className:"w-[88px] shrink-0",children:e.isDefault?u("span",{className:"inline-flex items-center gap-0.5 rounded bg-primary/10 border border-primary/20 px-1.5 py-0.5 text-[10px] font-semibold text-primary uppercase tracking-wide",title:"Default location for this type",children:[r(oi,{className:"h-2.5 w-2.5 fill-primary"}),"Default"]}):u("button",{onClick:()=>o(e),className:"inline-flex items-center gap-0.5 rounded border border-border px-1.5 py-0.5 text-[10px] font-medium text-foreground-subtle hover:text-foreground hover:bg-primary/10 hover:border-primary/30 uppercase tracking-wide",title:"Promote to default for this type",children:[r(oi,{className:"h-2.5 w-2.5"}),"Set default"]})}),r("span",{className:"text-[10px] uppercase tracking-wide text-foreground-subtle bg-background border border-border rounded px-1.5 py-0.5 font-mono",children:e.providerId}),e.isSystem&&r("span",{className:"text-[10px] uppercase tracking-wide text-foreground-subtle bg-background border border-border rounded px-1.5 py-0.5",title:"System-managed location — cannot be deleted; edit config to relocate",children:"system"}),u("div",{className:"min-w-0",children:[r("div",{className:"text-xs font-medium text-foreground truncate",children:e.displayName}),s&&r("div",{className:"text-[10px] text-foreground-subtle truncate font-mono",children:s})]})]}),u("div",{className:"flex items-center gap-1 shrink-0",children:[!e.isDefault&&u("button",{onClick:()=>o(e),className:"inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] font-medium text-foreground-subtle border border-border hover:text-foreground hover:bg-primary/10",title:"Set as default for this type",children:[r(oi,{className:"h-3 w-3"}),"Set default"]}),u("button",{onClick:()=>t(e),className:"inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] font-medium text-foreground-subtle border border-border hover:text-foreground hover:bg-primary/10",children:[r(Po,{className:"h-3 w-3"}),"Edit"]}),!e.isSystem&&ps[e.type]!=="singleton"&&r("button",{onClick:()=>n(e),className:"inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] font-medium text-danger hover:bg-danger/10",title:"Delete location",children:r(We,{className:"h-3 w-3"})})]})]})}function i9({type:e,displayName:t,description:n,locations:o,onAdd:s,onEdit:a,onDelete:i,onSetDefault:l}){const c=Q(()=>{const d=[...o];return d.sort((f,p)=>f.isDefault!==p.isDefault?f.isDefault?-1:1:f.displayName.localeCompare(p.displayName)),d},[o]);return u("div",{className:"rounded-lg border border-border bg-surface",children:[u("div",{className:"flex items-start justify-between border-b border-border px-3 py-2",children:[u("div",{className:"space-y-0.5",children:[u("div",{className:"flex items-center gap-2",children:[r("span",{className:"text-sm font-semibold text-foreground capitalize",children:t}),r("span",{className:"text-[10px] uppercase tracking-wide text-foreground-subtle bg-background border border-border rounded px-1.5 py-0.5 font-mono",children:e})]}),n&&r("p",{className:"text-[11px] text-foreground-subtle",children:n}),ps[e]==="singleton"&&r("p",{className:"text-[10px] text-foreground-subtle italic",children:"Singleton — one location per type. Edit the existing entry; it can't be split."})]}),ps[e]==="multi"&&u("button",{onClick:()=>s(e),className:"inline-flex items-center gap-1 rounded bg-primary px-2 py-1 text-[11px] font-medium text-primary-foreground hover:bg-primary/90",children:[r(Ot,{className:"h-3 w-3"}),"Add"]})]}),c.length===0?r("div",{className:"px-3 py-4 text-center text-[11px] text-foreground-subtle italic",children:ps[e]==="multi"?'No location registered. Click "Add" to register one.':"No location registered yet — should be auto-seeded at next boot."}):r("div",{children:c.map(d=>r(a9,{location:d,onEdit:a,onDelete:i,onSetDefault:l},d.id))})]})}function l9(e){const t=e.trim().toLowerCase();return t.length===0?"":t.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Np(e,t){const n=l9(t),o=n.length>0?n:"default";return`${e}:${o}`}function s0({initialType:e,onClose:t,onCreated:n}){const o=ke(),s=Le().trpcClient,[a,i]=$("picker"),[l,c]=$(e),[d,f]=$(null),[p,m]=$({}),[h,g]=$(""),[b,x]=$(null),[v,w]=$(!1),[y,N]=$(null),[k,S]=$(!1),M=Nc(),P=Q(()=>{const D=M.data;return Array.isArray(D)?D.filter(R=>R.supportedLocationTypes.includes(l)):[]},[M.data,l]),I=M.isLoading,F=da({onSuccess:()=>{o.invalidateQueries({queryKey:[["storage","listLocations"]]}),n()}}),E=Q(()=>b!==null&&b.length>0?b:Np(l,h),[l,h,b]),B=async()=>{if(d){S(!0),N(null);try{const R=await(L=>s.storage.testConfig.query(L))({providerId:d.providerId,config:p});N(R)}catch(D){N({ok:!1,error:D instanceof Error?D.message:String(D)})}finally{S(!1)}}},O=()=>{d&&F.mutate({id:E,type:l,displayName:h.trim(),providerId:d.providerId,config:p,isDefault:v})},A={picker:"Add Location — Pick provider",config:`Add Location — ${d?.displayName??""}`,naming:"Add Location — Name & defaults"};return r("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-background/80 backdrop-blur-sm",onClick:t,children:u("div",{className:"w-full max-w-md rounded-xl border border-border bg-surface shadow-2xl",onClick:D=>D.stopPropagation(),children:[u("div",{className:"flex items-start justify-between border-b border-border px-4 py-3",children:[u("div",{className:"space-y-0.5",children:[r("h2",{className:"text-sm font-semibold text-foreground",children:A[a]}),u("p",{className:"text-xs text-foreground-subtle",children:["Type: ",r("span",{className:"font-mono",children:l})]})]}),r("button",{onClick:t,className:"text-foreground-subtle hover:text-foreground",children:r(qe,{className:"h-4 w-4"})})]}),a==="picker"&&u("div",{className:"p-4 space-y-2",children:[I&&r("div",{className:"text-xs text-foreground-subtle animate-pulse",children:"Loading providers…"}),!I&&P.length===0&&u("div",{className:"rounded border border-border bg-background px-3 py-4 text-center text-xs text-foreground-subtle",children:['No storage-provider supports type "',l,'". Install a compatible addon (e.g. ',r("code",{className:"font-mono",children:"remote-storage"}),") to enable it."]}),P.map(D=>u("button",{onClick:()=>{f(D),i("config")},className:"flex w-full items-center gap-3 rounded-lg border border-border bg-background p-3 text-left hover:border-primary/40 hover:bg-primary/5 transition-colors",children:[u("div",{className:"flex-1 min-w-0",children:[r("p",{className:"text-xs font-semibold text-foreground",children:D.displayName}),r("p",{className:"text-[10px] text-foreground-subtle font-mono mt-0.5 truncate",children:D.providerId})]}),r(Mt,{className:"h-4 w-4 text-foreground-subtle flex-shrink-0"})]},D.providerId))]}),a==="config"&&d&&u("div",{className:"p-4 space-y-3 max-h-[60vh] overflow-y-auto",children:[r(Nn,{schema:d.configSchema,values:p,onChange:m}),y&&r("div",{className:`rounded border px-3 py-2 text-[11px] ${y.ok?"border-success/30 bg-success/5 text-success":"border-danger/30 bg-danger/5 text-danger"}`,children:y.ok?"Connection OK.":`Test failed: ${y.error??"unknown error"}`}),u("div",{className:"flex items-center justify-between pt-1",children:[r("button",{onClick:()=>i("picker"),className:"rounded px-3 py-1.5 text-xs text-foreground-subtle border border-border hover:text-foreground",children:"Back"}),u("div",{className:"flex items-center gap-2",children:[r("button",{onClick:()=>{B()},disabled:k,className:"rounded border border-border px-3 py-1.5 text-xs text-foreground hover:bg-primary/10 disabled:opacity-50",children:k?"Testing…":"Test connection"}),r("button",{onClick:()=>i("naming"),className:"rounded bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90",children:"Next"})]})]})]}),a==="naming"&&d&&u("div",{className:"p-4 space-y-3",children:[u("div",{className:"space-y-1",children:[r("label",{className:"text-[10px] uppercase tracking-wide text-foreground-subtle",children:"Display name"}),r("input",{type:"text",value:h,onChange:D=>g(D.target.value),placeholder:`${l} on ${d.displayName}`,className:"w-full rounded border border-border bg-background px-2 py-1.5 text-xs text-foreground focus:outline-none focus:ring-1 focus:ring-primary"})]}),u("div",{className:"space-y-1",children:[u("label",{className:"text-[10px] uppercase tracking-wide text-foreground-subtle",children:["Id ",r("span",{className:"lowercase tracking-normal text-foreground-subtle",children:"— auto-derived; override if needed"})]}),r("input",{type:"text",value:E,onChange:D=>x(D.target.value),placeholder:Np(l,h),className:"w-full rounded border border-border bg-background px-2 py-1.5 text-xs text-foreground font-mono focus:outline-none focus:ring-1 focus:ring-primary"}),u("p",{className:"text-[10px] text-foreground-subtle",children:["Format: ",r("code",{className:"font-mono",children:"<type>:<slug>"}),". Lowercase letters, digits, and hyphens only."]})]}),u("label",{className:"flex items-start gap-2 rounded border border-border bg-background px-3 py-2 cursor-pointer hover:bg-primary/5",children:[r("input",{type:"checkbox",checked:v,onChange:D=>w(D.target.checked),className:"accent-primary mt-0.5"}),u("div",{className:"space-y-0.5",children:[u("div",{className:"text-xs font-medium text-foreground",children:['Mark as default for type "',l,'"']}),u("div",{className:"text-[10px] text-foreground-subtle",children:["Setting this as default will demote the current default for this type. References like"," ",u("code",{className:"font-mono",children:['"',l,'"']})," resolve to whichever location is the default."]})]})]}),F.isError&&r("div",{className:"rounded border border-danger/30 bg-danger/5 text-danger px-3 py-2 text-[11px]",children:F.error instanceof Error?F.error.message:String(F.error)}),u("div",{className:"flex items-center justify-between pt-1",children:[r("button",{onClick:()=>i("config"),className:"rounded px-3 py-1.5 text-xs text-foreground-subtle border border-border hover:text-foreground",children:"Back"}),u("div",{className:"flex items-center gap-2",children:[r("button",{onClick:()=>{c(e),f(null),m({}),g(""),x(null),w(!1),N(null),i("picker")},className:"rounded px-3 py-1.5 text-xs text-foreground-subtle border border-border hover:text-foreground",children:"Reset"}),u("button",{onClick:O,disabled:F.isPending||h.trim().length===0,className:"inline-flex items-center gap-1.5 rounded bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50",children:[F.isPending?r(Pe,{className:"h-3.5 w-3.5 animate-spin"}):null,F.isPending?"Saving…":"Save"]})]})]})]})]})})}function c9({location:e,onClose:t,onSaved:n}){const o=ke(),s=Le().trpcClient,[a,i]=$({...e.config}),[l,c]=$(e.displayName),[d,f]=$(null),[p,m]=$(!1),h=Nc(),g=Q(()=>{const w=h.data;return Array.isArray(w)?w.find(N=>N.providerId===e.providerId)??null:null},[h.data,e.providerId]),b=da({onSuccess:()=>{o.invalidateQueries({queryKey:[["storage","listLocations"]]}),n()}}),x=async()=>{m(!0),f(null);try{const y=await(N=>s.storage.testConfig.query(N))({providerId:e.providerId,config:a});f(y)}catch(w){f({ok:!1,error:w instanceof Error?w.message:String(w)})}finally{m(!1)}},v=()=>{b.mutate({id:e.id,type:e.type,providerId:e.providerId,isDefault:e.isDefault,displayName:l.trim(),config:a})};return r("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-background/80 backdrop-blur-sm",onClick:t,children:u("div",{className:"w-full max-w-md rounded-xl border border-border bg-surface shadow-2xl",onClick:w=>w.stopPropagation(),children:[u("div",{className:"flex items-start justify-between border-b border-border px-4 py-3",children:[u("div",{className:"space-y-0.5",children:[u("h2",{className:"text-sm font-semibold text-foreground",children:["Edit ",e.displayName]}),u("p",{className:"text-xs text-foreground-subtle",children:[r("span",{className:"font-mono",children:e.id})," · ",g?.displayName??e.providerId]})]}),r("button",{onClick:t,className:"text-foreground-subtle hover:text-foreground",children:r(qe,{className:"h-4 w-4"})})]}),u("div",{className:"p-4 space-y-3 max-h-[60vh] overflow-y-auto",children:[u("div",{className:"space-y-1",children:[r("label",{className:"text-[10px] uppercase tracking-wide text-foreground-subtle",children:"Display name"}),r("input",{type:"text",value:l,onChange:w=>c(w.target.value),className:"w-full rounded border border-border bg-background px-2 py-1.5 text-xs text-foreground focus:outline-none focus:ring-1 focus:ring-primary"})]}),g&&r(Nn,{schema:g.configSchema,values:a,onChange:i}),!g&&!h.isLoading&&u("div",{className:"rounded border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-[11px] text-amber-700 dark:text-amber-300",children:["Provider ",r("code",{className:"font-mono",children:e.providerId})," is no longer registered. Field schema unavailable; raw config is preserved on save."]}),d&&r("div",{className:`rounded border px-3 py-2 text-[11px] ${d.ok?"border-success/30 bg-success/5 text-success":"border-danger/30 bg-danger/5 text-danger"}`,children:d.ok?"Connection OK.":`Test failed: ${d.error??"unknown error"}`}),b.isError&&r("div",{className:"rounded border border-danger/30 bg-danger/5 text-danger px-3 py-2 text-[11px]",children:b.error instanceof Error?b.error.message:String(b.error)})]}),u("div",{className:"flex items-center justify-between gap-2 border-t border-border px-4 py-3",children:[r("button",{onClick:t,className:"rounded px-3 py-1.5 text-xs text-foreground-subtle border border-border hover:text-foreground",children:"Cancel"}),u("div",{className:"flex items-center gap-2",children:[r("button",{onClick:()=>{x()},disabled:p||!g,className:"rounded border border-border px-3 py-1.5 text-xs text-foreground hover:bg-primary/10 disabled:opacity-50",children:p?"Testing…":"Test connection"}),u("button",{onClick:v,disabled:b.isPending||l.trim().length===0,className:"inline-flex items-center gap-1.5 rounded bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50",children:[b.isPending?r(Pe,{className:"h-3.5 w-3.5 animate-spin"}):null,b.isPending?"Saving…":"Save"]})]})]})]})})}const d9={data:"Data",media:"Media",recordings:"Recordings","recordings-high":"Recordings (High)","recordings-low":"Recordings (Low)","recordings-clips":"Recordings (Clips)","event-images":"Event Images",models:"Models","addons-data":"Addons Data",cache:"Cache",logs:"Logs",backups:"Backups"},u9={backups:"Snapshot archives. Default landing for `backup-orchestrator`.",recordings:"Continuous recordings (combined high + low + clips when no slot is specified).","recordings-high":"High-quality continuous recordings.","recordings-low":"Low-quality continuous recordings.","recordings-clips":"Event clips (motion / detection triggers).","event-images":"Detection snapshots, thumbnails, and crops.",models:"ML model files. Read by inference-engine addons.",logs:"Long-term log archives."};function p9(){const e=ke(),t=rt(),{data:n,isLoading:o,isError:s}=Kb({}),[a,i]=$(null),[l,c]=$(null),d=Gb({onSuccess:()=>{e.invalidateQueries({queryKey:[["storage","listLocations"]]})}}),f=da({onSuccess:()=>{e.invalidateQueries({queryKey:[["storage","listLocations"]]})}}),p=g=>{g.isDefault||f.mutate({id:g.id,type:g.type,providerId:g.providerId,displayName:g.displayName,config:g.config,isDefault:!0})},m=async g=>{if(g.isDefault){await t({title:"Cannot delete default location",message:`"${g.displayName}" is the default for type "${g.type}". Mark another location as default first, then delete this one.`,confirmLabel:"OK",variant:"warning"});return}await t({title:`Delete location "${g.displayName}"?`,message:"This removes the location record. Files on disk are not deleted; the underlying directory or remote path stays untouched.",confirmLabel:"Delete",variant:"danger"})&&d.mutate({id:g.id})},h=Q(()=>{const g=new Map;for(const b of Ed)g.set(b,[]);for(const b of n??[]){const x=g.get(b.type);x?x.push(b):g.set(b.type,[b])}return g},[n]);return u(It,{icon:lo,title:"Storage Locations",subtitle:u(ve,{children:["Register where each kind of data lives. Each type can have multiple locations — one is the default, the rest are addressable by their fully-qualified id (",r("code",{className:"font-mono",children:"<type>:<slug>"}),")."]}),children:[o&&r("div",{className:"text-xs text-foreground-subtle animate-pulse",children:"Loading locations…"}),s&&r("div",{className:"text-xs text-danger",children:"Failed to load storage locations."}),!o&&!s&&r("div",{className:"space-y-3",children:Ed.map(g=>r(i9,{type:g,displayName:d9[g],description:u9[g],locations:h.get(g)??[],onAdd:b=>i(b),onEdit:b=>c(b),onDelete:b=>{m(b)},onSetDefault:b=>p(b)},g))}),a!==null&&r(s0,{initialType:a,onClose:()=>i(null),onCreated:()=>{e.invalidateQueries({queryKey:[["storage","listLocations"]]}),i(null)}}),l!==null&&r(c9,{location:l,onClose:()=>c(null),onSaved:()=>{e.invalidateQueries({queryKey:[["storage","listLocations"]]}),c(null)}})]})}const f9=[["backup","listDestinations"]],m9=["backup","listArchives"];function h9({destinationId:e,restoreSupported:t,onOpenRestoreWizard:n}){const o=ke(),s=rt(),{data:a,isLoading:i,isError:l}=fc({destinationId:e}),c=a??[],d=pg({onSuccess:()=>{o.invalidateQueries({queryKey:[[...m9]]}),o.invalidateQueries({queryKey:f9})}}),f=q(async b=>{await s({title:"Delete this archive?",message:`Permanently deletes "${b.label??b.id}" and frees ${Nt(b.sizeBytes)}.`,confirmLabel:"Delete",variant:"danger"})&&d.mutate({destinationId:e,backupId:b.id})},[s,e,d]),[p,m]=$(null),h=q(async b=>{m(b.id);try{const x=localStorage.getItem("camstack_admin_token"),v={};x&&(v.Authorization=`Bearer ${x}`);const w=await fetch(g9(e,b.id),{headers:v});if(!w.ok)throw new Error(`download failed: ${w.status} ${w.statusText}`);const y=await w.blob(),N=URL.createObjectURL(y),k=document.createElement("a");k.href=N,k.download=`${b.label??b.id}.tar.gz`,document.body.appendChild(k),k.click(),k.remove(),URL.revokeObjectURL(N)}finally{m(null)}},[e]),g=Q(()=>[...c].sort((b,x)=>x.createdAt-b.createdAt),[c]);return i?r("div",{className:"text-xs text-foreground-subtle animate-pulse py-2",children:"Loading archives…"}):l?r("div",{className:"text-xs text-danger py-2",children:"Failed to read manifest for this destination"}):g.length===0?r("div",{className:"text-xs text-foreground-subtle italic py-2",children:"No archives at this destination yet."}):r("div",{className:"rounded border border-border bg-surface overflow-x-auto",children:u("table",{className:"w-full text-xs min-w-[640px]",children:[r("thead",{children:u("tr",{className:"text-foreground-subtle bg-background/30",children:[r("th",{className:"text-left px-3 py-1.5 font-medium",children:"When"}),r("th",{className:"text-left px-3 py-1.5 font-medium",children:"Label"}),r("th",{className:"text-left px-3 py-1.5 font-medium",children:"Includes"}),r("th",{className:"text-right px-3 py-1.5 font-medium",children:"Size"}),r("th",{className:"text-right px-3 py-1.5 font-medium w-52",children:"Actions"})]})}),r("tbody",{children:g.map(b=>u("tr",{className:"border-t border-border hover:bg-primary/5",children:[r("td",{className:"px-3 py-1.5 text-foreground tabular-nums",children:b9(b.createdAt)}),r("td",{className:"px-3 py-1.5 text-foreground",children:b.label??r("span",{className:"text-foreground-subtle italic",children:"—"})}),r("td",{className:"px-3 py-1.5 text-foreground-subtle",children:b.locations.join(", ")}),r("td",{className:"px-3 py-1.5 text-foreground text-right tabular-nums",children:Nt(b.sizeBytes)}),r("td",{className:"px-3 py-1.5",children:u("div",{className:"flex items-center justify-end gap-1",children:[u("button",{onClick:()=>{h(b)},disabled:p===b.id,className:"inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] font-medium text-foreground-subtle hover:text-foreground hover:bg-primary/10 disabled:opacity-50",title:"Download archive",children:[p===b.id?r(Pe,{className:"h-3 w-3 animate-spin"}):r(wn,{className:"h-3 w-3"}),"Download"]}),t&&n&&u("button",{onClick:()=>n({destinationId:e,archiveId:b.id}),className:"inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] font-medium text-primary hover:bg-primary/10",title:"Restore from this archive",children:[r(bt,{className:"h-3 w-3"}),"Restore"]}),r("button",{onClick:()=>{f(b)},disabled:d.isPending,className:"inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] font-medium text-danger hover:bg-danger/10 disabled:opacity-50",title:"Delete archive",children:d.isPending?r(Pe,{className:"h-3 w-3 animate-spin"}):r(We,{className:"h-3 w-3"})})]})})]},b.id))})]})})}function g9(e,t){return`/api/backup/download/${encodeURIComponent(e)}/${encodeURIComponent(t)}`}function b9(e){return new Date(e).toLocaleString(void 0,{day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit"})}const a0=[{id:"manual",label:"Manual only",cron:""},{id:"hourly",label:"Every hour",cron:"0 * * * *",description:"On the hour"},{id:"every-3h",label:"Every 3 hours",cron:"0 */3 * * *",description:"00:00, 03:00, 06:00, 09:00 …"},{id:"every-6h",label:"Every 6 hours",cron:"0 */6 * * *",description:"00:00, 06:00, 12:00, 18:00"},{id:"daily-3am",label:"Daily at 03:00",cron:"0 3 * * *",description:"Every night at 3 AM"},{id:"weekly-sun",label:"Weekly Sunday 03:00",cron:"0 3 * * 0",description:"Sunday morning at 3 AM"}];function x9(e){const t=e.trim();for(const n of a0)if(n.cron===t)return n.id;return"custom"}function y9({value:e,onChange:t,previewCount:n=5,disabled:o=!1}){const s=x9(e),[a,i]=$(s==="custom");Y(()=>{s!=="custom"&&i(!1)},[s]);const l=N9(e,250),c=mg({cron:l,count:n},{enabled:l.trim().length>0}),d=c.data??null,f=m=>{i(!1),t(m.cron)},p=a||s==="custom";return u("div",{className:"space-y-3",children:[u("div",{className:"space-y-1",children:[r("div",{className:"text-[10px] uppercase tracking-wide text-foreground-subtle",children:"Schedule preset"}),u("div",{className:"flex flex-wrap gap-1.5",children:[a0.map(m=>{const h=!a&&s===m.id;return r("button",{type:"button",onClick:()=>f(m),disabled:o,className:"rounded border px-2 py-1 text-[11px] transition-colors disabled:opacity-50 "+(h?"border-primary bg-primary/10 text-primary":"border-border bg-background text-foreground-subtle hover:bg-primary/5 hover:text-foreground"),title:m.description??m.label,children:m.label},m.id)}),r("button",{type:"button",onClick:()=>{i(!0),e.trim().length===0&&t("0 3 * * *")},disabled:o,className:"rounded border px-2 py-1 text-[11px] transition-colors disabled:opacity-50 "+(p?"border-primary bg-primary/10 text-primary":"border-border bg-background text-foreground-subtle hover:bg-primary/5 hover:text-foreground"),children:"Custom…"})]})]}),p&&u("div",{className:"space-y-1",children:[r("div",{className:"text-[10px] uppercase tracking-wide text-foreground-subtle",children:"Cron expression (5-field POSIX)"}),r("input",{type:"text",value:e,onChange:m=>t(m.target.value),disabled:o,placeholder:"0 3 * * *",spellCheck:!1,className:"w-full rounded border border-border bg-background px-2 py-1.5 text-xs font-mono text-foreground placeholder:text-foreground-subtle focus:outline-none focus:ring-1 focus:ring-primary"}),u("p",{className:"text-[10px] text-foreground-subtle",children:["Format: ",r("span",{className:"font-mono",children:"minute hour day-of-month month day-of-week"})," · all times server-local"]})]}),r(v9,{cron:l,preview:d,loading:c.isFetching})]})}function v9({cron:e,preview:t,loading:n}){return n&&t===null?u("div",{className:"flex items-center gap-2 rounded border border-border bg-background/40 px-3 py-2 text-[11px] text-foreground-subtle",children:[r(Pe,{className:"h-3 w-3 animate-spin"}),"Validating…"]}):t===null?null:t.ok?t.nextRuns.length===0?r("div",{className:"rounded border border-border bg-background/40 px-3 py-2 text-[11px] text-foreground-subtle",children:"No future runs match this expression."}):u("div",{className:"space-y-1",children:[r("div",{className:"text-[10px] uppercase tracking-wide text-foreground-subtle",children:"Next runs"}),r("ul",{className:"rounded border border-border bg-background/40 divide-y divide-border",children:t.nextRuns.map((o,s)=>u("li",{className:"flex items-center justify-between px-3 py-1.5 text-[11px]",children:[r("span",{className:"text-foreground tabular-nums",children:new Date(o).toLocaleString()}),r("span",{className:"text-foreground-subtle text-[10px] tabular-nums",children:w9(o)})]},`${o}-${s}`))})]}):r("div",{className:"rounded border border-danger/40 bg-danger/10 px-3 py-2 text-[11px] text-danger",children:t.error??"Invalid cron expression"})}function w9(e){const t=e-Date.now();if(t<=0)return"now";const n=Math.floor(t/1e3);if(n<60)return`in ${n}s`;const o=Math.floor(n/60);if(o<60)return`in ${o}m`;const s=Math.floor(o/60);return s<24?`in ${s}h`:`in ${Math.floor(s/24)}d`}function N9(e,t){const[n,o]=$(e),s=Q(()=>e,[e]);return Y(()=>{const a=setTimeout(()=>o(s),t);return()=>clearTimeout(a)},[s,t]),n}const k9=[["backup","listDestinations"]];function S9({onCreateAt:e,onOpenRestoreWizard:t}){const{data:n,isLoading:o,isError:s}=pc(),a=n??[],[i,l]=$(null),c=f=>{l(p=>p===f?null:f)},d=P9();return o?r("div",{className:"text-xs text-foreground-subtle animate-pulse",children:"Loading destinations…"}):s?r("div",{className:"text-xs text-danger",children:"Failed to load destinations"}):a.length===0?r("div",{className:"rounded-lg border border-border bg-surface px-4 py-8 text-center",children:r("p",{className:"text-xs text-foreground-subtle",children:"No `backups`-typed storage locations registered. Add one in Settings → Storage to begin."})}):r("div",{className:"rounded-lg border border-border bg-surface overflow-x-auto",children:u("table",{className:"w-full text-xs min-w-[720px]",children:[r("thead",{children:u("tr",{className:"text-foreground-subtle border-b border-border bg-background/40",children:[r("th",{className:"text-left px-3 py-2 font-medium w-6"}),r("th",{className:"text-left px-3 py-2 font-medium",children:"Destination"}),r("th",{className:"text-left px-3 py-2 font-medium w-20",children:"Enabled"}),r("th",{className:"text-left px-3 py-2 font-medium w-28",children:"Retention"}),r("th",{className:"text-left px-3 py-2 font-medium w-56",children:"Schedule"}),r("th",{className:"text-left px-3 py-2 font-medium w-44",children:"Last success"}),r("th",{className:"text-right px-3 py-2 font-medium w-44",children:"Actions"})]})}),r("tbody",{children:a.map(f=>{const p=d.get(f.id);return r(C9,{row:f,isOpen:i===f.id,onToggle:()=>c(f.id),onCreateAt:e,liveLastSuccessAt:p?.at,liveLastSuccessSizeBytes:p?.sizeBytes,...t?{onOpenRestoreWizard:t}:{}},f.id)})})]})})}function C9({row:e,isOpen:t,onToggle:n,onCreateAt:o,onOpenRestoreWizard:s,liveLastSuccessAt:a,liveLastSuccessSizeBytes:i}){const l=ke(),c=fg({onSuccess:()=>{l.invalidateQueries({queryKey:k9})}}),[d,f]=$(String(e.retentionCount));Y(()=>{f(String(e.retentionCount))},[e.retentionCount]);const[p,m]=$(!1),h=q(x=>{c.mutate({locationId:e.id,enabled:x,retentionCount:e.retentionCount,...e.label!==void 0?{label:e.label}:{},...e.cron!==void 0?{cron:e.cron}:{}})},[c,e.id,e.retentionCount,e.label,e.cron]),g=q(()=>{const x=Number.parseInt(d,10);if(Number.isNaN(x)||x<1){f(String(e.retentionCount));return}x!==e.retentionCount&&c.mutate({locationId:e.id,enabled:e.enabled,retentionCount:x,...e.label!==void 0?{label:e.label}:{},...e.cron!==void 0?{cron:e.cron}:{}})},[c,d,e.id,e.enabled,e.retentionCount,e.label,e.cron]),b=q(x=>{c.mutate({locationId:e.id,enabled:e.enabled,retentionCount:e.retentionCount,...e.label!==void 0?{label:e.label}:{},cron:x},{onSuccess:()=>{m(!1)}})},[c,e.id,e.enabled,e.retentionCount,e.label]);return u(ve,{children:[u("tr",{className:"border-t border-border first:border-t-0 hover:bg-primary/5",children:[r("td",{className:"px-2 py-2",children:r("button",{onClick:n,className:"inline-flex items-center justify-center rounded p-1 text-foreground-subtle hover:bg-primary/10 hover:text-foreground",title:t?"Hide archives":"Show archives",children:t?r(Rt,{className:"h-3.5 w-3.5"}):r(Mt,{className:"h-3.5 w-3.5"})})}),r("td",{className:"px-3 py-2",children:u("button",{onClick:n,className:"text-left hover:underline focus:outline-none",title:"View archives",children:[r("div",{className:"text-foreground font-medium",children:e.displayName}),u("div",{className:"flex items-center gap-1.5 mt-0.5",children:[r("span",{className:"text-[10px] uppercase tracking-wide text-foreground-subtle bg-background border border-border rounded px-1.5 py-0.5",children:e.kind}),r("span",{className:"text-[10px] text-foreground-subtle font-mono",children:e.id})]})]})}),r("td",{className:"px-3 py-2",children:r("label",{className:"inline-flex items-center cursor-pointer",children:r("input",{type:"checkbox",className:"accent-primary",checked:e.enabled,disabled:c.isPending,onChange:x=>h(x.target.checked)})})}),r("td",{className:"px-3 py-2",children:r("input",{type:"number",min:1,max:1e3,value:d,disabled:c.isPending,onChange:x=>f(x.target.value),onBlur:g,onKeyDown:x=>{x.key==="Enter"&&x.target.blur(),x.key==="Escape"&&f(String(e.retentionCount))},className:"w-16 rounded border border-border bg-background px-2 py-1 text-xs text-foreground focus:outline-none focus:ring-1 focus:ring-primary"})}),r("td",{className:"px-3 py-2",children:r(M9,{cron:e.cron,nextRunAt:e.nextRunAt,onEdit:()=>m(!0),disabled:c.isPending})}),r("td",{className:"px-3 py-2 text-foreground-subtle",children:(()=>{const x=E9(a,e.lastSuccessAt),v=x===a?i:e.lastSuccessSizeBytes;return x!==void 0?r($9,{at:x,sizeBytes:v}):r("span",{className:"italic",children:"Never"})})()}),r("td",{className:"px-3 py-2",children:r("div",{className:"flex items-center justify-end gap-1.5",children:e.triggerSupported&&u("button",{onClick:()=>o(e),className:"inline-flex items-center gap-1 rounded bg-primary px-2 py-1 text-[11px] font-medium text-primary-foreground hover:bg-primary/90",children:[r(Ot,{className:"h-3 w-3"}),"Create here"]})})})]}),t&&r("tr",{className:"border-t border-border bg-background/30",children:r("td",{colSpan:7,className:"px-4 py-3",children:r(h9,{destinationId:e.id,restoreSupported:e.restoreSupported,...s?{onOpenRestoreWizard:s}:{}})})}),p&&r(A9,{destinationName:e.displayName,currentCron:e.cron??"",onSave:b,onClose:()=>m(!1),saving:c.isPending,saveError:c.error instanceof Error?c.error.message:null})]})}function M9({cron:e,nextRunAt:t,onEdit:n,disabled:o}){const s=typeof e=="string"&&e.trim().length>0;return u("button",{type:"button",onClick:n,disabled:o,className:"group flex flex-col items-start gap-0.5 text-left rounded px-1.5 py-1 -mx-1.5 hover:bg-primary/5 disabled:opacity-50",title:"Edit schedule",children:[u("div",{className:"flex items-center gap-1.5",children:[r(aD,{className:"h-3 w-3 text-foreground-subtle group-hover:text-foreground"}),r("span",{className:s?"font-mono text-foreground":"italic text-foreground-subtle",children:s?e:"Manual"})]}),s&&t!==void 0&&u("span",{className:"text-[10px] text-foreground-subtle tabular-nums",children:["next ",I9(t)]})]})}function I9(e){const t=e-Date.now();if(t<=0)return"imminent";const n=Math.floor(t/1e3);if(n<60)return`in ${n}s`;const o=Math.floor(n/60);if(o<60)return`in ${o}m`;const s=Math.floor(o/60);return s<24?`in ${s}h`:`in ${Math.floor(s/24)}d`}function A9({destinationName:e,currentCron:t,onSave:n,onClose:o,saving:s,saveError:a}){const[i,l]=$(t);return r("tr",{children:r("td",{colSpan:7,className:"p-0",children:r("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-background/80 backdrop-blur-sm",onClick:o,children:u("div",{className:"w-full max-w-lg rounded-xl border border-border bg-surface shadow-2xl",onClick:c=>c.stopPropagation(),children:[u("div",{className:"flex items-start justify-between border-b border-border px-4 py-3",children:[u("div",{className:"space-y-0.5",children:[r("h2",{className:"text-sm font-semibold text-foreground",children:"Schedule"}),u("p",{className:"text-xs text-foreground-subtle",children:["→ ",e]})]}),r("button",{onClick:o,className:"text-foreground-subtle hover:text-foreground",title:"Close",children:r(qe,{className:"h-4 w-4"})})]}),u("div",{className:"p-4",children:[r(y9,{value:i,onChange:l,disabled:s}),a!==null&&r("div",{className:"mt-3 rounded border border-danger/40 bg-danger/10 px-3 py-2 text-[11px] text-danger",children:a})]}),u("div",{className:"flex justify-end gap-2 border-t border-border px-4 py-3",children:[r("button",{onClick:o,disabled:s,className:"rounded px-3 py-1.5 text-xs text-foreground-subtle border border-border hover:text-foreground disabled:opacity-50",children:"Cancel"}),r("button",{onClick:()=>n(i.trim()),disabled:s||i.trim()===t.trim(),className:"inline-flex items-center gap-1.5 rounded bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50",children:s?"Saving…":"Save"})]})]})})})})}function P9(){const{map:e}=ec(Ne.BackupCompleted,t=>t.destinationId);return Q(()=>{const t=new Map;for(const[n,o]of e)t.set(n,{at:Date.now(),sizeBytes:o.sizeMB*1024*1024});return t},[e])}function E9(e,t){return e===void 0?t:t===void 0||e>t?e:t}function $9({at:e,sizeBytes:t}){const n=_9(e),o=Q(()=>new Date(e).toLocaleString(),[e]);return u("span",{title:o,className:"text-foreground tabular-nums",children:[n,t!==void 0&&u("span",{className:"ml-1 text-foreground-subtle",children:["· ",Nt(t)]})]})}function _9(e){const[,t]=$(0);return Y(()=>{const n=setInterval(()=>t(o=>o+1),3e4);return()=>clearInterval(n)},[]),D9(e)}function D9(e){const t=Math.max(0,Date.now()-e),n=Math.floor(t/1e3);if(n<60)return`${n}s ago`;const o=Math.floor(n/60);if(o<60)return`${o}m ago`;const s=Math.floor(o/60);if(s<24)return`${s}h ago`;const a=Math.floor(s/24);if(a<30)return`${a}d ago`;const i=Math.floor(a/30);return i<12?`${i}mo ago`:`${Math.floor(a/365)}y ago`}const L9=[["backup","list"]];function T9({initialDestinationId:e,initialArchiveId:t,onClose:n,onScheduled:o}){const s=ke(),[a,i]=$(e&&t?2:1),[l,c]=$(e),[d,f]=$(t),[p,m]=$(new Set),{data:h}=pc(),g=h??[],{data:b,isLoading:x}=fc({destinationId:l??""},{enabled:!!l}),v=b??[];Y(()=>{if(l!==void 0)return;const F=g.filter(E=>E.restoreSupported);F.length===1&&c(F[0].id)},[l,g]);const{data:w}=dg({destinationId:l??"",backupId:d??""},{enabled:!!l&&!!d}),y=Q(()=>w?.locations??[],[w]);Y(()=>{y.length!==0&&m(F=>F.size===0?new Set(y):F)},[y]);const N=ug({onSuccess:()=>{s.invalidateQueries({queryKey:L9}),o(),n()}}),k=F=>{m(E=>{const B=new Set(E);return B.has(F)?B.delete(F):B.add(F),B})},S=!!l&&!!d,M=p.size>0,P=S&&M&&!N.isPending,I=()=>{!l||!d||N.mutate({destinationId:l,backupId:d,locations:[...p]})};return r("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-background/80 backdrop-blur-sm",onClick:n,children:u("div",{className:"w-full max-w-md rounded-xl border border-border bg-surface shadow-2xl",onClick:F=>F.stopPropagation(),children:[u("div",{className:"flex items-start justify-between border-b border-border px-4 py-3",children:[u("div",{className:"space-y-0.5",children:[r("h2",{className:"text-sm font-semibold text-foreground",children:"Restore Backup"}),u("p",{className:"text-xs text-foreground-subtle",children:["Step ",a," of 3 — ",a===1?"pick source":a===2?"pick locations":"confirm"]})]}),r("button",{onClick:n,className:"text-foreground-subtle hover:text-foreground",children:r(qe,{className:"h-4 w-4"})})]}),a===1&&r(R9,{destinations:g,destinationId:l,onPickDestination:F=>{c(F),f(void 0),m(new Set)},archives:v,archivesLoading:x,archiveId:d,onPickArchive:f}),a===2&&r(O9,{locations:y,picked:p,onToggle:k}),a===3&&r(z9,{destinationName:g.find(F=>F.id===l)?.displayName??l??"",archive:v.find(F=>F.id===d),picked:[...p]}),u("div",{className:"flex justify-between gap-2 border-t border-border px-4 py-3",children:[r("div",{children:a>1&&u("button",{onClick:()=>i(F=>F===3?2:1),className:"inline-flex items-center gap-1 rounded px-3 py-1.5 text-xs text-foreground-subtle border border-border hover:text-foreground",children:[r(Yx,{className:"h-3 w-3"}),"Back"]})}),u("div",{className:"flex items-center gap-2",children:[r("button",{onClick:n,className:"rounded px-3 py-1.5 text-xs text-foreground-subtle border border-border hover:text-foreground",children:"Cancel"}),a<3?u("button",{disabled:a===1&&!S||a===2&&!M,onClick:()=>i(F=>F===1?2:3),className:"inline-flex items-center gap-1 rounded bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50",children:["Next",r(Zx,{className:"h-3 w-3"})]}):u("button",{onClick:I,disabled:!P,className:"inline-flex items-center gap-1.5 rounded bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50",children:[N.isPending?r(Pe,{className:"h-3.5 w-3.5 animate-spin"}):r(bt,{className:"h-3.5 w-3.5"}),"Schedule Restore"]})]})]})]})})}function R9({destinations:e,destinationId:t,onPickDestination:n,archives:o,archivesLoading:s,archiveId:a,onPickArchive:i}){const l=e.filter(c=>c.restoreSupported);return u("div",{className:"p-4 space-y-3",children:[u("div",{className:"space-y-1.5",children:[r("label",{className:"text-[10px] text-foreground-subtle uppercase tracking-wide",children:"Destination"}),u("select",{value:t??"",onChange:c=>n(c.target.value),className:"w-full rounded border border-border bg-background px-2 py-1.5 text-xs text-foreground focus:outline-none focus:ring-1 focus:ring-primary",children:[r("option",{value:"",disabled:!0,children:"Select destination…"}),l.map(c=>u("option",{value:c.id,children:[c.displayName," (",c.kind,")"]},c.id))]})]}),u("div",{className:"space-y-1.5",children:[r("label",{className:"text-[10px] text-foreground-subtle uppercase tracking-wide",children:"Archive"}),!t&&r("div",{className:"text-xs text-foreground-subtle italic",children:"Pick a destination first."}),t&&s&&r("div",{className:"text-xs text-foreground-subtle animate-pulse",children:"Reading archives…"}),t&&!s&&o.length===0&&r("div",{className:"text-xs text-foreground-subtle italic",children:"No archives available at this destination."}),t&&o.length>0&&r("div",{className:"rounded border border-border bg-background divide-y divide-border max-h-64 overflow-y-auto",children:o.map(c=>{const d=a===c.id;return u("label",{className:`flex items-center justify-between px-3 py-2 text-xs cursor-pointer ${d?"bg-primary/10":"hover:bg-primary/5"}`,children:[u("div",{className:"flex items-center gap-2",children:[r("input",{type:"radio",name:"archive",checked:d,onChange:()=>i(c.id),className:"accent-primary"}),u("div",{children:[r("div",{className:"font-medium text-foreground",children:c.label??c.id}),r("div",{className:"text-[10px] text-foreground-subtle",children:new Date(c.createdAt).toLocaleString()})]})]}),r("span",{className:"text-[10px] text-foreground-subtle tabular-nums",children:Nt(c.sizeBytes)})]},c.id)})})]})]})}function O9({locations:e,picked:t,onToggle:n}){return e.length===0?r("div",{className:"p-4",children:r("div",{className:"text-xs text-foreground-subtle",children:"Loading archive manifest… If this persists, the archive may predate manifests — restoring will apply everything in the tarball."})}):u("div",{className:"p-4 space-y-3",children:[r("div",{className:"rounded border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-[11px] text-amber-700 dark:text-amber-300",children:"Selected entries will overwrite live data on the next server restart. Unchecked entries stay current."}),u("div",{className:"space-y-1.5",children:[r("label",{className:"text-[10px] text-foreground-subtle uppercase tracking-wide",children:"Apply"}),r("div",{className:"rounded border border-border bg-background divide-y divide-border max-h-64 overflow-y-auto",children:e.map(o=>u("label",{className:"flex items-center gap-2 px-3 py-2 text-xs hover:bg-primary/5 cursor-pointer",children:[r("input",{type:"checkbox",checked:t.has(o),onChange:()=>n(o),className:"accent-primary"}),r("span",{className:"font-mono text-foreground",children:o}),r("span",{className:"ml-auto text-[10px] text-foreground-subtle",children:F9(o)})]},o))})]})]})}function z9({destinationName:e,archive:t,picked:n}){return u("div",{className:"p-4 space-y-3 text-xs",children:[r("div",{className:"rounded border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-amber-700 dark:text-amber-300",children:"Restore is applied at next server boot. Active connections will drop when you restart."}),u("dl",{className:"space-y-1.5",children:[r(ns,{term:"Destination",value:e}),r(ns,{term:"Archive",value:t?.label??t?.id??"—"}),t&&r(ns,{term:"Created",value:`${new Date(t.createdAt).toLocaleString()} · ${Nt(t.sizeBytes)}`}),r(ns,{term:"Locations",value:n.length>0?n.join(", "):"— (full archive)"})]})]})}function ns({term:e,value:t}){return u("div",{className:"flex justify-between gap-3",children:[r("dt",{className:"text-foreground-subtle",children:e}),r("dd",{className:"text-foreground font-mono text-right truncate",children:t})]})}const B9={db:"Database",addons:"Addon configs","addons-data":"Addon data",tls:"TLS certificates",cache:"Cache",data:"Top-level data"};function F9(e){return B9[e]??""}const j9=[["backup","list"]],H9=[["backup","listLocations"]];function V9(){const e=ke(),t=rt(),{data:n}=cg(),o=lg({onSuccess:()=>{e.invalidateQueries({queryKey:j9}),e.invalidateQueries({queryKey:[["backup","listDestinations"]]}),e.invalidateQueries({queryKey:[["backup","listArchives"]]})}}),s=Uh(),[a,i]=$(null),[l,c]=$(null),[d,f]=$(!1),[p,m]=$(!1),[h,g]=$(!1),b=async()=>{await t({title:"Restart server now?",message:"Active connections will drop and the apply-backup hook will run before boot.",confirmLabel:"Restart",variant:"warning"})&&s.mutate({confirm:!0})};return u(It,{icon:Uc,title:"Backup & Restore",subtitle:"Schedule + per-destination retention live in the orchestrator. Each `backups` storage location is a destination.",actions:u(ve,{children:[u("button",{onClick:()=>g(!0),className:"inline-flex items-center gap-1.5 rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90",children:[r(Ot,{className:"h-3.5 w-3.5"}),"Add destination"]}),u("button",{onClick:()=>f(!0),className:"inline-flex items-center gap-1.5 rounded-lg bg-surface border border-border px-3 py-1.5 text-xs font-medium text-foreground hover:bg-primary/5 hover:border-primary/30",children:[r(bt,{className:"h-3.5 w-3.5"}),"Restore…"]})]}),children:[p&&r("div",{className:"rounded-lg border border-amber-500/30 bg-amber-500/10 px-3 py-2.5 text-xs text-amber-700 dark:text-amber-300",children:u("div",{className:"flex items-center justify-between gap-3",children:[u("div",{className:"flex items-center gap-2",children:[r(bt,{className:"h-3.5 w-3.5"}),r("span",{children:"Restore scheduled. Restart the server to apply."})]}),u("button",{onClick:()=>{b()},disabled:s.isPending,className:"inline-flex items-center gap-1.5 rounded bg-amber-500/20 px-2 py-1 font-medium text-amber-800 dark:text-amber-200 hover:bg-amber-500/30 disabled:opacity-50",children:[s.isPending?r(Pe,{className:"h-3.5 w-3.5 animate-spin"}):r(bt,{className:"h-3.5 w-3.5"}),"Restart Now"]})]})}),r(S9,{onCreateAt:x=>i(x),onOpenRestoreWizard:x=>c(x)}),a&&r(q9,{destination:a,locations:n??[],onClose:()=>i(null),onSubmit:(x,v)=>{o.mutate({destinations:[a.id],locations:x,label:v||void 0},{onSuccess:()=>{i(null),e.invalidateQueries({queryKey:H9})}})},submitting:o.isPending}),(l||d)&&r(T9,{...l?{initialDestinationId:l.destinationId,initialArchiveId:l.archiveId}:{},onClose:()=>{c(null),f(!1)},onScheduled:()=>m(!0)}),h&&r(s0,{initialType:"backups",onClose:()=>g(!1),onCreated:()=>{g(!1),e.invalidateQueries({queryKey:[["backup","listDestinations"]]})}})]})}function q9({destination:e,locations:t,onClose:n,onSubmit:o,submitting:s}){const a=t.filter(p=>p.present),[i,l]=$(""),[c,d]=$(()=>new Set(a.map(p=>p.name))),f=p=>{d(m=>{const h=new Set(m);return h.has(p)?h.delete(p):h.add(p),h})};return r("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-background/80 backdrop-blur-sm",onClick:n,children:u("div",{className:"w-full max-w-md rounded-xl border border-border bg-surface shadow-2xl",onClick:p=>p.stopPropagation(),children:[u("div",{className:"flex items-start justify-between border-b border-border px-4 py-3",children:[u("div",{className:"space-y-0.5",children:[r("h2",{className:"text-sm font-semibold text-foreground",children:"Create Backup"}),u("p",{className:"text-xs text-foreground-subtle",children:["→ ",e.displayName]})]}),r("button",{onClick:n,className:"text-foreground-subtle hover:text-foreground",children:r(qe,{className:"h-4 w-4"})})]}),u("div",{className:"p-4 space-y-3",children:[u("div",{className:"space-y-1",children:[r("label",{className:"text-[10px] text-foreground-subtle uppercase tracking-wide",children:"Label (optional)"}),r("input",{type:"text",value:i,onChange:p=>l(p.target.value),placeholder:"pre-upgrade",className:"w-full rounded border border-border bg-background px-2 py-1.5 text-xs text-foreground placeholder:text-foreground-subtle focus:outline-none focus:ring-1 focus:ring-primary"})]}),u("div",{className:"space-y-1.5",children:[r("label",{className:"text-[10px] text-foreground-subtle uppercase tracking-wide",children:"Include"}),u("div",{className:"rounded border border-border bg-background divide-y divide-border max-h-64 overflow-y-auto",children:[a.length===0&&r("div",{className:"px-3 py-2 text-xs text-foreground-subtle italic",children:"Nothing to back up."}),a.map(p=>u("label",{className:"flex items-center justify-between px-3 py-2 text-xs hover:bg-primary/5 cursor-pointer",children:[u("div",{className:"flex items-center gap-2",children:[r("input",{type:"checkbox",checked:c.has(p.name),onChange:()=>f(p.name),className:"accent-primary"}),r("span",{className:"font-mono text-foreground",children:p.name})]}),u("div",{className:"text-[10px] text-foreground-subtle tabular-nums",children:[Nt(p.sizeBytes)," · ",p.fileCount," files"]})]},p.name))]})]})]}),u("div",{className:"flex justify-end gap-2 border-t border-border px-4 py-3",children:[r("button",{onClick:n,className:"rounded px-3 py-1.5 text-xs text-foreground-subtle border border-border hover:text-foreground",children:"Cancel"}),u("button",{onClick:()=>o(Array.from(c),i.trim()),disabled:s||c.size===0,className:"inline-flex items-center gap-1.5 rounded bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50",children:[s?r(Pe,{className:"h-3.5 w-3.5 animate-spin"}):r(Uc,{className:"h-3.5 w-3.5"}),s?"Creating…":"Create"]})]})]})})}function Q9(){return r("div",{className:"flex flex-col",children:r("div",{className:"px-6 pt-6",children:r(td,{tabs:[{id:"storage",label:"Storage",icon:lo,content:r(p9,{})},{id:"backup",label:"Backup",icon:Uc,content:r(V9,{})}]})})})}function U9(){const{data:e,isLoading:t}=In(void 0,{staleTime:3e4}),n=(e??[]).find(s=>s.isHub&&s.isOnline),o=n?.addons.map(s=>s.id)??[];return u("div",{className:"flex flex-col h-full gap-4 p-4",children:[u("div",{className:"flex items-center gap-3",children:[r(wt,{className:"h-5 w-5 text-muted-foreground"}),r("h1",{className:"text-xl font-semibold",children:"Settings"}),n&&u("span",{className:"text-xs px-2 py-0.5 rounded-full bg-muted text-muted-foreground",children:["hub: ",n.name]})]}),t?r("div",{className:"flex items-center justify-center flex-1 text-muted-foreground text-sm",children:"Loading hub topology…"}):n?o.length===0?r("div",{className:"flex items-center justify-center flex-1 text-muted-foreground text-sm",children:"No addons installed on the hub yet."}):r("div",{className:"w-full",children:r(Rr,{nodeId:n.id,addonIds:o,level:"global"})}):u("div",{className:"flex flex-col items-center justify-center flex-1 text-muted-foreground text-sm gap-2",children:[r(wt,{className:"h-8 w-8 opacity-30"}),r("p",{children:"No online hub node found."}),r("p",{className:"text-xs",children:"Settings will appear once the hub is reachable."})]})]})}function K9(e){const t=new FormData;return t.append("file",e.file,e.file.name),t.append("nodeId",e.nodeId),e.addonId&&t.append("addonId",e.addonId),new Promise((n,o)=>{const s=new XMLHttpRequest;s.open("POST","/api/addons/upload"),e.token&&s.setRequestHeader("Authorization",`Bearer ${e.token}`),s.upload.addEventListener("progress",a=>{a.lengthComputable&&e.onProgress(Math.round(a.loaded/a.total*100))}),s.addEventListener("load",()=>{let a;try{a=JSON.parse(s.responseText)}catch{o(new Error(`HTTP ${s.status}`));return}s.status>=200&&s.status<300?n(a):o(new Error(a.error??`HTTP ${s.status}`))}),s.addEventListener("error",()=>o(new Error("Network error during upload"))),s.addEventListener("abort",()=>o(new Error("Upload aborted"))),s.send(t)})}function G9({nodeId:e,addons:t,isHub:n}){const o=ke(),s=rt(),[a,i]=$(null),[l,c]=$(null),[d,f]=$(!1),[p,m]=$(null),[h,g]=$(0),b=ne(null),x=ia(),v=Xg(),w=()=>{o.invalidateQueries({queryKey:[["nodes","topology"]]})},y=async M=>{i(M);try{await x.mutateAsync({nodeId:e,addonId:M}),w()}catch(P){console.error("Failed to restart addon:",P)}finally{i(null)}},N=async M=>{if(await s({title:"Uninstall addon",message:`Remove "${M}" from ${e}? The addon directory will be deleted on disk.`,confirmLabel:"Uninstall",variant:"danger"})){c(M);try{await v.mutateAsync({nodeId:e,addonId:M}),w()}catch(I){console.error("Failed to uninstall addon:",I)}finally{c(null)}}},S=u("div",{className:"flex items-center gap-2 mb-2",children:[r("input",{ref:b,type:"file",accept:".tgz,.tar.gz",className:"hidden",onChange:async M=>{const P=M.target.files?.[0];if(P){M.target.value="",m(null),f(!0),g(0);try{const I=localStorage.getItem("camstack_admin_token");await K9({file:P,nodeId:e,token:I,onProgress:g}),w()}catch(I){m(I instanceof Error?I.message:String(I))}finally{f(!1),g(0)}}}}),u("button",{onClick:()=>b.current?.click(),disabled:d,className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1 text-[11px] font-medium text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors disabled:opacity-50",children:[d?r(Pe,{className:"h-3 w-3 animate-spin"}):r(Xc,{className:"h-3 w-3"}),d?`Uploading… ${h}%`:"Upload addon (.tgz)"]}),d&&r("div",{className:"flex-1 h-1 rounded-full bg-muted overflow-hidden max-w-[140px]",children:r("div",{className:"h-full bg-primary transition-all",style:{width:`${h}%`}})}),p&&r("span",{className:"text-[10px] text-destructive",children:p})]});return t.length===0?u("div",{children:[S,r("div",{className:"py-4 text-xs text-muted-foreground text-center",children:"No addons on this node"})]}):u("div",{children:[S,u("table",{className:"w-full text-xs",children:[r("thead",{children:u("tr",{className:"text-muted-foreground text-left",children:[r("th",{className:"py-2 font-medium",children:"Addon"}),r("th",{className:"py-2 font-medium",children:"Capabilities"}),r("th",{className:"py-2 font-medium",children:"Status"}),r("th",{className:"py-2 font-medium w-16"})]})}),r("tbody",{children:t.map(M=>u("tr",{className:"border-t border-border/50",children:[r("td",{className:"py-2 font-medium",children:M.id}),r("td",{className:"py-2",children:r("div",{className:"flex flex-wrap gap-1",children:M.capabilities.length>0?M.capabilities.map(P=>r("span",{className:"text-[9px] px-1 py-0.5 rounded bg-blue-500/10 text-blue-400",children:P},P)):r("span",{className:"text-muted-foreground",children:"—"})})}),r("td",{className:"py-2",children:r("span",{className:`text-[10px] px-1.5 py-0.5 rounded-full ${M.status==="running"?"bg-success/10 text-success":M.status==="error"?"bg-destructive/10 text-destructive":"bg-muted text-muted-foreground"}`,children:M.status})}),r("td",{className:"py-2",children:u("div",{className:"flex items-center gap-1 justify-end",children:[r("button",{onClick:()=>y(M.id),disabled:a===M.id||l===M.id,className:"p-1 rounded hover:bg-muted text-muted-foreground hover:text-foreground transition-colors disabled:opacity-50",title:`Restart ${M.id}`,children:r(bt,{className:`h-3 w-3 ${a===M.id?"animate-spin":""}`})}),r("button",{onClick:()=>N(M.id),disabled:a===M.id||l===M.id,className:"p-1 rounded hover:bg-destructive/10 text-muted-foreground hover:text-destructive transition-colors disabled:opacity-50",title:`Uninstall ${M.id}`,children:l===M.id?r(Pe,{className:"h-3 w-3 animate-spin"}):r(We,{className:"h-3 w-3"})})]})})]},M.id))})]})]})}function W9(e){if(e<60)return`${e}s`;const t=Math.floor(e/60);if(t<60)return`${t}m`;const n=Math.floor(t/60);return n<24?`${n}h ${t%60}m`:`${Math.floor(n/24)}d ${n%24}h`}function Y9({state:e}){return r("span",{className:`text-[10px] px-1.5 py-0.5 rounded-full ${e==="running"?"bg-success/10 text-success":e==="crashed"?"bg-destructive/10 text-destructive":"bg-muted text-muted-foreground"}`,children:e})}const Z9=["trace","debug","info","warn","error"];function X9({proc:e,nodeId:t,defaultExpanded:n,activePanel:o,onTogglePanel:s}){const a=e.services??[],i=a.length===1,[l,c]=$(i||n),[d,f]=$(null),[p,m]=$("info"),h=e.name.includes("(core)"),g=ia(),b=Jg(),x=rb(),v=async N=>{f(N);try{await g.mutateAsync({nodeId:t,addonId:N})}catch(k){console.error("Failed to restart addon:",k)}finally{f(null)}},w=async()=>{f(e.name);try{await b.mutateAsync({nodeId:t,processName:e.name})}catch(N){console.error("Failed to restart process:",N)}finally{f(null)}},y=async N=>{const k=`${t}/${e.name}`;try{await x.mutateAsync({nodeId:k,level:N}),m(N)}catch(S){console.error("Failed to set log level:",S)}};return u("div",{className:"border border-border/50 rounded-lg overflow-hidden",children:[u("div",{role:i?void 0:"button",tabIndex:i?void 0:0,onClick:i?void 0:()=>c(!l),onKeyDown:i?void 0:N=>{(N.key==="Enter"||N.key===" ")&&c(!l)},className:`flex items-center gap-2 w-full px-3 py-2 bg-muted/20 transition-colors text-left select-none ${i?"":"hover:bg-muted/40 cursor-pointer"}`,children:[i?r("span",{className:"h-3 w-3 shrink-0"}):l?r(Rt,{className:"h-3 w-3 text-muted-foreground shrink-0"}):r(Mt,{className:"h-3 w-3 text-muted-foreground shrink-0"}),h?r(ln,{className:"h-3.5 w-3.5 text-primary shrink-0"}):r(ga,{className:"h-3.5 w-3.5 text-amber-500 shrink-0"}),r("span",{className:"text-xs font-semibold flex-1",children:e.name}),u("span",{className:"text-[10px] text-muted-foreground tabular-nums",children:["PID ",e.pid]}),r(Y9,{state:e.state}),u("span",{className:"text-[10px] text-muted-foreground tabular-nums",children:[e.cpuPercent,"% CPU"]}),r("span",{className:"text-[10px] text-muted-foreground tabular-nums",children:Nt(e.memoryRss)}),r("span",{className:"text-[10px] text-muted-foreground tabular-nums",children:W9(e.uptimeSeconds)}),!h&&u("div",{className:"flex items-center gap-1",onClick:N=>N.stopPropagation(),children:[u(Gm,{children:[r(Wm,{className:"text-[9px] px-1.5 py-0.5 rounded border border-border text-muted-foreground hover:text-foreground hover:bg-muted transition-colors font-mono",title:"Set log level",children:p}),r(Ym,{align:"end",className:"min-w-[70px] py-0.5",children:Z9.map(N=>r(Zm,{onClick:()=>y(N),className:`h-auto px-2 py-1 text-[10px] font-mono ${N===p?"text-primary font-semibold":""}`,children:N},N))})]}),r("button",{onClick:w,disabled:d===e.name,className:"p-1 rounded hover:bg-muted text-muted-foreground hover:text-foreground transition-colors disabled:opacity-50",title:"Restart process",children:r(bt,{className:`h-3 w-3 ${d===e.name?"animate-spin":""}`})})]})]}),l&&a.length>0&&r("div",{className:"divide-y divide-border/30",children:a.map(N=>u("div",{children:[u("div",{className:"flex items-center gap-2 px-3 py-1.5 pl-9 hover:bg-muted/10 transition-colors",children:[r("div",{className:`h-1.5 w-1.5 rounded-full shrink-0 ${N.status==="running"?"bg-success":"bg-muted-foreground/30"}`}),r("span",{className:"text-xs font-medium flex-1 min-w-0 truncate",children:N.addonId}),N.capabilities.length>0&&u("div",{className:"flex gap-1 flex-shrink-0",children:[N.capabilities.slice(0,3).map(k=>r("span",{className:"text-[9px] px-1 py-0.5 rounded bg-blue-500/10 text-blue-400 truncate max-w-[80px]",children:k},k)),N.capabilities.length>3&&u("span",{className:"text-[9px] text-muted-foreground",children:["+",N.capabilities.length-3]})]}),u("div",{className:"flex items-center gap-1 shrink-0",children:[r("button",{onClick:()=>s(N.addonId,"logs"),className:`p-0.5 rounded transition-colors ${o?.addonId===N.addonId&&o.type==="logs"?"bg-primary/10 text-primary":"hover:bg-muted text-muted-foreground hover:text-foreground"}`,title:`Show logs for ${N.addonId}`,children:r(Xe,{className:"h-3 w-3"})}),r("button",{onClick:()=>s(N.addonId,"events"),className:`p-0.5 rounded transition-colors ${o?.addonId===N.addonId&&o.type==="events"?"bg-primary/10 text-primary":"hover:bg-muted text-muted-foreground hover:text-foreground"}`,title:`Show events for ${N.addonId}`,children:r(Zc,{className:"h-3 w-3"})}),r("button",{onClick:()=>v(N.addonId),disabled:d===N.addonId,className:"p-0.5 rounded hover:bg-muted text-muted-foreground hover:text-foreground transition-colors disabled:opacity-50",title:`Restart ${N.addonId}`,children:r(bt,{className:`h-3 w-3 ${d===N.addonId?"animate-spin":""}`})})]})]}),o?.addonId===N.addonId&&o.type==="logs"&&r("div",{className:"border-t border-border/40 bg-muted/5",children:r(Wt,{addonId:N.addonId,agentId:t,maxHeight:"max-h-48",showFilters:!1,onClose:()=>s(N.addonId,"logs")})}),o?.addonId===N.addonId&&o.type==="events"&&r("div",{className:"border-t border-border/40 bg-muted/5",children:r(nr,{addonId:N.addonId,category:"addon.*",maxHeight:"max-h-48",onClose:()=>s(N.addonId,"events")})})]},N.addonId))}),l&&a.length===0&&r("div",{className:"px-3 py-2 pl-9 text-[10px] text-muted-foreground",children:"No services"})]})}function J9({nodeId:e,processes:t}){const[n,o]=$(null),s=(a,i)=>{o(l=>l?.addonId===a&&l.type===i?null:{addonId:a,type:i})};return t.length===0?r("div",{className:"py-4 text-xs text-muted-foreground text-center",children:"No processes on this node"}):r("div",{className:"space-y-2 py-1",children:t.map((a,i)=>r(X9,{proc:a,nodeId:e,defaultExpanded:i===0,activePanel:n,onTogglePanel:s},a.name))})}function e7(e){return e<60?`${e}s`:e<3600?`${Math.floor(e/60)}m ${e%60}s`:e<86400?`${Math.floor(e/3600)}h ${Math.floor(e%3600/60)}m`:`${Math.floor(e/86400)}d ${Math.floor(e%86400/3600)}h`}function t7(e,t=80){return e.length<=t?e:`…${e.slice(e.length-t+1)}`}function n7({nodeId:e}){const t=ke(),n=rt(),[o,s]=$("all"),a=Ar("metrics.node-processes-snapshot",k=>k.nodeId===e),{data:i}=Yg({nodeId:e},{staleTime:6e4}),l=a?.processes??i,c=Q(()=>l?[...l]:[],[l]),d=Q(()=>o==="ghost"?c.filter(k=>k.classification==="ghost"):c,[c,o]),f=Q(()=>{const k=c.filter(M=>M.classification==="ghost"),S=new Map;for(const M of k)S.has(M.ppid)||S.set(M.ppid,[]),S.get(M.ppid).push(M);return[...S.entries()].filter(([,M])=>M.length>1).map(([M,P])=>({ppid:M,children:P})).sort((M,P)=>P.children.length-M.children.length)},[c]),p=Zg({onSettled:()=>{t.invalidateQueries({queryKey:[["metricsProvider","listNodeProcesses"]]})}}),m=Q(()=>{const k=new Map;for(const S of c)k.set(S.pid,S.classification);return k},[c]),h=async(k,S)=>{if(k.classification==="root"||k.classification==="system")return;const M=k.classification==="ghost"?"ghost":k.addonId??"process",P=S?"SIGKILL":"SIGTERM";await n({title:`Send ${P}?`,message:`Target pid ${k.pid} (${M}) on node ${e}.`,confirmLabel:`Send ${P}`,variant:"danger"})&&p.mutate({nodeId:e,pid:k.pid,force:S})},g=async(k,S)=>{try{await p.mutateAsync({nodeId:e,pid:k,force:S})}catch{}},b=async k=>{const S=m.get(k.ppid);if(S==="root"||S==="system"){await n({title:"Cannot kill protected ancestor",message:S==="root"?`pid ${k.ppid} is the current node supervisor. Restart the node via the cluster page instead.`:`pid ${k.ppid} is a system ancestor (concurrently / vite / npm wrapper). Killing it would tear down the dev tree.`,confirmLabel:"OK",cancelLabel:"Close",variant:"warning"});return}await n({title:`Kill ghost parent + ${k.children.length} child(ren)?`,message:`SIGKILL parent pid ${k.ppid} and SIGTERM ${k.children.length} ghost child(ren) on node ${e}.`,confirmLabel:"Kill all",variant:"danger"})&&(await Promise.all([g(k.ppid,!0),...k.children.map(P=>g(P.pid,!1))]),t.invalidateQueries({queryKey:[["metricsProvider","listNodeProcesses"]]}))},x=async()=>{const k=c.filter(M=>M.classification==="ghost");k.length===0||!await n({title:`Kill all ${k.length} ghost process(es)?`,message:`SIGKILL ${k.length} ghost process(es) on node ${e}. This is irreversible.`,confirmLabel:"Kill all",variant:"danger"})||(await Promise.all(k.map(M=>g(M.pid,!0))),t.invalidateQueries({queryKey:[["metricsProvider","listNodeProcesses"]]}))},v=c.filter(k=>k.classification==="ghost").length,w=c.filter(k=>k.classification==="managed").length,y=c.filter(k=>k.classification==="root").length,N=c.filter(k=>k.classification==="system").length;return u("div",{className:"space-y-4",children:[u("div",{className:"flex items-start justify-between gap-4",children:[u("p",{className:"text-[11px] text-foreground-subtle",children:["ps"," scan + kernel `$process.list` cross-reference. Ghosts = camstack-shaped commands with no managed binding (usually orphaned to ppid=1). Refreshes every 10s."]}),u("button",{type:"button",onClick:()=>t.invalidateQueries({queryKey:[["metricsProvider","listNodeProcesses"]]}),className:"inline-flex items-center gap-1 rounded border border-border px-2 py-1 text-[11px] text-foreground hover:bg-surface-hover",children:[r(pt,{className:"h-3 w-3"})," Refresh"]})]}),u("div",{className:"grid grid-cols-4 gap-3",children:[u("div",{className:"rounded-lg border border-border p-3",children:[r("div",{className:"text-[10px] uppercase tracking-wider text-foreground-subtle",children:"Root"}),r("div",{className:"text-xl font-semibold text-foreground",children:y})]}),u("div",{className:"rounded-lg border border-border p-3",children:[r("div",{className:"text-[10px] uppercase tracking-wider text-foreground-subtle",children:"Managed"}),r("div",{className:"text-xl font-semibold text-foreground",children:w})]}),u("div",{className:"rounded-lg border border-border p-3",children:[r("div",{className:"text-[10px] uppercase tracking-wider text-foreground-subtle",children:"System"}),r("div",{className:"text-xl font-semibold text-foreground",children:N})]}),u("div",{className:`rounded-lg border p-3 ${v>0?"border-destructive/40 bg-destructive/5":"border-border"}`,children:[u("div",{className:"text-[10px] uppercase tracking-wider text-foreground-subtle flex items-center gap-1",children:[v>0&&r(Ko,{className:"h-3 w-3 text-destructive"})," Ghosts"]}),r("div",{className:`text-xl font-semibold ${v>0?"text-destructive":"text-foreground"}`,children:v})]})]}),f.length>0&&u("div",{className:"rounded-lg border border-amber-500/40 bg-amber-500/5 p-3",children:[u("div",{className:"flex items-center gap-1 text-[11px] font-semibold text-amber-400 mb-2",children:[r(xt,{className:"h-3 w-3"})," Recurring ghost parents (",f.length,")"]}),r("div",{className:"space-y-1.5",children:f.map(k=>u("div",{className:"text-[11px] text-foreground flex items-center justify-between gap-2",children:[u("div",{className:"flex items-center gap-2",children:[u("span",{className:"font-mono text-foreground-subtle",children:["ppid ",k.ppid]}),u("span",{children:["→ ",k.children.length," ghost(s)"]})]}),u("button",{type:"button",disabled:p.isPending,onClick:()=>{b(k)},className:"inline-flex items-center gap-1 rounded border border-amber-500/40 bg-amber-500/10 px-2 py-0.5 text-[10px] text-amber-400 hover:bg-amber-500/20 disabled:opacity-30",children:[r(Ko,{className:"h-3 w-3"})," Kill parent + ",k.children.length]})]},k.ppid))})]}),u("div",{className:"flex items-center justify-between gap-2 text-[11px]",children:[u("div",{className:"flex items-center gap-2",children:[r("span",{className:"text-foreground-subtle",children:"Filter:"}),u("button",{type:"button",className:`px-2 py-0.5 rounded ${o==="all"?"bg-primary text-primary-foreground":"border border-border text-foreground hover:bg-surface-hover"}`,onClick:()=>s("all"),children:["All (",c.length,")"]}),u("button",{type:"button",className:`px-2 py-0.5 rounded ${o==="ghost"?"bg-destructive text-destructive-foreground":"border border-border text-foreground hover:bg-surface-hover"}`,onClick:()=>s("ghost"),children:["Ghost only (",v,")"]})]}),v>0&&u("button",{type:"button",disabled:p.isPending,onClick:()=>{x()},className:"inline-flex items-center gap-1 rounded border border-destructive/40 bg-destructive/10 px-2 py-1 text-[11px] font-medium text-destructive hover:bg-destructive/20 disabled:opacity-30",children:[r(Ko,{className:"h-3 w-3"})," Kill all ",v," ghost(s)"]})]}),r("div",{className:"rounded-lg border border-border overflow-hidden",children:u("table",{className:"w-full text-xs",children:[r("thead",{className:"bg-surface",children:u("tr",{className:"text-foreground-subtle text-[10px] uppercase tracking-wider",children:[r("th",{className:"text-left px-3 py-2",children:"Class"}),r("th",{className:"text-right px-3 py-2",children:"PID"}),r("th",{className:"text-right px-3 py-2",children:"PPID"}),r("th",{className:"text-left px-3 py-2",children:"Addon"}),r("th",{className:"text-left px-3 py-2",children:"Command"}),r("th",{className:"text-right px-3 py-2",children:"CPU%"}),r("th",{className:"text-right px-3 py-2",children:"RSS"}),r("th",{className:"text-right px-3 py-2",children:"Uptime"}),r("th",{className:"w-44"})]})}),u("tbody",{children:[d.length===0&&r("tr",{children:r("td",{colSpan:9,className:"px-3 py-4 text-center text-foreground-subtle text-[11px]",children:o==="ghost"?"No ghost processes detected.":"Scanning…"})}),d.map(k=>u("tr",{className:`border-t border-border ${k.classification==="ghost"?"bg-destructive/5":""}`,children:[r("td",{className:"px-3 py-2",children:r("span",{className:`inline-block rounded-full px-1.5 py-0.5 text-[10px] font-medium ${k.classification==="ghost"?"bg-destructive/20 text-destructive":k.classification==="root"?"bg-sky-500/20 text-sky-400":k.classification==="system"?"bg-foreground-subtle/20 text-foreground-subtle":"bg-success/20 text-success"}`,children:k.classification})}),r("td",{className:"px-3 py-2 text-right font-mono text-foreground",children:k.pid}),u("td",{className:"px-3 py-2 text-right font-mono text-foreground-subtle",children:[k.ppid,k.orphaned?" ⚠":""]}),r("td",{className:"px-3 py-2 text-foreground-subtle text-[11px]",children:k.addonId??"—"}),r("td",{className:"px-3 py-2 font-mono text-[10px] text-foreground-subtle break-all",children:t7(k.command)}),r("td",{className:"px-3 py-2 text-right text-foreground",children:k.cpuPercent.toFixed(1)}),r("td",{className:"px-3 py-2 text-right text-foreground",children:Nt(k.memoryRssBytes)}),r("td",{className:"px-3 py-2 text-right text-foreground-subtle",children:e7(k.uptimeSec)}),r("td",{className:"px-3 py-2 text-right",children:u("div",{className:"inline-flex gap-1",children:[u("button",{type:"button",disabled:p.isPending||k.classification==="root"||k.classification==="system",onClick:()=>{h(k,!1)},title:"SIGTERM",className:"inline-flex items-center gap-1 px-1.5 py-0.5 rounded border border-border text-[10px] text-foreground hover:bg-surface-hover disabled:opacity-30",children:[r(We,{className:"h-3 w-3"})," Term"]}),u("button",{type:"button",disabled:p.isPending||k.classification==="root"||k.classification==="system",onClick:()=>{h(k,!0)},title:"SIGKILL",className:"inline-flex items-center gap-1 px-1.5 py-0.5 rounded border border-destructive/30 text-[10px] text-destructive hover:bg-destructive/10 disabled:opacity-30",children:[r(Ko,{className:"h-3 w-3"})," Kill"]})]})})]},k.pid))]})]})}),p.isError&&u("div",{className:"rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-[11px] text-destructive",children:["Kill failed: ",p.error instanceof Error?p.error.message:"unknown"]})]})}function r7({nodeId:e,addonIds:t}){return t.length===0?r("div",{className:"py-4 text-xs text-muted-foreground text-center",children:"No addons on this node"}):r("div",{className:"w-full py-2",children:r(Rr,{nodeId:e,addonIds:t,level:"global"})})}function o7({nodeId:e,addons:t}){const n=ke(),{data:o,isLoading:s}=hb({nodeId:e}),a=Q(()=>{const l=new Map;for(const c of t)for(const d of c.capabilities){const f=l.get(d)??[];f.push(c.id),l.set(d,f)}return[...l.entries()].sort(([c],[d])=>c.localeCompare(d)).map(([c,d])=>({capName:c,providers:d}))},[t]),i=gb({onSuccess:()=>{n.invalidateQueries({queryKey:[["pipelineOrchestrator","getCapabilityBindings"]]})}});return a.length===0?r("div",{className:"py-4 text-xs text-muted-foreground text-center",children:"No capabilities on this node"}):u("table",{className:"w-full text-xs",children:[r("thead",{children:u("tr",{className:"text-muted-foreground text-left",children:[r("th",{className:"py-2 font-medium w-1/2",children:"Capability"}),r("th",{className:"py-2 font-medium",children:"Bound provider"})]})}),r("tbody",{children:a.map(({capName:l,providers:c})=>{const f=o?.[l]??c[0]??"",p=c.length===1;return u("tr",{className:"border-t border-border/50",children:[r("td",{className:"py-2 font-medium",children:l}),r("td",{className:"py-2",children:r("select",{value:f,onChange:m=>i.mutate({nodeId:e,capName:l,addonId:m.target.value}),disabled:p||i.isPending||s,className:"w-full rounded-md border border-border bg-surface px-2 py-1 text-xs text-foreground focus:outline-none focus:ring-1 focus:ring-primary disabled:opacity-60",title:p?"Only one provider installed — choice becomes available once a second addon registers this capability":void 0,children:c.map(m=>r("option",{value:m,children:m},m))})})]},l)})})]})}function s7(e){if(e==null)return"—";const t=Math.floor(e/1e3),n=Math.floor(t/86400),o=Math.floor(t%86400/3600),s=Math.floor(t%3600/60);return n>0?`${n}d ${o}h ${s}m`:o>0?`${o}h ${s}m`:`${s}m`}function a7(e){const[t,n]=$(!1),[o,s]=$(e.name),a=ke(),i=tb({onSuccess:()=>{a.invalidateQueries({queryKey:[["nodes","topology"]]})}}),l=(e.localIps??[]).filter(p=>!p.includes(":")),c=(e.localIps??[]).filter(p=>p.includes(":")),d=async()=>{if(!o.trim()||o===e.name){n(!1);return}try{await i.mutateAsync({nodeId:e.nodeId,name:o.trim()}),n(!1)}catch(p){console.error("Rename failed:",p)}},f=[["Node ID",r("span",{className:"font-mono text-xs",children:e.nodeId})],["Display Name",t?u("div",{className:"flex items-center gap-1.5",children:[r("input",{type:"text",className:"flex-1 px-2 py-0.5 text-xs border border-border rounded bg-background focus:outline-none focus:ring-1 focus:ring-primary",value:o,onChange:p=>s(p.target.value),onKeyDown:p=>{p.key==="Enter"&&d(),p.key==="Escape"&&n(!1)},disabled:i.isPending,autoFocus:!0}),r("button",{onClick:()=>void d(),disabled:i.isPending,className:"p-0.5 text-success hover:bg-success/10 rounded",title:"Save",children:r(Ct,{className:"h-3.5 w-3.5"})}),r("button",{onClick:()=>n(!1),className:"p-0.5 text-muted-foreground hover:bg-muted rounded",title:"Cancel",children:r(qe,{className:"h-3.5 w-3.5"})})]}):u("div",{className:"flex items-center gap-1.5",children:[r("span",{className:"text-xs",children:e.name}),!e.isHub&&r("button",{onClick:()=>{s(e.name),n(!0)},className:"p-0.5 text-muted-foreground hover:text-primary rounded",title:"Rename",children:r(Po,{className:"h-3 w-3"})})]})],["Hostname",r("span",{className:"text-xs",children:e.hostname})],["Role",e.isHub?r("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-primary/10 text-primary font-medium",children:"Hub"}):r("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-muted text-muted-foreground font-medium",children:"Agent"})],["Platform",u("span",{className:"text-xs",children:[e.platform," / ",e.arch]})],["CPU",u("span",{className:"text-xs",children:[e.cpuModel??"—"," (",e.cpuCores," cores)"]})],["Memory",r("span",{className:"text-xs",children:e.memoryMB>0?`${(e.memoryMB/1024).toFixed(1)} GB`:"—"})],["Uptime",r("span",{className:"text-xs",children:s7(e.uptime)})],["Engines",e.engines.length>0?r("div",{className:"flex flex-wrap gap-1",children:e.engines.map(p=>r("span",{className:"text-[9px] px-1.5 py-0.5 rounded-full bg-purple-500/10 text-purple-400 font-medium",children:p},p))}):r("span",{className:"text-xs text-muted-foreground",children:"—"})]];return l.length>0&&f.push(["IPv4",r("div",{className:"flex flex-wrap gap-1.5",children:l.map((p,m)=>r("span",{className:"font-mono text-xs px-1.5 py-0.5 rounded bg-muted",children:p},`${p}-${m}`))})]),c.length>0&&f.push(["IPv6",r("div",{className:"flex flex-wrap gap-1.5",children:c.map((p,m)=>r("span",{className:"font-mono text-[10px] px-1.5 py-0.5 rounded bg-muted truncate max-w-[280px]",title:p,children:p},`${p}-${m}`))})]),r("div",{className:"py-2",children:r("table",{className:"w-full text-sm",children:r("tbody",{children:f.map(([p,m],h)=>u("tr",{className:h%2===0?"bg-muted/20":"",children:[r("td",{className:"py-1.5 px-2 text-xs font-medium text-muted-foreground w-28 align-top whitespace-nowrap",children:p}),r("td",{className:"py-1.5 px-2",children:m})]},p))})})})}function i7({node:e}){const[t,n]=$("info"),o=e.processes??[],s=e.addons.map(a=>a.id);return e.isOnline?u("div",{className:"border border-border rounded-xl overflow-hidden",children:[u("div",{className:"flex items-center gap-3 px-4 py-3 bg-muted/30 border-b border-border",children:[r("div",{className:"w-2.5 h-2.5 rounded-full bg-success"}),r("span",{className:"text-sm font-semibold",children:e.name}),u("span",{className:"text-xs text-muted-foreground",children:[e.cpuModel??e.platform," · ",e.memoryMB>0?`${Math.round(e.memoryMB/1024)}GB`:""," · ",e.arch]}),e.engines.map(a=>r("span",{className:"text-[9px] px-1.5 py-0.5 rounded-full bg-purple-500/10 text-purple-400 font-medium",children:a},a)),u("div",{className:"ml-auto flex gap-3 text-xs text-muted-foreground",children:[u("span",{className:"flex items-center gap-1",children:[r(ut,{className:"h-3 w-3"})," ",e.cpuPercent,"%"]}),u("span",{className:"flex items-center gap-1",children:[r(Wc,{className:"h-3 w-3"})," ",e.memoryPercent,"%"]})]})]}),r("div",{className:"flex border-b border-border px-4",children:["info","addons","forks","processes","settings","capabilities"].map(a=>r("button",{onClick:()=>n(a),className:`px-3 py-2 text-xs font-medium border-b-2 transition-colors ${t===a?"border-primary text-primary":"border-transparent text-muted-foreground hover:text-foreground"}`,children:a==="info"?"Info":a==="addons"?`Addons (${e.addons.length})`:a==="forks"?`Forks (${o.length})`:a==="processes"?"Processes":a==="settings"?"Settings":"Capabilities"},a))}),u("div",{className:"px-4 py-2",children:[t==="info"&&r(a7,{nodeId:e.id,name:e.name,hostname:e.hostname,platform:e.platform,arch:e.arch,cpuModel:e.cpuModel,cpuCores:e.cpuCores,memoryMB:e.memoryMB,engines:e.engines,isHub:e.isHub,uptime:e.uptime,localIps:e.localIps}),t==="addons"&&r(G9,{nodeId:e.id,addons:e.addons,isHub:e.isHub}),t==="forks"&&r(J9,{nodeId:e.id,processes:o}),t==="processes"&&r(n7,{nodeId:e.id}),t==="settings"&&r(r7,{nodeId:e.id,addonIds:s}),t==="capabilities"&&r(o7,{nodeId:e.id,addons:e.addons})]})]}):u("div",{className:"border border-border rounded-xl overflow-hidden opacity-60",children:[u("div",{className:"flex items-center gap-3 px-4 py-3 bg-muted/30",children:[r("div",{className:"w-2.5 h-2.5 rounded-full bg-destructive"}),r("span",{className:"text-sm font-semibold",children:e.name}),u("span",{className:"text-xs text-muted-foreground",children:[e.cpuModel??e.platform," · ",e.memoryMB>0?`${Math.round(e.memoryMB/1024)}GB`:""," · ",e.arch]}),e.engines.map(a=>r("span",{className:"text-[9px] px-1.5 py-0.5 rounded-full bg-purple-500/10 text-purple-400 font-medium",children:a},a)),r("span",{className:"ml-auto text-xs px-2 py-0.5 rounded-full bg-destructive/10 text-destructive",children:"offline"})]}),u("div",{className:"px-4 py-3 text-xs text-muted-foreground",children:[e.addons.length," addon",e.addons.length!==1?"s":""," assigned — will resume when node reconnects"]})]})}function l7({nodes:e}){const t=[...e].sort((n,o)=>n.isHub?-1:o.isHub?1:n.isOnline&&!o.isOnline?-1:!n.isOnline&&o.isOnline?1:n.name.localeCompare(o.name));return r("div",{className:"flex flex-col gap-4",children:t.map(n=>r(i7,{node:n},n.id))})}function Ue(e){if(typeof e=="string"||typeof e=="number")return""+e;let t="";if(Array.isArray(e))for(let n=0,o;n<e.length;n++)(o=Ue(e[n]))!==""&&(t+=(t&&" ")+o);else for(let n in e)e[n]&&(t+=(t&&" ")+n);return t}var c7={value:()=>{}};function Ca(){for(var e=0,t=arguments.length,n={},o;e<t;++e){if(!(o=arguments[e]+"")||o in n||/[\s.]/.test(o))throw new Error("illegal type: "+o);n[o]=[]}return new bs(n)}function bs(e){this._=e}function d7(e,t){return e.trim().split(/^|\s+/).map(function(n){var o="",s=n.indexOf(".");if(s>=0&&(o=n.slice(s+1),n=n.slice(0,s)),n&&!t.hasOwnProperty(n))throw new Error("unknown type: "+n);return{type:n,name:o}})}bs.prototype=Ca.prototype={constructor:bs,on:function(e,t){var n=this._,o=d7(e+"",n),s,a=-1,i=o.length;if(arguments.length<2){for(;++a<i;)if((s=(e=o[a]).type)&&(s=u7(n[s],e.name)))return s;return}if(t!=null&&typeof t!="function")throw new Error("invalid callback: "+t);for(;++a<i;)if(s=(e=o[a]).type)n[s]=kp(n[s],e.name,t);else if(t==null)for(s in n)n[s]=kp(n[s],e.name,null);return this},copy:function(){var e={},t=this._;for(var n in t)e[n]=t[n].slice();return new bs(e)},call:function(e,t){if((s=arguments.length-2)>0)for(var n=new Array(s),o=0,s,a;o<s;++o)n[o]=arguments[o+2];if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(a=this._[e],o=0,s=a.length;o<s;++o)a[o].value.apply(t,n)},apply:function(e,t,n){if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(var o=this._[e],s=0,a=o.length;s<a;++s)o[s].value.apply(t,n)}};function u7(e,t){for(var n=0,o=e.length,s;n<o;++n)if((s=e[n]).name===t)return s.value}function kp(e,t,n){for(var o=0,s=e.length;o<s;++o)if(e[o].name===t){e[o]=c7,e=e.slice(0,o).concat(e.slice(o+1));break}return n!=null&&e.push({name:t,value:n}),e}var fl="http://www.w3.org/1999/xhtml";const Sp={svg:"http://www.w3.org/2000/svg",xhtml:fl,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function Ma(e){var t=e+="",n=t.indexOf(":");return n>=0&&(t=e.slice(0,n))!=="xmlns"&&(e=e.slice(n+1)),Sp.hasOwnProperty(t)?{space:Sp[t],local:e}:e}function p7(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===fl&&t.documentElement.namespaceURI===fl?t.createElement(e):t.createElementNS(n,e)}}function f7(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function i0(e){var t=Ma(e);return(t.local?f7:p7)(t)}function m7(){}function rd(e){return e==null?m7:function(){return this.querySelector(e)}}function h7(e){typeof e!="function"&&(e=rd(e));for(var t=this._groups,n=t.length,o=new Array(n),s=0;s<n;++s)for(var a=t[s],i=a.length,l=o[s]=new Array(i),c,d,f=0;f<i;++f)(c=a[f])&&(d=e.call(c,c.__data__,f,a))&&("__data__"in c&&(d.__data__=c.__data__),l[f]=d);return new ft(o,this._parents)}function g7(e){return e==null?[]:Array.isArray(e)?e:Array.from(e)}function b7(){return[]}function l0(e){return e==null?b7:function(){return this.querySelectorAll(e)}}function x7(e){return function(){return g7(e.apply(this,arguments))}}function y7(e){typeof e=="function"?e=x7(e):e=l0(e);for(var t=this._groups,n=t.length,o=[],s=[],a=0;a<n;++a)for(var i=t[a],l=i.length,c,d=0;d<l;++d)(c=i[d])&&(o.push(e.call(c,c.__data__,d,i)),s.push(c));return new ft(o,s)}function c0(e){return function(){return this.matches(e)}}function d0(e){return function(t){return t.matches(e)}}var v7=Array.prototype.find;function w7(e){return function(){return v7.call(this.children,e)}}function N7(){return this.firstElementChild}function k7(e){return this.select(e==null?N7:w7(typeof e=="function"?e:d0(e)))}var S7=Array.prototype.filter;function C7(){return Array.from(this.children)}function M7(e){return function(){return S7.call(this.children,e)}}function I7(e){return this.selectAll(e==null?C7:M7(typeof e=="function"?e:d0(e)))}function A7(e){typeof e!="function"&&(e=c0(e));for(var t=this._groups,n=t.length,o=new Array(n),s=0;s<n;++s)for(var a=t[s],i=a.length,l=o[s]=[],c,d=0;d<i;++d)(c=a[d])&&e.call(c,c.__data__,d,a)&&l.push(c);return new ft(o,this._parents)}function u0(e){return new Array(e.length)}function P7(){return new ft(this._enter||this._groups.map(u0),this._parents)}function zs(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}zs.prototype={constructor:zs,appendChild:function(e){return this._parent.insertBefore(e,this._next)},insertBefore:function(e,t){return this._parent.insertBefore(e,t)},querySelector:function(e){return this._parent.querySelector(e)},querySelectorAll:function(e){return this._parent.querySelectorAll(e)}};function E7(e){return function(){return e}}function $7(e,t,n,o,s,a){for(var i=0,l,c=t.length,d=a.length;i<d;++i)(l=t[i])?(l.__data__=a[i],o[i]=l):n[i]=new zs(e,a[i]);for(;i<c;++i)(l=t[i])&&(s[i]=l)}function _7(e,t,n,o,s,a,i){var l,c,d=new Map,f=t.length,p=a.length,m=new Array(f),h;for(l=0;l<f;++l)(c=t[l])&&(m[l]=h=i.call(c,c.__data__,l,t)+"",d.has(h)?s[l]=c:d.set(h,c));for(l=0;l<p;++l)h=i.call(e,a[l],l,a)+"",(c=d.get(h))?(o[l]=c,c.__data__=a[l],d.delete(h)):n[l]=new zs(e,a[l]);for(l=0;l<f;++l)(c=t[l])&&d.get(m[l])===c&&(s[l]=c)}function D7(e){return e.__data__}function L7(e,t){if(!arguments.length)return Array.from(this,D7);var n=t?_7:$7,o=this._parents,s=this._groups;typeof e!="function"&&(e=E7(e));for(var a=s.length,i=new Array(a),l=new Array(a),c=new Array(a),d=0;d<a;++d){var f=o[d],p=s[d],m=p.length,h=T7(e.call(f,f&&f.__data__,d,o)),g=h.length,b=l[d]=new Array(g),x=i[d]=new Array(g),v=c[d]=new Array(m);n(f,p,b,x,v,h,t);for(var w=0,y=0,N,k;w<g;++w)if(N=b[w]){for(w>=y&&(y=w+1);!(k=x[y])&&++y<g;);N._next=k||null}}return i=new ft(i,o),i._enter=l,i._exit=c,i}function T7(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function R7(){return new ft(this._exit||this._groups.map(u0),this._parents)}function O7(e,t,n){var o=this.enter(),s=this,a=this.exit();return typeof e=="function"?(o=e(o),o&&(o=o.selection())):o=o.append(e+""),t!=null&&(s=t(s),s&&(s=s.selection())),n==null?a.remove():n(a),o&&s?o.merge(s).order():s}function z7(e){for(var t=e.selection?e.selection():e,n=this._groups,o=t._groups,s=n.length,a=o.length,i=Math.min(s,a),l=new Array(s),c=0;c<i;++c)for(var d=n[c],f=o[c],p=d.length,m=l[c]=new Array(p),h,g=0;g<p;++g)(h=d[g]||f[g])&&(m[g]=h);for(;c<s;++c)l[c]=n[c];return new ft(l,this._parents)}function B7(){for(var e=this._groups,t=-1,n=e.length;++t<n;)for(var o=e[t],s=o.length-1,a=o[s],i;--s>=0;)(i=o[s])&&(a&&i.compareDocumentPosition(a)^4&&a.parentNode.insertBefore(i,a),a=i);return this}function F7(e){e||(e=j7);function t(p,m){return p&&m?e(p.__data__,m.__data__):!p-!m}for(var n=this._groups,o=n.length,s=new Array(o),a=0;a<o;++a){for(var i=n[a],l=i.length,c=s[a]=new Array(l),d,f=0;f<l;++f)(d=i[f])&&(c[f]=d);c.sort(t)}return new ft(s,this._parents).order()}function j7(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function H7(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function V7(){return Array.from(this)}function q7(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var o=e[t],s=0,a=o.length;s<a;++s){var i=o[s];if(i)return i}return null}function Q7(){let e=0;for(const t of this)++e;return e}function U7(){return!this.node()}function K7(e){for(var t=this._groups,n=0,o=t.length;n<o;++n)for(var s=t[n],a=0,i=s.length,l;a<i;++a)(l=s[a])&&e.call(l,l.__data__,a,s);return this}function G7(e){return function(){this.removeAttribute(e)}}function W7(e){return function(){this.removeAttributeNS(e.space,e.local)}}function Y7(e,t){return function(){this.setAttribute(e,t)}}function Z7(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function X7(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttribute(e):this.setAttribute(e,n)}}function J7(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttributeNS(e.space,e.local):this.setAttributeNS(e.space,e.local,n)}}function ez(e,t){var n=Ma(e);if(arguments.length<2){var o=this.node();return n.local?o.getAttributeNS(n.space,n.local):o.getAttribute(n)}return this.each((t==null?n.local?W7:G7:typeof t=="function"?n.local?J7:X7:n.local?Z7:Y7)(n,t))}function p0(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function tz(e){return function(){this.style.removeProperty(e)}}function nz(e,t,n){return function(){this.style.setProperty(e,t,n)}}function rz(e,t,n){return function(){var o=t.apply(this,arguments);o==null?this.style.removeProperty(e):this.style.setProperty(e,o,n)}}function oz(e,t,n){return arguments.length>1?this.each((t==null?tz:typeof t=="function"?rz:nz)(e,t,n??"")):vr(this.node(),e)}function vr(e,t){return e.style.getPropertyValue(t)||p0(e).getComputedStyle(e,null).getPropertyValue(t)}function sz(e){return function(){delete this[e]}}function az(e,t){return function(){this[e]=t}}function iz(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function lz(e,t){return arguments.length>1?this.each((t==null?sz:typeof t=="function"?iz:az)(e,t)):this.node()[e]}function f0(e){return e.trim().split(/^|\s+/)}function od(e){return e.classList||new m0(e)}function m0(e){this._node=e,this._names=f0(e.getAttribute("class")||"")}m0.prototype={add:function(e){var t=this._names.indexOf(e);t<0&&(this._names.push(e),this._node.setAttribute("class",this._names.join(" ")))},remove:function(e){var t=this._names.indexOf(e);t>=0&&(this._names.splice(t,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(e){return this._names.indexOf(e)>=0}};function h0(e,t){for(var n=od(e),o=-1,s=t.length;++o<s;)n.add(t[o])}function g0(e,t){for(var n=od(e),o=-1,s=t.length;++o<s;)n.remove(t[o])}function cz(e){return function(){h0(this,e)}}function dz(e){return function(){g0(this,e)}}function uz(e,t){return function(){(t.apply(this,arguments)?h0:g0)(this,e)}}function pz(e,t){var n=f0(e+"");if(arguments.length<2){for(var o=od(this.node()),s=-1,a=n.length;++s<a;)if(!o.contains(n[s]))return!1;return!0}return this.each((typeof t=="function"?uz:t?cz:dz)(n,t))}function fz(){this.textContent=""}function mz(e){return function(){this.textContent=e}}function hz(e){return function(){var t=e.apply(this,arguments);this.textContent=t??""}}function gz(e){return arguments.length?this.each(e==null?fz:(typeof e=="function"?hz:mz)(e)):this.node().textContent}function bz(){this.innerHTML=""}function xz(e){return function(){this.innerHTML=e}}function yz(e){return function(){var t=e.apply(this,arguments);this.innerHTML=t??""}}function vz(e){return arguments.length?this.each(e==null?bz:(typeof e=="function"?yz:xz)(e)):this.node().innerHTML}function wz(){this.nextSibling&&this.parentNode.appendChild(this)}function Nz(){return this.each(wz)}function kz(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function Sz(){return this.each(kz)}function Cz(e){var t=typeof e=="function"?e:i0(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})}function Mz(){return null}function Iz(e,t){var n=typeof e=="function"?e:i0(e),o=t==null?Mz:typeof t=="function"?t:rd(t);return this.select(function(){return this.insertBefore(n.apply(this,arguments),o.apply(this,arguments)||null)})}function Az(){var e=this.parentNode;e&&e.removeChild(this)}function Pz(){return this.each(Az)}function Ez(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function $z(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function _z(e){return this.select(e?$z:Ez)}function Dz(e){return arguments.length?this.property("__data__",e):this.node().__data__}function Lz(e){return function(t){e.call(this,t,this.__data__)}}function Tz(e){return e.trim().split(/^|\s+/).map(function(t){var n="",o=t.indexOf(".");return o>=0&&(n=t.slice(o+1),t=t.slice(0,o)),{type:t,name:n}})}function Rz(e){return function(){var t=this.__on;if(t){for(var n=0,o=-1,s=t.length,a;n<s;++n)a=t[n],(!e.type||a.type===e.type)&&a.name===e.name?this.removeEventListener(a.type,a.listener,a.options):t[++o]=a;++o?t.length=o:delete this.__on}}}function Oz(e,t,n){return function(){var o=this.__on,s,a=Lz(t);if(o){for(var i=0,l=o.length;i<l;++i)if((s=o[i]).type===e.type&&s.name===e.name){this.removeEventListener(s.type,s.listener,s.options),this.addEventListener(s.type,s.listener=a,s.options=n),s.value=t;return}}this.addEventListener(e.type,a,n),s={type:e.type,name:e.name,value:t,listener:a,options:n},o?o.push(s):this.__on=[s]}}function zz(e,t,n){var o=Tz(e+""),s,a=o.length,i;if(arguments.length<2){var l=this.node().__on;if(l){for(var c=0,d=l.length,f;c<d;++c)for(s=0,f=l[c];s<a;++s)if((i=o[s]).type===f.type&&i.name===f.name)return f.value}return}for(l=t?Oz:Rz,s=0;s<a;++s)this.each(l(o[s],t,n));return this}function b0(e,t,n){var o=p0(e),s=o.CustomEvent;typeof s=="function"?s=new s(t,n):(s=o.document.createEvent("Event"),n?(s.initEvent(t,n.bubbles,n.cancelable),s.detail=n.detail):s.initEvent(t,!1,!1)),e.dispatchEvent(s)}function Bz(e,t){return function(){return b0(this,e,t)}}function Fz(e,t){return function(){return b0(this,e,t.apply(this,arguments))}}function jz(e,t){return this.each((typeof t=="function"?Fz:Bz)(e,t))}function*Hz(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var o=e[t],s=0,a=o.length,i;s<a;++s)(i=o[s])&&(yield i)}var x0=[null];function ft(e,t){this._groups=e,this._parents=t}function $o(){return new ft([[document.documentElement]],x0)}function Vz(){return this}ft.prototype=$o.prototype={constructor:ft,select:h7,selectAll:y7,selectChild:k7,selectChildren:I7,filter:A7,data:L7,enter:P7,exit:R7,join:O7,merge:z7,selection:Vz,order:B7,sort:F7,call:H7,nodes:V7,node:q7,size:Q7,empty:U7,each:K7,attr:ez,style:oz,property:lz,classed:pz,text:gz,html:vz,raise:Nz,lower:Sz,append:Cz,insert:Iz,remove:Pz,clone:_z,datum:Dz,on:zz,dispatch:jz,[Symbol.iterator]:Hz};function lt(e){return typeof e=="string"?new ft([[document.querySelector(e)]],[document.documentElement]):new ft([[e]],x0)}function qz(e){let t;for(;t=e.sourceEvent;)e=t;return e}function Pt(e,t){if(e=qz(e),t===void 0&&(t=e.currentTarget),t){var n=t.ownerSVGElement||t;if(n.createSVGPoint){var o=n.createSVGPoint();return o.x=e.clientX,o.y=e.clientY,o=o.matrixTransform(t.getScreenCTM().inverse()),[o.x,o.y]}if(t.getBoundingClientRect){var s=t.getBoundingClientRect();return[e.clientX-s.left-t.clientLeft,e.clientY-s.top-t.clientTop]}}return[e.pageX,e.pageY]}const Qz={passive:!1},uo={capture:!0,passive:!1};function ki(e){e.stopImmediatePropagation()}function ur(e){e.preventDefault(),e.stopImmediatePropagation()}function y0(e){var t=e.document.documentElement,n=lt(e).on("dragstart.drag",ur,uo);"onselectstart"in t?n.on("selectstart.drag",ur,uo):(t.__noselect=t.style.MozUserSelect,t.style.MozUserSelect="none")}function v0(e,t){var n=e.document.documentElement,o=lt(e).on("dragstart.drag",null);t&&(o.on("click.drag",ur,uo),setTimeout(function(){o.on("click.drag",null)},0)),"onselectstart"in n?o.on("selectstart.drag",null):(n.style.MozUserSelect=n.__noselect,delete n.__noselect)}const rs=e=>()=>e;function ml(e,{sourceEvent:t,subject:n,target:o,identifier:s,active:a,x:i,y:l,dx:c,dy:d,dispatch:f}){Object.defineProperties(this,{type:{value:e,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},subject:{value:n,enumerable:!0,configurable:!0},target:{value:o,enumerable:!0,configurable:!0},identifier:{value:s,enumerable:!0,configurable:!0},active:{value:a,enumerable:!0,configurable:!0},x:{value:i,enumerable:!0,configurable:!0},y:{value:l,enumerable:!0,configurable:!0},dx:{value:c,enumerable:!0,configurable:!0},dy:{value:d,enumerable:!0,configurable:!0},_:{value:f}})}ml.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};function Uz(e){return!e.ctrlKey&&!e.button}function Kz(){return this.parentNode}function Gz(e,t){return t??{x:e.x,y:e.y}}function Wz(){return navigator.maxTouchPoints||"ontouchstart"in this}function w0(){var e=Uz,t=Kz,n=Gz,o=Wz,s={},a=Ca("start","drag","end"),i=0,l,c,d,f,p=0;function m(N){N.on("mousedown.drag",h).filter(o).on("touchstart.drag",x).on("touchmove.drag",v,Qz).on("touchend.drag touchcancel.drag",w).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function h(N,k){if(!(f||!e.call(this,N,k))){var S=y(this,t.call(this,N,k),N,k,"mouse");S&&(lt(N.view).on("mousemove.drag",g,uo).on("mouseup.drag",b,uo),y0(N.view),ki(N),d=!1,l=N.clientX,c=N.clientY,S("start",N))}}function g(N){if(ur(N),!d){var k=N.clientX-l,S=N.clientY-c;d=k*k+S*S>p}s.mouse("drag",N)}function b(N){lt(N.view).on("mousemove.drag mouseup.drag",null),v0(N.view,d),ur(N),s.mouse("end",N)}function x(N,k){if(e.call(this,N,k)){var S=N.changedTouches,M=t.call(this,N,k),P=S.length,I,F;for(I=0;I<P;++I)(F=y(this,M,N,k,S[I].identifier,S[I]))&&(ki(N),F("start",N,S[I]))}}function v(N){var k=N.changedTouches,S=k.length,M,P;for(M=0;M<S;++M)(P=s[k[M].identifier])&&(ur(N),P("drag",N,k[M]))}function w(N){var k=N.changedTouches,S=k.length,M,P;for(f&&clearTimeout(f),f=setTimeout(function(){f=null},500),M=0;M<S;++M)(P=s[k[M].identifier])&&(ki(N),P("end",N,k[M]))}function y(N,k,S,M,P,I){var F=a.copy(),E=Pt(I||S,k),B,O,A;if((A=n.call(N,new ml("beforestart",{sourceEvent:S,target:m,identifier:P,active:i,x:E[0],y:E[1],dx:0,dy:0,dispatch:F}),M))!=null)return B=A.x-E[0]||0,O=A.y-E[1]||0,function D(_,R,L){var z=E,j;switch(_){case"start":s[P]=D,j=i++;break;case"end":delete s[P],--i;case"drag":E=Pt(L||R,k),j=i;break}F.call(_,N,new ml(_,{sourceEvent:R,subject:A,target:m,identifier:P,active:j,x:E[0]+B,y:E[1]+O,dx:E[0]-z[0],dy:E[1]-z[1],dispatch:F}),M)}}return m.filter=function(N){return arguments.length?(e=typeof N=="function"?N:rs(!!N),m):e},m.container=function(N){return arguments.length?(t=typeof N=="function"?N:rs(N),m):t},m.subject=function(N){return arguments.length?(n=typeof N=="function"?N:rs(N),m):n},m.touchable=function(N){return arguments.length?(o=typeof N=="function"?N:rs(!!N),m):o},m.on=function(){var N=a.on.apply(a,arguments);return N===a?m:N},m.clickDistance=function(N){return arguments.length?(p=(N=+N)*N,m):Math.sqrt(p)},m}function sd(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function N0(e,t){var n=Object.create(e.prototype);for(var o in t)n[o]=t[o];return n}function _o(){}var po=.7,Bs=1/po,pr="\\s*([+-]?\\d+)\\s*",fo="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",Ut="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",Yz=/^#([0-9a-f]{3,8})$/,Zz=new RegExp(`^rgb\\(${pr},${pr},${pr}\\)$`),Xz=new RegExp(`^rgb\\(${Ut},${Ut},${Ut}\\)$`),Jz=new RegExp(`^rgba\\(${pr},${pr},${pr},${fo}\\)$`),eB=new RegExp(`^rgba\\(${Ut},${Ut},${Ut},${fo}\\)$`),tB=new RegExp(`^hsl\\(${fo},${Ut},${Ut}\\)$`),nB=new RegExp(`^hsla\\(${fo},${Ut},${Ut},${fo}\\)$`),Cp={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074};sd(_o,Vn,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:Mp,formatHex:Mp,formatHex8:rB,formatHsl:oB,formatRgb:Ip,toString:Ip});function Mp(){return this.rgb().formatHex()}function rB(){return this.rgb().formatHex8()}function oB(){return k0(this).formatHsl()}function Ip(){return this.rgb().formatRgb()}function Vn(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=Yz.exec(e))?(n=t[1].length,t=parseInt(t[1],16),n===6?Ap(t):n===3?new nt(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?os(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?os(t>>12&15|t>>8&240,t>>8&15|t>>4&240,t>>4&15|t&240,((t&15)<<4|t&15)/255):null):(t=Zz.exec(e))?new nt(t[1],t[2],t[3],1):(t=Xz.exec(e))?new nt(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=Jz.exec(e))?os(t[1],t[2],t[3],t[4]):(t=eB.exec(e))?os(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=tB.exec(e))?$p(t[1],t[2]/100,t[3]/100,1):(t=nB.exec(e))?$p(t[1],t[2]/100,t[3]/100,t[4]):Cp.hasOwnProperty(e)?Ap(Cp[e]):e==="transparent"?new nt(NaN,NaN,NaN,0):null}function Ap(e){return new nt(e>>16&255,e>>8&255,e&255,1)}function os(e,t,n,o){return o<=0&&(e=t=n=NaN),new nt(e,t,n,o)}function sB(e){return e instanceof _o||(e=Vn(e)),e?(e=e.rgb(),new nt(e.r,e.g,e.b,e.opacity)):new nt}function hl(e,t,n,o){return arguments.length===1?sB(e):new nt(e,t,n,o??1)}function nt(e,t,n,o){this.r=+e,this.g=+t,this.b=+n,this.opacity=+o}sd(nt,hl,N0(_o,{brighter(e){return e=e==null?Bs:Math.pow(Bs,e),new nt(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?po:Math.pow(po,e),new nt(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new nt(zn(this.r),zn(this.g),zn(this.b),Fs(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:Pp,formatHex:Pp,formatHex8:aB,formatRgb:Ep,toString:Ep}));function Pp(){return`#${Tn(this.r)}${Tn(this.g)}${Tn(this.b)}`}function aB(){return`#${Tn(this.r)}${Tn(this.g)}${Tn(this.b)}${Tn((isNaN(this.opacity)?1:this.opacity)*255)}`}function Ep(){const e=Fs(this.opacity);return`${e===1?"rgb(":"rgba("}${zn(this.r)}, ${zn(this.g)}, ${zn(this.b)}${e===1?")":`, ${e})`}`}function Fs(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function zn(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function Tn(e){return e=zn(e),(e<16?"0":"")+e.toString(16)}function $p(e,t,n,o){return o<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new Et(e,t,n,o)}function k0(e){if(e instanceof Et)return new Et(e.h,e.s,e.l,e.opacity);if(e instanceof _o||(e=Vn(e)),!e)return new Et;if(e instanceof Et)return e;e=e.rgb();var t=e.r/255,n=e.g/255,o=e.b/255,s=Math.min(t,n,o),a=Math.max(t,n,o),i=NaN,l=a-s,c=(a+s)/2;return l?(t===a?i=(n-o)/l+(n<o)*6:n===a?i=(o-t)/l+2:i=(t-n)/l+4,l/=c<.5?a+s:2-a-s,i*=60):l=c>0&&c<1?0:i,new Et(i,l,c,e.opacity)}function iB(e,t,n,o){return arguments.length===1?k0(e):new Et(e,t,n,o??1)}function Et(e,t,n,o){this.h=+e,this.s=+t,this.l=+n,this.opacity=+o}sd(Et,iB,N0(_o,{brighter(e){return e=e==null?Bs:Math.pow(Bs,e),new Et(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?po:Math.pow(po,e),new Et(this.h,this.s,this.l*e,this.opacity)},rgb(){var e=this.h%360+(this.h<0)*360,t=isNaN(e)||isNaN(this.s)?0:this.s,n=this.l,o=n+(n<.5?n:1-n)*t,s=2*n-o;return new nt(Si(e>=240?e-240:e+120,s,o),Si(e,s,o),Si(e<120?e+240:e-120,s,o),this.opacity)},clamp(){return new Et(_p(this.h),ss(this.s),ss(this.l),Fs(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){const e=Fs(this.opacity);return`${e===1?"hsl(":"hsla("}${_p(this.h)}, ${ss(this.s)*100}%, ${ss(this.l)*100}%${e===1?")":`, ${e})`}`}}));function _p(e){return e=(e||0)%360,e<0?e+360:e}function ss(e){return Math.max(0,Math.min(1,e||0))}function Si(e,t,n){return(e<60?t+(n-t)*e/60:e<180?n:e<240?t+(n-t)*(240-e)/60:t)*255}const ad=e=>()=>e;function lB(e,t){return function(n){return e+n*t}}function cB(e,t,n){return e=Math.pow(e,n),t=Math.pow(t,n)-e,n=1/n,function(o){return Math.pow(e+o*t,n)}}function dB(e){return(e=+e)==1?S0:function(t,n){return n-t?cB(t,n,e):ad(isNaN(t)?n:t)}}function S0(e,t){var n=t-e;return n?lB(e,n):ad(isNaN(e)?t:e)}const js=(function e(t){var n=dB(t);function o(s,a){var i=n((s=hl(s)).r,(a=hl(a)).r),l=n(s.g,a.g),c=n(s.b,a.b),d=S0(s.opacity,a.opacity);return function(f){return s.r=i(f),s.g=l(f),s.b=c(f),s.opacity=d(f),s+""}}return o.gamma=e,o})(1);function uB(e,t){t||(t=[]);var n=e?Math.min(t.length,e.length):0,o=t.slice(),s;return function(a){for(s=0;s<n;++s)o[s]=e[s]*(1-a)+t[s]*a;return o}}function pB(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function fB(e,t){var n=t?t.length:0,o=e?Math.min(n,e.length):0,s=new Array(o),a=new Array(n),i;for(i=0;i<o;++i)s[i]=no(e[i],t[i]);for(;i<n;++i)a[i]=t[i];return function(l){for(i=0;i<o;++i)a[i]=s[i](l);return a}}function mB(e,t){var n=new Date;return e=+e,t=+t,function(o){return n.setTime(e*(1-o)+t*o),n}}function Vt(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}function hB(e,t){var n={},o={},s;(e===null||typeof e!="object")&&(e={}),(t===null||typeof t!="object")&&(t={});for(s in t)s in e?n[s]=no(e[s],t[s]):o[s]=t[s];return function(a){for(s in n)o[s]=n[s](a);return o}}var gl=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,Ci=new RegExp(gl.source,"g");function gB(e){return function(){return e}}function bB(e){return function(t){return e(t)+""}}function C0(e,t){var n=gl.lastIndex=Ci.lastIndex=0,o,s,a,i=-1,l=[],c=[];for(e=e+"",t=t+"";(o=gl.exec(e))&&(s=Ci.exec(t));)(a=s.index)>n&&(a=t.slice(n,a),l[i]?l[i]+=a:l[++i]=a),(o=o[0])===(s=s[0])?l[i]?l[i]+=s:l[++i]=s:(l[++i]=null,c.push({i,x:Vt(o,s)})),n=Ci.lastIndex;return n<t.length&&(a=t.slice(n),l[i]?l[i]+=a:l[++i]=a),l.length<2?c[0]?bB(c[0].x):gB(t):(t=c.length,function(d){for(var f=0,p;f<t;++f)l[(p=c[f]).i]=p.x(d);return l.join("")})}function no(e,t){var n=typeof t,o;return t==null||n==="boolean"?ad(t):(n==="number"?Vt:n==="string"?(o=Vn(t))?(t=o,js):C0:t instanceof Vn?js:t instanceof Date?mB:pB(t)?uB:Array.isArray(t)?fB:typeof t.valueOf!="function"&&typeof t.toString!="function"||isNaN(t)?hB:Vt)(e,t)}var Dp=180/Math.PI,bl={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function M0(e,t,n,o,s,a){var i,l,c;return(i=Math.sqrt(e*e+t*t))&&(e/=i,t/=i),(c=e*n+t*o)&&(n-=e*c,o-=t*c),(l=Math.sqrt(n*n+o*o))&&(n/=l,o/=l,c/=l),e*o<t*n&&(e=-e,t=-t,c=-c,i=-i),{translateX:s,translateY:a,rotate:Math.atan2(t,e)*Dp,skewX:Math.atan(c)*Dp,scaleX:i,scaleY:l}}var as;function xB(e){const t=new(typeof DOMMatrix=="function"?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?bl:M0(t.a,t.b,t.c,t.d,t.e,t.f)}function yB(e){return e==null||(as||(as=document.createElementNS("http://www.w3.org/2000/svg","g")),as.setAttribute("transform",e),!(e=as.transform.baseVal.consolidate()))?bl:(e=e.matrix,M0(e.a,e.b,e.c,e.d,e.e,e.f))}function I0(e,t,n,o){function s(d){return d.length?d.pop()+" ":""}function a(d,f,p,m,h,g){if(d!==p||f!==m){var b=h.push("translate(",null,t,null,n);g.push({i:b-4,x:Vt(d,p)},{i:b-2,x:Vt(f,m)})}else(p||m)&&h.push("translate("+p+t+m+n)}function i(d,f,p,m){d!==f?(d-f>180?f+=360:f-d>180&&(d+=360),m.push({i:p.push(s(p)+"rotate(",null,o)-2,x:Vt(d,f)})):f&&p.push(s(p)+"rotate("+f+o)}function l(d,f,p,m){d!==f?m.push({i:p.push(s(p)+"skewX(",null,o)-2,x:Vt(d,f)}):f&&p.push(s(p)+"skewX("+f+o)}function c(d,f,p,m,h,g){if(d!==p||f!==m){var b=h.push(s(h)+"scale(",null,",",null,")");g.push({i:b-4,x:Vt(d,p)},{i:b-2,x:Vt(f,m)})}else(p!==1||m!==1)&&h.push(s(h)+"scale("+p+","+m+")")}return function(d,f){var p=[],m=[];return d=e(d),f=e(f),a(d.translateX,d.translateY,f.translateX,f.translateY,p,m),i(d.rotate,f.rotate,p,m),l(d.skewX,f.skewX,p,m),c(d.scaleX,d.scaleY,f.scaleX,f.scaleY,p,m),d=f=null,function(h){for(var g=-1,b=m.length,x;++g<b;)p[(x=m[g]).i]=x.x(h);return p.join("")}}}var vB=I0(xB,"px, ","px)","deg)"),wB=I0(yB,", ",")",")"),NB=1e-12;function Lp(e){return((e=Math.exp(e))+1/e)/2}function kB(e){return((e=Math.exp(e))-1/e)/2}function SB(e){return((e=Math.exp(2*e))-1)/(e+1)}const xs=(function e(t,n,o){function s(a,i){var l=a[0],c=a[1],d=a[2],f=i[0],p=i[1],m=i[2],h=f-l,g=p-c,b=h*h+g*g,x,v;if(b<NB)v=Math.log(m/d)/t,x=function(M){return[l+M*h,c+M*g,d*Math.exp(t*M*v)]};else{var w=Math.sqrt(b),y=(m*m-d*d+o*b)/(2*d*n*w),N=(m*m-d*d-o*b)/(2*m*n*w),k=Math.log(Math.sqrt(y*y+1)-y),S=Math.log(Math.sqrt(N*N+1)-N);v=(S-k)/t,x=function(M){var P=M*v,I=Lp(k),F=d/(n*w)*(I*SB(t*P+k)-kB(k));return[l+F*h,c+F*g,d*I/Lp(t*P+k)]}}return x.duration=v*1e3*t/Math.SQRT2,x}return s.rho=function(a){var i=Math.max(.001,+a),l=i*i,c=l*l;return e(i,l,c)},s})(Math.SQRT2,2,4);var wr=0,Kr=0,Vr=0,A0=1e3,Hs,Gr,Vs=0,qn=0,Ia=0,mo=typeof performance=="object"&&performance.now?performance:Date,P0=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function id(){return qn||(P0(CB),qn=mo.now()+Ia)}function CB(){qn=0}function qs(){this._call=this._time=this._next=null}qs.prototype=E0.prototype={constructor:qs,restart:function(e,t,n){if(typeof e!="function")throw new TypeError("callback is not a function");n=(n==null?id():+n)+(t==null?0:+t),!this._next&&Gr!==this&&(Gr?Gr._next=this:Hs=this,Gr=this),this._call=e,this._time=n,xl()},stop:function(){this._call&&(this._call=null,this._time=1/0,xl())}};function E0(e,t,n){var o=new qs;return o.restart(e,t,n),o}function MB(){id(),++wr;for(var e=Hs,t;e;)(t=qn-e._time)>=0&&e._call.call(void 0,t),e=e._next;--wr}function Tp(){qn=(Vs=mo.now())+Ia,wr=Kr=0;try{MB()}finally{wr=0,AB(),qn=0}}function IB(){var e=mo.now(),t=e-Vs;t>A0&&(Ia-=t,Vs=e)}function AB(){for(var e,t=Hs,n,o=1/0;t;)t._call?(o>t._time&&(o=t._time),e=t,t=t._next):(n=t._next,t._next=null,t=e?e._next=n:Hs=n);Gr=e,xl(o)}function xl(e){if(!wr){Kr&&(Kr=clearTimeout(Kr));var t=e-qn;t>24?(e<1/0&&(Kr=setTimeout(Tp,e-mo.now()-Ia)),Vr&&(Vr=clearInterval(Vr))):(Vr||(Vs=mo.now(),Vr=setInterval(IB,A0)),wr=1,P0(Tp))}}function Rp(e,t,n){var o=new qs;return t=t==null?0:+t,o.restart(s=>{o.stop(),e(s+t)},t,n),o}var PB=Ca("start","end","cancel","interrupt"),EB=[],$0=0,Op=1,yl=2,ys=3,zp=4,vl=5,vs=6;function Aa(e,t,n,o,s,a){var i=e.__transition;if(!i)e.__transition={};else if(n in i)return;$B(e,n,{name:t,index:o,group:s,on:PB,tween:EB,time:a.time,delay:a.delay,duration:a.duration,ease:a.ease,timer:null,state:$0})}function ld(e,t){var n=Bt(e,t);if(n.state>$0)throw new Error("too late; already scheduled");return n}function Yt(e,t){var n=Bt(e,t);if(n.state>ys)throw new Error("too late; already running");return n}function Bt(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw new Error("transition not found");return n}function $B(e,t,n){var o=e.__transition,s;o[t]=n,n.timer=E0(a,0,n.time);function a(d){n.state=Op,n.timer.restart(i,n.delay,n.time),n.delay<=d&&i(d-n.delay)}function i(d){var f,p,m,h;if(n.state!==Op)return c();for(f in o)if(h=o[f],h.name===n.name){if(h.state===ys)return Rp(i);h.state===zp?(h.state=vs,h.timer.stop(),h.on.call("interrupt",e,e.__data__,h.index,h.group),delete o[f]):+f<t&&(h.state=vs,h.timer.stop(),h.on.call("cancel",e,e.__data__,h.index,h.group),delete o[f])}if(Rp(function(){n.state===ys&&(n.state=zp,n.timer.restart(l,n.delay,n.time),l(d))}),n.state=yl,n.on.call("start",e,e.__data__,n.index,n.group),n.state===yl){for(n.state=ys,s=new Array(m=n.tween.length),f=0,p=-1;f<m;++f)(h=n.tween[f].value.call(e,e.__data__,n.index,n.group))&&(s[++p]=h);s.length=p+1}}function l(d){for(var f=d<n.duration?n.ease.call(null,d/n.duration):(n.timer.restart(c),n.state=vl,1),p=-1,m=s.length;++p<m;)s[p].call(e,f);n.state===vl&&(n.on.call("end",e,e.__data__,n.index,n.group),c())}function c(){n.state=vs,n.timer.stop(),delete o[t];for(var d in o)return;delete e.__transition}}function ws(e,t){var n=e.__transition,o,s,a=!0,i;if(n){t=t==null?null:t+"";for(i in n){if((o=n[i]).name!==t){a=!1;continue}s=o.state>yl&&o.state<vl,o.state=vs,o.timer.stop(),o.on.call(s?"interrupt":"cancel",e,e.__data__,o.index,o.group),delete n[i]}a&&delete e.__transition}}function _B(e){return this.each(function(){ws(this,e)})}function DB(e,t){var n,o;return function(){var s=Yt(this,e),a=s.tween;if(a!==n){o=n=a;for(var i=0,l=o.length;i<l;++i)if(o[i].name===t){o=o.slice(),o.splice(i,1);break}}s.tween=o}}function LB(e,t,n){var o,s;if(typeof n!="function")throw new Error;return function(){var a=Yt(this,e),i=a.tween;if(i!==o){s=(o=i).slice();for(var l={name:t,value:n},c=0,d=s.length;c<d;++c)if(s[c].name===t){s[c]=l;break}c===d&&s.push(l)}a.tween=s}}function TB(e,t){var n=this._id;if(e+="",arguments.length<2){for(var o=Bt(this.node(),n).tween,s=0,a=o.length,i;s<a;++s)if((i=o[s]).name===e)return i.value;return null}return this.each((t==null?DB:LB)(n,e,t))}function cd(e,t,n){var o=e._id;return e.each(function(){var s=Yt(this,o);(s.value||(s.value={}))[t]=n.apply(this,arguments)}),function(s){return Bt(s,o).value[t]}}function _0(e,t){var n;return(typeof t=="number"?Vt:t instanceof Vn?js:(n=Vn(t))?(t=n,js):C0)(e,t)}function RB(e){return function(){this.removeAttribute(e)}}function OB(e){return function(){this.removeAttributeNS(e.space,e.local)}}function zB(e,t,n){var o,s=n+"",a;return function(){var i=this.getAttribute(e);return i===s?null:i===o?a:a=t(o=i,n)}}function BB(e,t,n){var o,s=n+"",a;return function(){var i=this.getAttributeNS(e.space,e.local);return i===s?null:i===o?a:a=t(o=i,n)}}function FB(e,t,n){var o,s,a;return function(){var i,l=n(this),c;return l==null?void this.removeAttribute(e):(i=this.getAttribute(e),c=l+"",i===c?null:i===o&&c===s?a:(s=c,a=t(o=i,l)))}}function jB(e,t,n){var o,s,a;return function(){var i,l=n(this),c;return l==null?void this.removeAttributeNS(e.space,e.local):(i=this.getAttributeNS(e.space,e.local),c=l+"",i===c?null:i===o&&c===s?a:(s=c,a=t(o=i,l)))}}function HB(e,t){var n=Ma(e),o=n==="transform"?wB:_0;return this.attrTween(e,typeof t=="function"?(n.local?jB:FB)(n,o,cd(this,"attr."+e,t)):t==null?(n.local?OB:RB)(n):(n.local?BB:zB)(n,o,t))}function VB(e,t){return function(n){this.setAttribute(e,t.call(this,n))}}function qB(e,t){return function(n){this.setAttributeNS(e.space,e.local,t.call(this,n))}}function QB(e,t){var n,o;function s(){var a=t.apply(this,arguments);return a!==o&&(n=(o=a)&&qB(e,a)),n}return s._value=t,s}function UB(e,t){var n,o;function s(){var a=t.apply(this,arguments);return a!==o&&(n=(o=a)&&VB(e,a)),n}return s._value=t,s}function KB(e,t){var n="attr."+e;if(arguments.length<2)return(n=this.tween(n))&&n._value;if(t==null)return this.tween(n,null);if(typeof t!="function")throw new Error;var o=Ma(e);return this.tween(n,(o.local?QB:UB)(o,t))}function GB(e,t){return function(){ld(this,e).delay=+t.apply(this,arguments)}}function WB(e,t){return t=+t,function(){ld(this,e).delay=t}}function YB(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?GB:WB)(t,e)):Bt(this.node(),t).delay}function ZB(e,t){return function(){Yt(this,e).duration=+t.apply(this,arguments)}}function XB(e,t){return t=+t,function(){Yt(this,e).duration=t}}function JB(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?ZB:XB)(t,e)):Bt(this.node(),t).duration}function eF(e,t){if(typeof t!="function")throw new Error;return function(){Yt(this,e).ease=t}}function tF(e){var t=this._id;return arguments.length?this.each(eF(t,e)):Bt(this.node(),t).ease}function nF(e,t){return function(){var n=t.apply(this,arguments);if(typeof n!="function")throw new Error;Yt(this,e).ease=n}}function rF(e){if(typeof e!="function")throw new Error;return this.each(nF(this._id,e))}function oF(e){typeof e!="function"&&(e=c0(e));for(var t=this._groups,n=t.length,o=new Array(n),s=0;s<n;++s)for(var a=t[s],i=a.length,l=o[s]=[],c,d=0;d<i;++d)(c=a[d])&&e.call(c,c.__data__,d,a)&&l.push(c);return new dn(o,this._parents,this._name,this._id)}function sF(e){if(e._id!==this._id)throw new Error;for(var t=this._groups,n=e._groups,o=t.length,s=n.length,a=Math.min(o,s),i=new Array(o),l=0;l<a;++l)for(var c=t[l],d=n[l],f=c.length,p=i[l]=new Array(f),m,h=0;h<f;++h)(m=c[h]||d[h])&&(p[h]=m);for(;l<o;++l)i[l]=t[l];return new dn(i,this._parents,this._name,this._id)}function aF(e){return(e+"").trim().split(/^|\s+/).every(function(t){var n=t.indexOf(".");return n>=0&&(t=t.slice(0,n)),!t||t==="start"})}function iF(e,t,n){var o,s,a=aF(t)?ld:Yt;return function(){var i=a(this,e),l=i.on;l!==o&&(s=(o=l).copy()).on(t,n),i.on=s}}function lF(e,t){var n=this._id;return arguments.length<2?Bt(this.node(),n).on.on(e):this.each(iF(n,e,t))}function cF(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function dF(){return this.on("end.remove",cF(this._id))}function uF(e){var t=this._name,n=this._id;typeof e!="function"&&(e=rd(e));for(var o=this._groups,s=o.length,a=new Array(s),i=0;i<s;++i)for(var l=o[i],c=l.length,d=a[i]=new Array(c),f,p,m=0;m<c;++m)(f=l[m])&&(p=e.call(f,f.__data__,m,l))&&("__data__"in f&&(p.__data__=f.__data__),d[m]=p,Aa(d[m],t,n,m,d,Bt(f,n)));return new dn(a,this._parents,t,n)}function pF(e){var t=this._name,n=this._id;typeof e!="function"&&(e=l0(e));for(var o=this._groups,s=o.length,a=[],i=[],l=0;l<s;++l)for(var c=o[l],d=c.length,f,p=0;p<d;++p)if(f=c[p]){for(var m=e.call(f,f.__data__,p,c),h,g=Bt(f,n),b=0,x=m.length;b<x;++b)(h=m[b])&&Aa(h,t,n,b,m,g);a.push(m),i.push(f)}return new dn(a,i,t,n)}var fF=$o.prototype.constructor;function mF(){return new fF(this._groups,this._parents)}function hF(e,t){var n,o,s;return function(){var a=vr(this,e),i=(this.style.removeProperty(e),vr(this,e));return a===i?null:a===n&&i===o?s:s=t(n=a,o=i)}}function D0(e){return function(){this.style.removeProperty(e)}}function gF(e,t,n){var o,s=n+"",a;return function(){var i=vr(this,e);return i===s?null:i===o?a:a=t(o=i,n)}}function bF(e,t,n){var o,s,a;return function(){var i=vr(this,e),l=n(this),c=l+"";return l==null&&(c=l=(this.style.removeProperty(e),vr(this,e))),i===c?null:i===o&&c===s?a:(s=c,a=t(o=i,l))}}function xF(e,t){var n,o,s,a="style."+t,i="end."+a,l;return function(){var c=Yt(this,e),d=c.on,f=c.value[a]==null?l||(l=D0(t)):void 0;(d!==n||s!==f)&&(o=(n=d).copy()).on(i,s=f),c.on=o}}function yF(e,t,n){var o=(e+="")=="transform"?vB:_0;return t==null?this.styleTween(e,hF(e,o)).on("end.style."+e,D0(e)):typeof t=="function"?this.styleTween(e,bF(e,o,cd(this,"style."+e,t))).each(xF(this._id,e)):this.styleTween(e,gF(e,o,t),n).on("end.style."+e,null)}function vF(e,t,n){return function(o){this.style.setProperty(e,t.call(this,o),n)}}function wF(e,t,n){var o,s;function a(){var i=t.apply(this,arguments);return i!==s&&(o=(s=i)&&vF(e,i,n)),o}return a._value=t,a}function NF(e,t,n){var o="style."+(e+="");if(arguments.length<2)return(o=this.tween(o))&&o._value;if(t==null)return this.tween(o,null);if(typeof t!="function")throw new Error;return this.tween(o,wF(e,t,n??""))}function kF(e){return function(){this.textContent=e}}function SF(e){return function(){var t=e(this);this.textContent=t??""}}function CF(e){return this.tween("text",typeof e=="function"?SF(cd(this,"text",e)):kF(e==null?"":e+""))}function MF(e){return function(t){this.textContent=e.call(this,t)}}function IF(e){var t,n;function o(){var s=e.apply(this,arguments);return s!==n&&(t=(n=s)&&MF(s)),t}return o._value=e,o}function AF(e){var t="text";if(arguments.length<1)return(t=this.tween(t))&&t._value;if(e==null)return this.tween(t,null);if(typeof e!="function")throw new Error;return this.tween(t,IF(e))}function PF(){for(var e=this._name,t=this._id,n=L0(),o=this._groups,s=o.length,a=0;a<s;++a)for(var i=o[a],l=i.length,c,d=0;d<l;++d)if(c=i[d]){var f=Bt(c,t);Aa(c,e,n,d,i,{time:f.time+f.delay+f.duration,delay:0,duration:f.duration,ease:f.ease})}return new dn(o,this._parents,e,n)}function EF(){var e,t,n=this,o=n._id,s=n.size();return new Promise(function(a,i){var l={value:i},c={value:function(){--s===0&&a()}};n.each(function(){var d=Yt(this,o),f=d.on;f!==e&&(t=(e=f).copy(),t._.cancel.push(l),t._.interrupt.push(l),t._.end.push(c)),d.on=t}),s===0&&a()})}var $F=0;function dn(e,t,n,o){this._groups=e,this._parents=t,this._name=n,this._id=o}function L0(){return++$F}var Jt=$o.prototype;dn.prototype={constructor:dn,select:uF,selectAll:pF,selectChild:Jt.selectChild,selectChildren:Jt.selectChildren,filter:oF,merge:sF,selection:mF,transition:PF,call:Jt.call,nodes:Jt.nodes,node:Jt.node,size:Jt.size,empty:Jt.empty,each:Jt.each,on:lF,attr:HB,attrTween:KB,style:yF,styleTween:NF,text:CF,textTween:AF,remove:dF,tween:TB,delay:YB,duration:JB,ease:tF,easeVarying:rF,end:EF,[Symbol.iterator]:Jt[Symbol.iterator]};function _F(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}var DF={time:null,delay:0,duration:250,ease:_F};function LF(e,t){for(var n;!(n=e.__transition)||!(n=n[t]);)if(!(e=e.parentNode))throw new Error(`transition ${t} not found`);return n}function TF(e){var t,n;e instanceof dn?(t=e._id,e=e._name):(t=L0(),(n=DF).time=id(),e=e==null?null:e+"");for(var o=this._groups,s=o.length,a=0;a<s;++a)for(var i=o[a],l=i.length,c,d=0;d<l;++d)(c=i[d])&&Aa(c,e,t,d,i,n||LF(c,t));return new dn(o,this._parents,e,t)}$o.prototype.interrupt=_B;$o.prototype.transition=TF;const is=e=>()=>e;function RF(e,{sourceEvent:t,target:n,transform:o,dispatch:s}){Object.defineProperties(this,{type:{value:e,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},target:{value:n,enumerable:!0,configurable:!0},transform:{value:o,enumerable:!0,configurable:!0},_:{value:s}})}function nn(e,t,n){this.k=e,this.x=t,this.y=n}nn.prototype={constructor:nn,scale:function(e){return e===1?this:new nn(this.k*e,this.x,this.y)},translate:function(e,t){return e===0&t===0?this:new nn(this.k,this.x+this.k*e,this.y+this.k*t)},apply:function(e){return[e[0]*this.k+this.x,e[1]*this.k+this.y]},applyX:function(e){return e*this.k+this.x},applyY:function(e){return e*this.k+this.y},invert:function(e){return[(e[0]-this.x)/this.k,(e[1]-this.y)/this.k]},invertX:function(e){return(e-this.x)/this.k},invertY:function(e){return(e-this.y)/this.k},rescaleX:function(e){return e.copy().domain(e.range().map(this.invertX,this).map(e.invert,e))},rescaleY:function(e){return e.copy().domain(e.range().map(this.invertY,this).map(e.invert,e))},toString:function(){return"translate("+this.x+","+this.y+") scale("+this.k+")"}};var Pa=new nn(1,0,0);T0.prototype=nn.prototype;function T0(e){for(;!e.__zoom;)if(!(e=e.parentNode))return Pa;return e.__zoom}function Mi(e){e.stopImmediatePropagation()}function qr(e){e.preventDefault(),e.stopImmediatePropagation()}function OF(e){return(!e.ctrlKey||e.type==="wheel")&&!e.button}function zF(){var e=this;return e instanceof SVGElement?(e=e.ownerSVGElement||e,e.hasAttribute("viewBox")?(e=e.viewBox.baseVal,[[e.x,e.y],[e.x+e.width,e.y+e.height]]):[[0,0],[e.width.baseVal.value,e.height.baseVal.value]]):[[0,0],[e.clientWidth,e.clientHeight]]}function Bp(){return this.__zoom||Pa}function BF(e){return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function FF(){return navigator.maxTouchPoints||"ontouchstart"in this}function jF(e,t,n){var o=e.invertX(t[0][0])-n[0][0],s=e.invertX(t[1][0])-n[1][0],a=e.invertY(t[0][1])-n[0][1],i=e.invertY(t[1][1])-n[1][1];return e.translate(s>o?(o+s)/2:Math.min(0,o)||Math.max(0,s),i>a?(a+i)/2:Math.min(0,a)||Math.max(0,i))}function R0(){var e=OF,t=zF,n=jF,o=BF,s=FF,a=[0,1/0],i=[[-1/0,-1/0],[1/0,1/0]],l=250,c=xs,d=Ca("start","zoom","end"),f,p,m,h=500,g=150,b=0,x=10;function v(A){A.property("__zoom",Bp).on("wheel.zoom",P,{passive:!1}).on("mousedown.zoom",I).on("dblclick.zoom",F).filter(s).on("touchstart.zoom",E).on("touchmove.zoom",B).on("touchend.zoom touchcancel.zoom",O).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}v.transform=function(A,D,_,R){var L=A.selection?A.selection():A;L.property("__zoom",Bp),A!==L?k(A,D,_,R):L.interrupt().each(function(){S(this,arguments).event(R).start().zoom(null,typeof D=="function"?D.apply(this,arguments):D).end()})},v.scaleBy=function(A,D,_,R){v.scaleTo(A,function(){var L=this.__zoom.k,z=typeof D=="function"?D.apply(this,arguments):D;return L*z},_,R)},v.scaleTo=function(A,D,_,R){v.transform(A,function(){var L=t.apply(this,arguments),z=this.__zoom,j=_==null?N(L):typeof _=="function"?_.apply(this,arguments):_,H=z.invert(j),T=typeof D=="function"?D.apply(this,arguments):D;return n(y(w(z,T),j,H),L,i)},_,R)},v.translateBy=function(A,D,_,R){v.transform(A,function(){return n(this.__zoom.translate(typeof D=="function"?D.apply(this,arguments):D,typeof _=="function"?_.apply(this,arguments):_),t.apply(this,arguments),i)},null,R)},v.translateTo=function(A,D,_,R,L){v.transform(A,function(){var z=t.apply(this,arguments),j=this.__zoom,H=R==null?N(z):typeof R=="function"?R.apply(this,arguments):R;return n(Pa.translate(H[0],H[1]).scale(j.k).translate(typeof D=="function"?-D.apply(this,arguments):-D,typeof _=="function"?-_.apply(this,arguments):-_),z,i)},R,L)};function w(A,D){return D=Math.max(a[0],Math.min(a[1],D)),D===A.k?A:new nn(D,A.x,A.y)}function y(A,D,_){var R=D[0]-_[0]*A.k,L=D[1]-_[1]*A.k;return R===A.x&&L===A.y?A:new nn(A.k,R,L)}function N(A){return[(+A[0][0]+ +A[1][0])/2,(+A[0][1]+ +A[1][1])/2]}function k(A,D,_,R){A.on("start.zoom",function(){S(this,arguments).event(R).start()}).on("interrupt.zoom end.zoom",function(){S(this,arguments).event(R).end()}).tween("zoom",function(){var L=this,z=arguments,j=S(L,z).event(R),H=t.apply(L,z),T=_==null?N(H):typeof _=="function"?_.apply(L,z):_,W=Math.max(H[1][0]-H[0][0],H[1][1]-H[0][1]),G=L.__zoom,ee=typeof D=="function"?D.apply(L,z):D,se=c(G.invert(T).concat(W/G.k),ee.invert(T).concat(W/ee.k));return function(te){if(te===1)te=ee;else{var X=se(te),re=W/X[2];te=new nn(re,T[0]-X[0]*re,T[1]-X[1]*re)}j.zoom(null,te)}})}function S(A,D,_){return!_&&A.__zooming||new M(A,D)}function M(A,D){this.that=A,this.args=D,this.active=0,this.sourceEvent=null,this.extent=t.apply(A,D),this.taps=0}M.prototype={event:function(A){return A&&(this.sourceEvent=A),this},start:function(){return++this.active===1&&(this.that.__zooming=this,this.emit("start")),this},zoom:function(A,D){return this.mouse&&A!=="mouse"&&(this.mouse[1]=D.invert(this.mouse[0])),this.touch0&&A!=="touch"&&(this.touch0[1]=D.invert(this.touch0[0])),this.touch1&&A!=="touch"&&(this.touch1[1]=D.invert(this.touch1[0])),this.that.__zoom=D,this.emit("zoom"),this},end:function(){return--this.active===0&&(delete this.that.__zooming,this.emit("end")),this},emit:function(A){var D=lt(this.that).datum();d.call(A,this.that,new RF(A,{sourceEvent:this.sourceEvent,target:v,transform:this.that.__zoom,dispatch:d}),D)}};function P(A,...D){if(!e.apply(this,arguments))return;var _=S(this,D).event(A),R=this.__zoom,L=Math.max(a[0],Math.min(a[1],R.k*Math.pow(2,o.apply(this,arguments)))),z=Pt(A);if(_.wheel)(_.mouse[0][0]!==z[0]||_.mouse[0][1]!==z[1])&&(_.mouse[1]=R.invert(_.mouse[0]=z)),clearTimeout(_.wheel);else{if(R.k===L)return;_.mouse=[z,R.invert(z)],ws(this),_.start()}qr(A),_.wheel=setTimeout(j,g),_.zoom("mouse",n(y(w(R,L),_.mouse[0],_.mouse[1]),_.extent,i));function j(){_.wheel=null,_.end()}}function I(A,...D){if(m||!e.apply(this,arguments))return;var _=A.currentTarget,R=S(this,D,!0).event(A),L=lt(A.view).on("mousemove.zoom",T,!0).on("mouseup.zoom",W,!0),z=Pt(A,_),j=A.clientX,H=A.clientY;y0(A.view),Mi(A),R.mouse=[z,this.__zoom.invert(z)],ws(this),R.start();function T(G){if(qr(G),!R.moved){var ee=G.clientX-j,se=G.clientY-H;R.moved=ee*ee+se*se>b}R.event(G).zoom("mouse",n(y(R.that.__zoom,R.mouse[0]=Pt(G,_),R.mouse[1]),R.extent,i))}function W(G){L.on("mousemove.zoom mouseup.zoom",null),v0(G.view,R.moved),qr(G),R.event(G).end()}}function F(A,...D){if(e.apply(this,arguments)){var _=this.__zoom,R=Pt(A.changedTouches?A.changedTouches[0]:A,this),L=_.invert(R),z=_.k*(A.shiftKey?.5:2),j=n(y(w(_,z),R,L),t.apply(this,D),i);qr(A),l>0?lt(this).transition().duration(l).call(k,j,R,A):lt(this).call(v.transform,j,R,A)}}function E(A,...D){if(e.apply(this,arguments)){var _=A.touches,R=_.length,L=S(this,D,A.changedTouches.length===R).event(A),z,j,H,T;for(Mi(A),j=0;j<R;++j)H=_[j],T=Pt(H,this),T=[T,this.__zoom.invert(T),H.identifier],L.touch0?!L.touch1&&L.touch0[2]!==T[2]&&(L.touch1=T,L.taps=0):(L.touch0=T,z=!0,L.taps=1+!!f);f&&(f=clearTimeout(f)),z&&(L.taps<2&&(p=T[0],f=setTimeout(function(){f=null},h)),ws(this),L.start())}}function B(A,...D){if(this.__zooming){var _=S(this,D).event(A),R=A.changedTouches,L=R.length,z,j,H,T;for(qr(A),z=0;z<L;++z)j=R[z],H=Pt(j,this),_.touch0&&_.touch0[2]===j.identifier?_.touch0[0]=H:_.touch1&&_.touch1[2]===j.identifier&&(_.touch1[0]=H);if(j=_.that.__zoom,_.touch1){var W=_.touch0[0],G=_.touch0[1],ee=_.touch1[0],se=_.touch1[1],te=(te=ee[0]-W[0])*te+(te=ee[1]-W[1])*te,X=(X=se[0]-G[0])*X+(X=se[1]-G[1])*X;j=w(j,Math.sqrt(te/X)),H=[(W[0]+ee[0])/2,(W[1]+ee[1])/2],T=[(G[0]+se[0])/2,(G[1]+se[1])/2]}else if(_.touch0)H=_.touch0[0],T=_.touch0[1];else return;_.zoom("touch",n(y(j,H,T),_.extent,i))}}function O(A,...D){if(this.__zooming){var _=S(this,D).event(A),R=A.changedTouches,L=R.length,z,j;for(Mi(A),m&&clearTimeout(m),m=setTimeout(function(){m=null},h),z=0;z<L;++z)j=R[z],_.touch0&&_.touch0[2]===j.identifier?delete _.touch0:_.touch1&&_.touch1[2]===j.identifier&&delete _.touch1;if(_.touch1&&!_.touch0&&(_.touch0=_.touch1,delete _.touch1),_.touch0)_.touch0[1]=this.__zoom.invert(_.touch0[0]);else if(_.end(),_.taps===2&&(j=Pt(j,this),Math.hypot(p[0]-j[0],p[1]-j[1])<x)){var H=lt(this).on("dblclick.zoom");H&&H.apply(this,arguments)}}}return v.wheelDelta=function(A){return arguments.length?(o=typeof A=="function"?A:is(+A),v):o},v.filter=function(A){return arguments.length?(e=typeof A=="function"?A:is(!!A),v):e},v.touchable=function(A){return arguments.length?(s=typeof A=="function"?A:is(!!A),v):s},v.extent=function(A){return arguments.length?(t=typeof A=="function"?A:is([[+A[0][0],+A[0][1]],[+A[1][0],+A[1][1]]]),v):t},v.scaleExtent=function(A){return arguments.length?(a[0]=+A[0],a[1]=+A[1],v):[a[0],a[1]]},v.translateExtent=function(A){return arguments.length?(i[0][0]=+A[0][0],i[1][0]=+A[1][0],i[0][1]=+A[0][1],i[1][1]=+A[1][1],v):[[i[0][0],i[0][1]],[i[1][0],i[1][1]]]},v.constrain=function(A){return arguments.length?(n=A,v):n},v.duration=function(A){return arguments.length?(l=+A,v):l},v.interpolate=function(A){return arguments.length?(c=A,v):c},v.on=function(){var A=d.on.apply(d,arguments);return A===d?v:A},v.clickDistance=function(A){return arguments.length?(b=(A=+A)*A,v):Math.sqrt(b)},v.tapDistance=function(A){return arguments.length?(x=+A,v):x},v}const Gt={error001:()=>"[React Flow]: Seems like you have not used zustand provider as an ancestor. Help: https://reactflow.dev/error#001",error002:()=>"It looks like you've created a new nodeTypes or edgeTypes object. If this wasn't on purpose please define the nodeTypes/edgeTypes outside of the component or memoize them.",error003:e=>`Node type "${e}" not found. Using fallback type "default".`,error004:()=>"The React Flow parent container needs a width and a height to render the graph.",error005:()=>"Only child nodes can use a parent extent.",error006:()=>"Can't create edge. An edge needs a source and a target.",error007:e=>`The old edge with id=${e} does not exist.`,error009:e=>`Marker type "${e}" doesn't exist.`,error008:(e,{id:t,sourceHandle:n,targetHandle:o})=>`Couldn't create edge for ${e} handle id: "${e==="source"?n:o}", edge id: ${t}.`,error010:()=>"Handle: No node id found. Make sure to only use a Handle inside a custom Node.",error011:e=>`Edge type "${e}" not found. Using fallback type "default".`,error012:e=>`Node with id "${e}" does not exist, it may have been removed. This can happen when a node is deleted before the "onNodeClick" handler is called.`,error013:(e="react")=>`It seems that you haven't loaded the styles. Please import '@xyflow/${e}/dist/style.css' or base.css to make sure everything is working properly.`,error014:()=>"useNodeConnections: No node ID found. Call useNodeConnections inside a custom Node or provide a node ID.",error015:()=>"It seems that you are trying to drag a node that is not initialized. Please use onNodesChange as explained in the docs."},ho=[[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY],[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]],O0=["Enter"," ","Escape"],z0={"node.a11yDescription.default":"Press enter or space to select a node. Press delete to remove it and escape to cancel.","node.a11yDescription.keyboardDisabled":"Press enter or space to select a node. You can then use the arrow keys to move the node around. Press delete to remove it and escape to cancel.","node.a11yDescription.ariaLiveMessage":({direction:e,x:t,y:n})=>`Moved selected node ${e}. New position, x: ${t}, y: ${n}`,"edge.a11yDescription.default":"Press enter or space to select an edge. You can then press delete to remove it or escape to cancel.","controls.ariaLabel":"Control Panel","controls.zoomIn.ariaLabel":"Zoom In","controls.zoomOut.ariaLabel":"Zoom Out","controls.fitView.ariaLabel":"Fit View","controls.interactive.ariaLabel":"Toggle Interactivity","minimap.ariaLabel":"Mini Map","handle.ariaLabel":"Handle"};var Nr;(function(e){e.Strict="strict",e.Loose="loose"})(Nr||(Nr={}));var Bn;(function(e){e.Free="free",e.Vertical="vertical",e.Horizontal="horizontal"})(Bn||(Bn={}));var go;(function(e){e.Partial="partial",e.Full="full"})(go||(go={}));const B0={inProgress:!1,isValid:null,from:null,fromHandle:null,fromPosition:null,fromNode:null,to:null,toHandle:null,toPosition:null,toNode:null,pointer:null};var xn;(function(e){e.Bezier="default",e.Straight="straight",e.Step="step",e.SmoothStep="smoothstep",e.SimpleBezier="simplebezier"})(xn||(xn={}));var Qs;(function(e){e.Arrow="arrow",e.ArrowClosed="arrowclosed"})(Qs||(Qs={}));var we;(function(e){e.Left="left",e.Top="top",e.Right="right",e.Bottom="bottom"})(we||(we={}));const Fp={[we.Left]:we.Right,[we.Right]:we.Left,[we.Top]:we.Bottom,[we.Bottom]:we.Top};function F0(e){return e===null?null:e?"valid":"invalid"}const j0=e=>"id"in e&&"source"in e&&"target"in e,HF=e=>"id"in e&&"position"in e&&!("source"in e)&&!("target"in e),dd=e=>"id"in e&&"internals"in e&&!("source"in e)&&!("target"in e),Do=(e,t=[0,0])=>{const{width:n,height:o}=fn(e),s=e.origin??t,a=n*s[0],i=o*s[1];return{x:e.position.x-a,y:e.position.y-i}},VF=(e,t={nodeOrigin:[0,0]})=>{if(e.length===0)return{x:0,y:0,width:0,height:0};const n=e.reduce((o,s)=>{const a=typeof s=="string";let i=!t.nodeLookup&&!a?s:void 0;t.nodeLookup&&(i=a?t.nodeLookup.get(s):dd(s)?s:t.nodeLookup.get(s.id));const l=i?Us(i,t.nodeOrigin):{x:0,y:0,x2:0,y2:0};return Ea(o,l)},{x:1/0,y:1/0,x2:-1/0,y2:-1/0});return $a(n)},Lo=(e,t={})=>{let n={x:1/0,y:1/0,x2:-1/0,y2:-1/0},o=!1;return e.forEach(s=>{(t.filter===void 0||t.filter(s))&&(n=Ea(n,Us(s)),o=!0)}),o?$a(n):{x:0,y:0,width:0,height:0}},ud=(e,t,[n,o,s]=[0,0,1],a=!1,i=!1)=>{const l={...Ro(t,[n,o,s]),width:t.width/s,height:t.height/s},c=[];for(const d of e.values()){const{measured:f,selectable:p=!0,hidden:m=!1}=d;if(i&&!p||m)continue;const h=f.width??d.width??d.initialWidth??null,g=f.height??d.height??d.initialHeight??null,b=bo(l,Sr(d)),x=(h??0)*(g??0),v=a&&b>0;(!d.internals.handleBounds||v||b>=x||d.dragging)&&c.push(d)}return c},qF=(e,t)=>{const n=new Set;return e.forEach(o=>{n.add(o.id)}),t.filter(o=>n.has(o.source)||n.has(o.target))};function QF(e,t){const n=new Map,o=t?.nodes?new Set(t.nodes.map(s=>s.id)):null;return e.forEach(s=>{s.measured.width&&s.measured.height&&(t?.includeHiddenNodes||!s.hidden)&&(!o||o.has(s.id))&&n.set(s.id,s)}),n}async function UF({nodes:e,width:t,height:n,panZoom:o,minZoom:s,maxZoom:a},i){if(e.size===0)return Promise.resolve(!0);const l=QF(e,i),c=Lo(l),d=pd(c,t,n,i?.minZoom??s,i?.maxZoom??a,i?.padding??.1);return await o.setViewport(d,{duration:i?.duration,ease:i?.ease,interpolate:i?.interpolate}),Promise.resolve(!0)}function H0({nodeId:e,nextPosition:t,nodeLookup:n,nodeOrigin:o=[0,0],nodeExtent:s,onError:a}){const i=n.get(e),l=i.parentId?n.get(i.parentId):void 0,{x:c,y:d}=l?l.internals.positionAbsolute:{x:0,y:0},f=i.origin??o;let p=i.extent||s;if(i.extent==="parent"&&!i.expandParent)if(!l)a?.("005",Gt.error005());else{const h=l.measured.width,g=l.measured.height;h&&g&&(p=[[c,d],[c+h,d+g]])}else l&&Cr(i.extent)&&(p=[[i.extent[0][0]+c,i.extent[0][1]+d],[i.extent[1][0]+c,i.extent[1][1]+d]]);const m=Cr(p)?Qn(t,p,i.measured):t;return(i.measured.width===void 0||i.measured.height===void 0)&&a?.("015",Gt.error015()),{position:{x:m.x-c+(i.measured.width??0)*f[0],y:m.y-d+(i.measured.height??0)*f[1]},positionAbsolute:m}}async function KF({nodesToRemove:e=[],edgesToRemove:t=[],nodes:n,edges:o,onBeforeDelete:s}){const a=new Set(e.map(m=>m.id)),i=[];for(const m of n){if(m.deletable===!1)continue;const h=a.has(m.id),g=!h&&m.parentId&&i.find(b=>b.id===m.parentId);(h||g)&&i.push(m)}const l=new Set(t.map(m=>m.id)),c=o.filter(m=>m.deletable!==!1),f=qF(i,c);for(const m of c)l.has(m.id)&&!f.find(g=>g.id===m.id)&&f.push(m);if(!s)return{edges:f,nodes:i};const p=await s({nodes:i,edges:f});return typeof p=="boolean"?p?{edges:f,nodes:i}:{edges:[],nodes:[]}:p}const kr=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),Qn=(e={x:0,y:0},t,n)=>({x:kr(e.x,t[0][0],t[1][0]-(n?.width??0)),y:kr(e.y,t[0][1],t[1][1]-(n?.height??0))});function V0(e,t,n){const{width:o,height:s}=fn(n),{x:a,y:i}=n.internals.positionAbsolute;return Qn(e,[[a,i],[a+o,i+s]],t)}const jp=(e,t,n)=>e<t?kr(Math.abs(e-t),1,t)/t:e>n?-kr(Math.abs(e-n),1,t)/t:0,q0=(e,t,n=15,o=40)=>{const s=jp(e.x,o,t.width-o)*n,a=jp(e.y,o,t.height-o)*n;return[s,a]},Ea=(e,t)=>({x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),x2:Math.max(e.x2,t.x2),y2:Math.max(e.y2,t.y2)}),wl=({x:e,y:t,width:n,height:o})=>({x:e,y:t,x2:e+n,y2:t+o}),$a=({x:e,y:t,x2:n,y2:o})=>({x:e,y:t,width:n-e,height:o-t}),Sr=(e,t=[0,0])=>{const{x:n,y:o}=dd(e)?e.internals.positionAbsolute:Do(e,t);return{x:n,y:o,width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}},Us=(e,t=[0,0])=>{const{x:n,y:o}=dd(e)?e.internals.positionAbsolute:Do(e,t);return{x:n,y:o,x2:n+(e.measured?.width??e.width??e.initialWidth??0),y2:o+(e.measured?.height??e.height??e.initialHeight??0)}},Q0=(e,t)=>$a(Ea(wl(e),wl(t))),bo=(e,t)=>{const n=Math.max(0,Math.min(e.x+e.width,t.x+t.width)-Math.max(e.x,t.x)),o=Math.max(0,Math.min(e.y+e.height,t.y+t.height)-Math.max(e.y,t.y));return Math.ceil(n*o)},Hp=e=>$t(e.width)&&$t(e.height)&&$t(e.x)&&$t(e.y),$t=e=>!isNaN(e)&&isFinite(e),GF=(e,t)=>{},To=(e,t=[1,1])=>({x:t[0]*Math.round(e.x/t[0]),y:t[1]*Math.round(e.y/t[1])}),Ro=({x:e,y:t},[n,o,s],a=!1,i=[1,1])=>{const l={x:(e-n)/s,y:(t-o)/s};return a?To(l,i):l},Ks=({x:e,y:t},[n,o,s])=>({x:e*s+n,y:t*s+o});function or(e,t){if(typeof e=="number")return Math.floor((t-t/(1+e))*.5);if(typeof e=="string"&&e.endsWith("px")){const n=parseFloat(e);if(!Number.isNaN(n))return Math.floor(n)}if(typeof e=="string"&&e.endsWith("%")){const n=parseFloat(e);if(!Number.isNaN(n))return Math.floor(t*n*.01)}return console.error(`[React Flow] The padding value "${e}" is invalid. Please provide a number or a string with a valid unit (px or %).`),0}function WF(e,t,n){if(typeof e=="string"||typeof e=="number"){const o=or(e,n),s=or(e,t);return{top:o,right:s,bottom:o,left:s,x:s*2,y:o*2}}if(typeof e=="object"){const o=or(e.top??e.y??0,n),s=or(e.bottom??e.y??0,n),a=or(e.left??e.x??0,t),i=or(e.right??e.x??0,t);return{top:o,right:i,bottom:s,left:a,x:a+i,y:o+s}}return{top:0,right:0,bottom:0,left:0,x:0,y:0}}function YF(e,t,n,o,s,a){const{x:i,y:l}=Ks(e,[t,n,o]),{x:c,y:d}=Ks({x:e.x+e.width,y:e.y+e.height},[t,n,o]),f=s-c,p=a-d;return{left:Math.floor(i),top:Math.floor(l),right:Math.floor(f),bottom:Math.floor(p)}}const pd=(e,t,n,o,s,a)=>{const i=WF(a,t,n),l=(t-i.x)/e.width,c=(n-i.y)/e.height,d=Math.min(l,c),f=kr(d,o,s),p=e.x+e.width/2,m=e.y+e.height/2,h=t/2-p*f,g=n/2-m*f,b=YF(e,h,g,f,t,n),x={left:Math.min(b.left-i.left,0),top:Math.min(b.top-i.top,0),right:Math.min(b.right-i.right,0),bottom:Math.min(b.bottom-i.bottom,0)};return{x:h-x.left+x.right,y:g-x.top+x.bottom,zoom:f}},xo=()=>typeof navigator<"u"&&navigator?.userAgent?.indexOf("Mac")>=0;function Cr(e){return e!=null&&e!=="parent"}function fn(e){return{width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}}function U0(e){return(e.measured?.width??e.width??e.initialWidth)!==void 0&&(e.measured?.height??e.height??e.initialHeight)!==void 0}function K0(e,t={width:0,height:0},n,o,s){const a={...e},i=o.get(n);if(i){const l=i.origin||s;a.x+=i.internals.positionAbsolute.x-(t.width??0)*l[0],a.y+=i.internals.positionAbsolute.y-(t.height??0)*l[1]}return a}function Vp(e,t){if(e.size!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;return!0}function ZF(){let e,t;return{promise:new Promise((o,s)=>{e=o,t=s}),resolve:e,reject:t}}function XF(e){return{...z0,...e||{}}}function ro(e,{snapGrid:t=[0,0],snapToGrid:n=!1,transform:o,containerBounds:s}){const{x:a,y:i}=_t(e),l=Ro({x:a-(s?.left??0),y:i-(s?.top??0)},o),{x:c,y:d}=n?To(l,t):l;return{xSnapped:c,ySnapped:d,...l}}const fd=e=>({width:e.offsetWidth,height:e.offsetHeight}),G0=e=>e?.getRootNode?.()||window?.document,JF=["INPUT","SELECT","TEXTAREA"];function W0(e){const t=e.composedPath?.()?.[0]||e.target;return t?.nodeType!==1?!1:JF.includes(t.nodeName)||t.hasAttribute("contenteditable")||!!t.closest(".nokey")}const Y0=e=>"clientX"in e,_t=(e,t)=>{const n=Y0(e),o=n?e.clientX:e.touches?.[0].clientX,s=n?e.clientY:e.touches?.[0].clientY;return{x:o-(t?.left??0),y:s-(t?.top??0)}},qp=(e,t,n,o,s)=>{const a=t.querySelectorAll(`.${e}`);return!a||!a.length?null:Array.from(a).map(i=>{const l=i.getBoundingClientRect();return{id:i.getAttribute("data-handleid"),type:e,nodeId:s,position:i.getAttribute("data-handlepos"),x:(l.left-n.left)/o,y:(l.top-n.top)/o,...fd(i)}})};function Z0({sourceX:e,sourceY:t,targetX:n,targetY:o,sourceControlX:s,sourceControlY:a,targetControlX:i,targetControlY:l}){const c=e*.125+s*.375+i*.375+n*.125,d=t*.125+a*.375+l*.375+o*.125,f=Math.abs(c-e),p=Math.abs(d-t);return[c,d,f,p]}function ls(e,t){return e>=0?.5*e:t*25*Math.sqrt(-e)}function Qp({pos:e,x1:t,y1:n,x2:o,y2:s,c:a}){switch(e){case we.Left:return[t-ls(t-o,a),n];case we.Right:return[t+ls(o-t,a),n];case we.Top:return[t,n-ls(n-s,a)];case we.Bottom:return[t,n+ls(s-n,a)]}}function X0({sourceX:e,sourceY:t,sourcePosition:n=we.Bottom,targetX:o,targetY:s,targetPosition:a=we.Top,curvature:i=.25}){const[l,c]=Qp({pos:n,x1:e,y1:t,x2:o,y2:s,c:i}),[d,f]=Qp({pos:a,x1:o,y1:s,x2:e,y2:t,c:i}),[p,m,h,g]=Z0({sourceX:e,sourceY:t,targetX:o,targetY:s,sourceControlX:l,sourceControlY:c,targetControlX:d,targetControlY:f});return[`M${e},${t} C${l},${c} ${d},${f} ${o},${s}`,p,m,h,g]}function J0({sourceX:e,sourceY:t,targetX:n,targetY:o}){const s=Math.abs(n-e)/2,a=n<e?n+s:n-s,i=Math.abs(o-t)/2,l=o<t?o+i:o-i;return[a,l,s,i]}function ej({sourceNode:e,targetNode:t,selected:n=!1,zIndex:o=0,elevateOnSelect:s=!1,zIndexMode:a="basic"}){if(a==="manual")return o;const i=s&&n?o+1e3:o,l=Math.max(e.parentId||s&&e.selected?e.internals.z:0,t.parentId||s&&t.selected?t.internals.z:0);return i+l}function tj({sourceNode:e,targetNode:t,width:n,height:o,transform:s}){const a=Ea(Us(e),Us(t));a.x===a.x2&&(a.x2+=1),a.y===a.y2&&(a.y2+=1);const i={x:-s[0]/s[2],y:-s[1]/s[2],width:n/s[2],height:o/s[2]};return bo(i,$a(a))>0}const nj=({source:e,sourceHandle:t,target:n,targetHandle:o})=>`xy-edge__${e}${t||""}-${n}${o||""}`,rj=(e,t)=>t.some(n=>n.source===e.source&&n.target===e.target&&(n.sourceHandle===e.sourceHandle||!n.sourceHandle&&!e.sourceHandle)&&(n.targetHandle===e.targetHandle||!n.targetHandle&&!e.targetHandle)),oj=(e,t,n={})=>{if(!e.source||!e.target)return t;const o=n.getEdgeId||nj;let s;return j0(e)?s={...e}:s={...e,id:o(e)},rj(s,t)?t:(s.sourceHandle===null&&delete s.sourceHandle,s.targetHandle===null&&delete s.targetHandle,t.concat(s))};function ev({sourceX:e,sourceY:t,targetX:n,targetY:o}){const[s,a,i,l]=J0({sourceX:e,sourceY:t,targetX:n,targetY:o});return[`M ${e},${t}L ${n},${o}`,s,a,i,l]}const Up={[we.Left]:{x:-1,y:0},[we.Right]:{x:1,y:0},[we.Top]:{x:0,y:-1},[we.Bottom]:{x:0,y:1}},sj=({source:e,sourcePosition:t=we.Bottom,target:n})=>t===we.Left||t===we.Right?e.x<n.x?{x:1,y:0}:{x:-1,y:0}:e.y<n.y?{x:0,y:1}:{x:0,y:-1},Kp=(e,t)=>Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2));function aj({source:e,sourcePosition:t=we.Bottom,target:n,targetPosition:o=we.Top,center:s,offset:a,stepPosition:i}){const l=Up[t],c=Up[o],d={x:e.x+l.x*a,y:e.y+l.y*a},f={x:n.x+c.x*a,y:n.y+c.y*a},p=sj({source:d,sourcePosition:t,target:f}),m=p.x!==0?"x":"y",h=p[m];let g=[],b,x;const v={x:0,y:0},w={x:0,y:0},[,,y,N]=J0({sourceX:e.x,sourceY:e.y,targetX:n.x,targetY:n.y});if(l[m]*c[m]===-1){m==="x"?(b=s.x??d.x+(f.x-d.x)*i,x=s.y??(d.y+f.y)/2):(b=s.x??(d.x+f.x)/2,x=s.y??d.y+(f.y-d.y)*i);const P=[{x:b,y:d.y},{x:b,y:f.y}],I=[{x:d.x,y:x},{x:f.x,y:x}];l[m]===h?g=m==="x"?P:I:g=m==="x"?I:P}else{const P=[{x:d.x,y:f.y}],I=[{x:f.x,y:d.y}];if(m==="x"?g=l.x===h?I:P:g=l.y===h?P:I,t===o){const A=Math.abs(e[m]-n[m]);if(A<=a){const D=Math.min(a-1,a-A);l[m]===h?v[m]=(d[m]>e[m]?-1:1)*D:w[m]=(f[m]>n[m]?-1:1)*D}}if(t!==o){const A=m==="x"?"y":"x",D=l[m]===c[A],_=d[A]>f[A],R=d[A]<f[A];(l[m]===1&&(!D&&_||D&&R)||l[m]!==1&&(!D&&R||D&&_))&&(g=m==="x"?P:I)}const F={x:d.x+v.x,y:d.y+v.y},E={x:f.x+w.x,y:f.y+w.y},B=Math.max(Math.abs(F.x-g[0].x),Math.abs(E.x-g[0].x)),O=Math.max(Math.abs(F.y-g[0].y),Math.abs(E.y-g[0].y));B>=O?(b=(F.x+E.x)/2,x=g[0].y):(b=g[0].x,x=(F.y+E.y)/2)}const k={x:d.x+v.x,y:d.y+v.y},S={x:f.x+w.x,y:f.y+w.y};return[[e,...k.x!==g[0].x||k.y!==g[0].y?[k]:[],...g,...S.x!==g[g.length-1].x||S.y!==g[g.length-1].y?[S]:[],n],b,x,y,N]}function ij(e,t,n,o){const s=Math.min(Kp(e,t)/2,Kp(t,n)/2,o),{x:a,y:i}=t;if(e.x===a&&a===n.x||e.y===i&&i===n.y)return`L${a} ${i}`;if(e.y===i){const d=e.x<n.x?-1:1,f=e.y<n.y?1:-1;return`L ${a+s*d},${i}Q ${a},${i} ${a},${i+s*f}`}const l=e.x<n.x?1:-1,c=e.y<n.y?-1:1;return`L ${a},${i+s*c}Q ${a},${i} ${a+s*l},${i}`}function Nl({sourceX:e,sourceY:t,sourcePosition:n=we.Bottom,targetX:o,targetY:s,targetPosition:a=we.Top,borderRadius:i=5,centerX:l,centerY:c,offset:d=20,stepPosition:f=.5}){const[p,m,h,g,b]=aj({source:{x:e,y:t},sourcePosition:n,target:{x:o,y:s},targetPosition:a,center:{x:l,y:c},offset:d,stepPosition:f});let x=`M${p[0].x} ${p[0].y}`;for(let v=1;v<p.length-1;v++)x+=ij(p[v-1],p[v],p[v+1],i);return x+=`L${p[p.length-1].x} ${p[p.length-1].y}`,[x,m,h,g,b]}function Gp(e){return e&&!!(e.internals.handleBounds||e.handles?.length)&&!!(e.measured.width||e.width||e.initialWidth)}function lj(e){const{sourceNode:t,targetNode:n}=e;if(!Gp(t)||!Gp(n))return null;const o=t.internals.handleBounds||Wp(t.handles),s=n.internals.handleBounds||Wp(n.handles),a=Yp(o?.source??[],e.sourceHandle),i=Yp(e.connectionMode===Nr.Strict?s?.target??[]:(s?.target??[]).concat(s?.source??[]),e.targetHandle);if(!a||!i)return e.onError?.("008",Gt.error008(a?"target":"source",{id:e.id,sourceHandle:e.sourceHandle,targetHandle:e.targetHandle})),null;const l=a?.position||we.Bottom,c=i?.position||we.Top,d=Un(t,a,l),f=Un(n,i,c);return{sourceX:d.x,sourceY:d.y,targetX:f.x,targetY:f.y,sourcePosition:l,targetPosition:c}}function Wp(e){if(!e)return null;const t=[],n=[];for(const o of e)o.width=o.width??1,o.height=o.height??1,o.type==="source"?t.push(o):o.type==="target"&&n.push(o);return{source:t,target:n}}function Un(e,t,n=we.Left,o=!1){const s=(t?.x??0)+e.internals.positionAbsolute.x,a=(t?.y??0)+e.internals.positionAbsolute.y,{width:i,height:l}=t??fn(e);if(o)return{x:s+i/2,y:a+l/2};switch(t?.position??n){case we.Top:return{x:s+i/2,y:a};case we.Right:return{x:s+i,y:a+l/2};case we.Bottom:return{x:s+i/2,y:a+l};case we.Left:return{x:s,y:a+l/2}}}function Yp(e,t){return e&&(t?e.find(n=>n.id===t):e[0])||null}function kl(e,t){return e?typeof e=="string"?e:`${t?`${t}__`:""}${Object.keys(e).sort().map(o=>`${o}=${e[o]}`).join("&")}`:""}function cj(e,{id:t,defaultColor:n,defaultMarkerStart:o,defaultMarkerEnd:s}){const a=new Set;return e.reduce((i,l)=>([l.markerStart||o,l.markerEnd||s].forEach(c=>{if(c&&typeof c=="object"){const d=kl(c,t);a.has(d)||(i.push({id:d,color:c.color||n,...c}),a.add(d))}}),i),[]).sort((i,l)=>i.id.localeCompare(l.id))}const tv=1e3,dj=10,md={nodeOrigin:[0,0],nodeExtent:ho,elevateNodesOnSelect:!0,zIndexMode:"basic",defaults:{}},uj={...md,checkEquality:!0};function hd(e,t){const n={...e};for(const o in t)t[o]!==void 0&&(n[o]=t[o]);return n}function pj(e,t,n){const o=hd(md,n);for(const s of e.values())if(s.parentId)bd(s,e,t,o);else{const a=Do(s,o.nodeOrigin),i=Cr(s.extent)?s.extent:o.nodeExtent,l=Qn(a,i,fn(s));s.internals.positionAbsolute=l}}function fj(e,t){if(!e.handles)return e.measured?t?.internals.handleBounds:void 0;const n=[],o=[];for(const s of e.handles){const a={id:s.id,width:s.width??1,height:s.height??1,nodeId:e.id,x:s.x,y:s.y,position:s.position,type:s.type};s.type==="source"?n.push(a):s.type==="target"&&o.push(a)}return{source:n,target:o}}function gd(e){return e==="manual"}function Sl(e,t,n,o={}){const s=hd(uj,o),a={i:0},i=new Map(t),l=s?.elevateNodesOnSelect&&!gd(s.zIndexMode)?tv:0;let c=e.length>0,d=!1;t.clear(),n.clear();for(const f of e){let p=i.get(f.id);if(s.checkEquality&&f===p?.internals.userNode)t.set(f.id,p);else{const m=Do(f,s.nodeOrigin),h=Cr(f.extent)?f.extent:s.nodeExtent,g=Qn(m,h,fn(f));p={...s.defaults,...f,measured:{width:f.measured?.width,height:f.measured?.height},internals:{positionAbsolute:g,handleBounds:fj(f,p),z:nv(f,l,s.zIndexMode),userNode:f}},t.set(f.id,p)}(p.measured===void 0||p.measured.width===void 0||p.measured.height===void 0)&&!p.hidden&&(c=!1),f.parentId&&bd(p,t,n,o,a),d||=f.selected??!1}return{nodesInitialized:c,hasSelectedNodes:d}}function mj(e,t){if(!e.parentId)return;const n=t.get(e.parentId);n?n.set(e.id,e):t.set(e.parentId,new Map([[e.id,e]]))}function bd(e,t,n,o,s){const{elevateNodesOnSelect:a,nodeOrigin:i,nodeExtent:l,zIndexMode:c}=hd(md,o),d=e.parentId,f=t.get(d);if(!f){console.warn(`Parent node ${d} not found. Please make sure that parent nodes are in front of their child nodes in the nodes array.`);return}mj(e,n),s&&!f.parentId&&f.internals.rootParentIndex===void 0&&c==="auto"&&(f.internals.rootParentIndex=++s.i,f.internals.z=f.internals.z+s.i*dj),s&&f.internals.rootParentIndex!==void 0&&(s.i=f.internals.rootParentIndex);const p=a&&!gd(c)?tv:0,{x:m,y:h,z:g}=hj(e,f,i,l,p,c),{positionAbsolute:b}=e.internals,x=m!==b.x||h!==b.y;(x||g!==e.internals.z)&&t.set(e.id,{...e,internals:{...e.internals,positionAbsolute:x?{x:m,y:h}:b,z:g}})}function nv(e,t,n){const o=$t(e.zIndex)?e.zIndex:0;return gd(n)?o:o+(e.selected?t:0)}function hj(e,t,n,o,s,a){const{x:i,y:l}=t.internals.positionAbsolute,c=fn(e),d=Do(e,n),f=Cr(e.extent)?Qn(d,e.extent,c):d;let p=Qn({x:i+f.x,y:l+f.y},o,c);e.extent==="parent"&&(p=V0(p,c,t));const m=nv(e,s,a),h=t.internals.z??0;return{x:p.x,y:p.y,z:h>=m?h+1:m}}function xd(e,t,n,o=[0,0]){const s=[],a=new Map;for(const i of e){const l=t.get(i.parentId);if(!l)continue;const c=a.get(i.parentId)?.expandedRect??Sr(l),d=Q0(c,i.rect);a.set(i.parentId,{expandedRect:d,parent:l})}return a.size>0&&a.forEach(({expandedRect:i,parent:l},c)=>{const d=l.internals.positionAbsolute,f=fn(l),p=l.origin??o,m=i.x<d.x?Math.round(Math.abs(d.x-i.x)):0,h=i.y<d.y?Math.round(Math.abs(d.y-i.y)):0,g=Math.max(f.width,Math.round(i.width)),b=Math.max(f.height,Math.round(i.height)),x=(g-f.width)*p[0],v=(b-f.height)*p[1];(m>0||h>0||x||v)&&(s.push({id:c,type:"position",position:{x:l.position.x-m+x,y:l.position.y-h+v}}),n.get(c)?.forEach(w=>{e.some(y=>y.id===w.id)||s.push({id:w.id,type:"position",position:{x:w.position.x+m,y:w.position.y+h}})})),(f.width<i.width||f.height<i.height||m||h)&&s.push({id:c,type:"dimensions",setAttributes:!0,dimensions:{width:g+(m?p[0]*m-x:0),height:b+(h?p[1]*h-v:0)}})}),s}function gj(e,t,n,o,s,a,i){const l=o?.querySelector(".xyflow__viewport");let c=!1;if(!l)return{changes:[],updatedInternals:c};const d=[],f=window.getComputedStyle(l),{m22:p}=new window.DOMMatrixReadOnly(f.transform),m=[];for(const h of e.values()){const g=t.get(h.id);if(!g)continue;if(g.hidden){t.set(g.id,{...g,internals:{...g.internals,handleBounds:void 0}}),c=!0;continue}const b=fd(h.nodeElement),x=g.measured.width!==b.width||g.measured.height!==b.height;if(!!(b.width&&b.height&&(x||!g.internals.handleBounds||h.force))){const w=h.nodeElement.getBoundingClientRect(),y=Cr(g.extent)?g.extent:a;let{positionAbsolute:N}=g.internals;g.parentId&&g.extent==="parent"?N=V0(N,b,t.get(g.parentId)):y&&(N=Qn(N,y,b));const k={...g,measured:b,internals:{...g.internals,positionAbsolute:N,handleBounds:{source:qp("source",h.nodeElement,w,p,g.id),target:qp("target",h.nodeElement,w,p,g.id)}}};t.set(g.id,k),g.parentId&&bd(k,t,n,{nodeOrigin:s,zIndexMode:i}),c=!0,x&&(d.push({id:g.id,type:"dimensions",dimensions:b}),g.expandParent&&g.parentId&&m.push({id:g.id,parentId:g.parentId,rect:Sr(k,s)}))}}if(m.length>0){const h=xd(m,t,n,s);d.push(...h)}return{changes:d,updatedInternals:c}}async function bj({delta:e,panZoom:t,transform:n,translateExtent:o,width:s,height:a}){if(!t||!e.x&&!e.y)return Promise.resolve(!1);const i=await t.setViewportConstrained({x:n[0]+e.x,y:n[1]+e.y,zoom:n[2]},[[0,0],[s,a]],o),l=!!i&&(i.x!==n[0]||i.y!==n[1]||i.k!==n[2]);return Promise.resolve(l)}function Zp(e,t,n,o,s,a){let i=s;const l=o.get(i)||new Map;o.set(i,l.set(n,t)),i=`${s}-${e}`;const c=o.get(i)||new Map;if(o.set(i,c.set(n,t)),a){i=`${s}-${e}-${a}`;const d=o.get(i)||new Map;o.set(i,d.set(n,t))}}function rv(e,t,n){e.clear(),t.clear();for(const o of n){const{source:s,target:a,sourceHandle:i=null,targetHandle:l=null}=o,c={edgeId:o.id,source:s,target:a,sourceHandle:i,targetHandle:l},d=`${s}-${i}--${a}-${l}`,f=`${a}-${l}--${s}-${i}`;Zp("source",c,f,e,s,i),Zp("target",c,d,e,a,l),t.set(o.id,o)}}function ov(e,t){if(!e.parentId)return!1;const n=t.get(e.parentId);return n?n.selected?!0:ov(n,t):!1}function Xp(e,t,n){let o=e;do{if(o?.matches?.(t))return!0;if(o===n)return!1;o=o?.parentElement}while(o);return!1}function xj(e,t,n,o){const s=new Map;for(const[a,i]of e)if((i.selected||i.id===o)&&(!i.parentId||!ov(i,e))&&(i.draggable||t&&typeof i.draggable>"u")){const l=e.get(a);l&&s.set(a,{id:a,position:l.position||{x:0,y:0},distance:{x:n.x-l.internals.positionAbsolute.x,y:n.y-l.internals.positionAbsolute.y},extent:l.extent,parentId:l.parentId,origin:l.origin,expandParent:l.expandParent,internals:{positionAbsolute:l.internals.positionAbsolute||{x:0,y:0}},measured:{width:l.measured.width??0,height:l.measured.height??0}})}return s}function Ii({nodeId:e,dragItems:t,nodeLookup:n,dragging:o=!0}){const s=[];for(const[i,l]of t){const c=n.get(i)?.internals.userNode;c&&s.push({...c,position:l.position,dragging:o})}if(!e)return[s[0],s];const a=n.get(e)?.internals.userNode;return[a?{...a,position:t.get(e)?.position||a.position,dragging:o}:s[0],s]}function yj({dragItems:e,snapGrid:t,x:n,y:o}){const s=e.values().next().value;if(!s)return null;const a={x:n-s.distance.x,y:o-s.distance.y},i=To(a,t);return{x:i.x-a.x,y:i.y-a.y}}function vj({onNodeMouseDown:e,getStoreItems:t,onDragStart:n,onDrag:o,onDragStop:s}){let a={x:null,y:null},i=0,l=new Map,c=!1,d={x:0,y:0},f=null,p=!1,m=null,h=!1,g=!1,b=null;function x({noDragClassName:w,handleSelector:y,domNode:N,isSelectable:k,nodeId:S,nodeClickDistance:M=0}){m=lt(N);function P({x:B,y:O}){const{nodeLookup:A,nodeExtent:D,snapGrid:_,snapToGrid:R,nodeOrigin:L,onNodeDrag:z,onSelectionDrag:j,onError:H,updateNodePositions:T}=t();a={x:B,y:O};let W=!1;const G=l.size>1,ee=G&&D?wl(Lo(l)):null,se=G&&R?yj({dragItems:l,snapGrid:_,x:B,y:O}):null;for(const[te,X]of l){if(!A.has(te))continue;let re={x:B-X.distance.x,y:O-X.distance.y};R&&(re=se?{x:Math.round(re.x+se.x),y:Math.round(re.y+se.y)}:To(re,_));let ge=null;if(G&&D&&!X.extent&&ee){const{positionAbsolute:J}=X.internals,ae=J.x-ee.x+D[0][0],fe=J.x+X.measured.width-ee.x2+D[1][0],he=J.y-ee.y+D[0][1],V=J.y+X.measured.height-ee.y2+D[1][1];ge=[[ae,he],[fe,V]]}const{position:Z,positionAbsolute:U}=H0({nodeId:te,nextPosition:re,nodeLookup:A,nodeExtent:ge||D,nodeOrigin:L,onError:H});W=W||X.position.x!==Z.x||X.position.y!==Z.y,X.position=Z,X.internals.positionAbsolute=U}if(g=g||W,!!W&&(T(l,!0),b&&(o||z||!S&&j))){const[te,X]=Ii({nodeId:S,dragItems:l,nodeLookup:A});o?.(b,l,te,X),z?.(b,te,X),S||j?.(b,X)}}async function I(){if(!f)return;const{transform:B,panBy:O,autoPanSpeed:A,autoPanOnNodeDrag:D}=t();if(!D){c=!1,cancelAnimationFrame(i);return}const[_,R]=q0(d,f,A);(_!==0||R!==0)&&(a.x=(a.x??0)-_/B[2],a.y=(a.y??0)-R/B[2],await O({x:_,y:R})&&P(a)),i=requestAnimationFrame(I)}function F(B){const{nodeLookup:O,multiSelectionActive:A,nodesDraggable:D,transform:_,snapGrid:R,snapToGrid:L,selectNodesOnDrag:z,onNodeDragStart:j,onSelectionDragStart:H,unselectNodesAndEdges:T}=t();p=!0,(!z||!k)&&!A&&S&&(O.get(S)?.selected||T()),k&&z&&S&&e?.(S);const W=ro(B.sourceEvent,{transform:_,snapGrid:R,snapToGrid:L,containerBounds:f});if(a=W,l=xj(O,D,W,S),l.size>0&&(n||j||!S&&H)){const[G,ee]=Ii({nodeId:S,dragItems:l,nodeLookup:O});n?.(B.sourceEvent,l,G,ee),j?.(B.sourceEvent,G,ee),S||H?.(B.sourceEvent,ee)}}const E=w0().clickDistance(M).on("start",B=>{const{domNode:O,nodeDragThreshold:A,transform:D,snapGrid:_,snapToGrid:R}=t();f=O?.getBoundingClientRect()||null,h=!1,g=!1,b=B.sourceEvent,A===0&&F(B),a=ro(B.sourceEvent,{transform:D,snapGrid:_,snapToGrid:R,containerBounds:f}),d=_t(B.sourceEvent,f)}).on("drag",B=>{const{autoPanOnNodeDrag:O,transform:A,snapGrid:D,snapToGrid:_,nodeDragThreshold:R,nodeLookup:L}=t(),z=ro(B.sourceEvent,{transform:A,snapGrid:D,snapToGrid:_,containerBounds:f});if(b=B.sourceEvent,(B.sourceEvent.type==="touchmove"&&B.sourceEvent.touches.length>1||S&&!L.has(S))&&(h=!0),!h){if(!c&&O&&p&&(c=!0,I()),!p){const j=_t(B.sourceEvent,f),H=j.x-d.x,T=j.y-d.y;Math.sqrt(H*H+T*T)>R&&F(B)}(a.x!==z.xSnapped||a.y!==z.ySnapped)&&l&&p&&(d=_t(B.sourceEvent,f),P(z))}}).on("end",B=>{if(!(!p||h)&&(c=!1,p=!1,cancelAnimationFrame(i),l.size>0)){const{nodeLookup:O,updateNodePositions:A,onNodeDragStop:D,onSelectionDragStop:_}=t();if(g&&(A(l,!1),g=!1),s||D||!S&&_){const[R,L]=Ii({nodeId:S,dragItems:l,nodeLookup:O,dragging:!1});s?.(B.sourceEvent,l,R,L),D?.(B.sourceEvent,R,L),S||_?.(B.sourceEvent,L)}}}).filter(B=>{const O=B.target;return!B.button&&(!w||!Xp(O,`.${w}`,N))&&(!y||Xp(O,y,N))});m.call(E)}function v(){m?.on(".drag",null)}return{update:x,destroy:v}}function wj(e,t,n){const o=[],s={x:e.x-n,y:e.y-n,width:n*2,height:n*2};for(const a of t.values())bo(s,Sr(a))>0&&o.push(a);return o}const Nj=250;function kj(e,t,n,o){let s=[],a=1/0;const i=wj(e,n,t+Nj);for(const l of i){const c=[...l.internals.handleBounds?.source??[],...l.internals.handleBounds?.target??[]];for(const d of c){if(o.nodeId===d.nodeId&&o.type===d.type&&o.id===d.id)continue;const{x:f,y:p}=Un(l,d,d.position,!0),m=Math.sqrt(Math.pow(f-e.x,2)+Math.pow(p-e.y,2));m>t||(m<a?(s=[{...d,x:f,y:p}],a=m):m===a&&s.push({...d,x:f,y:p}))}}if(!s.length)return null;if(s.length>1){const l=o.type==="source"?"target":"source";return s.find(c=>c.type===l)??s[0]}return s[0]}function sv(e,t,n,o,s,a=!1){const i=o.get(e);if(!i)return null;const l=s==="strict"?i.internals.handleBounds?.[t]:[...i.internals.handleBounds?.source??[],...i.internals.handleBounds?.target??[]],c=(n?l?.find(d=>d.id===n):l?.[0])??null;return c&&a?{...c,...Un(i,c,c.position,!0)}:c}function av(e,t){return e||(t?.classList.contains("target")?"target":t?.classList.contains("source")?"source":null)}function Sj(e,t){let n=null;return t?n=!0:e&&!t&&(n=!1),n}const iv=()=>!0;function Cj(e,{connectionMode:t,connectionRadius:n,handleId:o,nodeId:s,edgeUpdaterType:a,isTarget:i,domNode:l,nodeLookup:c,lib:d,autoPanOnConnect:f,flowId:p,panBy:m,cancelConnection:h,onConnectStart:g,onConnect:b,onConnectEnd:x,isValidConnection:v=iv,onReconnectEnd:w,updateConnection:y,getTransform:N,getFromHandle:k,autoPanSpeed:S,dragThreshold:M=1,handleDomNode:P}){const I=G0(e.target);let F=0,E;const{x:B,y:O}=_t(e),A=av(a,P),D=l?.getBoundingClientRect();let _=!1;if(!D||!A)return;const R=sv(s,A,o,c,t);if(!R)return;let L=_t(e,D),z=!1,j=null,H=!1,T=null;function W(){if(!f||!D)return;const[Z,U]=q0(L,D,S);m({x:Z,y:U}),F=requestAnimationFrame(W)}const G={...R,nodeId:s,type:A,position:R.position},ee=c.get(s);let te={inProgress:!0,isValid:null,from:Un(ee,G,we.Left,!0),fromHandle:G,fromPosition:G.position,fromNode:ee,to:L,toHandle:null,toPosition:Fp[G.position],toNode:null,pointer:L};function X(){_=!0,y(te),g?.(e,{nodeId:s,handleId:o,handleType:A})}M===0&&X();function re(Z){if(!_){const{x:V,y:ie}=_t(Z),ue=V-B,de=ie-O;if(!(ue*ue+de*de>M*M))return;X()}if(!k()||!G){ge(Z);return}const U=N();L=_t(Z,D),E=kj(Ro(L,U,!1,[1,1]),n,c,G),z||(W(),z=!0);const J=lv(Z,{handle:E,connectionMode:t,fromNodeId:s,fromHandleId:o,fromType:i?"target":"source",isValidConnection:v,doc:I,lib:d,flowId:p,nodeLookup:c});T=J.handleDomNode,j=J.connection,H=Sj(!!E,J.isValid);const ae=c.get(s),fe=ae?Un(ae,G,we.Left,!0):te.from,he={...te,from:fe,isValid:H,to:J.toHandle&&H?Ks({x:J.toHandle.x,y:J.toHandle.y},U):L,toHandle:J.toHandle,toPosition:H&&J.toHandle?J.toHandle.position:Fp[G.position],toNode:J.toHandle?c.get(J.toHandle.nodeId):null,pointer:L};y(he),te=he}function ge(Z){if(!("touches"in Z&&Z.touches.length>0)){if(_){(E||T)&&j&&H&&b?.(j);const{inProgress:U,...J}=te,ae={...J,toPosition:te.toHandle?te.toPosition:null};x?.(Z,ae),a&&w?.(Z,ae)}h(),cancelAnimationFrame(F),z=!1,H=!1,j=null,T=null,I.removeEventListener("mousemove",re),I.removeEventListener("mouseup",ge),I.removeEventListener("touchmove",re),I.removeEventListener("touchend",ge)}}I.addEventListener("mousemove",re),I.addEventListener("mouseup",ge),I.addEventListener("touchmove",re),I.addEventListener("touchend",ge)}function lv(e,{handle:t,connectionMode:n,fromNodeId:o,fromHandleId:s,fromType:a,doc:i,lib:l,flowId:c,isValidConnection:d=iv,nodeLookup:f}){const p=a==="target",m=t?i.querySelector(`.${l}-flow__handle[data-id="${c}-${t?.nodeId}-${t?.id}-${t?.type}"]`):null,{x:h,y:g}=_t(e),b=i.elementFromPoint(h,g),x=b?.classList.contains(`${l}-flow__handle`)?b:m,v={handleDomNode:x,isValid:!1,connection:null,toHandle:null};if(x){const w=av(void 0,x),y=x.getAttribute("data-nodeid"),N=x.getAttribute("data-handleid"),k=x.classList.contains("connectable"),S=x.classList.contains("connectableend");if(!y||!w)return v;const M={source:p?y:o,sourceHandle:p?N:s,target:p?o:y,targetHandle:p?s:N};v.connection=M;const I=k&&S&&(n===Nr.Strict?p&&w==="source"||!p&&w==="target":y!==o||N!==s);v.isValid=I&&d(M),v.toHandle=sv(y,w,N,f,n,!0)}return v}const Cl={onPointerDown:Cj,isValid:lv};function Mj({domNode:e,panZoom:t,getTransform:n,getViewScale:o}){const s=lt(e);function a({translateExtent:l,width:c,height:d,zoomStep:f=1,pannable:p=!0,zoomable:m=!0,inversePan:h=!1}){const g=y=>{if(y.sourceEvent.type!=="wheel"||!t)return;const N=n(),k=y.sourceEvent.ctrlKey&&xo()?10:1,S=-y.sourceEvent.deltaY*(y.sourceEvent.deltaMode===1?.05:y.sourceEvent.deltaMode?1:.002)*f,M=N[2]*Math.pow(2,S*k);t.scaleTo(M)};let b=[0,0];const x=y=>{(y.sourceEvent.type==="mousedown"||y.sourceEvent.type==="touchstart")&&(b=[y.sourceEvent.clientX??y.sourceEvent.touches[0].clientX,y.sourceEvent.clientY??y.sourceEvent.touches[0].clientY])},v=y=>{const N=n();if(y.sourceEvent.type!=="mousemove"&&y.sourceEvent.type!=="touchmove"||!t)return;const k=[y.sourceEvent.clientX??y.sourceEvent.touches[0].clientX,y.sourceEvent.clientY??y.sourceEvent.touches[0].clientY],S=[k[0]-b[0],k[1]-b[1]];b=k;const M=o()*Math.max(N[2],Math.log(N[2]))*(h?-1:1),P={x:N[0]-S[0]*M,y:N[1]-S[1]*M},I=[[0,0],[c,d]];t.setViewportConstrained({x:P.x,y:P.y,zoom:N[2]},I,l)},w=R0().on("start",x).on("zoom",p?v:null).on("zoom.wheel",m?g:null);s.call(w,{})}function i(){s.on("zoom",null)}return{update:a,destroy:i,pointer:Pt}}const _a=e=>({x:e.x,y:e.y,zoom:e.k}),Ai=({x:e,y:t,zoom:n})=>Pa.translate(e,t).scale(n),ar=(e,t)=>e.target.closest(`.${t}`),cv=(e,t)=>t===2&&Array.isArray(e)&&e.includes(2),Ij=e=>((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2,Pi=(e,t=0,n=Ij,o=()=>{})=>{const s=typeof t=="number"&&t>0;return s||o(),s?e.transition().duration(t).ease(n).on("end",o):e},dv=e=>{const t=e.ctrlKey&&xo()?10:1;return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*t};function Aj({zoomPanValues:e,noWheelClassName:t,d3Selection:n,d3Zoom:o,panOnScrollMode:s,panOnScrollSpeed:a,zoomOnPinch:i,onPanZoomStart:l,onPanZoom:c,onPanZoomEnd:d}){return f=>{if(ar(f,t))return f.ctrlKey&&f.preventDefault(),!1;f.preventDefault(),f.stopImmediatePropagation();const p=n.property("__zoom").k||1;if(f.ctrlKey&&i){const x=Pt(f),v=dv(f),w=p*Math.pow(2,v);o.scaleTo(n,w,x,f);return}const m=f.deltaMode===1?20:1;let h=s===Bn.Vertical?0:f.deltaX*m,g=s===Bn.Horizontal?0:f.deltaY*m;!xo()&&f.shiftKey&&s!==Bn.Vertical&&(h=f.deltaY*m,g=0),o.translateBy(n,-(h/p)*a,-(g/p)*a,{internal:!0});const b=_a(n.property("__zoom"));clearTimeout(e.panScrollTimeout),e.isPanScrolling?(c?.(f,b),e.panScrollTimeout=setTimeout(()=>{d?.(f,b),e.isPanScrolling=!1},150)):(e.isPanScrolling=!0,l?.(f,b))}}function Pj({noWheelClassName:e,preventScrolling:t,d3ZoomHandler:n}){return function(o,s){const a=o.type==="wheel",i=!t&&a&&!o.ctrlKey,l=ar(o,e);if(o.ctrlKey&&a&&l&&o.preventDefault(),i||l)return null;o.preventDefault(),n.call(this,o,s)}}function Ej({zoomPanValues:e,onDraggingChange:t,onPanZoomStart:n}){return o=>{if(o.sourceEvent?.internal)return;const s=_a(o.transform);e.mouseButton=o.sourceEvent?.button||0,e.isZoomingOrPanning=!0,e.prevViewport=s,o.sourceEvent?.type==="mousedown"&&t(!0),n&&n?.(o.sourceEvent,s)}}function $j({zoomPanValues:e,panOnDrag:t,onPaneContextMenu:n,onTransformChange:o,onPanZoom:s}){return a=>{e.usedRightMouseButton=!!(n&&cv(t,e.mouseButton??0)),a.sourceEvent?.sync||o([a.transform.x,a.transform.y,a.transform.k]),s&&!a.sourceEvent?.internal&&s?.(a.sourceEvent,_a(a.transform))}}function _j({zoomPanValues:e,panOnDrag:t,panOnScroll:n,onDraggingChange:o,onPanZoomEnd:s,onPaneContextMenu:a}){return i=>{if(!i.sourceEvent?.internal&&(e.isZoomingOrPanning=!1,a&&cv(t,e.mouseButton??0)&&!e.usedRightMouseButton&&i.sourceEvent&&a(i.sourceEvent),e.usedRightMouseButton=!1,o(!1),s)){const l=_a(i.transform);e.prevViewport=l,clearTimeout(e.timerId),e.timerId=setTimeout(()=>{s?.(i.sourceEvent,l)},n?150:0)}}}function Dj({zoomActivationKeyPressed:e,zoomOnScroll:t,zoomOnPinch:n,panOnDrag:o,panOnScroll:s,zoomOnDoubleClick:a,userSelectionActive:i,noWheelClassName:l,noPanClassName:c,lib:d,connectionInProgress:f}){return p=>{const m=e||t,h=n&&p.ctrlKey,g=p.type==="wheel";if(p.button===1&&p.type==="mousedown"&&(ar(p,`${d}-flow__node`)||ar(p,`${d}-flow__edge`)))return!0;if(!o&&!m&&!s&&!a&&!n||i||f&&!g||ar(p,l)&&g||ar(p,c)&&(!g||s&&g&&!e)||!n&&p.ctrlKey&&g)return!1;if(!n&&p.type==="touchstart"&&p.touches?.length>1)return p.preventDefault(),!1;if(!m&&!s&&!h&&g||!o&&(p.type==="mousedown"||p.type==="touchstart")||Array.isArray(o)&&!o.includes(p.button)&&p.type==="mousedown")return!1;const b=Array.isArray(o)&&o.includes(p.button)||!p.button||p.button<=1;return(!p.ctrlKey||g)&&b}}function Lj({domNode:e,minZoom:t,maxZoom:n,translateExtent:o,viewport:s,onPanZoom:a,onPanZoomStart:i,onPanZoomEnd:l,onDraggingChange:c}){const d={isZoomingOrPanning:!1,usedRightMouseButton:!1,prevViewport:{},mouseButton:0,timerId:void 0,panScrollTimeout:void 0,isPanScrolling:!1},f=e.getBoundingClientRect(),p=R0().scaleExtent([t,n]).translateExtent(o),m=lt(e).call(p);w({x:s.x,y:s.y,zoom:kr(s.zoom,t,n)},[[0,0],[f.width,f.height]],o);const h=m.on("wheel.zoom"),g=m.on("dblclick.zoom");p.wheelDelta(dv);function b(E,B){return m?new Promise(O=>{p?.interpolate(B?.interpolate==="linear"?no:xs).transform(Pi(m,B?.duration,B?.ease,()=>O(!0)),E)}):Promise.resolve(!1)}function x({noWheelClassName:E,noPanClassName:B,onPaneContextMenu:O,userSelectionActive:A,panOnScroll:D,panOnDrag:_,panOnScrollMode:R,panOnScrollSpeed:L,preventScrolling:z,zoomOnPinch:j,zoomOnScroll:H,zoomOnDoubleClick:T,zoomActivationKeyPressed:W,lib:G,onTransformChange:ee,connectionInProgress:se,paneClickDistance:te,selectionOnDrag:X}){A&&!d.isZoomingOrPanning&&v();const re=D&&!W&&!A;p.clickDistance(X?1/0:!$t(te)||te<0?0:te);const ge=re?Aj({zoomPanValues:d,noWheelClassName:E,d3Selection:m,d3Zoom:p,panOnScrollMode:R,panOnScrollSpeed:L,zoomOnPinch:j,onPanZoomStart:i,onPanZoom:a,onPanZoomEnd:l}):Pj({noWheelClassName:E,preventScrolling:z,d3ZoomHandler:h});if(m.on("wheel.zoom",ge,{passive:!1}),!A){const U=Ej({zoomPanValues:d,onDraggingChange:c,onPanZoomStart:i});p.on("start",U);const J=$j({zoomPanValues:d,panOnDrag:_,onPaneContextMenu:!!O,onPanZoom:a,onTransformChange:ee});p.on("zoom",J);const ae=_j({zoomPanValues:d,panOnDrag:_,panOnScroll:D,onPaneContextMenu:O,onPanZoomEnd:l,onDraggingChange:c});p.on("end",ae)}const Z=Dj({zoomActivationKeyPressed:W,panOnDrag:_,zoomOnScroll:H,panOnScroll:D,zoomOnDoubleClick:T,zoomOnPinch:j,userSelectionActive:A,noPanClassName:B,noWheelClassName:E,lib:G,connectionInProgress:se});p.filter(Z),T?m.on("dblclick.zoom",g):m.on("dblclick.zoom",null)}function v(){p.on("zoom",null)}async function w(E,B,O){const A=Ai(E),D=p?.constrain()(A,B,O);return D&&await b(D),new Promise(_=>_(D))}async function y(E,B){const O=Ai(E);return await b(O,B),new Promise(A=>A(O))}function N(E){if(m){const B=Ai(E),O=m.property("__zoom");(O.k!==E.zoom||O.x!==E.x||O.y!==E.y)&&p?.transform(m,B,null,{sync:!0})}}function k(){const E=m?T0(m.node()):{x:0,y:0,k:1};return{x:E.x,y:E.y,zoom:E.k}}function S(E,B){return m?new Promise(O=>{p?.interpolate(B?.interpolate==="linear"?no:xs).scaleTo(Pi(m,B?.duration,B?.ease,()=>O(!0)),E)}):Promise.resolve(!1)}function M(E,B){return m?new Promise(O=>{p?.interpolate(B?.interpolate==="linear"?no:xs).scaleBy(Pi(m,B?.duration,B?.ease,()=>O(!0)),E)}):Promise.resolve(!1)}function P(E){p?.scaleExtent(E)}function I(E){p?.translateExtent(E)}function F(E){const B=!$t(E)||E<0?0:E;p?.clickDistance(B)}return{update:x,destroy:v,setViewport:y,setViewportConstrained:w,getViewport:k,scaleTo:S,scaleBy:M,setScaleExtent:P,setTranslateExtent:I,syncViewport:N,setClickDistance:F}}var Mr;(function(e){e.Line="line",e.Handle="handle"})(Mr||(Mr={}));function Tj({width:e,prevWidth:t,height:n,prevHeight:o,affectsX:s,affectsY:a}){const i=e-t,l=n-o,c=[i>0?1:i<0?-1:0,l>0?1:l<0?-1:0];return i&&s&&(c[0]=c[0]*-1),l&&a&&(c[1]=c[1]*-1),c}function Jp(e){const t=e.includes("right")||e.includes("left"),n=e.includes("bottom")||e.includes("top"),o=e.includes("left"),s=e.includes("top");return{isHorizontal:t,isVertical:n,affectsX:o,affectsY:s}}function gn(e,t){return Math.max(0,t-e)}function bn(e,t){return Math.max(0,e-t)}function cs(e,t,n){return Math.max(0,t-e,e-n)}function ef(e,t){return e?!t:t}function Rj(e,t,n,o,s,a,i,l){let{affectsX:c,affectsY:d}=t;const{isHorizontal:f,isVertical:p}=t,m=f&&p,{xSnapped:h,ySnapped:g}=n,{minWidth:b,maxWidth:x,minHeight:v,maxHeight:w}=o,{x:y,y:N,width:k,height:S,aspectRatio:M}=e;let P=Math.floor(f?h-e.pointerX:0),I=Math.floor(p?g-e.pointerY:0);const F=k+(c?-P:P),E=S+(d?-I:I),B=-a[0]*k,O=-a[1]*S;let A=cs(F,b,x),D=cs(E,v,w);if(i){let L=0,z=0;c&&P<0?L=gn(y+P+B,i[0][0]):!c&&P>0&&(L=bn(y+F+B,i[1][0])),d&&I<0?z=gn(N+I+O,i[0][1]):!d&&I>0&&(z=bn(N+E+O,i[1][1])),A=Math.max(A,L),D=Math.max(D,z)}if(l){let L=0,z=0;c&&P>0?L=bn(y+P,l[0][0]):!c&&P<0&&(L=gn(y+F,l[1][0])),d&&I>0?z=bn(N+I,l[0][1]):!d&&I<0&&(z=gn(N+E,l[1][1])),A=Math.max(A,L),D=Math.max(D,z)}if(s){if(f){const L=cs(F/M,v,w)*M;if(A=Math.max(A,L),i){let z=0;!c&&!d||c&&!d&&m?z=bn(N+O+F/M,i[1][1])*M:z=gn(N+O+(c?P:-P)/M,i[0][1])*M,A=Math.max(A,z)}if(l){let z=0;!c&&!d||c&&!d&&m?z=gn(N+F/M,l[1][1])*M:z=bn(N+(c?P:-P)/M,l[0][1])*M,A=Math.max(A,z)}}if(p){const L=cs(E*M,b,x)/M;if(D=Math.max(D,L),i){let z=0;!c&&!d||d&&!c&&m?z=bn(y+E*M+B,i[1][0])/M:z=gn(y+(d?I:-I)*M+B,i[0][0])/M,D=Math.max(D,z)}if(l){let z=0;!c&&!d||d&&!c&&m?z=gn(y+E*M,l[1][0])/M:z=bn(y+(d?I:-I)*M,l[0][0])/M,D=Math.max(D,z)}}}I=I+(I<0?D:-D),P=P+(P<0?A:-A),s&&(m?F>E*M?I=(ef(c,d)?-P:P)/M:P=(ef(c,d)?-I:I)*M:f?(I=P/M,d=c):(P=I*M,c=d));const _=c?y+P:y,R=d?N+I:N;return{width:k+(c?-P:P),height:S+(d?-I:I),x:a[0]*P*(c?-1:1)+_,y:a[1]*I*(d?-1:1)+R}}const uv={width:0,height:0,x:0,y:0},Oj={...uv,pointerX:0,pointerY:0,aspectRatio:1};function zj(e){return[[0,0],[e.measured.width,e.measured.height]]}function Bj(e,t,n){const o=t.position.x+e.position.x,s=t.position.y+e.position.y,a=e.measured.width??0,i=e.measured.height??0,l=n[0]*a,c=n[1]*i;return[[o-l,s-c],[o+a-l,s+i-c]]}function Fj({domNode:e,nodeId:t,getStoreItems:n,onChange:o,onEnd:s}){const a=lt(e);let i={controlDirection:Jp("bottom-right"),boundaries:{minWidth:0,minHeight:0,maxWidth:Number.MAX_VALUE,maxHeight:Number.MAX_VALUE},resizeDirection:void 0,keepAspectRatio:!1};function l({controlPosition:d,boundaries:f,keepAspectRatio:p,resizeDirection:m,onResizeStart:h,onResize:g,onResizeEnd:b,shouldResize:x}){let v={...uv},w={...Oj};i={boundaries:f,resizeDirection:m,keepAspectRatio:p,controlDirection:Jp(d)};let y,N=null,k=[],S,M,P,I=!1;const F=w0().on("start",E=>{const{nodeLookup:B,transform:O,snapGrid:A,snapToGrid:D,nodeOrigin:_,paneDomNode:R}=n();if(y=B.get(t),!y)return;N=R?.getBoundingClientRect()??null;const{xSnapped:L,ySnapped:z}=ro(E.sourceEvent,{transform:O,snapGrid:A,snapToGrid:D,containerBounds:N});v={width:y.measured.width??0,height:y.measured.height??0,x:y.position.x??0,y:y.position.y??0},w={...v,pointerX:L,pointerY:z,aspectRatio:v.width/v.height},S=void 0,y.parentId&&(y.extent==="parent"||y.expandParent)&&(S=B.get(y.parentId),M=S&&y.extent==="parent"?zj(S):void 0),k=[],P=void 0;for(const[j,H]of B)if(H.parentId===t&&(k.push({id:j,position:{...H.position},extent:H.extent}),H.extent==="parent"||H.expandParent)){const T=Bj(H,y,H.origin??_);P?P=[[Math.min(T[0][0],P[0][0]),Math.min(T[0][1],P[0][1])],[Math.max(T[1][0],P[1][0]),Math.max(T[1][1],P[1][1])]]:P=T}h?.(E,{...v})}).on("drag",E=>{const{transform:B,snapGrid:O,snapToGrid:A,nodeOrigin:D}=n(),_=ro(E.sourceEvent,{transform:B,snapGrid:O,snapToGrid:A,containerBounds:N}),R=[];if(!y)return;const{x:L,y:z,width:j,height:H}=v,T={},W=y.origin??D,{width:G,height:ee,x:se,y:te}=Rj(w,i.controlDirection,_,i.boundaries,i.keepAspectRatio,W,M,P),X=G!==j,re=ee!==H,ge=se!==L&&X,Z=te!==z&&re;if(!ge&&!Z&&!X&&!re)return;if((ge||Z||W[0]===1||W[1]===1)&&(T.x=ge?se:v.x,T.y=Z?te:v.y,v.x=T.x,v.y=T.y,k.length>0)){const fe=se-L,he=te-z;for(const V of k)V.position={x:V.position.x-fe+W[0]*(G-j),y:V.position.y-he+W[1]*(ee-H)},R.push(V)}if((X||re)&&(T.width=X&&(!i.resizeDirection||i.resizeDirection==="horizontal")?G:v.width,T.height=re&&(!i.resizeDirection||i.resizeDirection==="vertical")?ee:v.height,v.width=T.width,v.height=T.height),S&&y.expandParent){const fe=W[0]*(T.width??0);T.x&&T.x<fe&&(v.x=fe,w.x=w.x-(T.x-fe));const he=W[1]*(T.height??0);T.y&&T.y<he&&(v.y=he,w.y=w.y-(T.y-he))}const U=Tj({width:v.width,prevWidth:j,height:v.height,prevHeight:H,affectsX:i.controlDirection.affectsX,affectsY:i.controlDirection.affectsY}),J={...v,direction:U};x?.(E,J)!==!1&&(I=!0,g?.(E,J),o(T,R))}).on("end",E=>{I&&(b?.(E,{...v}),s?.({...v}),I=!1)});a.call(F)}function c(){a.on(".drag",null)}return{update:l,destroy:c}}var pv={exports:{}},fv={};/**
|
|
1085
1085
|
* @license React
|
|
1086
1086
|
* use-sync-external-store-shim/with-selector.production.js
|
|
1087
1087
|
*
|