@camstack/addon-admin-ui 1.2.53 → 1.2.55
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/{AddLocationWizard-CTZRH8Z5.js → AddLocationWizard-BWvvcMyb.js} +1 -1
- package/dist/assets/{AddonCollectionPage-D-p4HN2Y.js → AddonCollectionPage-Ckxfpzo7.js} +1 -1
- package/dist/assets/Addons-CzByWp7W.js +1 -0
- package/dist/assets/{AdminTabs-DyjWcTkF.js → AdminTabs-BXEhxCj0.js} +1 -1
- package/dist/assets/{AiProfiles-5buIYxWX.js → AiProfiles-DJkiEAGj.js} +1 -1
- package/dist/assets/{BrokerForm-D-nVBA-o.js → BrokerForm-DjMStxWR.js} +1 -1
- package/dist/assets/Build-rgGY63ER.js +32 -0
- package/dist/assets/{Capabilities-BNz3VrvR.js → Capabilities-B1xz532o.js} +1 -1
- package/dist/assets/{CapabilityBadges-Dy-fCgkC.js → CapabilityBadges-Dod41sYV.js} +1 -1
- package/dist/assets/Cluster-BTgdYtnl.js +1 -0
- package/dist/assets/{Data-CxIEICSc.js → Data-C_1Pyfta.js} +1 -1
- package/dist/assets/{DetectionIntelligence-Bow03mZW.js → DetectionIntelligence-CzvM15vc.js} +1 -1
- package/dist/assets/{DeviceAggregateSection-D3GgzLed.js → DeviceAggregateSection-n-EPWZZr.js} +1 -1
- package/dist/assets/DeviceDetail-Cf7EiAYj.js +2 -0
- package/dist/assets/{Devices-BQFYrt_N.js → Devices-Crj69Baf.js} +1 -1
- package/dist/assets/{EmbedPlayerPage-C-lzc6gT.js → EmbedPlayerPage-CvHYMXl7.js} +1 -1
- package/dist/assets/Events-CxX3Qrw_.js +1 -0
- package/dist/assets/{FormBuilder-9AyvljDu.js → FormBuilder-B1p15b6p.js} +1 -1
- package/dist/assets/Identity-Bn_lLl-Y.js +1 -0
- package/dist/assets/IntegrationDetail-CKmbntak.js +1 -0
- package/dist/assets/{Integrations-Dy6aGdNk.js → Integrations-CCzFtCKr.js} +1 -1
- package/dist/assets/{Integrations-2hJS885p.js → Integrations-ZydMIfls.js} +1 -1
- package/dist/assets/{Logs-2uU6ZNE6.js → Logs-UiFFsPuc.js} +1 -1
- package/dist/assets/{MotionZonesSettings-TAZs0iQF.js → MotionZonesSettings-gX4cCPfn.js} +1 -1
- package/dist/assets/MyAccess-CwZDSuVD.js +2 -0
- package/dist/assets/Network-XmpYwBZJ.js +1 -0
- package/dist/assets/{NodeAddonsSettingsPanel-BEd9xkul.js → NodeAddonsSettingsPanel-Cc6eK0w1.js} +1 -1
- package/dist/assets/{NodeInferenceDevices-Bo3q56ME.js → NodeInferenceDevices-j_wrfCuc.js} +1 -1
- package/dist/assets/Notifications-1iF_hGtj.js +1 -0
- package/dist/assets/Pipeline-B50SZqsP.js +1 -0
- package/dist/assets/{Plates-VOllqnia.js → Plates-CH4cT8pd.js} +1 -1
- package/dist/assets/{PrivacyMaskSettings-CyiOeki9.js → PrivacyMaskSettings-BJokOnXq.js} +1 -1
- package/dist/assets/{ProviderIcon-lr-CBThV.js → ProviderIcon-BFPv4wws.js} +1 -1
- package/dist/assets/{Recordings-cNKeFWdX.js → Recordings-BegJiF6M.js} +1 -1
- package/dist/assets/{ScanNetworkModal-C8eQs-oa.js → ScanNetworkModal-BOCd4ene.js} +1 -1
- package/dist/assets/{Settings-DUnGk-Ze.js → Settings-D2MA9Dep.js} +1 -1
- package/dist/assets/{Showroom-CXqbw81j.js → Showroom-D3FeCiS7.js} +1 -1
- package/dist/assets/{Terminal-DCg-c08F.js → Terminal-CQtijhK7.js} +2 -2
- package/dist/assets/{__vite-browser-external-DQHwpgVa.js → __vite-browser-external-B6qJ4svC.js} +3 -3
- package/dist/assets/{_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-BwtyD_uY.js → _virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-DjdplOZ0.js} +1 -1
- package/dist/assets/{bell-ring-Bva0sp7P.js → bell-ring-DVYgCiuX.js} +1 -1
- package/dist/assets/{boxes-DaaA1U2C.js → boxes-BAPHU21k.js} +1 -1
- package/dist/assets/{build-cluster-graph-DmatAPiL.js → build-cluster-graph-BHbSkxPE.js} +2 -2
- package/dist/assets/circle-check-big-BU8Z1nvB.js +1 -0
- package/dist/assets/{circle-x-DukPu47a.js → circle-x-D8tkl9U0.js} +1 -1
- package/dist/assets/clock-CxUDARJh.js +1 -0
- package/dist/assets/{copy-CDwMOr_d.js → copy-DERe_X8j.js} +1 -1
- package/dist/assets/{debounced-invalidate-DdpdBiw5.js → debounced-invalidate-BHYRiwPD.js} +1 -1
- package/dist/assets/dist-CawjP_cp.js +345 -0
- package/dist/assets/{dist-C61wZXG_.js → dist-D4q0IXSf.js} +1 -1
- package/dist/assets/{download-BgcYzk2Q.js → download-CXEPE2lw.js} +1 -1
- package/dist/assets/{face-bbox-CwWXxJeF.js → face-bbox-CiazA6JA.js} +1 -1
- package/dist/assets/{hard-drive-DBS5CobV.js → hard-drive-BsC1Lb8K.js} +1 -1
- package/dist/assets/{hostInit-BRYz12QA.js → hostInit-qO7zf83T.js} +1 -1
- package/dist/assets/index-BxnMqiYH.js +4 -0
- package/dist/assets/{index-DchMAgXl.css → index-DuDia5Gb.css} +1 -1
- package/dist/assets/{key-round-zsF7PT11.js → key-round-DXJWRmE5.js} +1 -1
- package/dist/assets/{mf-entry-bootstrap-0-5949baa8.js → mf-entry-bootstrap-0-3cb4bcaf.js} +2 -2
- package/dist/assets/{pencil-DoFsGHJs.js → pencil-gmfJxKQf.js} +1 -1
- package/dist/assets/play-CkW0xDC3.js +1 -0
- package/dist/assets/{player-overlays-C-3liTTP.js → player-overlays-H5rD3ZP3.js} +1 -1
- package/dist/assets/plus-BlsiiKYm.js +1 -0
- package/dist/assets/power-bZi2AxzL.js +1 -0
- package/dist/assets/{radio-BLrBPWuP.js → radio-C02Qj5rg.js} +1 -1
- package/dist/assets/{refresh-cw-DcXpV7xr.js → refresh-cw-C3lx1ppr.js} +1 -1
- package/dist/assets/remoteEntry-Hbnv0GQ-.js +1 -0
- package/dist/assets/rotate-ccw-B8IL7YJE.js +1 -0
- package/dist/assets/rotate-cw-DBD7lbZQ.js +1 -0
- package/dist/assets/search-DliTh-pg.js +1 -0
- package/dist/assets/{send-lVWoIHYN.js → send-Cs7xh34W.js} +1 -1
- package/dist/assets/{server-CrysozOm.js → server-CJt4Xl7p.js} +1 -1
- package/dist/assets/square-CcAa1SRj.js +1 -0
- package/dist/assets/{square-check-big-CItT96VK.js → square-check-big-DKi6ipve.js} +1 -1
- package/dist/assets/src-BPc_UYBv.js +67 -0
- package/dist/assets/src-C5APVTn-.js +345 -0
- package/dist/assets/{undo-2-BJ4kacMc.js → undo-2-DEPDrng4.js} +1 -1
- package/dist/assets/{upload-Cug_X6EC.js → upload-Dgf2pYnC.js} +1 -1
- package/dist/assets/{useEventInvalidation-BwhFlT4Q.js → useEventInvalidation-4Fc-dQYg.js} +1 -1
- package/dist/assets/{video-CDgzsesk.js → video-hnQuQlJv.js} +1 -1
- package/dist/assets/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-B8LLmlIG.js → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-7qrqOExj.js} +2 -2
- package/dist/assets/{wifi-B6L90xdN.js → wifi-Daw8zrsS.js} +1 -1
- package/dist/assets/{zap-RxnCgRQ7.js → zap-Dw5xT3PE.js} +1 -1
- package/dist/index.html +7 -7
- package/dist/server/addon.js +1850 -26
- package/package.json +1 -1
- package/dist/assets/Addons-hLgZ2H01.js +0 -1
- package/dist/assets/Build-gYggCQtz.js +0 -32
- package/dist/assets/Cluster-79wiomQQ.js +0 -1
- package/dist/assets/DeviceDetail-xGas7OKY.js +0 -2
- package/dist/assets/Events-CVnzxEgV.js +0 -1
- package/dist/assets/Identity-DdsiRBNP.js +0 -1
- package/dist/assets/IntegrationDetail-Dmbq_Wgu.js +0 -1
- package/dist/assets/MyAccess-DcPz5T-h.js +0 -2
- package/dist/assets/Network-BOtKpCey.js +0 -1
- package/dist/assets/Notifications-CwTETm0t.js +0 -1
- package/dist/assets/Pipeline-DhHsaSYf.js +0 -1
- package/dist/assets/circle-check-big-B89lSUUk.js +0 -1
- package/dist/assets/clock-DhfaWKQT.js +0 -1
- package/dist/assets/dist-DqDvuSSn.js +0 -345
- package/dist/assets/index-fyPDUdJN.js +0 -4
- package/dist/assets/play-Bhpu49mx.js +0 -1
- package/dist/assets/plus-C9xW_jEC.js +0 -1
- package/dist/assets/power-dfEFBp4-.js +0 -1
- package/dist/assets/remoteEntry-Cyq1R_C0.js +0 -1
- package/dist/assets/rotate-ccw-CkObSlR8.js +0 -1
- package/dist/assets/rotate-cw-DMKQK91h.js +0 -1
- package/dist/assets/search-CBZXGB7v.js +0 -1
- package/dist/assets/square-C1CVou2Z.js +0 -1
- package/dist/assets/src-9rmmBstM.js +0 -345
- package/dist/assets/src-BFsyqPDw.js +0 -67
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Bo as e,Fo as t,Ro as n,So as r,Vo as i,as as a,cs as o,ds as s,er as c,es as l,fs as u,is as d,ls as f,os as p,rs as m,sa as h,ts as g,us as _,w as v,zo as y}from"./src-BPc_UYBv.js";import{Q as b,S as x,W as S,a as C,b as w,i as T,o as E,q as D,t as O,x as k,z as A}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-DTufy7Ue.js";import{B as j,C as M,L as ee,Q as N,S as P,T as te,V as F,_ as ne,b as re,f as ie,g as ae,h as oe,m as se,p as ce,v as le,w as ue,x as de,y as fe}from"./src-C5APVTn-.js";import{D as pe,E as me,_ as he,j as ge,v as _e}from"./__vite-browser-external-B6qJ4svC.js";import{p as I}from"./player-overlays-H5rD3ZP3.js";import{n as ve,t as ye}from"./bell-ring-DVYgCiuX.js";import{t as be}from"./circle-check-big-BU8Z1nvB.js";import{t as xe}from"./copy-DERe_X8j.js";import{t as Se}from"./pencil-gmfJxKQf.js";import{t as Ce}from"./plus-BlsiiKYm.js";import{t as we}from"./refresh-cw-C3lx1ppr.js";import{t as Te}from"./rotate-ccw-B8IL7YJE.js";import{t as Ee}from"./search-DliTh-pg.js";import{t as De}from"./send-Cs7xh34W.js";import{t as Oe}from"./zap-Dw5xT3PE.js";import{C as ke,E as Ae,J as je,N as Me,S as L,V as Ne,W as Pe,f as Fe,i as Ie,o as Le,s as R}from"./index-BxnMqiYH.js";import{t as z}from"./AdminPage-Dq33XE9j.js";import{t as Re}from"./AdminTabs-BXEhxCj0.js";var ze=Pe(`flask-conical`,[[`path`,{d:`M14 2v6a2 2 0 0 0 .245.96l5.51 10.08A2 2 0 0 1 18 22H6a2 2 0 0 1-1.755-2.96l5.51-10.08A2 2 0 0 0 10 8V2`,key:`18mbvz`}],[`path`,{d:`M6.453 15h11.094`,key:`3shlmq`}],[`path`,{d:`M8.5 2h7`,key:`csnxdl`}]]),Be=Pe(`history`,[[`path`,{d:`M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8`,key:`1357e3`}],[`path`,{d:`M3 3v5h5`,key:`1xhq8a`}],[`path`,{d:`M12 7v5l4 2`,key:`1fdv2h`}]]),Ve=Pe(`images`,[[`path`,{d:`M18 22H4a2 2 0 0 1-2-2V6`,key:`pblm9e`}],[`path`,{d:`m22 13-1.296-1.296a2.41 2.41 0 0 0-3.408 0L11 18`,key:`nf6bnh`}],[`circle`,{cx:`12`,cy:`8`,r:`2`,key:`1822b1`}],[`rect`,{width:`16`,height:`16`,x:`6`,y:`2`,rx:`2`,key:`12espp`}]]),He=Pe(`languages`,[[`path`,{d:`m5 8 6 6`,key:`1wu5hv`}],[`path`,{d:`m4 14 6-6 2-3`,key:`1k1g8d`}],[`path`,{d:`M2 5h12`,key:`or177f`}],[`path`,{d:`M7 2h1`,key:`1t2jsx`}],[`path`,{d:`m22 22-5-10-5 10`,key:`don7ne`}],[`path`,{d:`M14 18h6`,key:`1m8k6r`}]]);b();var Ue={home:`Home`,away:`Away`,night:`Night`};function We(e){return Ue[e]??e}function Ge(e,t){if(e<=0)return t;if(e<60)return`${e} s`;let n=Math.floor(e/60),r=e%60;return r===0?`${n} min`:`${n} min ${r} s`}function Ke(e,t){return e.ruleCount===0?`Arms nothing — no enabled rule is gated on this mode.`:e.allDevices?`Every device — ${Xe(e.ruleCount,`rule`)} with no device scope.`:e.deviceIds.length===0?`${Xe(e.ruleCount,`rule`)}, no device restriction.`:e.deviceIds.map(e=>t.get(e)??`Device ${e}`).join(`, `)}function qe(e,t){if(e.length===0)return``;let n=e.map(e=>`${t.get(e.deviceId)??`Device ${e.deviceId}`} (${Je[e.reason]})`);return`${e.length} excluded: ${n.join(`, `)}`}var Je={muted:`notifications muted`,"detection-off":`detection off`,offline:`offline`};function Ye(e){return e.ruleCount===0}function Xe(e,t){return e===1?`1 ${t}`:`${e} ${t}s`}function Ze(e,t){let n=e.trim();if(n===``)return null;let r=Number(n);return!Number.isFinite(r)||!Number.isInteger(r)||r<0||r>t?null:r}var Qe=[`notificationRules`,`getAlarmConfig`],$e=[`notificationOutput`,`listTargets`],et=[`deviceManager`,`listAll`,`alarm-coverage`],tt=600,nt=3600;function rt({label:e,hint:t,value:n,max:r,zeroMeans:i,disabled:a,onCommit:o}){let[s,c]=D(null);return x(`div`,{className:`flex flex-col gap-1`,children:[k(`label`,{className:`text-sm font-medium`,children:e}),x(`div`,{className:`flex items-center gap-2`,children:[k(f,{type:`number`,min:0,max:r,value:s??String(n),disabled:a,onChange:e=>c(e.target.value),onBlur:()=>{let e=s===null?null:Ze(s,r);c(null),e!==null&&e!==n&&o(e)},className:`w-28`,"data-testid":`alarm-delay-${e.toLowerCase().replace(/\s+/g,`-`)}`}),k(`span`,{className:`text-sm text-foreground-subtle`,children:Ge(n,i)})]}),k(`p`,{className:`text-xs text-foreground-subtle`,children:t})]})}function it(){let e=I(),t=E(),n=C({queryKey:Qe,queryFn:async()=>e.trpcClient.notificationRules.getAlarmConfig.query({})}),i=C({queryKey:$e,queryFn:async()=>(await e.trpcClient.notificationOutput.listTargets.query({})).map(e=>({id:e.id,name:e.name,enabled:e.enabled}))}),a=C({queryKey:et,queryFn:async()=>(await e.trpcClient.deviceManager.listAll.query({projection:`slim`})).map(e=>({id:e.id,name:e.name}))}),o=O({mutationFn:t=>e.trpcClient.notificationRules.setAlarmConfig.mutate({patch:t}),onSuccess:()=>t.invalidateQueries({queryKey:Qe})}),c=S(()=>{let e=new Map;for(let t of a.data??[])e.set(t.id,t.name);return e},[a.data]);if(n.isLoading)return k(z,{icon:Fe,title:`Alarm`,subtitle:`Panel delays and mode coverage.`,children:k(L,{className:`h-5 w-5 animate-spin`})});let l=n.data;if(l===void 0||n.isError)return k(z,{icon:Fe,title:`Alarm`,subtitle:`Panel delays and mode coverage.`,children:k(r,{title:`Alarm settings are not available`,message:`This hub has not been updated to serve the alarm configuration yet.`})});if(l.deviceId===null)return k(z,{icon:Fe,title:`Alarm`,subtitle:`Panel delays and mode coverage.`,children:k(_,{className:`p-4`,children:k(`p`,{className:`text-sm text-foreground-subtle`,children:`This installation has no alarm panel. The panel is created by the Notification Center on the hub — if this is the hub, its creation failed and the server log says why.`})})});let u=l.settings,d=o.isPending,f=i.data??[],m=u.announceTargets,h=e=>{o.mutate(e)},g=e=>{h({announceTargets:m.includes(e)?m.filter(t=>t!==e):[...m,e]})};return k(z,{icon:Fe,title:`Alarm`,subtitle:`Panel delays, and what each mode actually arms.`,children:x(`div`,{className:`flex flex-col gap-4`,children:[o.isError?k(r,{title:`Could not save`,message:String(o.error)}):null,x(_,{className:`p-4`,children:[k(`h3`,{className:`text-sm font-semibold mb-3`,children:`Delays`}),x(`div`,{className:`grid gap-4 sm:grid-cols-3`,children:[k(rt,{label:`Exit delay`,hint:`Time between arming and the mode taking effect — long enough to leave.`,value:u.exitDelaySec,max:tt,zeroMeans:`arms immediately`,disabled:d,onCommit:e=>h({exitDelaySec:e})}),k(rt,{label:`Entry delay`,hint:`Time between a trigger and the alarm firing — long enough to reach the keypad.`,value:u.entryDelaySec,max:tt,zeroMeans:`fires immediately`,disabled:d,onCommit:e=>h({entryDelaySec:e})}),k(rt,{label:`Triggered for`,hint:`How long the alarm stays triggered before re-arming itself.`,value:u.triggeredDurationSec,max:nt,zeroMeans:`until disarmed`,disabled:d,onCommit:e=>h({triggeredDurationSec:e})})]})]}),x(_,{className:`p-4`,children:[x(`div`,{className:`flex items-start justify-between gap-4`,children:[x(`div`,{children:[k(`h3`,{className:`text-sm font-semibold`,children:`Announce when a mode is armed`}),k(`p`,{className:`text-xs text-foreground-subtle mt-1`,children:`Sends one notification listing the devices that mode arms — the list below, as it stands at that moment.`})]}),k(p,{checked:u.announceArm,disabled:d,onCheckedChange:e=>h({announceArm:e}),"data-testid":`alarm-announce-toggle`})]}),u.announceArm?x(`div`,{className:`mt-3 flex flex-col gap-2`,children:[f.length===0?k(`p`,{className:`text-xs text-foreground-subtle`,children:`No notification targets are configured — nothing can be sent.`}):f.map(e=>x(`label`,{className:`flex items-center gap-2 text-sm`,children:[k(`input`,{type:`checkbox`,checked:m.includes(e.id),disabled:d,onChange:()=>g(e.id),"data-testid":`alarm-target-${e.id}`}),k(`span`,{children:e.name}),e.enabled?null:k(s,{variant:`warning`,children:`disabled`})]},e.id)),m.length===0?k(`p`,{className:`text-xs text-warning`,children:`No target selected — the announcement will not be sent.`}):null]}):null]}),x(_,{className:`p-4`,children:[k(`h3`,{className:`text-sm font-semibold mb-1`,children:`What each mode arms`}),k(`p`,{className:`text-xs text-foreground-subtle mb-3`,children:`Derived from the enabled rules gated on this panel. Nothing here is stored — change a rule and this changes with it.`}),k(`div`,{className:`flex flex-col gap-2`,"data-testid":`alarm-coverage`,children:l.coverage.map(e=>x(`div`,{className:`flex items-start gap-3 rounded border border-border p-2`,"data-mode":e.mode,"data-empty":Ye(e)?`true`:`false`,children:[k(`div`,{className:`w-20 shrink-0 text-sm font-medium`,children:We(e.mode)}),x(`div`,{className:`flex-1 text-sm text-foreground-subtle`,children:[Ke(e,c),e.skippedDevices.length>0?k(`div`,{className:`mt-0.5 text-xs text-warning`,"data-testid":`alarm-skipped`,children:qe(e.skippedDevices,c)}):null]}),Ye(e)?k(Le,{className:`h-4 w-4 shrink-0 text-warning`}):null]},e.mode))})]})]})})}b();var at=[{value:1,label:`Last hour`},{value:24,label:`Last 24 hours`},{value:168,label:`Last 7 days`},{value:0,label:`All time`}],ot=[{value:``,label:`Any status`},{value:`pending`,label:`Pending`},{value:`sent`,label:`Sent`},{value:`dead`,label:`Dead`}],st=[50,100,250,500];function ct(){return{ruleId:``,deviceId:``,status:``,windowHours:24,limit:100}}function lt(e){return e===`pending`||e===`sent`||e===`dead`?e:void 0}function ut(e){switch(e){case`pending`:return`info`;case`sent`:return`success`;case`dead`:return`danger`}}function dt(){let e=I(),[n,r]=D(ct),i=e=>r(t=>({...t,...e})),a=C({queryKey:[`notificationRules`,`listRules`,`forHistory`],queryFn:async()=>(await e.trpcClient.notificationRules.listRules.query({})).rules}),s=C({queryKey:[`deviceManager`,`listAll`,`forHistory`],queryFn:async()=>(await e.trpcClient.deviceManager.listAll.query({})).filter(e=>e.type===N.Camera).map(e=>({id:e.id,name:e.name}))}),c=Date.now(),l=C({queryKey:[`notificationRules`,`getHistory`,n],retry:!1,queryFn:async()=>{let t=n.windowHours>0?c-n.windowHours*36e5:void 0;return(await e.trpcClient.notificationRules.getHistory.query({filter:{limit:n.limit,...n.ruleId?{ruleId:n.ruleId}:{},...n.deviceId?{deviceId:Number(n.deviceId)}:{},...lt(n.status)?{status:lt(n.status)}:{},...t===void 0?{}:{since:t}}})).entries}}),u=S(()=>{let e=new Map;for(let t of s.data??[])e.set(t.id,t.name);return e},[s.data]),d=e=>u.get(e)??`Camera #${String(e)}`,f=l.data??[],p=l.isError;return x(z,{icon:Be,title:`Delivery history`,subtitle:`A searchable log of every notification the rules delivered (or failed to deliver).`,children:[x(`div`,{className:`mb-4 grid grid-cols-2 gap-2 sm:grid-cols-5`,children:[x(`div`,{children:[k(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:`Rule`}),k(o,{value:n.ruleId,onChange:e=>i({ruleId:e.target.value}),options:[{value:``,label:`All rules`},...(a.data??[]).map(e=>({value:e.id,label:e.name}))]})]}),x(`div`,{children:[k(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:`Camera`}),k(o,{value:n.deviceId,onChange:e=>i({deviceId:e.target.value}),options:[{value:``,label:`All cameras`},...(s.data??[]).map(e=>({value:String(e.id),label:e.name}))]})]}),x(`div`,{children:[k(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:`Status`}),k(o,{value:n.status,onChange:e=>i({status:e.target.value}),options:ot.map(e=>({value:e.value,label:e.label}))})]}),x(`div`,{children:[k(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:`Window`}),k(o,{value:String(n.windowHours),onChange:e=>i({windowHours:Number(e.target.value)}),options:at.map(e=>({value:String(e.value),label:e.label}))})]}),x(`div`,{children:[k(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:`Limit`}),k(o,{value:String(n.limit),onChange:e=>i({limit:Number(e.target.value)}),options:st.map(e=>({value:String(e),label:String(e)}))})]})]}),l.isLoading&&k(`div`,{className:`flex items-center justify-center py-16`,children:k(L,{className:`h-6 w-6 animate-spin text-primary`})}),p&&!l.isLoading&&k(_,{children:x(`div`,{className:`flex flex-col items-center gap-2 px-4 py-14 text-center`,children:[k(Be,{className:`h-6 w-6 text-foreground-subtle`}),k(`div`,{className:`text-sm font-medium text-foreground`,children:`Delivery history requires a server update`}),k(`p`,{className:`max-w-md text-xs text-foreground-subtle`,children:`The history query is not available on this hub yet. It becomes queryable after the next server update ships the notification-center history endpoint. Rules still deliver and record their outcome in the meantime.`}),x(`button`,{type:`button`,onClick:()=>void l.refetch(),className:`mt-1 inline-flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1 text-[11px] text-foreground-subtle hover:bg-surface-hover hover:text-foreground`,children:[k(we,{className:`h-3 w-3`}),` Retry`]})]})}),!p&&!l.isLoading&&f.length===0&&k(`div`,{className:`py-16 text-center text-xs text-foreground-subtle`,children:`No deliveries match these filters.`}),!p&&f.length>0&&k(_,{children:k(t,{columns:ft(d),rows:f,rowKey:e=>e.id,minWidthPx:720,bordered:!1})})]})}function ft(e){return[{key:`when`,header:`When`,nowrap:!0,render:e=>k(`span`,{className:`text-[11px] text-foreground-subtle`,children:new Date(e.createdAt).toLocaleString()})},{key:`rule`,header:`Rule`,render:e=>k(`span`,{className:`text-xs font-medium text-foreground`,children:e.ruleName})},{key:`camera`,header:`Camera`,nowrap:!0,render:t=>k(`span`,{className:`text-[11px] text-foreground-subtle`,children:e(t.deviceId)})},{key:`subject`,header:`Subject`,render:e=>x(`span`,{className:`text-[11px] text-foreground-subtle`,children:[e.subject.label??e.subject.className,e.subject.confidence===void 0?``:` · ${Math.round(e.subject.confidence*100)}%`]})},{key:`status`,header:`Status`,nowrap:!0,render:e=>x(`span`,{className:`flex items-center gap-1.5`,children:[k(s,{variant:ut(e.status),children:e.status}),e.attempts>1?x(`span`,{className:`text-[10px] text-foreground-subtle`,children:[`×`,e.attempts]}):null]})},{key:`error`,header:`Detail`,render:e=>e.error?k(`span`,{className:`text-[11px] text-danger`,children:e.error}):k(`span`,{className:`text-[11px] text-foreground-subtle`,children:`—`})}]}function pt(e){let t=[],n=e.find(e=>e.type===N.AlarmPanel);n!==void 0&&t.push({id:`trigger-alarm`,label:`Trigger the alarm`,hint:`Presses ${n.name}. The panel's entry delay still runs, and a disarm during it cancels the alarm.`,build:()=>({name:`trigger the alarm`,enabled:!0,actions:[{kind:`cap`,deviceId:n.id,cap:`alarm-panel`,method:`trigger`,args:{}}]})});for(let n of e.filter(e=>e.type===N.Siren))t.push({id:`siren-${String(n.id)}`,label:`Sound ${n.name}`,hint:`On, 30 seconds, off. A siren left on by a failed step is the one this sequence exists to avoid.`,build:()=>({name:`sound ${n.name}`.toLowerCase(),enabled:!0,minDelaySec:60,actions:[{kind:`cap`,deviceId:n.id,cap:`switch`,method:`setState`,args:{on:!0}},{kind:`wait`,seconds:30},{kind:`cap`,deviceId:n.id,cap:`switch`,method:`setState`,args:{on:!1}}]})});return t}function mt(e,t){let n=t.build(),r=new Set(e.sequences.map(e=>e.name.trim())),i=n.name;for(let e=2;r.has(i);e+=1)i=`${n.name} ${String(e)}`;return{...e,sequences:[...e.sequences,{...n,name:i}]}}var ht=[{value:`acknowledge`,label:`Acknowledge`},{value:`dismiss`,label:`Dismiss`},{value:`silence`,label:`Silence`},{value:`snooze`,label:`Snooze`},{value:`view`,label:`View`},{value:`play`,label:`Play`},{value:`camera`,label:`Camera`},{value:`open`,label:`Open`},{value:`close`,label:`Close`},{value:`unlock`,label:`Unlock`},{value:`lock`,label:`Lock`},{value:`disarm`,label:`Disarm`},{value:`arm`,label:`Arm`},{value:`arm-home`,label:`Arm — home`},{value:`arm-away`,label:`Arm — away`},{value:`arm-night`,label:`Arm — night`},{value:`light`,label:`Light`},{value:`alert`,label:`Alert`}],gt={sequences:[],buttons:[]};function _t(e){return e===void 0?gt:{sequences:[...e.onTrigger??[]],buttons:[...e.buttons??[]]}}function vt(e){let t=e.sequences.filter(e=>e.name.trim()!==``),n=e.buttons.filter(e=>e.id.trim()!==``&&e.label.trim()!==``);if(!(t.length===0&&n.length===0))return{...t.length>0?{onTrigger:t}:{},...n.length>0?{buttons:n}:{}}}function yt(e){let t=[],n=new Set;for(let r of e.sequences){let e=r.name.trim();e!==``&&(n.has(e)&&t.push({kind:`duplicate-sequence`,message:`Two sequences are called "${e}". The name is how a button points at one, and how its throttle is keyed.`}),n.add(e),r.actions.length===0&&t.push({kind:`empty-sequence`,message:`"${e}" has no steps, so it would do nothing.`}))}let r=new Set;for(let i of e.buttons){let e=i.id.trim();e!==``&&(r.has(e)&&t.push({kind:`duplicate-button`,message:`Two buttons share the id "${e}". The id is what the audit line names when one is tapped.`}),r.add(e),n.has(i.sequence.trim())||t.push({kind:`unknown-sequence`,message:`"${i.label||e}" points at the sequence "${i.sequence}", which this rule does not have. It would never appear on a notification.`}))}return t}function bt(e){return{name:`sequence ${String(e+1)}`,enabled:!1,actions:[]}}function xt(e,t){return{id:`action-${String(e+1)}`,label:`Action`,sequence:t}}function St(){return{kind:`wait`,seconds:5}}var Ct=`mt-1 w-full rounded border border-border bg-background px-2 py-1 text-xs`,B=`block text-[11px] font-medium text-foreground`;function wt({value:e,onChange:t,devices:n}){let r=yt(e),i=pt(n),a=(n,r)=>t({...e,sequences:e.sequences.map((e,t)=>t===n?r:e)}),o=(n,r)=>t({...e,buttons:e.buttons.map((e,t)=>t===n?r:e)});return x(`div`,{className:`space-y-4`,children:[r.length>0&&k(`div`,{className:`space-y-1 rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-[11px] text-warning`,children:r.map(e=>k(`p`,{children:e.message},e.message))}),x(`section`,{className:`space-y-2`,children:[x(`div`,{className:`flex items-center justify-between`,children:[x(`div`,{children:[k(`h4`,{className:`text-xs font-semibold text-foreground`,children:`What this rule does`}),k(`p`,{className:`text-[11px] text-foreground-subtle`,children:`Runs when the rule matches. A sequence stops at the first failed step, and its own delay limits how often it may physically run — separate from the notification cooldown.`})]}),x(`div`,{className:`flex items-center gap-1`,children:[i.map(n=>x(u,{size:`sm`,variant:`ghost`,type:`button`,title:n.hint,onClick:()=>t(mt(e,n)),children:[k(Oe,{className:`h-3.5 w-3.5`}),` `,n.label]},n.id)),x(u,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>t({...e,sequences:[...e.sequences,bt(e.sequences.length)]}),children:[k(Ce,{className:`h-3.5 w-3.5`}),` Sequence`]})]})]}),e.sequences.length===0?k(`p`,{className:`rounded border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:`This rule actuates nothing — it only notifies.`}):e.sequences.map((r,i)=>k(Tt,{sequence:r,devices:n,onChange:e=>a(i,e),onRemove:()=>t({...e,sequences:e.sequences.filter((e,t)=>t!==i)})},`seq-${String(i)}`))]}),x(`section`,{className:`space-y-2`,children:[x(`div`,{className:`flex items-center justify-between`,children:[x(`div`,{children:[k(`h4`,{className:`text-xs font-semibold text-foreground`,children:`Buttons on the notification`}),k(`p`,{className:`text-[11px] text-foreground-subtle`,children:`Each button runs one of the sequences above when tapped.`})]}),x(u,{size:`sm`,variant:`ghost`,type:`button`,disabled:e.sequences.length===0,onClick:()=>t({...e,buttons:[...e.buttons,xt(e.buttons.length,e.sequences[0]?.name??``)]}),children:[k(Ce,{className:`h-3.5 w-3.5`}),` Button`]})]}),e.buttons.length>0&&x(`div`,{className:`flex items-start gap-2 rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-[11px] text-warning`,children:[k(Le,{className:`mt-0.5 h-3.5 w-3.5 shrink-0`}),x(`span`,{children:[`A button's link travels inside the notification — through ntfy, a push relay, anyone it is forwarded to. The link is the only authority: it does not check who taps it. Anyone holding the notification can run the button `,k(`strong`,{children:`once`}),`, within 15 minutes. Do not add one for something you would not want a forwarded screenshot to do.`]})]}),e.sequences.length===0?k(`p`,{className:`rounded border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:`Add a sequence first — a button runs one, it does not define its own steps.`}):e.buttons.length===0?k(`p`,{className:`rounded border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:`No buttons. The notification arrives with nothing to tap.`}):e.buttons.map((n,r)=>k(Ot,{button:n,sequenceNames:e.sequences.map(e=>e.name),onChange:e=>o(r,e),onRemove:()=>t({...e,buttons:e.buttons.filter((e,t)=>t!==r)})},`btn-${String(r)}`))]})]})}function Tt({sequence:e,devices:t,onChange:n,onRemove:r}){let i=(t,r)=>n({...e,actions:e.actions.map((e,n)=>n===t?r:e)});return x(`div`,{className:`space-y-2 rounded-md border border-border p-3`,children:[x(`div`,{className:`flex flex-wrap items-end gap-2`,children:[x(`div`,{className:`min-w-0 flex-1`,children:[k(`label`,{className:B,children:`Name`}),k(f,{className:`mt-1`,value:e.name,onChange:t=>n({...e,name:t.target.value})})]}),x(`div`,{className:`w-28`,children:[k(`label`,{className:B,children:`Min delay (s)`}),k(`input`,{type:`number`,min:0,className:Ct,value:e.minDelaySec??``,onChange:t=>{let r=t.target.value,i={...e};r===``?delete i.minDelaySec:i.minDelaySec=Number(r),n(i)}})]}),x(`div`,{className:`flex items-center gap-2 pb-1`,children:[k(p,{checked:e.enabled,onCheckedChange:t=>n({...e,enabled:t})}),k(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.enabled?`Runs on match`:`Only when a button is tapped`})]}),k(u,{size:`sm`,variant:`ghost`,type:`button`,onClick:r,title:`Remove`,children:k(R,{className:`h-3.5 w-3.5`})})]}),x(`div`,{className:`space-y-2 border-l-2 border-border-subtle pl-3`,children:[e.actions.map((r,a)=>k(Et,{step:r,devices:t,onChange:e=>i(a,e),onRemove:()=>n({...e,actions:e.actions.filter((e,t)=>t!==a)})},`step-${String(a)}`)),x(u,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>n({...e,actions:[...e.actions,St()]}),children:[k(Ce,{className:`h-3.5 w-3.5`}),` Step`]})]})]})}function Et({step:e,devices:t,onChange:n,onRemove:r}){return x(`div`,{className:`flex flex-wrap items-end gap-2`,children:[x(`div`,{className:`w-24`,children:[k(`label`,{className:B,children:`Step`}),x(`select`,{className:Ct,value:e.kind,onChange:e=>n(e.target.value===`wait`?{kind:`wait`,seconds:5}:{kind:`cap`,deviceId:t[0]?.id??0,cap:``,method:``}),children:[k(`option`,{value:`cap`,children:`Do`}),k(`option`,{value:`wait`,children:`Wait`})]})]}),e.kind===`wait`?x(`div`,{className:`w-28`,children:[k(`label`,{className:B,children:`Seconds`}),k(`input`,{type:`number`,min:0,max:300,className:Ct,value:e.seconds,onChange:e=>n({kind:`wait`,seconds:Number(e.target.value)})})]}):k(Dt,{step:e,devices:t,onChange:n}),k(u,{size:`sm`,variant:`ghost`,type:`button`,onClick:r,title:`Remove step`,children:k(R,{className:`h-3.5 w-3.5`})})]})}function Dt({step:e,devices:t,onChange:n}){let r=I(),i=C({queryKey:[`deviceManager`,`getBindings`,e.deviceId],enabled:e.deviceId>0,staleTime:6e4,queryFn:async()=>{let t=await r.trpcClient.deviceManager.getBindings.query({deviceId:e.deviceId});return[...new Set(t.entries.map(e=>e.capName))].sort((e,t)=>e.localeCompare(t))}}).data??[];return x(w,{children:[x(`div`,{className:`min-w-[9rem] flex-1`,children:[k(`label`,{className:B,children:`Device`}),x(`select`,{className:Ct,value:String(e.deviceId),onChange:t=>n({...e,deviceId:Number(t.target.value),cap:``}),children:[k(`option`,{value:`0`,children:`Select…`}),t.map(e=>k(`option`,{value:String(e.id),children:e.name},e.id))]})]}),x(`div`,{className:`min-w-[8rem] flex-1`,children:[k(`label`,{className:B,children:`Capability`}),x(`select`,{className:Ct,value:e.cap,disabled:i.length===0,onChange:t=>n({...e,cap:t.target.value,method:``}),children:[k(`option`,{value:``,children:i.length===0?`No devices bound`:`Select…`}),i.map(e=>k(`option`,{value:e,children:e},e))]})]}),x(`div`,{className:`min-w-[7rem] flex-1`,children:[k(`label`,{className:B,children:`Method`}),k(f,{className:`mt-1`,value:e.method,placeholder:`arm`,onChange:t=>n({...e,method:t.target.value})})]}),x(`div`,{className:`min-w-[8rem] flex-1`,children:[k(`label`,{className:B,children:`Arguments (JSON)`}),k(f,{className:`mt-1`,value:e.args===void 0?``:JSON.stringify(e.args),placeholder:`{"mode":"away"}`,onChange:t=>{let r=t.target.value.trim();if(r===``){let t={...e};delete t.args,n(t);return}try{let t=JSON.parse(r);typeof t==`object`&&t&&!Array.isArray(t)&&n({...e,args:t})}catch{}}})]})]})}function Ot({button:e,sequenceNames:t,onChange:n,onRemove:r}){return x(`div`,{className:`flex flex-wrap items-end gap-2 rounded-md border border-border p-3`,children:[x(`div`,{className:`min-w-[7rem] flex-1`,children:[k(`label`,{className:B,children:`Label`}),k(f,{className:`mt-1`,value:e.label,onChange:t=>n({...e,label:t.target.value})})]}),x(`div`,{className:`min-w-[8rem] flex-1`,children:[k(`label`,{className:B,children:`Runs`}),x(`select`,{className:Ct,value:e.sequence,onChange:t=>n({...e,sequence:t.target.value}),children:[!t.includes(e.sequence)&&x(`option`,{value:e.sequence,children:[e.sequence,` (missing)`]}),t.map(e=>k(`option`,{value:e,children:e},e))]})]}),x(`div`,{className:`w-32`,children:[k(`label`,{className:B,children:`Icon`}),x(`select`,{className:Ct,value:e.icon??``,onChange:t=>{let r={...e};if(t.target.value===``)delete r.icon;else{let e=ht.find(e=>e.value===t.target.value);e!==void 0&&(r.icon=e.value)}n(r)},children:[k(`option`,{value:``,children:`None`}),ht.map(e=>k(`option`,{value:e.value,children:e.label},e.value))]})]}),x(`div`,{className:`flex items-center gap-2 pb-1`,children:[k(p,{checked:e.destructive===!0,onCheckedChange:t=>{let r={...e};t?r.destructive=!0:delete r.destructive,n(r)}}),k(s,{variant:e.destructive===!0?`danger`:`default`,children:`Destructive style`})]}),k(u,{size:`sm`,variant:`ghost`,type:`button`,onClick:r,title:`Remove`,children:k(R,{className:`h-3.5 w-3.5`})})]})}function V(e){return t=>Object.prototype.hasOwnProperty.call(e,t)}var kt=V({devices:!0}),At=V({classes:!0,classesExclude:!0,labelEquals:!0,identities:!0,identitiesExclude:!0,eventTypeTokens:!0,sensorKinds:!0}),jt=V({zonesExclude:!0}),Mt=V({minConfidence:!0,minImportance:!0,minLabelConfidence:!0}),Nt=V({minDwellSeconds:!0}),Pt=V({source:!0}),Ft=V({crossing:!0}),It=V({packagePhase:!0}),Lt=V({zones:!0}),Rt=V({plates:!0}),zt=V({occupancy:!0}),Bt={op:`became-occupied`,count:1,sustainSeconds:15},Vt=V({audio:!0}),Ht=V({systemEvent:!0}),Ut=V({deviceState:!0});function Wt(e,t){let n=e[t];return Array.isArray(n)?n:[]}function Gt(e,t){let n=e[t];return typeof n==`number`?n:void 0}var Kt=[{id:`system`,label:`System events`},{id:`scope`,label:`Scope`},{id:`class`,label:`Classes`},{id:`zones`,label:`Zones`},{id:`quality`,label:`Quality`},{id:`label`,label:`Identity & plates`},{id:`device`,label:`Device event`},{id:`package`,label:`Package`},{id:`occupancy`,label:`Occupancy`},{id:`audio`,label:`Sound`},{id:`schedule`,label:`Schedule`}];function qt(e){let t=e.replace(/[-_]/g,` `);return t.charAt(0).toUpperCase()+t.slice(1)}function Jt(e,t){let n=e.filter(t),r=new Set(Kt.map(e=>e.id)),i=[];for(let e of Kt){let t=n.filter(t=>t.group===e.id);t.length>0&&i.push({id:e.id,label:e.label,descriptors:t})}let a=[];for(let e of n)r.has(e.group)||a.includes(e.group)||a.push(e.group);for(let e of a)i.push({id:e,label:qt(e),descriptors:n.filter(t=>t.group===e)});return i}b();function Yt(e,t){let n=I().trpcClient,r=T({queries:e.map(e=>({queryKey:[[`nc-pickers`,`zones`],{deviceId:e}],staleTime:3e4,queryFn:async()=>({deviceId:e,zones:(await n.zones.listZones.query({deviceId:e})).map(e=>({id:e.id,name:e.name}))})}))});return S(()=>{let e=[],n=new Set;for(let i of r){if(!i.data)continue;let r=t.find(e=>e.id===i.data.deviceId)?.name;for(let t of i.data.zones)n.has(t.id)||(n.add(t.id),e.push({value:t.id,label:t.name,...r===void 0?{}:{hint:r}}))}return{options:e,loading:r.some(e=>e.isLoading)}},[r,t])}function Xt(e){let t=I().trpcClient,n=T({queries:e.map(e=>({queryKey:[[`nc-pickers`,`event-kinds`],{deviceId:e}],staleTime:6e4,queryFn:async()=>(await t.pipelineAnalytics.listEventKinds.query({deviceId:e})).map(e=>({kind:e.kind,label:e.label}))}))});return S(()=>{let e=new Map;for(let t of n)for(let n of t.data??[])e.has(n.kind)||e.set(n.kind,n.label);let t=[...e.entries()].map(([e,t])=>({value:e,label:t}));return t.sort((e,t)=>e.label.localeCompare(t.label)),{options:t,loading:n.some(e=>e.isLoading)}},[n])}function Zt(){let e=c();return S(()=>({options:(e.data??[]).map(e=>({value:e.name,label:e.name})),loading:e.isLoading}),[e.data,e.isLoading])}function Qt(){let e=h({limit:200});return S(()=>{let t=new Set;for(let n of e.data??[])n.text.trim().length>0&&t.add(n.text);return[...t].sort()},[e.data])}function H({options:e,value:t,onChange:n,loading:r,emptyHint:i,placeholder:a,noFreeText:o=!1}){let[s,c]=D(``),l=S(()=>new Set(e.map(e=>e.value)),[e]),u=S(()=>new Set(t),[t]),d=t.filter(e=>!l.has(e)),f=e=>{n(u.has(e)?t.filter(t=>t!==e):[...t,e])},p=()=>{let e=s.trim();e.length===0||t.includes(e)||(n([...t,e]),c(``))};return x(`div`,{className:`mt-1 space-y-1.5`,children:[d.length>0&&k(`div`,{className:`flex flex-wrap gap-1`,children:d.map(e=>x(`button`,{type:`button`,onClick:()=>n(t.filter(t=>t!==e)),className:`inline-flex items-center gap-1 rounded border border-border px-1.5 py-0.5 text-[10px] text-foreground hover:bg-surface-hover`,title:`Custom value — click to remove`,children:[e,` ×`]},e))}),e.length>0?k(`div`,{className:`max-h-40 overflow-y-auto rounded-md border border-border divide-y divide-border`,children:e.map(e=>x(`label`,{className:`flex items-center gap-2.5 px-3 py-1.5 text-xs text-foreground cursor-pointer hover:bg-surface-hover`,children:[k(`input`,{type:`checkbox`,checked:u.has(e.value),onChange:()=>f(e.value),className:`accent-primary`}),k(`span`,{className:`flex-1 truncate`,children:e.label}),e.hint!==void 0&&k(`span`,{className:`text-[10px] text-foreground-subtle`,children:e.hint})]},e.value))}):k(`p`,{className:`text-[10px] text-foreground-subtle`,children:r===!0?`Loading…`:i}),!o&&k(`input`,{value:s,onChange:e=>c(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),p())},placeholder:a,className:`w-full rounded-md border border-border bg-background px-2 py-1 text-xs text-foreground placeholder:text-foreground-subtle`})]})}var $t=[{value:`immediate`,label:`Immediate`,hint:`Fires on the first matching detection of a track (lowest latency).`},{value:`track-end`,label:`Track end`,hint:`Evaluates the finalised track record when it closes.`},{value:`device-event`,label:`Device event`,hint:`Doorbell press, sensor state change, or an occupancy edge on a linked device.`},{value:`package-event`,label:`Package event`,hint:`A parcel delivery or pick-up.`},{value:`system-event`,label:`System event`,hint:`The installation itself: a camera or stream going offline, a node leaving the cluster, an addon or server update becoming available.`}];function en(e){return $t.find(t=>t.value===e)?.label??e}function tn(e){return $t.find(t=>t.value===e)?.value}function nn(e){return $t.some(t=>t.value===e)}function rn(e){return e===`system-event`}var an=[{key:`all`,label:`All rules`,blurb:`Every notification rule, whatever its trigger. Each rule picks a trigger, matches conditions and fans out to one or more delivery targets.`,newRuleLabel:`New rule`,emptyHint:`No notification rules yet. Click "New rule" to author one.`},{key:`detection`,label:`Detections & devices`,blurb:`Rules driven by what the cameras and sensors SEE — detections, tracks, doorbell presses and package events.`,newRuleLabel:`New detection rule`,emptyHint:`No detection rules yet. Click "New detection rule" to author one.`},{key:`audio`,label:`Sound`,blurb:`Rules on what the cameras HEAR: a sustained window of sound loud enough, or classified as one of the sounds you name. A sound rule is an immediate rule carrying the sound condition — it fires only on a confirmed sampling window, never on a picture.`,newRuleLabel:`New sound rule`,emptyHint:`No sound rules yet. Click "New sound rule" — it opens on the sound condition already filled in with a level threshold, so you only have to name the sounds and the targets.`},{key:`occupancy`,label:`Occupancy`,blurb:`Rules on how many objects are in a camera frame or a zone, and for how long: "the driveway became occupied", "the garden emptied". An occupancy rule is a device-event rule carrying the occupancy condition.`,newRuleLabel:`New occupancy rule`,emptyHint:`No occupancy rules yet. Click "New occupancy rule" — it opens on the occupancy condition; pick the camera on the Devices tab, then the zone and the count.`},{key:`system`,label:`System events`,blurb:`Rules about the installation itself: a camera or stream dropping, a node leaving the cluster, an addon or server update becoming available. These carry no image and are not tied to a detection.`,newRuleLabel:`New system rule`,emptyHint:`No system-event rules yet. Click "New system rule" to be told when a camera drops, a node leaves or an update lands.`}];function on(e){return an.find(t=>t.key===e)?.key}function sn(e){return e.conditions.audio!==void 0}function cn(e){return e.conditions.occupancy!==void 0}function ln(e,t){return t===`all`?!0:t===`system`?rn(e.delivery):t===`audio`?sn(e):t===`occupancy`?cn(e):!rn(e.delivery)&&!sn(e)&&!cn(e)}var un={hitPercent:fe.hitPercent,samplingSeconds:fe.samplingSeconds,dbThreshold:-30};function dn(e){switch(e){case`system`:return{delivery:`system-event`,conditions:{}};case`audio`:return{delivery:`immediate`,conditions:{audio:un}};case`occupancy`:return{delivery:`device-event`,conditions:{occupancy:Bt}};default:return{delivery:`immediate`,conditions:{}}}}var fn=[{value:0,label:`No cooldown`},{value:30,label:`30 seconds`},{value:60,label:`1 minute`},{value:300,label:`5 minutes`},{value:600,label:`10 minutes`},{value:1800,label:`30 minutes`},{value:3600,label:`1 hour`}];function pn(e){let t=fn.find(t=>t.value===e);return t?t.label:e%3600==0?`${e/3600} hours`:e%60==0?`${e/60} minutes`:`${e} seconds`}function mn(e){return fn.some(t=>t.value===e)?fn:[...fn,{value:e,label:pn(e)}].toSorted((e,t)=>e.value-t.value)}function hn(e){if(e.trim().length===0)return;let t=Number(e);return Number.isFinite(t)&&t>=0?t:void 0}var gn=[{value:`best`,label:`Best available image`,description:`The best subject crop available when the notification is sent.`},{value:`best-matching`,label:`Best matching image`,description:`The image that explains why the rule fired — the face crop for an identity rule, the plate crop for a plate rule; falls back to the best image otherwise.`},{value:`keyFrame`,label:`Key frame`,description:`The clean full scene frame with no subject box.`},{value:`none`,label:`No attachment`,description:`Send the notification with no image.`}];function _n(e){return gn.find(t=>t.value===e)?.value}var vn=[{value:``,label:`Automatic`},{value:`cropped`,label:`Cropped on the subject`},{value:`full`,label:`Full frame`},{value:`boxed`,label:`Full frame with boxes`}];function yn(e){let t=vn.find(t=>t.value===e)?.value;return t===``?void 0:t}var bn=[{value:``,label:`Lowest available`},{value:`low`,label:`Low`},{value:`mid`,label:`Medium`},{value:`high`,label:`High`}];function xn(e){let t=bn.find(t=>t.value===e)?.value;return t===``?void 0:t}var Sn=[{value:`any`,label:`Any source`},{value:`pipeline`,label:`Pipeline`},{value:`onboard`,label:`Onboard (camera)`},{value:`sensor`,label:`Sensor`}],Cn=[{value:`delivered`,label:`Delivered`},{value:`picked-up`,label:`Picked up`},{value:`both`,label:`Both`}],wn=[{value:``,label:`Not set — entering`,hint:`Entries, and every detection that is not a crossing at all. Exits are excluded. This is what a rule without a crossing condition already does, and choosing it writes nothing to the rule.`},{value:`enter`,label:`Entered a zone`,hint:`The same matches as "not set", stated explicitly: entries and non-crossing detections pass, exits do not.`},{value:`exit`,label:`Left a zone`,hint:`ONLY an exit crossing. A detection that is not a crossing fails, so this rule cannot fire on ordinary movement — pair it with the zones the subject must have left.`},{value:`any`,label:`Entered or left`,hint:`No direction filter: entries, exits and non-crossing detections alike. This is the only choice that adds exits to what the rule already matched.`}];function Tn(e){let t=wn.find(t=>t.value===e)?.value;return t===``||t===void 0?void 0:t}var En=[{value:`any`,label:`Any of`},{value:`all`,label:`All of`}],Dn=[{value:1,label:`1 — Min`},{value:2,label:`2 — Low`},{value:3,label:`3 — Default`},{value:4,label:`4 — High`},{value:5,label:`5 — Max`}],On=[10,30,60],kn=[5,10,15,30,60,120,240,480];function An(e){return e>=60&&e%60==0?`${e/60} h`:`${e} min`}var jn=new Set([`alarm-arming`,`alarm-triggered`,`alarm-armed`,`alarm-disarmed`]),Mn=`alarm-panel`;function Nn(e,t){for(let t of e.systemEvent?.kinds??[])if(jn.has(t))return!0;for(let e of t)for(let t of e.actions)if(t.kind===`cap`&&t.cap===Mn)return!0;return!1}function Pn(e=`immediate`,t={}){return{name:``,enabled:!0,delivery:e,targetIds:[],targetUsers:[],targetParams:{},priority:3,mediaAttach:`best`,mediaZoneCrop:!1,mediaFrame:void 0,mediaGif:!1,mediaClip:!1,mediaProfile:void 0,mediaClipSpeed:void 0,templateTitle:``,templateBody:``,conditions:t,schedule:void 0,snoozeAllowGlobal:!1,snoozeOptions:void 0,actions:gt,deviceIds:[],cooldownSec:60}}function Fn(e){let t={};for(let n of e.targets)n.params&&Object.keys(n.params).length>0&&(t[n.targetId]=n.params);return{name:e.name,enabled:e.enabled,delivery:e.delivery,targetIds:e.targets.map(e=>e.targetId),targetUsers:e.targetUsers??[],targetParams:t,priority:e.priority,mediaAttach:e.media.attach,mediaZoneCrop:e.media.zoneCrop===!0,mediaFrame:e.media.frame,mediaGif:e.media.gif===!0,mediaClip:e.media.clip===!0,mediaProfile:e.media.profile,mediaClipSpeed:e.media.clipSpeed,templateTitle:e.template?.title??``,templateBody:e.template?.body??``,conditions:e.conditions,schedule:e.schedule,snoozeAllowGlobal:e.snoozeAllowGlobal===!0,snoozeOptions:e.snoozeOptions,actions:_t(e.actions),deviceIds:e.conditions.devices??[],cooldownSec:e.throttle.cooldownSec}}function In(e){let t=[];return re(e.conditions.audio)&&t.push(`This sound rule names neither a sound nor a level threshold, so it can never fire — every sample would count as a hit and the engine refuses it rather than notifying on silence. Pick at least one sound, or add a level.`),t}function Ln(e){return In(e).length===0&&nn(e.delivery)&&(!rn(e.delivery)||Rn(e)>0)&&e.name.trim().length>0&&(e.targetIds.length>0||e.targetUsers.length>0)&&yt(e.actions).length===0}function Rn(e){return e.conditions.systemEvent?.kinds.length??0}function zn(e,t){return e.appliesTo.includes(t)}var Bn={source:`any`};function Vn(e,t){if(t==null)return!0;if(Array.isArray(t))return t.length===0;if(typeof t==`string`)return t.length===0||Bn[e]===t;if(typeof t==`number`)return!Number.isFinite(t);if(typeof t==`object`){if(`ids`in t){let e=t.ids;return!Array.isArray(e)||e.length===0}if(`values`in t){let e=t.values;return!Array.isArray(e)||e.length===0}return!1}return!1}var Hn=j.filter(e=>e.id===`audio`);function Un(e){if(e.length===0)return e;let t=new Set(e.map(e=>e.id)),n=Hn.filter(e=>!t.has(e.id));return n.length===0?e:[...e,...n]}function Wn(e,t,n){let r=n.length===0?null:new Set(n.filter(e=>e.id!==`schedule`&&zn(e,t)).map(e=>e.id)),i={};for(let[t,n]of Object.entries(e))r!==null&&!r.has(t)||Vn(t,n)||(i[t]=n);return i}function Gn(e){return e!==void 0&&e.windows.length>0}function Kn(e,t,n=[]){let r=e.templateTitle.trim(),i=e.templateBody.trim(),a=r.length>0||i.length>0?{...r.length>0?{title:r}:{},...i.length>0?{body:i}:{}}:void 0,o=vt(e.actions),s=(n.length===0||n.some(t=>t.id===`schedule`&&zn(t,e.delivery)))&&Gn(e.schedule)?e.schedule:void 0,c=n.length===0?!0:n.some(t=>t.id===`devices`&&zn(t,e.delivery));return{name:e.name.trim(),enabled:e.enabled,delivery:e.delivery,conditions:{...Wn(e.conditions,e.delivery,n),...c&&e.deviceIds.length>0?{devices:[...e.deviceIds]}:{}},...s?{schedule:s}:{},targets:e.targetIds.map(t=>{let n=e.targetParams[t];return n&&Object.keys(n).length>0?{targetId:t,params:n}:{targetId:t}}),...e.targetUsers.length>0?{targetUsers:[...e.targetUsers]}:{},media:rn(e.delivery)?{attach:`none`}:{attach:e.mediaAttach,...e.mediaZoneCrop?{zoneCrop:!0}:{},...e.mediaFrame===void 0?{}:{frame:e.mediaFrame},...e.mediaGif?{gif:!0}:{},...e.mediaClip?{clip:!0}:{},...e.mediaProfile===void 0?{}:{profile:e.mediaProfile},...e.mediaClipSpeed===void 0?{}:{clipSpeed:e.mediaClipSpeed}},throttle:{cooldownSec:e.cooldownSec,scope:t?.throttle.scope??`rule-device`,...t?.throttle.granularity===void 0?{}:{granularity:t.throttle.granularity}},priority:e.priority,...a?{template:a}:{},...e.snoozeAllowGlobal?{snoozeAllowGlobal:!0}:{},...e.snoozeOptions===void 0?{}:{snoozeOptions:[...e.snoozeOptions]},...o===void 0?{}:{actions:o}}}function qn(e,t){return e.options&&e.options.length>0?e.options:t}var Jn=[{value:``,label:`Default (2×)`},{value:`1`,label:`1× — real time`},{value:`2`,label:`2×`},{value:`3`,label:`3×`},{value:`4`,label:`4×`},{value:`6`,label:`6×`},{value:`8`,label:`8×`}];function Yn(e){if(e===``)return;let t=Number(e);return Number.isFinite(t)&&t>=1&&t<=8?t:void 0}var Xn=[{key:`rule`,label:`Rule`,fields:[`name`,`enabled`,`delivery`,`targetIds`,`targetUsers`,`targetParams`]},{key:`devices`,label:`Devices`,fields:[`deviceIds`]},{key:`conditions`,label:`Conditions`,fields:[`conditions`,`schedule`]},{key:`notification`,label:`Notification`,fields:[`priority`,`mediaAttach`,`mediaFrame`,`mediaZoneCrop`,`mediaGif`,`mediaClip`,`mediaProfile`,`mediaClipSpeed`,`templateTitle`,`templateBody`]},{key:`actions`,label:`Actions`,fields:[`actions`]},{key:`advanced`,label:`Advanced`,fields:[`snoozeAllowGlobal`,`snoozeOptions`,`cooldownSec`]}];function Zn(e,t={}){if(rn(e))return Xn.filter(e=>e.key!==`devices`).map(e=>e.key===`conditions`?{...e,label:`Events`}:e);let n=Qn(t);return n===void 0?Xn:Xn.map(e=>e.key===`conditions`?{...e,label:n}:e)}function Qn(e){if(e.audio!==void 0)return`Sound`;if(e.occupancy!==void 0)return`Occupancy`}var $n=`rule`;function er(e){return Xn.find(t=>t.key===e)?.key}b();var U=`block text-[11px] font-medium text-foreground`,W=`text-[10px] text-foreground-subtle mt-0.5`;function tr({cameras:e,value:t,onChange:n}){if(e.length===0)return k(`p`,{className:W,children:`No cameras available — the rule applies to all devices.`});let r=e=>n(t.includes(e)?t.filter(t=>t!==e):[...t,e]);return k(`div`,{className:`mt-1 max-h-40 overflow-y-auto rounded-md border border-border divide-y divide-border`,children:e.map(e=>x(`label`,{className:`flex items-center gap-2.5 px-3 py-1.5 text-xs text-foreground cursor-pointer hover:bg-surface-hover`,children:[k(`input`,{type:`checkbox`,checked:t.includes(e.id),onChange:()=>r(e.id),className:`accent-primary`}),k(`span`,{className:`flex-1 truncate`,children:e.name})]},e.id))})}function nr({value:e,placeholder:t,onChange:n}){let[r,i]=D(``),a=()=>{let t=r.trim();if(t.length===0||e.includes(t)){i(``);return}n([...e,t]),i(``)},o=t=>n(e.filter(e=>e!==t));return x(`div`,{className:`mt-1 space-y-1.5`,children:[e.length>0&&k(`div`,{className:`flex flex-wrap gap-1`,children:e.map(e=>x(`span`,{className:`inline-flex items-center gap-1 rounded bg-surface-hover px-1.5 py-0.5 text-[11px] text-foreground`,children:[e,k(`button`,{type:`button`,onClick:()=>o(e),"aria-label":`remove ${e}`,className:`text-foreground-subtle hover:text-danger`,children:k(Ie,{className:`h-3 w-3`})})]},e))}),k(f,{value:r,placeholder:t,onChange:e=>i(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),a())},onBlur:a})]})}function rr({picker:e,value:t,onChange:n}){let r=S(()=>ae(e),[e]),i=S(()=>new Set(t),[t]),a=t.filter(e=>!r.has(e)),o=e=>{n(i.has(e)?t.filter(t=>t!==e):[...t,e])};return x(`div`,{className:`space-y-2`,children:[a.length>0&&k(`div`,{className:`flex flex-wrap gap-1`,children:a.map(e=>x(`button`,{type:`button`,onClick:()=>n(t.filter(t=>t!==e)),className:`inline-flex items-center gap-1 rounded border border-border px-1.5 py-0.5 text-[10px] text-foreground hover:bg-surface-hover`,title:`Custom value — click to remove`,children:[e,` ×`]},e))}),e.groups.map(e=>x(`div`,{children:[k(`div`,{className:`text-[10px] uppercase tracking-wide text-foreground-muted mb-1`,children:e.fallbackLabel}),k(`div`,{className:`flex flex-wrap gap-1`,children:e.options.map(e=>{let t=i.has(e.value);return k(`button`,{type:`button`,"aria-pressed":t,onClick:()=>o(e.value),className:t?`rounded border border-primary bg-primary/15 px-1.5 py-0.5 text-[10px] text-foreground`:`rounded border border-border px-1.5 py-0.5 text-[10px] text-foreground hover:bg-surface-hover`,children:e.label},e.value)})})]},e.key))]})}function ir({value:e,min:t,max:n,step:r,onChange:i}){return x(`div`,{className:`mt-1 flex items-center gap-2`,children:[k(f,{type:`number`,value:e??``,min:t,max:n,step:r,className:`max-w-[8rem]`,onChange:e=>{let t=e.target.value;if(t===``){i(void 0);return}let n=Number(t);i(Number.isFinite(n)?n:void 0)}}),e!==void 0&&n!==void 0&&k(`input`,{type:`range`,min:t,max:n,step:r,value:e,onChange:e=>i(Number(e.target.value)),className:`flex-1 accent-primary`,"aria-label":`value`})]})}function ar({value:e,onChange:t,options:n}){let r=e??``,i=n&&n.length>0?n:wn,a=i.find(e=>e.value===r);return x(`div`,{className:`mt-1 space-y-1`,children:[k(o,{value:r,options:i.map(e=>({value:e.value,label:e.label})),onChange:e=>t(Tn(e.target.value))}),a!==void 0&&k(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:a.hint})]})}function or({deviceIds:e,cameras:t,value:n,onChange:r}){let i=n?.ids??[],a=n?.match??`any`,s=e=>r(e.length>0?{ids:e,match:a}:void 0),c=e=>r(i.length>0?{ids:i,match:e}:void 0);return x(`div`,{className:`mt-1 space-y-1.5`,children:[k(`div`,{className:`max-w-[10rem]`,children:k(o,{value:a,options:En.map(e=>({value:e.value,label:e.label})),onChange:e=>c(e.target.value===`all`?`all`:`any`)})}),k(sr,{deviceIds:e,cameras:t,value:i,onChange:s})]})}function sr({deviceIds:e,cameras:t,value:n,onChange:r}){let{options:i,loading:a}=Yt(e,t);return k(H,{options:i,value:n,onChange:r,loading:a,noFreeText:!0,emptyHint:e.length===0?`Select cameras first — a rule can only use zones those cameras actually have.`:`The selected cameras have no zones. Draw one in the camera’s zone editor first.`,placeholder:``})}function cr({value:e,onChange:t}){let{options:n,loading:r}=Zt();return k(H,{options:n,value:e,onChange:t,loading:r,emptyHint:`No identities in the face gallery yet — type a name.`,placeholder:`Identity name…`})}function lr({deviceIds:e,value:t,onChange:n}){let{options:r,loading:i}=Xt(e);return k(H,{options:r,value:t,onChange:n,loading:i,emptyHint:e.length===0?`Select cameras above to pick their event kinds — or type a token.`:`No event kinds reported for the selected cameras — type a token.`,placeholder:`Event token…`})}var ur=[{value:`became-occupied`,label:`Became occupied`},{value:`became-free`,label:`Became free`},{value:`>=`,label:`Count ≥`},{value:`<=`,label:`Count ≤`}];function dr(e,t){let n=e.map(e=>({value:e.value,label:e.label}));return t===void 0||t===``||n.some(e=>e.value===t)?n:[...n,{value:t,label:`${t} — sub-type, never counts (always 0)`}]}function fr({deviceIds:e,cameras:t,classOptions:n,value:r,onChange:i}){let{options:a,loading:s}=Yt(e,t),c=r??Bt,l=e=>i({...c,...e}),u=c.op===`became-occupied`||c.op===`became-free`,d=dr(n,c.className);return x(`div`,{className:`mt-1 space-y-1.5`,children:[x(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[k(`div`,{className:`min-w-[10rem]`,children:k(o,{value:c.zoneId??``,options:[{value:``,label:s?`Loading zones…`:`— whole frame —`},...a.map(e=>({value:e.value,label:e.label}))],onChange:e=>l({zoneId:e.target.value===``?void 0:e.target.value})})}),k(`div`,{className:`min-w-[9rem]`,children:k(o,{value:c.className??``,options:[{value:``,label:`— any class —`},...d],onChange:e=>l({className:e.target.value===``?void 0:e.target.value})})}),k(`div`,{className:`min-w-[9rem]`,children:k(o,{value:c.op,options:ur.map(e=>({value:e.value,label:e.label})),onChange:e=>{let t=ur.find(t=>t.value===e.target.value);t&&l({op:t.value})}})})]}),x(`div`,{className:`flex flex-wrap items-center gap-3 text-xs text-foreground-subtle`,children:[x(`label`,{className:`flex items-center gap-1`,children:[u?`Threshold`:`Count`,k(f,{type:`number`,min:0,className:`w-16`,value:String(c.count),onChange:e=>l({count:Math.max(0,Number(e.target.value)||0)})})]}),x(`label`,{className:`flex items-center gap-1`,children:[`Hold for`,k(f,{type:`number`,min:0,max:3600,className:`w-16`,value:String(c.sustainSeconds),onChange:e=>l({sustainSeconds:Math.min(3600,Math.max(0,Number(e.target.value)||0))})}),`s`]}),r===void 0?null:k(`button`,{type:`button`,onClick:()=>i(void 0),className:`underline hover:text-foreground`,children:`Clear`})]}),e.length===0&&k(`p`,{className:`text-[11px] text-warning`,children:`No camera picked on the Devices tab: this watches EVERY camera's occupancy, and no zone can be offered until you choose one — a zone id belongs to a camera.`}),k(`p`,{className:`text-[11px] text-foreground-subtle`,children:`Counts confirmed tracked objects from zone analytics. The change must hold for the sustain window before it fires; with no snapshot for the camera or zone the rule never fires.`})]})}function pr({taxonomy:e,value:t,onChange:n}){let r=P(t),i=e=>n(ue(t,e)),{choices:a,unknownLabels:o}=de(e,r.labels);return x(`div`,{className:`mt-1 space-y-2`,children:[k(`div`,{className:`flex flex-wrap gap-1`,children:a.map(e=>{let t=M(r.labels,e.value),n=e.unknown?`border-dashed border-warning text-warning`:t?`border-primary bg-primary/15 text-foreground`:`border-border text-foreground hover:bg-surface-hover`;return x(`button`,{type:`button`,"aria-pressed":t,title:e.unknown?`Stored by the rule — not offered by this hub`:void 0,onClick:()=>i({labels:te(r.labels,e.value)}),className:`rounded border px-1.5 py-0.5 text-[10px] ${n}`,children:[k(`span`,{"aria-hidden":`true`,children:e.icon}),` `,e.label]},e.value)})}),o.length>0&&x(`p`,{className:`text-[10px] text-warning`,children:[`Kept from the rule, unknown to this hub: `,o.join(`, `)]}),k(`div`,{className:`flex flex-wrap items-center gap-3 text-xs text-foreground-subtle`,children:r.dbThreshold===void 0?x(`button`,{type:`button`,onClick:()=>i({dbThreshold:-30}),className:`rounded border border-border px-2 py-0.5 text-[11px] text-foreground hover:bg-surface-hover`,children:[`Add a level threshold (`,-30,` dBFS)`]}):x(`label`,{className:`flex items-center gap-1`,children:[`Louder than`,k(f,{type:`number`,min:le,max:0,step:3,className:`w-20`,value:String(r.dbThreshold),onChange:e=>i({dbThreshold:Number(e.target.value)})}),`dBFS`,k(`button`,{type:`button`,onClick:()=>i({dbThreshold:void 0}),className:`underline hover:text-foreground`,children:`any level`})]})}),x(`div`,{className:`flex flex-wrap items-center gap-3 text-xs text-foreground-subtle`,children:[x(`label`,{className:`flex items-center gap-1`,children:[`Hits`,k(f,{type:`number`,min:1,max:100,step:5,className:`w-16`,value:String(r.hitPercent),onChange:e=>i({hitPercent:Number(e.target.value)})}),`% (default `,fe.hitPercent,`)`]}),x(`label`,{className:`flex items-center gap-1`,children:[`over`,k(f,{type:`number`,min:1,max:300,step:5,className:`w-16`,value:String(r.samplingSeconds),onChange:e=>i({samplingSeconds:Number(e.target.value)})}),`s (default `,fe.samplingSeconds,`)`]}),t===void 0?null:k(`button`,{type:`button`,onClick:()=>n(void 0),className:`underline hover:text-foreground`,children:`Clear`})]}),re(t)?k(`p`,{className:`text-[11px] text-warning`,children:`With neither a sound nor a level threshold this can never match — every sample would be a hit, so the engine refuses it rather than notifying on silence.`}):null,x(`p`,{className:`text-[11px] text-foreground-subtle`,children:[`dBFS is negative-going: 0 is full scale, `,le,` is silence — so `,`−`,`30 is loud and `,`−`,`60 is faint. The window must be FULL before it can match.`]})]})}function mr({value:e,onChange:t}){let n=e?.values??[],r=e?.maxDistance??1,i=e=>t(e.length>0?{values:e,maxDistance:r}:void 0),a=e=>t(n.length>0?{values:n,maxDistance:e}:void 0),o=Qt().filter(e=>!n.includes(e));return x(`div`,{className:`mt-1 space-y-1.5`,children:[k(nr,{value:n,placeholder:`Plate text…`,onChange:i}),o.length>0&&x(`div`,{className:`flex flex-wrap items-center gap-1`,children:[k(`span`,{className:`text-[10px] text-foreground-subtle`,children:`Seen:`}),o.slice(0,12).map(e=>k(`button`,{type:`button`,onClick:()=>i([...n,e]),className:`rounded border border-border px-1.5 py-0.5 text-[10px] text-foreground-subtle hover:bg-surface-hover hover:text-foreground`,children:e},e))]}),x(`label`,{className:`flex items-center gap-2 text-[11px] text-foreground-subtle`,children:[`Max distance`,k(f,{type:`number`,min:0,max:3,step:1,value:r,className:`max-w-[5rem]`,onChange:e=>{let t=Number(e.target.value);a(Number.isFinite(t)?Math.max(0,Math.min(3,t)):1)}})]})]})}function hr({gateable:e,value:t,onChange:n}){let r=e.find(e=>e.id===t?.deviceId),i=new Set(t?.states??[]),a=e=>{let t=Number(e);if(!Number.isFinite(t)||t===0)return n(void 0);n({deviceId:t,states:[]})},s=e=>{if(t===void 0)return;let r=new Set(i);r.has(e)?r.delete(e):r.add(e),n(r.size===0?void 0:{deviceId:t.deviceId,states:[...r]})};return x(`div`,{className:`mt-1 space-y-2`,children:[k(o,{value:t===void 0?``:String(t.deviceId),options:[{value:``,label:`— no device gate —`},...e.map(e=>({value:String(e.id),label:e.name}))],onChange:e=>a(e.target.value)}),r!==void 0&&k(`div`,{className:`flex flex-wrap gap-1.5`,children:r.states.map(e=>k(`button`,{type:`button`,onClick:()=>s(e),className:i.has(e)?`rounded-md border border-primary bg-primary/10 px-2 py-0.5 text-[11px] text-primary`:`rounded-md border border-border px-2 py-0.5 text-[11px] text-foreground-subtle`,children:e},e))}),r!==void 0&&r.states.length===0&&k(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:`This device reports no state the gate can read, so it cannot arm a rule.`}),t!==void 0&&k(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:`The rule is silent while the device is in any other state — including when its state cannot be read at all.`})]})}var gr=[{value:1,label:`Mon`},{value:2,label:`Tue`},{value:3,label:`Wed`},{value:4,label:`Thu`},{value:5,label:`Fri`},{value:6,label:`Sat`},{value:0,label:`Sun`}];function _r(e){let t=Math.floor(e/60),n=e%60;return`${String(t).padStart(2,`0`)}:${String(n).padStart(2,`0`)}`}function vr(e){let[t,n]=e.split(`:`),r=Number(t)*60+Number(n);return Number.isFinite(r)?Math.max(0,Math.min(1439,r)):0}function yr(){return{days:[1,2,3,4,5],startMinute:540,endMinute:1080}}function br({value:e,onChange:t}){let n=e?.windows??[],r=e?.invert??!1,i=(n,r)=>{if(n.length===0){t(void 0);return}t({windows:n,...r?{invert:!0}:{},...e?.timezone?{timezone:e.timezone}:{}})},a=()=>i([...n,yr()],r),o=e=>i(n.filter((t,n)=>n!==e),r),s=(e,t)=>i(n.map((n,r)=>r===e?t:n),r);return x(`div`,{className:`mt-1 space-y-2`,children:[n.length===0?k(`p`,{className:W,children:`Always active — add a window to restrict when the rule fires.`}):n.map((e,t)=>k(xr,{window:e,onChange:e=>s(t,e),onRemove:()=>o(t)},t)),x(`div`,{className:`flex items-center gap-3`,children:[x(`button`,{type:`button`,onClick:a,className:`flex items-center gap-1 rounded-md bg-surface-hover px-2 py-1 text-[11px] text-foreground-subtle hover:text-foreground`,children:[k(Ce,{className:`h-3 w-3`}),` Add window`]}),n.length>0&&x(`label`,{className:`flex items-center gap-1.5 text-[11px] text-foreground-subtle`,children:[k(`input`,{type:`checkbox`,checked:r,onChange:e=>i([...n],e.target.checked),className:`accent-primary`}),`Active outside the windows`]})]})]})}function xr({window:e,onChange:t,onRemove:n}){let r=n=>{let r=e.days.includes(n)?e.days.filter(e=>e!==n):[...e.days,n];r.length!==0&&t({...e,days:r})};return x(`div`,{className:`space-y-1.5 rounded-md border border-border p-2`,children:[x(`div`,{className:`flex items-center gap-2 text-xs`,children:[k(`input`,{type:`time`,value:_r(e.startMinute),onChange:n=>t({...e,startMinute:vr(n.target.value)}),className:`rounded-md border border-border bg-background px-1 py-0.5`}),k(`span`,{className:`text-foreground-subtle`,children:`→`}),k(`input`,{type:`time`,value:_r(e.endMinute),onChange:n=>t({...e,endMinute:vr(n.target.value)}),className:`rounded-md border border-border bg-background px-1 py-0.5`}),k(`span`,{className:`flex-1`}),k(`button`,{type:`button`,onClick:n,"aria-label":`Remove window`,className:`text-foreground-subtle hover:text-danger`,children:k(R,{className:`h-3.5 w-3.5`})})]}),k(`div`,{className:`flex flex-wrap gap-1`,children:gr.map(t=>k(`button`,{type:`button`,onClick:()=>r(t.value),className:`rounded px-1.5 py-0.5 text-[10px] ${e.days.includes(t.value)?`bg-primary text-primary-foreground`:`bg-surface-hover text-foreground-subtle`}`,children:t.label},t.value))})]})}var Sr=[{id:`liveness`,label:`Devices & streams`,hint:`A device the hub can no longer reach, or a stream that stopped or came back.`,kinds:[{value:`device-offline`,label:`Device offline`},{value:`device-online`,label:`Device online`},{value:`stream-offline`,label:`Stream offline`},{value:`stream-online`,label:`Stream online`}]},{id:`switches`,label:`Device switch`,hint:`A device an operator turned off or back on. Not a fault — a choice.`,kinds:[{value:`device-disabled`,label:`Device switched off`},{value:`device-enabled`,label:`Device switched on`}]},{id:`nodes`,label:`Nodes`,hint:`An agent or worker node joining or leaving the cluster.`,kinds:[{value:`node-offline`,label:`Node offline`},{value:`node-online`,label:`Node online`}]},{id:`alarm`,label:`Alarm`,hint:`The alarm panel refusing to arm, arming, armed, going off, or being disarmed.`,kinds:[{value:`alarm-arm-refused`,label:`Alarm arm refused (something is open)`},{value:`alarm-arming`,label:`Alarm arming (exit delay)`},{value:`alarm-armed`,label:`Alarm armed`},{value:`alarm-triggered`,label:`Alarm triggered`},{value:`alarm-disarmed`,label:`Alarm disarmed`}]},{id:`updates`,label:`Updates`,hint:`A newer version of an addon or of the server itself is available.`,kinds:[{value:`addon-update-available`,label:`Addon update available`},{value:`server-update-available`,label:`Server update available`}]}],Cr=Sr.flatMap(e=>e.kinds);function wr(e){return Cr.find(t=>t.value===e)?.label??e}function Tr(e){return{devices:e.some(e=>e.startsWith(`device-`)||e.startsWith(`stream-`)||e===`alarm-triggered`),deviceTypes:e.some(e=>e.startsWith(`device-`)),nodes:e.some(e=>e.startsWith(`node-`)||e===`addon-update-available`),packages:e.some(e=>e.endsWith(`update-available`))}}var Er=Object.values(N).map(e=>({value:e,label:Dr(e)})).toSorted((e,t)=>e.label.localeCompare(t.label));function Dr(e){let t=e.replaceAll(`-`,` `);return t.charAt(0).toUpperCase()+t.slice(1)}function Or(e,t){let n=e?.kinds??[],r=n.includes(t)?n.filter(e=>e!==t):Cr.filter(e=>e.value===t||n.includes(e.value)).map(e=>e.value);if(r.length!==0)return jr(e,r)}function kr(e,t){let n=e?.kinds??[];if(n.length===0)return;let r=Ar(t,`deviceIds`,e?.deviceIds),i=Ar(t,`deviceTypes`,e?.deviceTypes),a=Ar(t,`nodeIds`,e?.nodeIds),o=Ar(t,`packageNames`,e?.packageNames);return{kinds:[...n],...r===void 0?{}:{deviceIds:[...r]},...i===void 0?{}:{deviceTypes:[...i]},...a===void 0?{}:{nodeIds:[...a]},...o===void 0?{}:{packageNames:[...o]}}}function Ar(e,t,n){let r=Object.prototype.hasOwnProperty.call(e,t)?e[t]:n;return r!==void 0&&r.length===0?void 0:r}function jr(e,t){let n=Tr(t),r=n.devices?e?.deviceIds:void 0,i=n.deviceTypes?e?.deviceTypes:void 0,a=n.nodes?e?.nodeIds:void 0,o=n.packages?e?.packageNames:void 0;return{kinds:[...t],...r&&r.length>0?{deviceIds:[...r]}:{},...i&&i.length>0?{deviceTypes:[...i]}:{},...a&&a.length>0?{nodeIds:[...a]}:{},...o&&o.length>0?{packageNames:[...o]}:{}}}function Mr(e,t=2){if(e===void 0||e.length===0)return`No event selected`;let n=e.slice(0,t).map(wr).join(`, `),r=e.length-Math.min(t,e.length);return r>0?`${n} +${r}`:n}function Nr(e){if(e===void 0)return`—`;let t=[],n=e.deviceIds?.length??0,r=e.deviceTypes?.length??0,i=e.nodeIds?.length??0,a=e.packageNames?.length??0;return r>0&&t.push(e.deviceTypes?.map(Dr).join(`, `)??``),n>0&&t.push(`${n} device${n===1?``:`s`}`),i>0&&t.push(`${i} node${i===1?``:`s`}`),a>0&&t.push(`${a} package${a===1?``:`s`}`),t.length===0?`Everything`:t.join(` · `)}b();var Pr=[`nc-pickers`,`nodes`],Fr=[`nc-pickers`,`addon-packages`];function Ir(){let e=I().trpcClient,t=C({queryKey:Pr,staleTime:6e4,queryFn:async()=>(await e.nodes.topology.query()).map(e=>({value:e.id,label:e.name.length>0?e.name:e.id,hint:e.isOnline?e.id:`${e.id} · offline`}))});return{options:t.data??[],loading:t.isLoading}}function Lr(){let e=I().trpcClient,t=C({queryKey:Fr,staleTime:6e4,queryFn:async()=>(await e.addons.listPackages.query()).map(e=>({value:e.name,label:e.name,hint:e.version})).toSorted((e,t)=>e.label.localeCompare(t.label))});return{options:t.data??[],loading:t.isLoading}}function Rr({value:e,cameras:t,onChange:n}){let r=S(()=>e?.kinds??[],[e]),i=Tr(r),a=Ir(),o=Lr();return x(`div`,{className:`mt-1 space-y-3`,"data-testid":`system-event-field`,children:[Sr.map(t=>x(`div`,{children:[k(`div`,{className:`text-[10px] font-semibold uppercase tracking-wide text-foreground-subtle`,children:t.label}),k(`div`,{className:`mt-1 flex flex-wrap gap-1.5`,children:t.kinds.map(t=>{let i=r.includes(t.value);return k(`button`,{type:`button`,role:`checkbox`,"aria-checked":i,"aria-label":t.label,onClick:()=>n(Or(e,t.value)),className:i?`rounded-md border border-primary bg-primary/10 px-2 py-1 text-[11px] text-primary`:`rounded-md border border-border px-2 py-1 text-[11px] text-foreground hover:bg-surface-hover`,children:t.label},t.value)})}),k(`p`,{className:W,children:t.hint})]},t.id)),r.length===0&&k(`p`,{className:`rounded-md border border-warning/40 bg-warning/10 px-2.5 py-1.5 text-[11px] text-warning`,children:`Pick at least one event — a system rule with no event selected is never evaluated, and the hub refuses to save it.`}),i.deviceTypes&&x(`div`,{children:[k(`label`,{className:`block text-[11px] font-medium text-foreground`,children:`Only these device types (optional)`}),k(H,{options:Er,value:e?.deviceTypes??[],onChange:t=>n(kr(e,{deviceTypes:t})),emptyHint:`No device types listed — the rule watches every type.`,placeholder:`Device type…`}),k(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:`Liveness is reported for EVERY device — cameras, plugs, sensors, the containers that hold them. Leave this empty to be told about all of them, or pick “Camera” to hear only about cameras.`})]}),i.devices&&x(`div`,{children:[k(`label`,{className:`block text-[11px] font-medium text-foreground`,children:`Only these cameras (optional)`}),k(tr,{cameras:t,value:e?.deviceIds??[],onChange:t=>n(kr(e,{deviceIds:t}))}),k(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:`Leave everything unchecked to watch every camera.`})]}),i.nodes&&x(`div`,{children:[k(`label`,{className:`block text-[11px] font-medium text-foreground`,children:`Only these nodes (optional)`}),k(H,{options:a.options,value:e?.nodeIds??[],onChange:t=>n(kr(e,{nodeIds:t})),loading:a.loading,emptyHint:`No nodes reported — the rule watches every node.`,placeholder:`Node id…`}),k(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:`Leave everything unchecked to watch every node.`})]}),i.packages&&x(`div`,{children:[k(`label`,{className:`block text-[11px] font-medium text-foreground`,children:`Only these packages (optional)`}),k(H,{options:o.options,value:e?.packageNames??[],onChange:t=>n(kr(e,{packageNames:t})),loading:o.loading,emptyHint:`No installed packages listed — the rule watches every package.`,placeholder:`Package name…`}),k(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:`Leave everything unchecked to be told about every addon and server update.`})]})]})}b();function zr({catalog:e,taxonomy:t,delivery:n,conditions:r,schedule:i,deviceIds:a,cameras:o,gateable:c,onConditionsChange:l,onScheduleChange:u}){let d=(e,t)=>{let n={...r};t===void 0?delete n[e]:n[e]=t,l(n)},f=S(()=>Jt(e,e=>e.id!==`devices`&&Vr(e,n,r)),[e,n,r]),p=S(()=>Jt(e,e=>e.id!==`devices`&&!Vr(e,n,r)),[e,n,r]),[m,h]=D(()=>{if(Hr(r,i))return!0;try{return localStorage.getItem(Br)===`1`}catch{return!1}}),g=()=>{let e=!m;h(e);try{localStorage.setItem(Br,e?`1`:`0`)}catch{}},_=e=>e.map(e=>x(`div`,{className:`space-y-2.5`,children:[k(`div`,{className:`text-[11px] font-semibold uppercase tracking-wide text-foreground-subtle`,children:e.label}),e.descriptors.map(e=>{let l=zn(e,n);return x(`div`,{className:l?``:`opacity-50`,"data-testid":`condition-${e.id}`,children:[x(`div`,{className:`flex items-center justify-between gap-2`,children:[k(`label`,{className:U,children:e.label}),!l&&x(s,{variant:`default`,children:[`not for `,e.appliesTo.join(` / `)]})]}),l?k(Ur,{descriptor:e,taxonomy:t,conditions:r,schedule:i,deviceIds:a,cameras:o,gateable:c,onFieldChange:d,onScheduleChange:u}):k(`p`,{className:W,children:`Not evaluated for the selected trigger — switch the trigger to use it.`}),l&&e.description&&k(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:e.description})]},e.id)})]},e.id));return x(`div`,{className:`space-y-4`,children:[_(f),p.length>0&&k(`button`,{type:`button`,onClick:g,"data-testid":`nc-advanced-toggle`,className:`w-full rounded-md border border-border px-3 py-1.5 text-left text-[11px] font-medium text-foreground-subtle hover:bg-surface-hover hover:text-foreground`,children:m?`▾ Hide advanced configurations`:`▸ Show more configurations`}),m&&_(p)]})}var Br=`camstack.nc.showAdvanced`;function Vr(e,t,n={}){return t===`system-event`?e.id===`systemEvent`:e.id===`audio`?n.audio!==void 0:e.id===`occupancy`?n.occupancy!==void 0:oe(e.id)}function Hr(e,t){for(let[t,n]of Object.entries(e))if(!oe(t)&&t!==`systemEvent`&&!(t===`audio`||t===`occupancy`)&&n!==void 0&&!(Array.isArray(n)&&n.length===0))return!0;return t!==void 0&&t.windows.length>0}function Ur({descriptor:e,taxonomy:t,conditions:n,schedule:r,deviceIds:i,cameras:a,gateable:s,onFieldChange:c,onScheduleChange:l}){switch(e.valueType){case`deviceIdList`:{if(!kt(e.id))break;let t=e.id;return k(tr,{cameras:a,value:n[t]??[],onChange:e=>c(t,e.length>0?e:void 0)})}case`stringList`:{if(!At(e.id))break;let r=e.id,a=e=>c(r,e.length>0?e:void 0);if(r===`identities`||r===`identitiesExclude`)return k(cr,{value:Wt(n,r),onChange:a});if(r===`eventTypeTokens`)return k(lr,{deviceIds:i,value:Wt(n,r),onChange:a});let o=ne(r,t);return o===null?k(nr,{value:Wt(n,r),placeholder:`Add value…`,onChange:a}):k(rr,{picker:o,value:Wt(n,r),onChange:a})}case`zoneIdList`:{if(!jt(e.id))break;let t=e.id;return k(sr,{deviceIds:i,cameras:a,value:Wt(n,t),onChange:e=>c(t,e.length>0?e:void 0)})}case`number01`:{if(!Mt(e.id))break;let t=e.id;return k(ir,{value:Gt(n,t),min:0,max:1,step:.05,onChange:e=>c(t,e)})}case`number`:{if(!Nt(e.id))break;let t=e.id;return k(ir,{value:Gt(n,t),min:0,step:1,onChange:e=>c(t,e)})}case`sourceSelect`:{if(!Pt(e.id))break;let t=e.id;return k(o,{value:n[t]??`any`,options:qn(e,Sn).map(e=>({value:e.value,label:e.label})),onChange:e=>c(t,Kr(e.target.value))})}case`systemEvent`:{if(!Ht(e.id))break;let t=e.id;return k(Rr,{value:n[t],cameras:a,onChange:e=>c(t,e)})}case`deviceState`:if(!Ut(e.id))break;return k(hr,{gateable:s,value:n.deviceState,onChange:e=>c(`deviceState`,e)});case`crossingSelect`:{if(!Ft(e.id))break;let t=e.id;return k(ar,{value:n[t],onChange:e=>c(t,e),...e.options?{options:e.options}:{}})}case`packagePhase`:{if(!It(e.id))break;let t=e.id;return k(o,{value:n[t]??``,options:[{value:``,label:`— any phase —`},...qn(e,Cn).map(e=>({value:e.value,label:e.label}))],onChange:e=>c(t,qr(e.target.value))})}case`zoneSelection`:{if(!Lt(e.id))break;let t=e.id;return k(or,{deviceIds:i,cameras:a,value:n[t],onChange:e=>c(t,e)})}case`plateMatcher`:{if(!Rt(e.id))break;let t=e.id;return k(mr,{value:n[t],onChange:e=>c(t,e)})}case`occupancy`:{if(!zt(e.id))break;let r=e.id;return k(fr,{deviceIds:i,cameras:a,classOptions:Wr(t),value:n[r],onChange:e=>c(r,e)})}case`audio`:{if(!Vt(e.id))break;let r=e.id;return k(pr,{taxonomy:t,value:n[r],onChange:e=>c(r,e)})}case`schedule`:return k(br,{value:r,onChange:l});default:break}return k(Gr,{descriptor:e,conditions:n})}function Wr(e){let t=ne(`occupancy`,e);return t===null?[]:t.groups.flatMap(e=>e.options)}function Gr({descriptor:e,conditions:t}){let n=Object.entries(t).find(([t])=>t===e.id);return x(`p`,{className:W,children:[n!==void 0&&n[1]!==void 0?`Authored elsewhere and preserved — this admin editor cannot change it yet.`:`Not editable here yet — this condition has no admin editor.`,` `,x(`span`,{className:`text-foreground-muted`,children:[`(`,e.valueType,`)`]})]})}function Kr(e){if(e===`pipeline`||e===`onboard`||e===`sensor`||e===`any`)return e}function qr(e){return Cn.find(t=>t.value===e)?.value}var Jr={search:``,types:[],selectedOnly:!1};function Yr(e){let t=new Map;for(let n of e)t.set(n.type,(t.get(n.type)??0)+1);return[...t.entries()].map(([e,t])=>({type:e,count:t})).sort((e,t)=>t.count-e.count||e.type.localeCompare(t.type))}function Xr(e,t,n){let r=new Set(n),i=t.search.trim().toLowerCase(),a=new Set(t.types);return e.filter(e=>r.has(e.id)?!0:!(t.selectedOnly||a.size>0&&!a.has(e.type)||i!==``&&!e.name.toLowerCase().includes(i)))}function Zr(e){let t=new Map,n=[];for(let r of e){if(r.location===null||r.location===``){n.push(r);continue}let e=t.get(r.location)??[];e.push(r),t.set(r.location,e)}let r=[...t.entries()].sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>({location:e,devices:[...t].sort((e,t)=>e.name.localeCompare(t.name))}));return n.length>0&&r.push({location:null,devices:[...n].sort((e,t)=>e.name.localeCompare(t.name))}),r}function Qr(e,t){let n=new Set(t);for(let t of e)n.add(t.id);return[...n]}function $r(e,t){let n=new Set(e.map(e=>e.id));return t.filter(e=>!n.has(e))}function ei(e,t){return e.length===0?`Every device (${String(t)}) — no restriction`:`${String(e.length)} of ${String(t)} selected`}b();function ti({devices:e,value:t,onChange:n,loading:r=!1}){let[i,a]=D(Jr),o=S(()=>Yr(e),[e]),c=S(()=>Xr(e,i,t),[e,i,t]),l=S(()=>Zr(c),[c]),d=e=>a(t=>({...t,types:t.types.includes(e)?t.types.filter(t=>t!==e):[...t.types,e]})),p=e=>n(t.includes(e)?t.filter(t=>t!==e):[...t,e]);return r?k(`p`,{className:`text-[11px] text-foreground-subtle`,children:`Loading devices…`}):x(`div`,{className:`space-y-3`,children:[x(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[k(`p`,{className:`text-[11px] text-foreground-subtle`,children:ei(t,e.length)}),x(`div`,{className:`flex items-center gap-1`,children:[k(u,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>n(Qr(c,t)),children:`Select shown`}),k(u,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>n($r(c,t)),children:`Clear shown`})]})]}),x(`div`,{className:`flex flex-wrap items-center gap-2`,children:[k(f,{className:`min-w-[10rem] flex-1`,value:i.search,placeholder:`Search by name…`,leftSlot:k(Ee,{className:`h-3.5 w-3.5 text-foreground-subtle`}),onChange:e=>a(t=>({...t,search:e.target.value}))}),x(`label`,{className:`flex items-center gap-1.5 text-[11px] text-foreground-subtle`,children:[k(`input`,{type:`checkbox`,checked:i.selectedOnly,onChange:e=>a(t=>({...t,selectedOnly:e.target.checked}))}),`Selected only`]})]}),k(`div`,{className:`flex flex-wrap gap-1`,children:o.map(e=>x(`button`,{type:`button`,onClick:()=>d(e.type),className:i.types.includes(e.type)?`rounded-full border border-primary bg-primary/10 px-2 py-0.5 text-[10px] text-foreground`:`rounded-full border border-border px-2 py-0.5 text-[10px] text-foreground-muted hover:bg-surface-hover`,children:[e.type,` `,k(`span`,{className:`text-foreground-subtle`,children:e.count})]},e.type))}),c.length===0?k(`p`,{className:`rounded border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:`No device matches this filter.`}):k(`div`,{className:`max-h-72 space-y-2 overflow-y-auto`,children:l.map(e=>x(`div`,{children:[k(`p`,{className:`px-1 pb-1 text-[10px] uppercase tracking-wide text-foreground-subtle`,children:e.location??`No location`}),k(`div`,{className:`divide-y divide-border rounded-md border border-border`,children:e.devices.map(e=>x(`label`,{className:`flex cursor-pointer items-center gap-2.5 px-3 py-1.5 text-xs text-foreground hover:bg-surface-hover`,children:[k(`input`,{type:`checkbox`,checked:t.includes(e.id),onChange:()=>p(e.id),className:`accent-primary`}),k(`span`,{className:`flex-1 truncate`,children:e.name}),k(s,{variant:`default`,children:e.type})]},e.id))})]},e.location??`__unplaced`))})]})}b();var ni=[`notificationRules`,`listSnoozes`],ri=3e4;function ii(e,t){return Math.max(0,Math.ceil((e.expiresAt-t)/6e4))}function ai(e){if(e===0)return`ending`;if(e<60)return`${e}m left`;let t=Math.floor(e/60),n=e%60;return n===0?`${t}h left`:`${t}h ${n}m left`}function oi({rules:e}){let t=I(),n=E(),r=C({queryKey:ni,refetchInterval:ri,queryFn:async()=>(await t.trpcClient.notificationRules.listSnoozes.query({})).snoozes}),i=O({mutationFn:e=>t.trpcClient.notificationRules.cancelSnooze.mutate({snoozeId:e}),onSuccess:()=>n.invalidateQueries({queryKey:ni})}),a=S(()=>{let t=new Map;for(let n of e)t.set(n.id,n.name);return t},[e]),o=Date.now(),c=(r.data??[]).filter(e=>o>=e.startedAt&&o<e.expiresAt);return x(_,{className:`p-4`,children:[x(`div`,{className:`flex items-center gap-2 mb-3`,children:[k(ve,{className:`h-4 w-4 text-foreground-subtle`}),k(`h3`,{className:`text-sm font-medium text-foreground`,children:`Silenced right now`})]}),c.length===0&&k(`p`,{className:`text-[11px] text-foreground-subtle`,children:`Nothing is silenced. A snooze opened from the app or from a notification button appears here until its clock runs out.`}),k(`div`,{className:`space-y-2`,children:c.map(e=>x(`div`,{className:`flex items-center justify-between gap-3 rounded-md border border-border px-3 py-2`,children:[x(`div`,{className:`min-w-0`,children:[x(`div`,{className:`flex items-center gap-2`,children:[k(`span`,{className:`text-xs text-foreground truncate`,children:e.scope===`all`?`Everything`:e.scope===`device`?`Camera ${e.deviceId??`?`}`:a.get(e.ruleId??``)??`A rule`}),e.global&&k(s,{variant:`warning`,className:`text-[10px]`,children:`everyone`}),e.classes!==void 0&&e.classes.length>0&&k(s,{variant:`info`,className:`text-[10px]`,children:e.classes.join(`, `)}),!e.summary&&k(s,{variant:`default`,className:`text-[10px]`,children:`no summary`})]}),x(`span`,{className:`text-[10px] text-foreground-subtle`,children:[`set by `,e.userId,` · `,ai(ii(e,o))]})]}),k(u,{size:`sm`,variant:`outline`,disabled:i.isPending,onClick:()=>i.mutate(e.id),children:`End now`})]},e.id))})]})}b();var si=[`notificationRules`,`listRules`],ci=[`notificationOutput`,`listTargets`,`forRules`],li=[`notificationRules`,`getConditionCatalog`],ui=[`deviceManager`,`listAll`,`forRules`],di=[`deviceManager`,`listAll`,`forRuleActions`],fi=[`deviceManager`,`gateableDevices`],pi=F.options;function mi({onSimulateRule:a}={}){let o=I(),[s,c]=D({mode:`closed`}),[l,d]=D(null),[f,p]=D(`all`),m=C({queryKey:si,queryFn:async()=>(await o.trpcClient.notificationRules.listRules.query({})).rules}),h=C({queryKey:ci,queryFn:()=>o.trpcClient.notificationOutput.listTargets.query({})}),g=C({queryKey:li,queryFn:()=>o.trpcClient.notificationRules.getConditionCatalog.query({})}),v=C({queryKey:fi,queryFn:async()=>{let e=await o.trpcClient.deviceManager.listAll.query({}),t=[];for(let n of e){let e=ee(await o.trpcClient.deviceManager.loadRuntimeState.query({deviceId:n.id}),pi);e.length>0&&t.push({id:n.id,name:n.name,states:e})}return t},staleTime:6e4}),y=C({queryKey:di,queryFn:async()=>(await o.trpcClient.deviceManager.listAll.query({projection:`slim`})).map(e=>({id:e.id,name:e.name,type:String(e.type),location:e.location??null})).sort((e,t)=>e.name.localeCompare(t.name)),staleTime:6e4}),b=C({queryKey:ui,queryFn:async()=>(await o.trpcClient.deviceManager.listAll.query({})).filter(e=>e.type===N.Camera).map(e=>({id:e.id,name:e.name}))}),w=S(()=>{let e=new Map;for(let t of h.data??[])e.set(t.id,t.name);return e},[h.data]),T=O({mutationFn:e=>o.trpcClient.notificationRules.setRuleEnabled.mutate(e),onSuccess:()=>void m.refetch()}),E=O({mutationFn:e=>o.trpcClient.notificationRules.deleteRule.mutate({ruleId:e}),onSuccess:()=>{d(null),m.refetch()}}),A=m.data??[],j=S(()=>A.filter(e=>ln(e,f)),[A,f]),M=S(()=>{let e=new Map;for(let t of an)e.set(t.key,A.filter(e=>ln(e,t.key)).length);return e},[A]),P=an.find(e=>e.key===f)??an[0],te=f===`system`;return x(z,{icon:ye,title:`Notification Rules`,subtitle:P.blurb,actions:x(u,{size:`sm`,type:`button`,onClick:()=>c({mode:`form`,rule:null,seed:dn(f)}),children:[k(Ce,{className:`h-3.5 w-3.5`}),P.newRuleLabel]}),children:[k(n,{value:f,onValueChange:e=>p(on(e)??f),children:k(e,{className:`mb-3`,children:an.map(e=>x(i,{value:e.key,children:[e.label,k(`span`,{className:`ml-1.5 text-[10px] text-foreground-subtle`,children:M.get(e.key)??0})]},e.key))})}),k(oi,{rules:A}),m.isLoading&&k(`div`,{className:`flex items-center justify-center py-16`,children:k(L,{className:`h-6 w-6 animate-spin text-primary`})}),m.isError&&!m.isLoading&&k(r,{title:`Failed to load rules`,message:m.error instanceof Error?m.error.message:`Unknown error`,onRetry:()=>void m.refetch()}),!m.isLoading&&!m.isError&&j.length===0&&k(`div`,{className:`text-xs text-foreground-subtle text-center py-16`,children:P.emptyHint}),j.length>0&&k(_,{children:k(t,{columns:te?gi({targetNameById:w,confirmDeleteId:l,deletePending:E.isPending,onToggle:(e,t)=>T.mutate({ruleId:e.id,enabled:t}),onEdit:e=>c({mode:`form`,rule:e}),onDuplicate:e=>c({mode:`form`,rule:{...e,id:``,name:`${e.name} (copy)`}}),onAskDelete:d,onConfirmDelete:e=>E.mutate(e.id)}):hi({targetNameById:w,confirmDeleteId:l,deletePending:E.isPending,onToggle:(e,t)=>T.mutate({ruleId:e.id,enabled:t}),onEdit:e=>c({mode:`form`,rule:e}),onDuplicate:e=>c({mode:`form`,rule:{...e,id:``,name:`${e.name} (copy)`}}),onAskDelete:d,onConfirmDelete:e=>E.mutate(e.id),...a?{onTest:a}:{}}),rows:j,rowKey:e=>e.id,minWidthPx:760,bordered:!1})}),s.mode===`form`&&k(_i,{rule:s.rule,...s.seed?{seed:s.seed}:{},targets:h.data??[],actuatable:y.data??[],catalog:Un(g.data?.catalog??[]),taxonomy:g.data?.taxonomy,cameras:b.data??[],gateable:v.data??[],onCancel:()=>c({mode:`closed`}),onSaved:()=>{c({mode:`closed`}),m.refetch()}})]})}function hi(e){return[{key:`name`,header:`Rule`,render:e=>x(`span`,{className:`flex items-center gap-2`,children:[k(`span`,{className:`truncate text-sm font-medium text-foreground`,children:e.name}),!e.enabled&&k(s,{variant:`warning`,children:`disabled`}),Nn(e.conditions,e.actions?.onTrigger??[])&&k(s,{variant:`info`,children:`Snooze disabled (alarm rule)`})]})},{key:`trigger`,header:`Trigger`,nowrap:!0,render:e=>x(`span`,{className:`flex items-center gap-1.5`,children:[k(`span`,{className:`text-[11px] text-foreground-subtle`,children:en(e.delivery)}),!nn(e.delivery)&&k(s,{variant:`warning`,children:`read-only`})]})},{key:`targets`,header:`Targets`,render:t=>{let n=t.targets[0],r=n?e.targetNameById.get(n.targetId)??n.targetId:null;return k(`span`,{className:`text-[11px] text-foreground-subtle`,children:t.targets.length===1&&r?r:`${t.targets.length} target${t.targets.length===1?``:`s`}`})}},{key:`priority`,header:`Priority`,align:`center`,nowrap:!0,render:e=>k(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.priority})},{key:`enabled`,header:`On`,align:`center`,nowrap:!0,render:t=>k(p,{checked:t.enabled,onCheckedChange:n=>e.onToggle(t,n),"aria-label":`toggle ${t.name}`})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:t=>x(`span`,{className:`flex items-center justify-end gap-1`,children:[e.onTest&&k(u,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onTest?.(t),title:`Test — simulate an event this rule should match`,"aria-label":`test ${t.name}`,children:k(ze,{className:`h-3.5 w-3.5`})}),k(u,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onEdit(t),title:`Edit`,children:k(Se,{className:`h-3.5 w-3.5`})}),k(u,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onDuplicate(t),title:`Duplicate`,children:k(xe,{className:`h-3.5 w-3.5`})}),e.confirmDeleteId===t.id?x(w,{children:[x(u,{size:`sm`,variant:`danger`,type:`button`,disabled:e.deletePending,onClick:()=>e.onConfirmDelete(t),children:[e.deletePending&&k(L,{className:`h-3.5 w-3.5 animate-spin`}),`Confirm`]}),k(u,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onAskDelete(null),children:`Cancel`})]}):k(u,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onAskDelete(t.id),title:`Delete`,children:k(R,{className:`h-3.5 w-3.5 text-danger`})})]})}]}function gi(e){let t=hi(e),n=e=>t.filter(t=>t.key===e);return[...n(`name`),{key:`events`,header:`Events`,render:e=>k(`span`,{className:`text-[11px] text-foreground-subtle`,children:Mr(e.conditions.systemEvent?.kinds)})},{key:`scope`,header:`Scope`,nowrap:!0,render:e=>k(`span`,{className:`text-[11px] text-foreground-subtle`,children:Nr(e.conditions.systemEvent)})},{key:`targets`,header:`Targets`,render:t=>{let n=t.targets[0],r=n?e.targetNameById.get(n.targetId)??n.targetId:null;return k(`span`,{className:`text-[11px] text-foreground-subtle`,children:t.targets.length===1&&r?r:`${t.targets.length} target${t.targets.length===1?``:`s`}`})}},{key:`cooldown`,header:`Cooldown`,nowrap:!0,render:e=>k(`span`,{className:`text-[11px] text-foreground-subtle`,children:pn(e.throttle.cooldownSec)})},...n(`enabled`),...n(`actions`)]}function _i({rule:t,seed:r,targets:a,catalog:c,taxonomy:d,cameras:m,gateable:h,actuatable:_,onSaved:v,onCancel:b}){let S=I(),T=t!=null&&t.id.length>0,[E,A]=D(()=>t?Fn(t):Pn(r?.delivery,r?.conditions)),[j,M]=D(null),[ee,N]=D(null),[P,te]=D($n),F=e=>A(t=>({...t,...e})),ne=T&&t?{throttle:t.throttle}:void 0,re=O({mutationFn:async()=>{let e=Kn(E,ne,c);T&&t?await S.trpcClient.notificationRules.updateRule.mutate({ruleId:t.id,patch:e}):await S.trpcClient.notificationRules.createRule.mutate({rule:e})},onSuccess:v,onError:e=>M(e instanceof Error?e.message:`Save failed`)}),ie=O({mutationFn:async()=>{let e=Kn(E,ne,c);return(await S.trpcClient.notificationRules.testRule.mutate({rule:e,lookbackMinutes:60})).results},onMutate:()=>N(null),onSuccess:e=>N(e),onError:e=>M(e instanceof Error?e.message:`Test failed`)}),ae=E.targetIds.map(e=>a.find(t=>t.id===e)?.name??e),oe=e=>F({targetIds:E.targetIds.includes(e)?E.targetIds.filter(t=>t!==e):[...E.targetIds,e]}),se=C({queryKey:[`userManagement`,`listUsers`],queryFn:()=>S.trpcClient.userManagement.listUsers.query()}).data,ce=e=>F({targetUsers:E.targetUsers.includes(e)?E.targetUsers.filter(t=>t!==e):[...E.targetUsers,e]}),le=$t.find(e=>e.value===E.delivery)?.hint,ue=In(E),de=rn(E.delivery),fe=Nn(E.conditions,E.actions.sequences),pe=Zn(E.delivery,E.conditions),me=pe.some(e=>e.key===P)?P:$n;return nn(E.delivery)?k(l,{open:!0,onOpenChange:e=>!e&&b(),children:x(g,{width:`lg`,placement:`sheet-on-mobile`,children:[x(`div`,{className:`flex items-center justify-between mb-3`,children:[x(`h3`,{className:`text-sm font-semibold text-foreground flex items-center gap-2`,children:[k(ye,{className:`h-4 w-4 text-foreground-subtle`}),T?`Edit ${t?.name}`:`New notification rule`]}),k(u,{size:`sm`,variant:`ghost`,type:`button`,onClick:b,children:`Cancel`})]}),j&&k(`div`,{className:`rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger mb-3`,children:j}),x(n,{value:me,onValueChange:e=>te(er(e)??P),children:[k(e,{className:`mb-3`,children:pe.map(e=>k(i,{value:e.key,children:e.label},e.key))}),x(y,{value:`rule`,className:`space-y-4`,children:[x(`div`,{className:`flex items-end gap-3`,children:[x(`div`,{className:`min-w-0 flex-1`,children:[k(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Name`}),k(f,{value:E.name,onChange:e=>F({name:e.target.value}),placeholder:`e.g. Front door package`})]}),x(`label`,{className:`flex items-center gap-2 pb-1.5 text-[11px] font-medium text-foreground`,children:[k(p,{checked:E.enabled,onCheckedChange:e=>F({enabled:e}),"aria-label":`enabled`}),`Enabled`]})]}),x(`div`,{children:[k(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Trigger`}),k(o,{value:E.delivery,onChange:e=>{let t=tn(e.target.value);t&&F({delivery:t})},options:$t.map(e=>({value:e.value,label:e.label}))}),le&&k(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:le})]}),x(`div`,{children:[k(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Delivery targets`}),a.length===0?k(`p`,{className:`text-[11px] text-foreground-subtle`,children:`No delivery targets configured. Add one under the Targets tab first.`}):k(`div`,{className:`rounded-md border border-border divide-y divide-border`,children:a.map(e=>x(`label`,{className:`flex items-center gap-2.5 px-3 py-1.5 text-xs text-foreground cursor-pointer hover:bg-surface-hover`,children:[k(`input`,{type:`checkbox`,checked:E.targetIds.includes(e.id),onChange:()=>oe(e.id),className:`accent-primary`}),k(`span`,{className:`flex-1 truncate`,children:e.name}),!e.enabled&&k(s,{variant:`warning`,children:`disabled`})]},e.id))})]}),x(`div`,{children:[k(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Notify users`}),(se??[]).length===0?k(`p`,{className:`text-[11px] text-foreground-subtle`,children:`No users to notify.`}):k(`div`,{className:`rounded-md border border-border divide-y divide-border`,children:(se??[]).map(e=>x(`label`,{className:`flex items-center gap-2.5 px-3 py-1.5 text-xs text-foreground cursor-pointer hover:bg-surface-hover`,children:[k(`input`,{type:`checkbox`,checked:E.targetUsers.includes(e.id),onChange:()=>ce(e.id),className:`accent-primary`}),k(`span`,{className:`flex-1 truncate`,children:e.username}),e.isAdmin&&k(s,{variant:`info`,children:`admin`})]},e.id))}),k(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:`Delivers to the targets each user owns, only for cameras that user can access.`})]})]}),k(y,{value:`devices`,className:`space-y-4`,children:k(ti,{devices:_,value:E.deviceIds,onChange:e=>F({deviceIds:e}),loading:_.length===0})}),k(y,{value:`actions`,className:`space-y-4`,children:k(wt,{value:E.actions,onChange:e=>F({actions:e}),devices:_})}),x(y,{value:`advanced`,className:`space-y-4`,children:[x(`div`,{children:[k(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Cooldown`}),k(o,{value:String(E.cooldownSec),onChange:e=>{let t=hn(e.target.value);t!==void 0&&F({cooldownSec:t})},options:mn(E.cooldownSec).map(e=>({value:String(e.value),label:e.label}))}),k(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:de?`A camera that flaps, or a node that reconnects every minute, would otherwise send one notification per flap. The cooldown is the shortest gap between two deliveries of this rule.`:`The shortest gap between two deliveries of this rule. Counted per device unless the rule was configured otherwise.`})]}),x(`div`,{children:[x(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[k(p,{checked:E.snoozeAllowGlobal,onCheckedChange:e=>F({snoozeAllowGlobal:e}),"aria-label":`allow global snooze`,disabled:fe}),`Anyone may snooze this rule for everyone`]}),k(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:`A snooze is personal by default — it silences only the person who set it. Turn this on for a rule where silencing the whole household is legitimate (the gardener is here all afternoon). Admins can always do it.`})]}),x(`div`,{children:[k(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Snooze buttons`}),fe?k(`div`,{className:`rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:`Snooze disabled (alarm rule). This rule concerns — or triggers — the alarm panel, and no snooze window can silence it: not a notification button, not a pause opened from the app on this camera or on the whole feed.`}):x(w,{children:[k(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:kn.map(e=>{let t=E.snoozeOptions??On,n=t.includes(e);return k(u,{type:`button`,size:`sm`,variant:n?`primary`:`outline`,onClick:()=>F({snoozeOptions:n?t.filter(t=>t!==e):[...t,e].toSorted((e,t)=>e-t)}),children:An(e)},e)})}),k(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:E.snoozeOptions===void 0?`Not set — the notification offers the defaults (${On.map(An).join(`, `)}). A pause opened from a button silences this camera for this class of subject, only for whoever received the notification, and sends no summary.`:E.snoozeOptions.length===0?`No snooze buttons on this rule. That is an explicit choice: the notification cannot be silenced from the lock screen.`:`Four at most. Every snooze button takes space from the rule’s action buttons — ntfy accepts three in total.`}),E.snoozeOptions!==void 0&&k(u,{type:`button`,size:`sm`,variant:`ghost`,className:`mt-1`,onClick:()=>F({snoozeOptions:void 0}),children:`Back to the defaults`})]})]})]}),x(y,{value:`notification`,className:`space-y-4`,children:[x(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[x(`div`,{children:[k(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Priority`}),k(o,{value:String(E.priority),onChange:e=>F({priority:Number(e.target.value)}),options:Dn.map(e=>({value:String(e.value),label:e.label}))})]}),de&&k(`div`,{className:`rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:`A system event carries no image: there is no camera frame behind "a node went offline". This rule sends text only.`}),!de&&x(`div`,{children:[k(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Media attachment`}),k(o,{value:E.mediaAttach,onChange:e=>{let t=_n(e.target.value);t&&F({mediaAttach:t})},options:gn.map(e=>({value:e.value,label:e.label}))}),k(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:gn.find(e=>e.value===E.mediaAttach)?.description}),x(`div`,{className:`mt-2 space-y-1`,children:[x(`label`,{className:`flex items-center gap-2 text-xs text-foreground cursor-pointer`,children:[k(`input`,{type:`checkbox`,checked:E.mediaZoneCrop,onChange:e=>F({mediaZoneCrop:e.target.checked}),className:`accent-primary`}),`Crop the image to the rule's zone`]}),x(`label`,{className:`flex items-center gap-2 text-xs text-foreground cursor-pointer`,children:[k(`input`,{type:`checkbox`,checked:E.mediaGif,onChange:e=>F({mediaGif:e.target.checked}),className:`accent-primary`}),`Attach a GIF around the event`]}),x(`label`,{className:`flex items-center gap-2 text-xs text-foreground cursor-pointer`,children:[k(`input`,{type:`checkbox`,checked:E.mediaClip,onChange:e=>F({mediaClip:e.target.checked}),className:`accent-primary`}),`Attach an MP4 clip around the event`]})]}),(E.mediaGif||E.mediaClip)&&x(`div`,{className:`mt-2`,children:[k(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Video quality`}),k(o,{value:E.mediaProfile??``,onChange:e=>F({mediaProfile:xn(e.target.value)}),options:bn.map(e=>({value:e.value,label:e.label}))}),k(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:`A notification is watched on a phone — the cheapest stream is normally the right one, and the high profile only costs CPU to render.`}),k(`label`,{className:`mt-2 block text-[11px] font-medium text-foreground mb-1`,children:`Playback speed`}),k(o,{value:E.mediaClipSpeed===void 0?``:String(E.mediaClipSpeed),onChange:e=>F({mediaClipSpeed:Yn(e.target.value)}),options:Jn.map(e=>({value:e.value,label:e.label}))}),k(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:`A notification clip is glanced at, not watched: at 2× the recipient sees the whole passage in half the time and the file is half the size. Real time is there when the detail matters more than the glance.`})]})]}),!de&&x(`div`,{children:[k(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Image frame`}),k(o,{value:E.mediaFrame??``,onChange:e=>F({mediaFrame:yn(e.target.value)}),options:vn.map(e=>({value:e.value,label:e.label}))}),k(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:`What the attached still shows. "Automatic" leaves it to the attachment mode above.`})]})]}),x(`div`,{className:`space-y-2`,children:[x(`div`,{children:[k(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Notification title`}),k(f,{value:E.templateTitle,onChange:e=>F({templateTitle:e.target.value}),placeholder:`{{camera}} — {{class}}`})]}),x(`div`,{children:[k(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Notification body`}),k(`textarea`,{value:E.templateBody,onChange:e=>F({templateBody:e.target.value}),rows:2,placeholder:`{{label}} seen in {{zone}} at {{time}}`,className:`w-full rounded-md border border-border bg-surface px-2.5 py-1.5 text-xs text-foreground placeholder:text-foreground-subtle focus:outline-none focus:ring-1 focus:ring-primary`})]}),x(`p`,{className:`text-[10px] text-foreground-subtle`,children:[`Leave blank to use the backend default text. Supported variables include`,` `,k(`code`,{children:`{{camera}}`}),`, `,k(`code`,{children:`{{class}}`}),`, `,k(`code`,{children:`{{label}}`}),`,`,` `,k(`code`,{children:`{{zone}}`}),`, `,k(`code`,{children:`{{confidence}}`}),`,`,` `,k(`code`,{children:`{{time}}`}),`.`]})]})]}),x(y,{value:`conditions`,className:`space-y-4`,children:[x(`div`,{className:`rounded-md border border-border px-3 py-3`,children:[k(`div`,{className:`mb-2 text-[11px] font-semibold text-foreground`,children:de?`Which system events`:Qn(E.conditions)??`Conditions`}),E.conditions.audio!==void 0&&k(`p`,{className:`mb-2 text-[10px] text-foreground-subtle`,children:`This is a SOUND rule: it fires on a confirmed sampling window of audio, never on a picture. Name the sounds and/or keep a level threshold — with neither it can never match. Everything else below still composes (a camera scope, a schedule).`}),E.conditions.occupancy!==void 0&&k(`p`,{className:`mb-2 text-[10px] text-foreground-subtle`,children:`This is an OCCUPANCY rule: it fires when the count in a camera frame or a zone crosses your threshold and holds. Pick the camera on the Devices tab first — the zone list is that camera's.`}),de&&k(`p`,{className:`mb-2 text-[10px] text-foreground-subtle`,children:`Pick the events this rule reacts to, then narrow them if you want. Nothing else on a system rule is a condition — there is no detection behind it.`}),c.length===0?k(`p`,{className:`text-[10px] text-foreground-subtle`,children:`Condition catalog unavailable — this rule matches on its trigger and targets alone.`}):k(zr,{catalog:c,taxonomy:d,delivery:E.delivery,conditions:E.conditions,schedule:E.schedule,deviceIds:E.deviceIds,cameras:m,gateable:h,onConditionsChange:e=>F({conditions:e}),onScheduleChange:e=>F({schedule:e})})]}),!de&&x(`div`,{className:`rounded-md border border-border px-3 py-3`,children:[x(`div`,{className:`flex items-center justify-between gap-2`,children:[k(`div`,{className:`text-[11px] font-semibold text-foreground`,children:`Test rule`}),x(u,{size:`sm`,variant:`outline`,type:`button`,disabled:ie.isPending||!Ln(E),onClick:()=>{M(null),ie.mutate()},children:[ie.isPending?k(L,{className:`h-3.5 w-3.5 animate-spin`}):k(ze,{className:`h-3.5 w-3.5`}),`Dry-run (last 60 min)`]})]}),k(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:`Evaluate the CURRENT (unsaved) rule against recently persisted records — no notification is sent.`}),ee!==null&&k(yi,{delivery:E.delivery,results:ee,targetNames:ae})]})]})]}),ue.length>0&&k(`div`,{"data-testid":`rule-form-problems`,className:`mt-3 rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-[11px] text-warning space-y-1`,children:ue.map(e=>k(`p`,{children:e},e))}),x(`div`,{className:`flex justify-end gap-2 mt-4`,children:[k(u,{variant:`secondary`,size:`sm`,type:`button`,onClick:b,children:`Cancel`}),x(u,{size:`sm`,type:`button`,disabled:re.isPending||!Ln(E),onClick:()=>{M(null),re.mutate()},children:[re.isPending&&k(L,{className:`h-3.5 w-3.5 animate-spin`}),T?`Save changes`:`Create rule`]})]})]})}):k(vi,{rule:t,onCancel:b})}function vi({rule:e,onCancel:t}){let n=Object.keys(e?.conditions??{});return k(l,{open:!0,onOpenChange:e=>!e&&t(),children:x(g,{width:`lg`,placement:`sheet-on-mobile`,children:[x(`div`,{className:`flex items-center justify-between mb-3`,children:[x(`h3`,{className:`text-sm font-semibold text-foreground flex items-center gap-2`,children:[k(ye,{className:`h-4 w-4 text-foreground-subtle`}),e?.name??`Rule`]}),k(s,{variant:`warning`,children:`read-only`})]}),x(`div`,{className:`rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-xs text-warning`,"data-testid":`unsupported-trigger-notice`,children:[`This rule uses the trigger `,k(`code`,{children:e?.delivery}),`, which this version of the admin UI cannot author. It is shown exactly as stored and nothing here can change it — editing it with an editor that does not know the trigger would rewrite it. Update the server bundle, or edit this rule from the viewer app.`]}),x(`dl`,{className:`mt-3 space-y-1.5 text-[11px]`,children:[x(`div`,{className:`flex gap-2`,children:[k(`dt`,{className:`w-24 shrink-0 text-foreground-subtle`,children:`Trigger`}),k(`dd`,{className:`text-foreground`,children:e?.delivery})]}),x(`div`,{className:`flex gap-2`,children:[k(`dt`,{className:`w-24 shrink-0 text-foreground-subtle`,children:`Enabled`}),k(`dd`,{className:`text-foreground`,children:e?.enabled?`yes`:`no`})]}),x(`div`,{className:`flex gap-2`,children:[k(`dt`,{className:`w-24 shrink-0 text-foreground-subtle`,children:`Targets`}),k(`dd`,{className:`text-foreground`,children:e?.targets.length??0})]}),x(`div`,{className:`flex gap-2`,children:[k(`dt`,{className:`w-24 shrink-0 text-foreground-subtle`,children:`Conditions`}),k(`dd`,{className:`text-foreground`,children:n.length>0?n.join(`, `):`none`})]})]}),k(`div`,{className:`flex justify-end gap-2 mt-4`,children:k(u,{variant:`secondary`,size:`sm`,type:`button`,onClick:t,children:`Close`})})]})})}function yi({delivery:e,results:t,targetNames:n}){if(e===`device-event`)return k(`p`,{className:`mt-2 text-[11px] text-foreground-subtle`,children:`Device-event rules cannot be dry-run: the sensor-event store has no cross-device scan surface, so a test returns no candidate records. The rule still fires live on a matching doorbell press / sensor change.`});if(t.length===0)return k(`p`,{className:`mt-2 text-[11px] text-foreground-subtle`,children:`No records in the last 60 minutes matched — nothing to evaluate.`});let r=t.filter(e=>e.wouldFire).length;return x(`div`,{className:`mt-2 space-y-1.5`,children:[x(`div`,{className:`text-[11px] text-foreground-subtle`,children:[r,` of `,t.length,` evaluated record`,t.length===1?``:`s`,` would fire.`]}),k(`ul`,{className:`divide-y divide-border rounded-md border border-border`,children:t.slice(0,50).map(e=>x(`li`,{className:`flex items-center gap-2 px-2.5 py-1.5 text-[11px]`,children:[e.wouldFire?k(be,{className:`h-3.5 w-3.5 shrink-0 text-success`}):k(Me,{className:`h-3.5 w-3.5 shrink-0 text-foreground-subtle`}),k(`span`,{className:`w-32 shrink-0 text-foreground-subtle`,children:new Date(e.timestamp).toLocaleString()}),x(`span`,{className:`w-14 shrink-0 text-foreground-subtle`,children:[`#`,e.deviceId]}),k(`span`,{className:`min-w-0 flex-1 truncate text-foreground`,children:e.label??e.className??`object`}),e.wouldFire?x(`span`,{className:`shrink-0 truncate text-success`,children:[`→ `,n.join(`, `)||`targets`]}):e.failedCondition&&x(`span`,{className:`shrink-0 text-foreground-subtle`,children:[`failed: `,e.failedCondition]})]},e.recordId))})]})}var bi=[{value:`object-event`,label:`Object detection`,hint:`A detection on a live track — what an "Immediate" rule sees.`},{value:`track-end`,label:`Track end`,hint:`A finalised track: importance, dwell and label confidence exist only here.`},{value:`device-event`,label:`Device event`,hint:`A doorbell press or a linked sensor changing state.`},{value:`package-event`,label:`Package event`,hint:`A parcel delivered or picked up.`},{value:`audio-event`,label:`Audio event`,hint:`A classified audio episode. Rides the Immediate delivery, gated by the audio classes.`},{value:`occupancy-event`,label:`Occupancy edge`,hint:`A zone count crossing its threshold. Rides the Device-event delivery.`}];function xi(e){return bi.find(t=>t.value===e)?.value}function Si(e){return e===`object-event`||e===`audio-event`?`immediate`:e===`occupancy-event`?`device-event`:e}function Ci(e){return``}var wi={x:.25,y:.25,w:.5,h:.5},Ti={zoneId:``,zoneName:``,className:``,count:1,previousCount:0,occupied:!0,threshold:1};function Ei(){return{trigger:`object-event`,deviceId:null,sourceDeviceId:null,classNames:[],label:``,confidence:void 0,labelConfidence:void 0,importance:void 0,dwellSeconds:void 0,zones:[],crossingEnabled:!1,crossingZoneId:``,crossingDirection:`enter`,sensorKind:``,eventType:``,packagePhase:``,source:``,bboxEnabled:!1,bbox:wi,occupancy:Ti,timestampLocal:``,onlyRuleId:``,bypassCooldown:!1,bypassMute:!1,runActions:!1,still:`live`}}function Di(e){return e.deviceId!==null}function Oi(e){if(e.trim().length===0)return;let t=Number(e);return Number.isFinite(t)?t:void 0}function ki(e){if(e.trim().length===0)return;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}function Ai(e){let t=new Date(e),n=e=>String(e).padStart(2,`0`);return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())}T${n(t.getHours())}:${n(t.getMinutes())}`}function ji(e){if(e.deviceId===null)return null;let t=e.trigger,n=ki(e.timestampLocal),r=e.label.trim(),i=e.sensorKind.trim(),a=e.eventType.trim(),o=e.onlyRuleId.trim(),s=t===`device-event`,c=t===`occupancy-event`;return{trigger:t,deviceId:e.deviceId,...s&&e.sourceDeviceId!==null&&e.sourceDeviceId!==e.deviceId?{sourceDeviceId:e.sourceDeviceId}:{},classNames:[...e.classNames],...r.length>0?{label:r}:{},...e.confidence===void 0?{}:{confidence:e.confidence},...e.labelConfidence===void 0?{}:{labelConfidence:e.labelConfidence},...e.importance===void 0?{}:{importance:e.importance},...e.dwellSeconds===void 0?{}:{dwellSeconds:e.dwellSeconds},zones:[...e.zones],...t===`object-event`&&e.crossingEnabled?{crossing:{zoneId:e.crossingZoneId,direction:e.crossingDirection}}:{},...s&&i.length>0?{sensorKind:i}:{},...s&&a.length>0?{eventType:a}:{},...t===`package-event`&&e.packagePhase!==``?{packagePhase:e.packagePhase}:{},...e.source===``?{}:{source:e.source},...e.bboxEnabled?{bbox:{...e.bbox}}:{},...c?{occupancy:Mi(e.occupancy)}:{},...n===void 0?{}:{timestamp:n},...o.length>0?{onlyRuleId:o}:{},bypassCooldown:e.bypassCooldown,bypassMute:e.bypassMute,runActions:e.runActions,still:e.still}}function Mi(e){let t=e.zoneId.trim(),n=e.zoneName.trim(),r=e.className.trim();return{...t.length>0?{zoneId:t}:{},...n.length>0?{zoneName:n}:{},...r.length>0?{className:r}:{},count:Math.max(0,Math.round(e.count)),previousCount:Math.max(0,Math.round(e.previousCount)),occupied:e.occupied,threshold:Math.max(1,Math.round(e.threshold))}}function Ni(e){return Math.min(1,Math.round((e+.05)*100)/100)}function Pi(e){if(e.delivery===`immediate`){let t=e.conditions.classes??[];return t.length>0&&t.every(e=>e.startsWith(`audio-`))?`audio-event`:`object-event`}return e.delivery===`device-event`?e.conditions.occupancy===void 0?`device-event`:`occupancy-event`:e.delivery===`track-end`?`track-end`:`package-event`}function Fi(e){let t=Ei(),n=e.conditions,r=Pi(e),i=n.zones?.ids??[],a=n.identities?.[0]??n.labelEquals?.[0]??n.plates?.values?.[0],o=n.crossing===`exit`?`exit`:n.crossing===void 0?void 0:`enter`,s=r===`package-event`?n.packagePhase===`picked-up`?`picked-up`:`delivered`:``;return{...t,trigger:r,deviceId:n.devices?.[0]??null,classNames:[...n.classes??[]],...a===void 0?{}:{label:a},...n.minConfidence===void 0?{}:{confidence:Ni(n.minConfidence)},...n.minLabelConfidence===void 0?{}:{labelConfidence:Ni(n.minLabelConfidence)},...n.minImportance===void 0?{}:{importance:Ni(n.minImportance)},...n.minDwellSeconds===void 0?{}:{dwellSeconds:Math.round(n.minDwellSeconds)+1},zones:[...i],...r===`object-event`&&o!==void 0?{crossingEnabled:!0,crossingZoneId:i[0]??``,crossingDirection:o}:{},...n.sensorKinds?.[0]===void 0?{}:{sensorKind:n.sensorKinds[0]},...n.eventTypeTokens?.[0]===void 0?{}:{eventType:n.eventTypeTokens[0]},packagePhase:s,source:n.source!==void 0&&n.source!==`any`?n.source:Ci(r),...n.customZones!==void 0&&n.customZones.length>0?{bboxEnabled:!0}:{},...n.occupancy===void 0?{}:{occupancy:Ii(n.occupancy)},onlyRuleId:e.id}}function Ii(e){let t=Math.max(1,Math.round(e.count)),n={zoneId:e.zoneId??``,zoneName:``,className:e.className??``,threshold:t};if(e.op===`became-free`)return{...n,count:0,previousCount:t,occupied:!1};if(e.op===`<=`){let t=Math.max(0,Math.round(e.count));return{...n,count:t,previousCount:t+1,occupied:t>0}}return{...n,count:t,previousCount:Math.max(0,t-1),occupied:!0}}function Li(e){let t=[];return e.conditions.deviceState!==void 0&&t.push({conditionId:`deviceState`,note:`This rule is gated on device #${e.conditions.deviceState.deviceId} being in a given state. The gate reads the REAL device — put it in that state first, or the simulation fails closed exactly as production would.`}),e.conditions.customZones!==void 0&&e.conditions.customZones.length>0&&t.push({conditionId:`customZones`,note:`This rule matches viewer-drawn polygons against the subject bbox. The bbox below is enabled but centred — move it over the polygon, or the condition fails.`}),t}function Ri(e){return{form:Fi(e),caveats:Li(e),ruleName:e.name}}var zi=null;function Bi(e){zi=e}function Vi(){return zi}function Hi(){zi=null}var Ui=[`n/a`,`clear`,`suppressed`,`bypassed`],Wi=[`live`,`none`,`unavailable`,`unattachable`];function Gi(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function G(e,t){let n=e[t];return typeof n==`string`?n:void 0}function Ki(e,t){let n=e[t];return Array.isArray(n)?n.filter(e=>typeof e==`string`):[]}function qi(e){if(!Gi(e))return null;let t=G(e,`ruleId`),n=G(e,`ruleName`),r=G(e,`cooldown`),i=Ui.find(e=>e===r);if(t===void 0||n===void 0||i===void 0||typeof e.matched!=`boolean`)return null;let a=G(e,`failedCondition`),o=Array.isArray(e.matchedOn)?Ki(e,`matchedOn`):void 0;return{ruleId:t,ruleName:n,matched:e.matched,...a===void 0?{}:{failedCondition:a},...o===void 0?{}:{matchedOn:o},cooldown:i,enqueued:typeof e.enqueued==`number`?e.enqueued:0,targetIds:Ki(e,`targetIds`)}}function Ji(e){if(!Gi(e))return null;let t=G(e,`recordId`),n=G(e,`delivery`),r=G(e,`still`),i=Wi.find(e=>e===r);if(t===void 0||n===void 0||i===void 0||e.origin!==`synthetic`)return null;let a=Array.isArray(e.outcomes)?e.outcomes:[],o=[];for(let e of a){let t=qi(e);t!==null&&o.push(t)}let s=G(e,`droppedBy`);return{recordId:t,origin:`synthetic`,delivery:n,candidates:typeof e.candidates==`number`?e.candidates:0,outcomes:o,still:i,notes:Ki(e,`notes`),...s===void 0?{}:{droppedBy:s}}}function Yi(e){if(e.droppedBy!==void 0)return`Dropped before evaluation (${e.droppedBy}) — no rule was consulted.`;if(e.candidates===0)return`No enabled rule declares the "${e.delivery}" delivery, so nothing was evaluated.`;let t=e.outcomes.filter(e=>e.matched).length,n=e.outcomes.reduce((e,t)=>e+t.enqueued,0);return t===0?`${e.candidates} candidate rule${e.candidates===1?``:`s`} evaluated, none matched.`:`${t} of ${e.candidates} candidate rule${e.candidates===1?``:`s`} matched — ${n} notification${n===1?``:`s`} enqueued.`}var Xi=new Set([`sensor`,`control`,`custom`]);function Zi({form:e,cameras:t,taxonomy:n,kinds:r,kindsLoading:i,onPatch:a}){let s=e.deviceId===null?[]:[e.deviceId],c=ne(`classes`,n);if(e.trigger===`device-event`)return x(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-2`,children:[k(`div`,{className:`text-[11px] font-semibold text-foreground`,children:`What happened`}),k(Qi,{form:e,kinds:r,loading:i,onPatch:a})]});if(e.trigger===`audio-event`){let n=r.filter(e=>e.category===`audio`&&e.level===`sub`).map(e=>({value:e.kind,label:e.label}));return x(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-2`,children:[k(`div`,{className:`text-[11px] font-semibold text-foreground`,children:`What happened`}),x(`div`,{children:[k(`label`,{className:U,children:`Audio classes`}),k(H,{options:n,value:e.classNames,onChange:e=>a({classNames:e}),loading:i,emptyHint:e.deviceId===null?`Pick a camera first — the audio vocabulary is per camera.`:`This camera advertises no audio kinds. The audio classifier is probably off for it.`,placeholder:`Audio class id…`})]}),x(`div`,{children:[k(`label`,{className:U,children:`Zones`}),k(sr,{deviceIds:s,cameras:t,value:e.zones,onChange:e=>a({zones:e})})]})]})}return e.trigger===`occupancy-event`?x(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-2`,children:[k(`div`,{className:`text-[11px] font-semibold text-foreground`,children:`What happened`}),k($i,{form:e,cameras:t,taxonomy:n,onPatch:a})]}):x(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-2`,children:[k(`div`,{className:`text-[11px] font-semibold text-foreground`,children:`What happened`}),x(`div`,{children:[k(`label`,{className:U,children:`Detected classes`}),c===null?k(nr,{value:e.classNames,placeholder:`Class id (person, car…)`,onChange:e=>a({classNames:e})}):k(rr,{picker:c,value:e.classNames,onChange:e=>a({classNames:e})})]}),x(`div`,{children:[k(`label`,{className:U,children:`Zones the subject is in`}),k(sr,{deviceIds:s,cameras:t,value:e.zones,onChange:e=>a({zones:e})})]}),e.trigger===`package-event`&&x(`div`,{className:`max-w-[14rem]`,children:[k(`label`,{className:`block text-[11px] font-medium text-foreground`,children:`Package phase`}),k(o,{value:e.packagePhase,options:[{value:``,label:`— none —`},{value:`delivered`,label:`Delivered`},{value:`picked-up`,label:`Picked up`}],onChange:e=>a({packagePhase:e.target.value===`delivered`?`delivered`:e.target.value===`picked-up`?`picked-up`:``})})]})]})}function Qi({form:e,kinds:t,loading:n,onPatch:r}){let i=t.filter(e=>Xi.has(e.category)),a=i.find(t=>t.kind===e.sensorKind);return x(w,{children:[x(`div`,{children:[k(`label`,{className:U,children:`Event kind`}),k(o,{value:e.sensorKind,options:[{value:``,label:n?`Loading kinds…`:`— pick a kind —`},...i.map(e=>({value:e.kind,label:`${e.label} (${e.category})`}))],onChange:e=>{let t=i.find(t=>t.kind===e.target.value);r({sensorKind:t?.kind??``,sourceDeviceId:t?.source.deviceId??null})}}),!n&&i.length===0&&k(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:e.deviceId===null?`Pick a camera first — sensor and control kinds come from the devices linked to it.`:`This camera has no linked sensor or control device, so it can produce no device event. Link one on the camera page first.`})]}),x(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[x(`div`,{children:[k(`label`,{className:U,children:`Source device`}),k(f,{type:`number`,value:e.sourceDeviceId===null?``:String(e.sourceDeviceId),placeholder:`the camera itself`,onChange:e=>r({sourceDeviceId:Oi(e.target.value)??null})}),k(`p`,{className:W,children:a===void 0?`The linked device whose state changed. Filled in for you when you pick a kind.`:`Filled in from "${a.label}" — contributed by device #${a.source.deviceId} via the ${a.source.capName} capability.`})]}),x(`div`,{children:[k(`label`,{className:U,children:`Event type token`}),k(f,{value:e.eventType,placeholder:`press, press_long…`,onChange:e=>r({eventType:e.target.value})}),k(`p`,{className:W,children:`Only event-emitter sources carry one. A passive sensor emits none, and a rule gating on a token would fail closed for it.`})]})]})]})}function $i({form:e,cameras:t,taxonomy:n,onPatch:r}){let i=e.deviceId===null?[]:[e.deviceId],a=ne(`occupancy`,n),s=a===null?[]:a.groups.flatMap(e=>e.options),c=e.occupancy,l=e=>r({occupancy:{...c,...e}});return x(w,{children:[x(`div`,{children:[k(`label`,{className:U,children:`Zone`}),k(sr,{deviceIds:i,cameras:t,value:c.zoneId===``?[]:[c.zoneId],onChange:e=>l({zoneId:e[e.length-1]??``})}),k(`p`,{className:W,children:`Leave empty for the whole frame.`})]}),x(`div`,{className:`max-w-[14rem]`,children:[k(`label`,{className:U,children:`Class`}),k(o,{value:c.className,options:[{value:``,label:`— any class —`},...s.map(e=>({value:e.value,label:e.label}))],onChange:e=>l({className:e.target.value})})]}),x(`div`,{className:`flex flex-wrap items-end gap-3`,children:[x(`label`,{className:`text-[11px] text-foreground-subtle`,children:[`Count now`,k(f,{type:`number`,min:0,className:`w-20`,value:String(c.count),onChange:e=>l({count:Oi(e.target.value)??0})})]}),x(`label`,{className:`text-[11px] text-foreground-subtle`,children:[`Count before`,k(f,{type:`number`,min:0,className:`w-20`,value:String(c.previousCount),onChange:e=>l({previousCount:Oi(e.target.value)??0})})]}),x(`label`,{className:`text-[11px] text-foreground-subtle`,children:[`Threshold`,k(f,{type:`number`,min:1,className:`w-20`,value:String(c.threshold),onChange:e=>l({threshold:Oi(e.target.value)??1})})]}),x(`label`,{className:`flex items-center gap-2 pb-1 text-[11px] text-foreground`,children:[k(p,{checked:c.occupied,onCheckedChange:e=>l({occupied:e}),"aria-label":`occupied`}),`Occupied`]})]})]})}function ea({form:e,cameras:t,onPatch:n}){let r=e.deviceId===null?[]:[e.deviceId];return x(`details`,{className:`rounded-md border border-border px-3 py-2`,children:[k(`summary`,{className:`cursor-pointer text-[11px] font-semibold text-foreground`,children:`Advanced`}),x(`div`,{className:`mt-2 space-y-3`,children:[e.trigger===`object-event`&&x(`div`,{children:[x(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[k(p,{checked:e.crossingEnabled,onCheckedChange:e=>n({crossingEnabled:e}),"aria-label":`zone crossing`}),`This event is a confirmed zone crossing`]}),e.crossingEnabled&&x(`div`,{className:`mt-1 space-y-1.5`,children:[k(`div`,{className:`max-w-[12rem]`,children:k(o,{value:e.crossingDirection,options:[{value:`enter`,label:`Entered the zone`},{value:`exit`,label:`Left the zone`}],onChange:e=>n({crossingDirection:e.target.value===`exit`?`exit`:`enter`})})}),k(sr,{deviceIds:r,cameras:t,value:e.crossingZoneId===``?[]:[e.crossingZoneId],onChange:e=>n({crossingZoneId:e[e.length-1]??``})})]})]}),x(`div`,{children:[x(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[k(p,{checked:e.bboxEnabled,onCheckedChange:e=>n({bboxEnabled:e}),"aria-label":`bounding box`}),`Carry a bounding box`]}),k(`p`,{className:W,children:"Normalized 0–1, top-left origin. Feeds the `customZones` condition and decides how the still is cropped or boxed."}),e.bboxEnabled&&k(`div`,{className:`mt-1 flex flex-wrap gap-2`,children:[`x`,`y`,`w`,`h`].map(t=>x(`label`,{className:`text-[11px] text-foreground-subtle`,children:[t,k(f,{type:`number`,min:0,max:1,step:.05,className:`w-20`,value:String(e.bbox[t]),onChange:r=>n({bbox:{...e.bbox,[t]:Oi(r.target.value)??0}})})]},t))})]}),x(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[x(`div`,{children:[k(`label`,{className:U,children:`Happened at`}),x(`div`,{className:`flex items-center gap-2`,children:[k(f,{type:`datetime-local`,value:e.timestampLocal,onChange:e=>n({timestampLocal:e.target.value})}),e.timestampLocal===``?k(u,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>n({timestampLocal:Ai(Date.now())}),children:`Set`}):k(u,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>n({timestampLocal:``}),children:`Now`})]}),k(`p`,{className:W,children:`Empty = now. Set it to a time inside (or outside) a rule's schedule window to test the schedule without waiting for the hour.`})]}),x(`div`,{children:[k(`label`,{className:U,children:`Detection source`}),k(o,{value:e.source,options:[{value:``,label:`— unset (reads as pipeline) —`},{value:`pipeline`,label:`Pipeline`},{value:`onboard`,label:`Onboard (camera)`},{value:`sensor`,label:`Sensor`},{value:`audio`,label:`Audio`}],onChange:e=>{let t=e.target.value;n({source:t===`pipeline`||t===`onboard`||t===`sensor`||t===`audio`?t:``})}})]})]})]})]})}function ta({checked:e,label:t,hint:n,danger:r=!1,onChange:i}){return x(`div`,{children:[x(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[k(p,{checked:e,onCheckedChange:i,"aria-label":t}),t,r&&k(s,{variant:`danger`,children:`actuates devices`})]}),k(`p`,{className:W,children:n})]})}b();var na={live:`A live snapshot of the camera was taken and attached.`,none:`No still was requested.`,unavailable:`A still was requested but the camera could not produce one.`,unattachable:`This trigger cannot carry a still at all — an audio or occupancy notification freezes no media owner, so it ships text-only in production too. This is not a limit of the test.`},ra={"n/a":`The rule did not match, so no cooldown was consulted.`,clear:`No cooldown was in effect — the rule was free to fire.`,suppressed:`A cooldown from an earlier fire silenced this one. Re-run with "Ignore cooldown".`,bypassed:`A cooldown was in effect and was deliberately ignored for this run.`};function ia({result:e,targetName:t}){return x(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-3`,children:[k(`p`,{className:`text-xs font-medium text-foreground`,children:Yi(e)}),x(`div`,{className:`flex flex-wrap items-center gap-2 text-[11px] text-foreground-subtle`,children:[k(aa,{recordId:e.recordId}),x(`span`,{children:[`delivery `,k(`span`,{className:`text-foreground`,children:e.delivery})]}),x(`span`,{children:[`candidates `,k(`span`,{className:`text-foreground`,children:e.candidates})]}),x(`span`,{title:na[e.still],children:[`still `,k(`span`,{className:`text-foreground`,children:e.still})]}),e.droppedBy!==void 0&&x(s,{variant:`warning`,children:[`dropped: `,e.droppedBy]})]}),e.notes.length>0&&k(`ul`,{className:`space-y-1 rounded-md border border-border bg-surface px-2.5 py-2`,children:e.notes.map(e=>k(`li`,{className:`text-[11px] leading-snug text-foreground-subtle`,children:e},e))}),e.outcomes.length===0?x(`p`,{className:`text-[11px] text-foreground-subtle`,children:[`No rule was evaluated. Either no enabled rule declares the`,` `,k(`span`,{className:`text-foreground`,children:e.delivery}),` delivery, or the ones that do were filtered out before evaluation — the notes above say which.`]}):k(`ul`,{className:`divide-y divide-border rounded-md border border-border`,children:e.outcomes.map(e=>k(oa,{outcome:e,targetName:t},e.ruleId))})]})}function aa({recordId:e}){let[t,n]=D(!1);return x(`span`,{className:`inline-flex items-center gap-1 rounded border border-border px-1.5 py-0.5`,children:[k(`code`,{className:`text-[10px] text-foreground`,children:e}),k(u,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>{let t=navigator.clipboard;t!==void 0&&t.writeText(e).then(()=>{n(!0),setTimeout(()=>n(!1),1500)},()=>n(!1))},title:`Copy record id`,children:k(xe,{className:`h-3 w-3`})}),t&&k(`span`,{className:`text-[10px] text-success`,children:`copied`})]})}function oa({outcome:e,targetName:t}){return x(`li`,{className:`space-y-1 px-2.5 py-2`,children:[x(`div`,{className:`flex items-center gap-2`,children:[e.matched?k(be,{className:`h-3.5 w-3.5 shrink-0 text-success`}):k(Me,{className:`h-3.5 w-3.5 shrink-0 text-foreground-subtle`}),k(`span`,{className:`min-w-0 flex-1 truncate text-xs text-foreground`,children:e.ruleName}),x(`span`,{className:`shrink-0 text-[10px] text-foreground-subtle`,title:ra[e.cooldown],children:[`cooldown: `,e.cooldown]})]}),!e.matched&&k(`p`,{className:`pl-5 text-[11px] text-foreground-subtle`,children:e.failedCondition===void 0?`Did not match. The engine reported no failing condition id.`:x(w,{children:[`Did not match — first failing condition`,` `,k(`code`,{className:`text-foreground`,children:e.failedCondition}),`.`]})}),e.matched&&x(`p`,{className:`pl-5 text-[11px] text-foreground-subtle`,children:[e.enqueued,` outbox row`,e.enqueued===1?``:`s`,` enqueued`,e.targetIds.length>0?` → ${e.targetIds.map(t).join(`, `)}`:` — no target resolved, so nothing will be delivered`,`.`]}),e.matchedOn!==void 0&&e.matchedOn.length>0&&x(`p`,{className:`pl-5 text-[10px] text-foreground-muted`,children:[`matched on: `,e.matchedOn.join(`, `)]})]})}b();var sa=`pipeline-analytics`,ca=`nc.injectTestEvent`;function la(){let e=I(),[t,n]=D(()=>Vi()?.form??Ei()),[i]=D(()=>Vi()?.caveats??[]),[a]=D(()=>Vi()?.ruleName??null);A(()=>Hi(),[]);let[s,c]=D(null),[l,d]=D(!1),[p,m]=D(null),h=e=>n(t=>({...t,...e})),g=C({queryKey:ui,queryFn:async()=>(await e.trpcClient.deviceManager.listAll.query({})).filter(e=>e.type===N.Camera).map(e=>({id:e.id,name:e.name}))}),v=C({queryKey:li,queryFn:()=>e.trpcClient.notificationRules.getConditionCatalog.query({})}),y=C({queryKey:si,queryFn:async()=>(await e.trpcClient.notificationRules.listRules.query({})).rules}),b=C({queryKey:ci,queryFn:()=>e.trpcClient.notificationOutput.listTargets.query({})}),w=t.deviceId,T=C({queryKey:[[`pipelineAnalytics`,`listEventKindsBatch`],{deviceId:w}],enabled:w!==null,staleTime:6e4,queryFn:async()=>w===null?[]:(await e.trpcClient.pipelineAnalytics.listEventKindsBatch.query({deviceIds:[w]})).flatMap(e=>[...e.kinds])}),E=g.data??[],j=v.data?.taxonomy,M=T.data??[],ee=S(()=>{let e=new Map;for(let t of b.data??[])e.set(t.id,t.name);return e},[b.data]),P=O({mutationFn:async()=>{let n=ji(t);if(n===null)throw Error(`Pick a camera first.`);return e.trpcClient.addons.custom.mutate({addonId:sa,action:ca,input:n})},onMutate:()=>{c(null),d(!1),m(null)},onSuccess:e=>{let t=Ji(e);c(t),d(t===null)},onError:e=>m(e instanceof Error?e.message:`The simulation failed.`)}),te=Si(t.trigger),F=y.data?.find(e=>e.id===t.onlyRuleId);return x(z,{icon:ze,title:`Simulate an event`,subtitle:`Inject a synthetic detection, doorbell press or occupancy edge and see exactly which rules match it, which condition each one fails on, and what would be delivered. Nothing is persisted — no track, no event row, no media.`,children:[g.isError&&k(r,{title:`Failed to load cameras`,message:g.error instanceof Error?g.error.message:`Unknown error`,onRetry:()=>void g.refetch()}),a!==null&&x(`div`,{className:`rounded-md border border-primary/40 bg-primary/5 px-3 py-2 text-[11px] text-foreground`,children:[`Seeded from the rule `,k(`span`,{className:`font-medium`,children:a}),`. Only that rule will be evaluated — clear "Evaluate only one rule" below to run the whole rule set.`]}),i.length>0&&k(`div`,{className:`space-y-1 rounded-md border border-warning/40 bg-warning/5 px-3 py-2`,children:i.map(e=>x(`p`,{className:`flex gap-1.5 text-[11px] text-foreground`,children:[k(Le,{className:`mt-0.5 h-3 w-3 shrink-0 text-warning`}),k(`span`,{children:e.note})]},e.conditionId))}),x(_,{className:`space-y-4`,children:[x(`div`,{children:[k(`label`,{className:U,children:`Camera`}),k(o,{"data-testid":`simulate-camera`,value:t.deviceId===null?``:String(t.deviceId),options:[{value:``,label:E.length===0?`Loading cameras…`:`— pick a camera —`},...E.map(e=>({value:String(e.id),label:e.name}))],onChange:e=>{h({deviceId:Oi(e.target.value)??null,zones:[],crossingZoneId:``,sensorKind:``,sourceDeviceId:null,occupancy:{...t.occupancy,zoneId:``}})}}),k(`p`,{className:W,children:`The camera the event is attributed to — what a notification shows.`})]}),x(`div`,{children:[k(`label`,{className:U,children:`Trigger`}),k(o,{"data-testid":`simulate-trigger`,value:t.trigger,options:bi.map(e=>({value:e.value,label:e.label})),onChange:e=>{let n=xi(e.target.value);if(!n)return;let r=Ci(t.trigger);h({trigger:n,source:t.source===``||t.source===r?Ci(n):t.source})}}),x(`p`,{className:W,children:[bi.find(e=>e.value===t.trigger)?.hint,` Only rules whose trigger is `,k(`span`,{className:`text-foreground`,children:te}),` are candidates.`]})]}),k(Zi,{form:t,cameras:E,taxonomy:j,kinds:M,kindsLoading:T.isLoading,onPatch:h}),x(`details`,{className:`rounded-md border border-border px-3 py-2`,open:!0,children:[k(`summary`,{className:`cursor-pointer text-[11px] font-semibold text-foreground`,children:`Quality`}),x(`div`,{className:`mt-2 space-y-3`,children:[k(`p`,{className:W,children:`Every field here can be left EMPTY, and empty is a real state: a rule with a minimum confidence FAILS on a subject that carries none. Leave one blank to reproduce exactly that.`}),x(`div`,{children:[k(`label`,{className:U,children:`Label (identity name / plate / subclass)`}),k(f,{value:t.label,placeholder:`e.g. Marco, AB123CD`,onChange:e=>h({label:e.target.value})})]}),x(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[x(`div`,{children:[k(`label`,{className:U,children:`Detection confidence`}),k(ir,{value:t.confidence,min:0,max:1,step:.05,onChange:e=>h({confidence:e})})]}),x(`div`,{children:[k(`label`,{className:U,children:`Label-match confidence`}),k(ir,{value:t.labelConfidence,min:0,max:1,step:.05,onChange:e=>h({labelConfidence:e})})]}),x(`div`,{children:[k(`label`,{className:U,children:`Importance`}),k(ir,{value:t.importance,min:0,max:1,step:.05,onChange:e=>h({importance:e})})]}),x(`div`,{children:[k(`label`,{className:U,children:`Dwell (seconds)`}),k(ir,{value:t.dwellSeconds,min:0,step:1,onChange:e=>h({dwellSeconds:e})})]})]})]})]}),k(ea,{form:t,cameras:E,onPatch:h}),x(`div`,{className:`space-y-2 rounded-md border border-border px-3 py-2`,children:[k(`div`,{className:`text-[11px] font-semibold text-foreground`,children:`How to run it`}),k(ta,{checked:t.bypassCooldown,label:`Ignore the cooldown`,hint:`A rule that already fired recently is normally silenced. Turn this on to fire anyway; leave it off to SEE the suppression.`,onChange:e=>h({bypassCooldown:e})}),k(ta,{checked:t.bypassMute,label:`Ignore mutes and snoozes`,hint:`A muted camera or a snoozed rule drops the event before any rule is consulted.`,onChange:e=>h({bypassMute:e})}),k(ta,{checked:t.runActions,danger:!0,label:`Run the rule's actions — this actuates real devices`,hint:`A matched rule's onTrigger sequences run for real: locks unlock, lights switch, sirens sound. Off unless you mean it.`,onChange:e=>h({runActions:e})}),x(`div`,{className:`max-w-[14rem]`,children:[k(`label`,{className:U,children:`Still image`}),k(o,{value:t.still,options:[{value:`live`,label:`Live snapshot of the camera`},{value:`none`,label:`No image`}],onChange:e=>h({still:e.target.value===`none`?`none`:`live`})})]}),x(`div`,{children:[k(`label`,{className:U,children:`Evaluate only one rule`}),k(o,{value:t.onlyRuleId,options:[{value:``,label:`— every enabled rule —`},...(y.data??[]).map(e=>({value:e.id,label:e.name}))],onChange:e=>h({onlyRuleId:e.target.value})}),t.onlyRuleId.length>0&&F===void 0&&x(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:[`Rule `,k(`code`,{children:t.onlyRuleId}),` is not in the current list — it may have been deleted. The run will find no candidate.`]})]})]}),p!==null&&k(`div`,{className:`rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger`,children:p}),x(`div`,{className:`flex items-center justify-between gap-2`,children:[k(`p`,{className:`text-[10px] text-foreground-subtle`,children:`Nothing is persisted: no track, no event row, no stored media. Delivery is real.`}),x(u,{size:`sm`,type:`button`,disabled:P.isPending||!Di(t),onClick:()=>P.mutate(),children:[P.isPending?k(L,{className:`h-3.5 w-3.5 animate-spin`}):k(ze,{className:`h-3.5 w-3.5`}),`Inject event`]})]})]}),l&&k(`div`,{className:`rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-[11px] text-foreground`,children:`The hub answered, but this build could not read the answer. That is what a hub older than the simulator looks like — update the server, then re-run.`}),s!==null&&k(ia,{result:s,targetName:e=>ee.get(e)??e})]})}b();var K=`block text-[11px] font-medium text-foreground mb-1`,ua=`mt-1 text-[10px] text-foreground-subtle`;function q({title:e,hint:t,children:n}){return x(`div`,{className:`rounded-md border border-border px-3 py-3`,children:[k(`div`,{className:`mb-2 text-[11px] font-semibold text-foreground`,children:e}),t!==void 0&&k(`p`,{className:`mb-2 text-[10px] text-foreground-subtle`,children:t}),k(`div`,{className:`space-y-3`,children:n})]})}function da({problems:e,testId:t=`digest-problems`}){return e.length===0?null:x(`div`,{className:`rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-[11px] text-danger`,"data-testid":t,children:[x(`div`,{className:`mb-1 flex items-center gap-1.5 font-medium`,children:[k(Le,{className:`h-3.5 w-3.5`}),`This rule could never produce anything, so it cannot be saved:`]}),k(`ul`,{className:`list-disc space-y-0.5 pl-4`,children:e.map(e=>k(`li`,{children:e},e))})]})}function fa({warnings:e,testId:t=`digest-warnings`}){return e.length===0?null:x(`div`,{className:`rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-[11px] text-warning`,"data-testid":t,children:[x(`div`,{className:`mb-1 flex items-center gap-1.5 font-medium`,children:[k(ke,{className:`h-3.5 w-3.5`}),`Worth knowing:`]}),k(`ul`,{className:`list-disc space-y-0.5 pl-4`,children:e.map(e=>k(`li`,{children:e},e))})]})}function pa({cameras:e,value:t,onChange:n,loading:r=!1,hint:i}){let[a,o]=D(``),s=S(()=>{let t=a.trim().toLowerCase();return t.length===0?e:e.filter(e=>e.name.toLowerCase().includes(t))},[e,a]),c=e=>n(t.includes(e)?t.filter(t=>t!==e):[...t,e]);return r?k(`p`,{className:`text-[11px] text-foreground-subtle`,children:`Loading cameras…`}):x(`div`,{className:`space-y-2`,children:[x(`div`,{className:`flex items-center gap-2`,children:[k(f,{className:`flex-1`,value:a,placeholder:`Search a camera…`,leftSlot:k(Ee,{className:`h-3.5 w-3.5 text-foreground-subtle`}),onChange:e=>o(e.target.value),"data-testid":`digest-camera-search`}),k(`span`,{className:`whitespace-nowrap text-[11px] text-foreground-subtle`,children:t.length===0?`No camera selected`:`${t.length} selected`})]}),e.length===0?k(`p`,{className:`rounded border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:`No camera is available on this hub.`}):x(`div`,{className:`max-h-56 divide-y divide-border overflow-y-auto rounded-md border border-border`,"data-testid":`digest-camera-list`,children:[s.map(e=>x(`label`,{className:`flex cursor-pointer items-center gap-2.5 px-3 py-1.5 text-xs text-foreground hover:bg-surface-hover`,children:[k(`input`,{type:`checkbox`,checked:t.includes(e.id),onChange:()=>c(e.id),className:`accent-primary`,"data-testid":`digest-camera-${e.id}`}),k(`span`,{className:`flex-1 truncate`,children:e.name}),x(`span`,{className:`text-[10px] text-foreground-subtle`,children:[`#`,e.id]})]},e.id)),s.length===0&&k(`p`,{className:`px-3 py-2 text-[11px] text-foreground-subtle`,children:`No camera matches that search.`})]}),i!==void 0&&k(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:i})]})}function ma({targets:e,value:t,onChange:n}){let r=e=>n(t.includes(e)?t.filter(t=>t!==e):[...t,e]);return e.length===0?k(`p`,{className:`text-[11px] text-foreground-subtle`,children:`No delivery target is configured. Add one on the Targets tab first — without one the artefact is rendered and thrown away.`}):k(`div`,{className:`divide-y divide-border rounded-md border border-border`,"data-testid":`digest-targets`,children:e.map(e=>x(`label`,{className:`flex cursor-pointer items-center gap-2.5 px-3 py-1.5 text-xs text-foreground hover:bg-surface-hover`,children:[k(`input`,{type:`checkbox`,checked:t.includes(e.id),onChange:()=>r(e.id),className:`accent-primary`,"data-testid":`digest-target-${e.id}`}),k(`span`,{className:`flex-1 truncate`,children:e.name}),!e.enabled&&k(s,{variant:`warning`,children:`disabled`})]},e.id))})}function J({label:e,value:t,onChange:n,min:r,max:i,step:a,hint:o,emptyPlaceholder:s,testId:c,disabled:l=!1}){return x(`div`,{children:[k(`label`,{className:K,children:e}),k(f,{type:`number`,value:t===void 0?``:String(t),disabled:l,...r===void 0?{}:{min:r},...i===void 0?{}:{max:i},...a===void 0?{}:{step:a},...s===void 0?{}:{placeholder:s},...c===void 0?{}:{"data-testid":c},onChange:e=>{let t=e.target.value.trim();if(t.length===0){n(void 0);return}let r=Number(t);Number.isFinite(r)&&n(r)}}),o!==void 0&&k(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:o})]})}function ha({label:e,checked:t,onChange:n,hint:r,testId:i}){return x(`div`,{children:[x(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[k(p,{checked:t,onCheckedChange:n,"aria-label":e,...i===void 0?{}:{"data-testid":i}}),e]}),r!==void 0&&k(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:r})]})}function ga({title:e,body:t,onTitleChange:n,onBodyChange:r,variables:i,testIdPrefix:a}){return x(`div`,{className:`space-y-2`,children:[x(`div`,{children:[k(`label`,{className:K,children:`Notification title`}),k(f,{value:e,onChange:e=>n(e.target.value),"data-testid":`${a}-title`})]}),x(`div`,{children:[k(`label`,{className:K,children:`Notification body`}),k(`textarea`,{value:t,rows:2,onChange:e=>r(e.target.value),"data-testid":`${a}-body`,className:`w-full rounded-md border border-border bg-surface px-2.5 py-1.5 text-xs text-foreground placeholder:text-foreground-subtle focus:outline-none focus:ring-1 focus:ring-primary`})]}),x(`p`,{className:`text-[10px] text-foreground-subtle`,children:[`Leave both blank to use the hub's own wording (editable on the Texts tab). Variables:`,` `,i.map(e=>k(`code`,{className:`mr-1`,children:`{{${e}}}`},e))]})]})}function _a({open:e,ruleName:t,windowDescription:n,targetDescription:r,pending:i,onConfirm:a,onCancel:o,extra:s,confirmDisabled:c=!1}){return e?k(l,{open:!0,onOpenChange:e=>!e&&o(),children:k(g,{width:`sm`,children:x(`div`,{className:`space-y-3`,"data-testid":`digest-test-confirm`,children:[x(`h3`,{className:`flex items-center gap-2 text-sm font-semibold text-foreground`,children:[k(De,{className:`h-4 w-4 text-warning`}),`Send a real notification now?`]}),x(`p`,{className:`text-xs text-foreground-subtle`,children:[`"`,t,`" will be produced over `,n,` and DELIVERED to`,` `,r,` — on every phone that target reaches, right now. This is not a dry run.`]}),k(`p`,{className:`text-[11px] text-foreground-subtle`,children:`It does not consume the schedule: the next scheduled run still happens.`}),s,x(`div`,{className:`flex justify-end gap-2`,children:[k(u,{size:`sm`,variant:`secondary`,type:`button`,onClick:o,children:`Cancel`}),k(u,{size:`sm`,type:`button`,disabled:i||c,onClick:a,"data-testid":`digest-test-confirm-send`,children:i?`Sending…`:`Produce and send`})]})]})})}):null}function va(e){if(e<60)return`${e}s`;let t=Math.floor(e/60);if(t<60)return`${t}m`;let n=Math.floor(t/60),r=t%60;return r===0?`${n}h`:`${n}h${r}m`}var ya=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function ba(e){let t=Math.floor(e/60),n=e%60;return`${String(t).padStart(2,`0`)}:${String(n).padStart(2,`0`)}`}function xa(e){let t=e.windows[0];if(t===void 0)return`No window`;let n=t.days.toSorted((e,t)=>e-t).map(e=>ya[e]??String(e)).join(` `),r=t.startMinute>t.endMinute?` (overnight)`:``,i=e.windows.length-1,a=e.invert===!0?` · outside`:``;return`${n} ${ba(t.startMinute)}–${ba(t.endMinute)}${r}${i>0?` +${i}`:``}${a}`}function Sa(e,t,n){if(e===void 0||e<=0)return n;let r=Math.max(0,t-e);return`${va(Math.round(r/1e3))} ago`}function Ca(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function wa(e){return Array.isArray(e)?`[${e.map(wa).join(`,`)}]`:Ca(e)?`{${Object.keys(e).toSorted().map(t=>`${JSON.stringify(t)}:${wa(e[t])}`).join(`,`)}}`:JSON.stringify(e)??`null`}function Y(e,t){return wa(e)===wa(t)}function Ta(e){return e.map(e=>({targetId:e}))}var X=`pipeline-analytics`,Ea=`nc.getTexts`,Da=`nc.setLanguage`,Oa=`nc.setTextOverrides`,ka={en:`English`,it:`Italiano`};function Aa(e){return e===`en`||e===`it`}function ja(e){return e===`override`||e===`shipped`||e===`fallback`}function Ma(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Na(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(typeof n!=`string`)return null;t.push(n)}return t}function Pa(e){if(!Ma(e))return null;let{key:t,shipped:n,shippedLanguage:r,override:i,effective:a,source:o}=e;if(typeof t!=`string`||t.length===0||typeof n!=`string`||typeof a!=`string`||!Aa(r)||!ja(o)||i!==null&&typeof i!=`string`)return null;let s=Na(e.placeholders),c=Na(e.pluralCategories);return s===null||c===null?null:{key:t,shipped:n,shippedLanguage:r,override:i,effective:a,source:o,placeholders:s,pluralCategories:c}}function Fa(e){if(!Ma(e))return null;let{language:t,activeLanguage:n}=e;if(!Aa(t)||!Aa(n))return null;let r=Na(e.languages);if(r===null||r.length===0)return null;let i=[];for(let e of r)Aa(e)&&i.push(e);if(i.length===0)return null;let a=e.entries;if(!Array.isArray(a))return null;let o=[];for(let e of a){let t=Pa(e);if(t===null)return null;o.push(t)}return{language:t,activeLanguage:n,languages:i,entries:o}}function Ia(e,t){return t.get(e.key)??e.override??e.shipped}function La(e,t){let n={};for(let r of e){let e=t.get(r.key);if(e===void 0)continue;let i=e.trim().length===0||e===r.shipped?null:e;i!==r.override&&(n[r.key]=i)}return n}function Ra(e,t){return Object.keys(La(e,t)).length}function za(e,t){let n=t.toLowerCase().split(/\s+/).filter(e=>e.length>0);return n.length===0?e:e.filter(e=>{let t=`${e.key}\n${e.shipped}\n${e.override??``}`.toLowerCase();return n.every(e=>t.includes(e))})}function Ba(e){return e.placeholders.length===0?`No variables — this text is printed as written.`:`Variables: ${e.placeholders.map(e=>`{{${e}}}`).join(` `)}`}function Va(e){return e.pluralCategories.length===0?null:`This text has one form per count (${e.pluralCategories.join(`, `)}). An override replaces all of them with a single sentence.`}var Ha=`nc.listSummaryRules`,Ua=`nc.upsertSummaryRule`,Wa=`nc.deleteSummaryRule`,Ga=`nc.testSummaryRule`,Ka=3600,qa=86400,Ja=3600,Ya=3600,Xa=3*36e5,Za=[`importance`,`recency`,`dwell`],Qa={importance:`Most important`,recency:`Most recent`,dwell:`Longest stay`};function $a(e){return e.window.kind!==`unsupported`&&!e.readOnly}function Z(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function eo(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(typeof n!=`number`||!Number.isFinite(n))return null;t.push(n)}return t}function to(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(typeof n!=`string`)return null;t.push(n)}return t}function no(e){if(e!==void 0)return typeof e==`string`?e:null}function ro(e){if(e!==void 0)return typeof e==`number`&&Number.isFinite(e)?e:null}function io(e){return Za.some(t=>t===e)}function ao(e){if(!Z(e)||!Array.isArray(e.windows)||e.windows.length===0)return null;let t=[];for(let n of e.windows){if(!Z(n))return null;let e=eo(n.days),r=n.startMinute,i=n.endMinute;if(e===null||e.length===0||typeof r!=`number`||typeof i!=`number`)return null;t.push({days:[...e],startMinute:r,endMinute:i})}let n=no(e.timezone);if(n===null)return null;let r=e.invert;return r!==void 0&&typeof r!=`boolean`?null:{windows:t,...n===void 0?{}:{timezone:n},...r===!0?{invert:!0}:{}}}function oo(e){if(!Z(e)||typeof e.kind!=`string`)return null;if(e.kind===`schedule`){let t=ao(e.schedule);return t===null?null:{kind:`schedule`,schedule:t}}if(e.kind===`motion`){let t=e.quietSeconds,n=e.maxWindowSeconds;return typeof t!=`number`||typeof n!=`number`?null:{kind:`motion`,quietSeconds:t,maxWindowSeconds:n}}return{kind:`unsupported`,raw:e.kind}}function so(e){if(e==null)return;if(!Z(e))return null;let t=e.classes===void 0?void 0:to(e.classes),n=e.classesExclude===void 0?void 0:to(e.classesExclude),r=e.zones===void 0?void 0:to(e.zones);if(t===null||n===null||r===null)return null;let i=ro(e.minImportance),a=ro(e.minDwellSeconds);return i===null||a===null?null:{...t===void 0?{}:{classes:t},...n===void 0?{}:{classesExclude:n},...r===void 0?{}:{zones:r},...i===void 0?{}:{minImportance:i},...a===void 0?{}:{minDwellSeconds:a}}}function co(e){if(e==null)return;if(!Z(e))return null;let t=no(e.title),n=no(e.body);return t===null||n===null?null:{...t===void 0?{}:{title:t},...n===void 0?{}:{body:n}}}function lo(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(!Z(n)||typeof n.targetId!=`string`)return null;let e=n.params;if(e!==void 0&&!Z(e))return null;t.push({targetId:n.targetId,...e===void 0?{}:{params:e}})}return t}function uo(e){if(!Z(e))return null;let{id:t,name:n,enabled:r,maxTiles:i,maxAiImages:a,rank:o,barrierSeconds:s,deliverEmpty:c}=e;if(typeof t!=`string`||t.length===0||typeof n!=`string`||typeof r!=`boolean`||typeof i!=`number`||typeof a!=`number`||!io(o)||typeof s!=`number`||typeof c!=`boolean`||typeof e.priority!=`number`)return null;let l=eo(e.deviceIds),u=oo(e.window),d=lo(e.targets);if(l===null||u===null||d===null)return null;let f=so(e.filters),p=co(e.template);if(f===null||p===null)return null;let m=no(e.captionText),h=ro(e.generatedAt);if(m===null||h===null)return null;let g=e.ai;return{id:t,name:n,enabled:r,deviceIds:l,window:u,...f===void 0?{}:{filters:f},maxTiles:i,maxAiImages:a,rank:o,barrierSeconds:s,targets:d,...p===void 0?{}:{template:p},...m===void 0?{}:{captionText:m},deliverEmpty:c,priority:e.priority,...h===void 0?{}:{generatedAt:h},readOnly:e.readOnly===!0,hasAi:Z(g),aiEnabled:Z(g)&&g.enabled===!0}}function fo(e){if(!Z(e)||!Array.isArray(e.rules))return null;let t=[];for(let n of e.rules){let e=uo(n);if(e===null)return null;t.push(e)}return t}function po(e){if(!Z(e)||typeof e.produced!=`number`)return null;let t=[`tiles`,`cameras`,`matched`,`enqueued`,`mosaicBytes`],n={produced:e.produced};for(let r of t){let t=ro(e[r]);if(t===null)return null;t!==void 0&&(n[r]=t)}for(let t of[`windowStartMs`,`windowEndMs`]){let r=ro(e[t]);if(r===null)return null;r!==void 0&&(n[t]=r)}for(let t of[`mosaicUrl`,`error`]){let r=no(e[t]);if(r===null)return null;r!==void 0&&(n[t]=r)}return{produced:e.produced,...typeof n.tiles==`number`?{tiles:n.tiles}:{},...typeof n.cameras==`number`?{cameras:n.cameras}:{},...typeof n.matched==`number`?{matched:n.matched}:{},...typeof n.enqueued==`number`?{enqueued:n.enqueued}:{},...typeof n.mosaicBytes==`number`?{mosaicBytes:n.mosaicBytes}:{},...typeof n.mosaicUrl==`string`?{mosaicUrl:n.mosaicUrl}:{},...typeof n.windowStartMs==`number`?{windowStartMs:n.windowStartMs}:{},...typeof n.windowEndMs==`number`?{windowEndMs:n.windowEndMs}:{},...typeof n.error==`string`?{error:n.error}:{}}}function mo(){return{name:``,enabled:!0,deviceIds:[],windowKind:`motion`,schedule:void 0,quietSeconds:300,maxWindowSeconds:3600,classes:[],classesExclude:[],zones:[],minImportance:void 0,minDwellSeconds:void 0,maxTiles:9,maxAiImages:6,rank:`importance`,barrierSeconds:120,targetIds:[],templateTitle:``,templateBody:``,captionText:``,deliverEmpty:!1,priority:3}}function ho(e){let t=mo(),n=e.window.kind===`motion`?e.window:null;return{name:e.name,enabled:e.enabled,deviceIds:[...e.deviceIds],windowKind:e.window.kind,schedule:e.window.kind===`schedule`?e.window.schedule:void 0,quietSeconds:n?.quietSeconds??t.quietSeconds,maxWindowSeconds:n?.maxWindowSeconds??t.maxWindowSeconds,classes:[...e.filters?.classes??[]],classesExclude:[...e.filters?.classesExclude??[]],zones:[...e.filters?.zones??[]],minImportance:e.filters?.minImportance,minDwellSeconds:e.filters?.minDwellSeconds,maxTiles:e.maxTiles,maxAiImages:e.maxAiImages,rank:e.rank,barrierSeconds:e.barrierSeconds,targetIds:e.targets.map(e=>e.targetId),templateTitle:e.template?.title??``,templateBody:e.template?.body??``,captionText:e.captionText??``,deliverEmpty:e.deliverEmpty,priority:e.priority}}function go(e){return e.windowKind===`schedule`&&e.schedule!==void 0?{kind:`schedule`,schedule:e.schedule}:{kind:`motion`,quietSeconds:e.quietSeconds,maxWindowSeconds:e.maxWindowSeconds}}function _o(e){let t={...e.classes.length>0?{classes:[...e.classes]}:{},...e.classesExclude.length>0?{classesExclude:[...e.classesExclude]}:{},...e.zones.length>0?{zones:[...e.zones]}:{},...e.minImportance===void 0?{}:{minImportance:e.minImportance},...e.minDwellSeconds===void 0?{}:{minDwellSeconds:e.minDwellSeconds}};return Object.keys(t).length===0?void 0:t}function vo(e){let t=e.templateTitle.trim(),n=e.templateBody.trim();if(!(t.length===0&&n.length===0))return{...t.length>0?{title:t}:{},...n.length>0?{body:n}:{}}}function yo(e){return Ta(e.targetIds)}function bo(e){let t=_o(e),n=vo(e),r=e.captionText.trim();return{name:e.name.trim(),enabled:e.enabled,deviceIds:[...e.deviceIds],window:go(e),...t===void 0?{}:{filters:t},maxTiles:e.maxTiles,maxAiImages:e.maxAiImages,rank:e.rank,barrierSeconds:e.barrierSeconds,targets:yo(e),...n===void 0?{}:{template:n},...r.length>0?{captionText:r}:{},deliverEmpty:e.deliverEmpty,priority:e.priority}}function xo(e,t){let n=bo(e),r={};return n.name!==t.name&&(r.name=n.name),n.enabled!==t.enabled&&(r.enabled=n.enabled),Y(n.deviceIds,t.deviceIds)||(r.deviceIds=n.deviceIds),Y(n.window,t.window)||(r.window=n.window),Y(n.filters,t.filters)||(r.filters=n.filters??null),n.maxTiles!==t.maxTiles&&(r.maxTiles=n.maxTiles),n.maxAiImages!==t.maxAiImages&&(r.maxAiImages=n.maxAiImages),n.rank!==t.rank&&(r.rank=n.rank),n.barrierSeconds!==t.barrierSeconds&&(r.barrierSeconds=n.barrierSeconds),Y(n.targets,t.targets)||(r.targets=n.targets),Y(n.template,t.template)||(r.template=n.template??null),(n.captionText??``)!==(t.captionText??``)&&(r.captionText=n.captionText??``),n.deliverEmpty!==t.deliverEmpty&&(r.deliverEmpty=n.deliverEmpty),n.priority!==t.priority&&(r.priority=n.priority),r}function So(e){let t=[];e.name.trim().length===0&&t.push(`Give the digest a name — it is what the notification is signed with.`),e.deviceIds.length===0&&t.push(`Pick at least one camera. A digest with no camera has nothing to collect.`),e.deviceIds.length>64&&t.push(`A digest spans at most 64 cameras.`),e.targetIds.length===0&&t.push(`Pick at least one delivery target, or the digest is rendered and never sent.`),e.windowKind===`schedule`&&e.schedule===void 0&&t.push(`A scheduled digest needs at least one time window — the digest is produced when that window CLOSES, so without one nothing ever closes.`),e.windowKind===`motion`&&((e.quietSeconds<30||e.quietSeconds>3600)&&t.push(`The quiet period must be between 30s and ${Ka}s.`),(e.maxWindowSeconds<60||e.maxWindowSeconds>86400)&&t.push(`The longest window must be between 60s and ${qa}s.`)),(e.maxTiles<1||e.maxTiles>24)&&t.push(`The mosaic holds between 1 and 24 tiles.`),e.maxAiImages>e.maxTiles&&t.push(`AI images (${e.maxAiImages}) cannot exceed tiles (${e.maxTiles}) — the model cannot judge frames the mosaic does not contain.`),(e.barrierSeconds<0||e.barrierSeconds>3600)&&t.push(`The track-close wait is between 0s and ${Ja}s.`),e.minImportance!==void 0&&(e.minImportance<0||e.minImportance>1)&&t.push(`Minimum importance is a score between 0 and 1.`),e.minDwellSeconds!==void 0&&(e.minDwellSeconds<0||e.minDwellSeconds>3600)&&t.push(`Minimum stay is between 0s and ${Ya}s.`),e.captionText.length>200&&t.push(`The caption is at most 200 characters.`),(e.priority<1||e.priority>5)&&t.push(`Priority is between 1 and 5.`);let n=new Set(e.classesExclude);return e.classes.length>0&&e.classes.every(e=>n.has(e))&&t.push(`Every class this digest includes is also excluded, so no track can ever become a tile.`),t}function Co(e){return So(e).length===0}function wo(e){let t=[];e.windowKind===`motion`&&e.quietSeconds>=e.maxWindowSeconds&&t.push(`The quiet period is at least as long as the longest window, so it can never close one: every window will run to the ceiling instead.`);let n=new Set(e.classesExclude),r=e.classes.filter(e=>n.has(e));return r.length>0&&r.length<e.classes.length&&t.push(`Excluded and included at the same time — the exclusion wins: ${r.join(`, `)}.`),e.windowKind===`schedule`&&e.schedule?.invert===!0&&t.push(`This schedule is inverted: the digest covers the time OUTSIDE the windows below.`),e.deviceIds.length===1&&t.push(`One camera is allowed, but a digest is a MULTI-camera artefact — with one camera a timelapse rule is usually the better tool.`),t}function To(e){return e.kind===`motion`?`Motion · ${va(e.quietSeconds)} quiet · max ${va(e.maxWindowSeconds)}`:e.kind===`unsupported`?`Unsupported window (${e.raw}) — authored on a newer hub`:`Schedule · ${xa(e.schedule)}`}function Eo(e,t){return Sa(e,t,`Never run`)}function Do(e){if(e===void 0)return`All tracks`;let t=[];return e.classes!==void 0&&e.classes.length>0&&t.push(e.classes.join(`, `)),e.classesExclude!==void 0&&e.classesExclude.length>0&&t.push(`not ${e.classesExclude.join(`, `)}`),e.zones!==void 0&&e.zones.length>0&&t.push(`${e.zones.length} zone${e.zones.length===1?``:`s`}`),e.minImportance!==void 0&&t.push(`importance ≥ ${e.minImportance}`),e.minDwellSeconds!==void 0&&t.push(`stay ≥ ${va(e.minDwellSeconds)}`),t.length===0?`All tracks`:t.join(` · `)}function Oo(e){return{windowStartMs:e-Xa,windowEndMs:e}}b();var ko=[`rule`,`cameras`,`tiles`,`matched`,`from`,`to`];function Ao(e){return Za.find(t=>t===e)}function jo({rule:e,cameras:t,camerasLoading:n,targets:r,taxonomy:i,onSaved:a,onCancel:s}){let c=I(),[d,p]=D(()=>e===null?mo():ho(e)),[m,h]=D(null),_=e=>p(t=>({...t,...e})),v=S(()=>{let e=ne(`occupancy`,i);return e===null?[]:e.groups.flatMap(e=>e.options)},[i]),{options:y,loading:b}=Yt(d.deviceIds,t.map(e=>({id:e.id,name:e.name}))),C=O({mutationFn:async()=>{let t=e===null?{rule:bo(d)}:{ruleId:e.id,patch:xo(d,e)};await c.trpcClient.addons.custom.mutate({addonId:X,action:Ua,input:t})},onSuccess:a,onError:e=>h(e instanceof Error?e.message:`Save failed`)}),w=So(d),T=wo(d),E=Co(d)&&!C.isPending;return k(l,{open:!0,onOpenChange:e=>!e&&s(),children:x(g,{width:`lg`,placement:`sheet-on-mobile`,children:[x(`div`,{className:`mb-3 flex items-center justify-between`,children:[x(`h3`,{className:`flex items-center gap-2 text-sm font-semibold text-foreground`,children:[k(Ve,{className:`h-4 w-4 text-foreground-subtle`}),e===null?`New summary`:`Edit ${e.name}`]}),k(u,{size:`sm`,variant:`ghost`,type:`button`,onClick:s,children:`Cancel`})]}),m!==null&&k(`div`,{className:`mb-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger`,children:m}),x(`div`,{className:`max-h-[70vh] space-y-3 overflow-y-auto pr-1`,children:[k(da,{problems:w,testId:`summary-problems`}),k(fa,{warnings:T,testId:`summary-warnings`}),k(q,{title:`What it is`,hint:`One window, one picture: the best shot of every track the window held, laid out as one mosaic and delivered once.`,children:x(`div`,{className:`flex items-end gap-3`,children:[x(`div`,{className:`min-w-0 flex-1`,children:[k(`label`,{className:K,children:`Name`}),k(f,{value:d.name,onChange:e=>_({name:e.target.value}),placeholder:`e.g. Overnight sweep`,"data-testid":`summary-name`})]}),k(`div`,{className:`pb-1.5`,children:k(ha,{label:`Enabled`,checked:d.enabled,onChange:e=>_({enabled:e}),testId:`summary-enabled`})})]})}),k(q,{title:`Cameras`,hint:`Every camera in the digest gets at least one tile when it contributed anything — a digest in which two of six cameras never appear is not multi-camera.`,children:k(pa,{cameras:t,value:d.deviceIds,loading:n,onChange:e=>_({deviceIds:e}),hint:`The first camera selected owns the delivered notification.`})}),x(q,{title:`When the window closes`,children:[x(`div`,{children:[k(`label`,{className:K,children:`Window`}),k(o,{value:d.windowKind,options:[{value:`motion`,label:`Motion — opened and closed by activity`},{value:`schedule`,label:`Schedule — fixed weekly windows`}],onChange:e=>_({windowKind:e.target.value===`schedule`?`schedule`:`motion`}),"data-testid":`summary-window-kind`})]}),d.windowKind===`motion`?x(`div`,{className:`grid grid-cols-2 gap-3`,children:[k(J,{label:`Quiet period (seconds)`,value:d.quietSeconds,min:30,max:Ka,onChange:e=>_({quietSeconds:e??0}),hint:`The window opens on the first motion on any of these cameras and stays open while more arrives. This much silence closes it.`,testId:`summary-quiet`}),k(J,{label:`Longest window (seconds)`,value:d.maxWindowSeconds,min:60,max:qa,onChange:e=>_({maxWindowSeconds:e??0}),hint:`A permanently busy driveway would otherwise never deliver. At this bound the window closes with whatever it holds.`,testId:`summary-max-window`})]}):x(`div`,{children:[k(`label`,{className:K,children:`Weekly windows`}),k(br,{value:d.schedule,onChange:e=>_({schedule:e})}),k(`p`,{className:ua,children:`The digest is produced when a window CLOSES, and covers exactly that window. The first one is the first window that closes after you save — nothing is backfilled.`})]}),k(J,{label:`Wait for open tracks (seconds)`,value:d.barrierSeconds,min:0,max:Ja,onChange:e=>_({barrierSeconds:e??0}),hint:`A track's best shot is written when the track ENDS. Rendering the instant the window closes would show every still-moving subject with no picture. 0 disables the wait.`,testId:`summary-barrier`})]}),x(q,{title:`What goes in`,hint:`Evaluated on tracks: one passage is one tile.`,children:[x(`div`,{children:[k(`label`,{className:K,children:`Classes`}),k(H,{options:v,value:d.classes,onChange:e=>_({classes:e}),emptyHint:`No class vocabulary from this hub — leave empty to keep every class.`,placeholder:``,noFreeText:!0}),k(`p`,{className:ua,children:`Empty = every class. Only the macro classes are offered: a digest matches the class stored on the track, and tracks store macros — a sub-type would match nothing, forever.`})]}),x(`div`,{children:[k(`label`,{className:K,children:`Excluded classes`}),k(H,{options:v,value:d.classesExclude,onChange:e=>_({classesExclude:e}),emptyHint:`No class vocabulary from this hub.`,placeholder:``,noFreeText:!0})]}),x(`div`,{children:[k(`label`,{className:K,children:`Zones`}),k(H,{options:y,value:d.zones,onChange:e=>_({zones:e}),loading:b,emptyHint:`Pick a camera first — the zones offered are its own.`,placeholder:``,noFreeText:!0}),k(`p`,{className:ua,children:`Zones are scoped per camera: picking a zone on one camera does not mute the others, which keep matching on the whole frame.`})]}),x(`div`,{className:`grid grid-cols-2 gap-3`,children:[k(J,{label:`Minimum importance`,value:d.minImportance,min:0,max:1,step:.05,emptyPlaceholder:`any`,onChange:e=>_({minImportance:e}),hint:`The pipeline's own score, 0–1. Empty keeps everything.`,testId:`summary-min-importance`}),k(J,{label:`Minimum stay (seconds)`,value:d.minDwellSeconds,min:0,max:Ya,emptyPlaceholder:`any`,onChange:e=>_({minDwellSeconds:e}),hint:`Drops the passages too brief to be worth a tile.`,testId:`summary-min-dwell`})]})]}),x(q,{title:`The mosaic`,children:[x(`div`,{className:`grid grid-cols-2 gap-3`,children:[k(J,{label:`Tiles`,value:d.maxTiles,min:1,max:24,onChange:e=>_({maxTiles:e??1}),hint:`9 (a 3×3 grid) is the most a phone lock-screen thumbnail can carry and still be read.`,testId:`summary-max-tiles`}),x(`div`,{children:[k(`label`,{className:K,children:`When there are more tracks than tiles`}),k(o,{value:d.rank,options:Za.map(e=>({value:e,label:Qa[e]})),onChange:e=>{let t=Ao(e.target.value);t!==void 0&&_({rank:t})},"data-testid":`summary-rank`}),k(`p`,{className:ua,children:`Every contributing camera keeps its single best tile first; the remaining slots go to this ranking.`})]})]}),x(`div`,{children:[k(`label`,{className:K,children:`Caption burned onto the mosaic`}),k(f,{value:d.captionText,onChange:e=>_({captionText:e.target.value}),placeholder:`Leave empty for no caption`,"data-testid":`summary-caption`})]})]}),x(q,{title:`Delivery`,children:[k(ma,{targets:r,value:d.targetIds,onChange:e=>_({targetIds:e})}),x(`div`,{className:`grid grid-cols-2 gap-3`,children:[k(J,{label:`Priority`,value:d.priority,min:1,max:5,onChange:e=>_({priority:e??3}),testId:`summary-priority`}),k(ha,{label:`Deliver a window that matched nothing`,checked:d.deliverEmpty,onChange:e=>_({deliverEmpty:e}),hint:`Off by default: a nightly '0 events' is a line nobody reads, and it costs the lines beside it their reader.`,testId:`summary-deliver-empty`})]}),k(ga,{title:d.templateTitle,body:d.templateBody,onTitleChange:e=>_({templateTitle:e}),onBodyChange:e=>_({templateBody:e}),variables:ko,testIdPrefix:`summary-template`})]}),x(q,{title:`AI summary`,hint:`Declared in the rule and not wired yet: nothing on this hub reads it. A rule that already carries one keeps it — editing here never removes it.`,children:[k(`p`,{className:`text-[11px] text-foreground-subtle`,"data-testid":`summary-ai-dormant`,children:e?.hasAi===!0?`This rule carries an AI section (${e.aiEnabled?`enabled`:`disabled`}), authored through the API. It is preserved untouched.`:`No AI section on this rule.`}),k(J,{label:`Frames the model may look at`,value:d.maxAiImages,min:1,max:8,onChange:e=>_({maxAiImages:e??1}),hint:`Bounded separately from the tile budget, and never larger than it. Has no effect until the AI pass is wired.`,testId:`summary-max-ai-images`})]})]}),x(`div`,{className:`mt-3 flex justify-end gap-2`,children:[k(u,{size:`sm`,variant:`secondary`,type:`button`,onClick:s,children:`Cancel`}),x(u,{size:`sm`,type:`button`,disabled:!E,onClick:()=>C.mutate(),children:[C.isPending&&k(L,{className:`h-3.5 w-3.5 animate-spin`}),e===null?`Create`:`Save`]})]})]})})}b();var Mo=[`notificationSummaries`,`listSummaryRules`],No=[`deviceManager`,`listAll`,`forSummaries`],Po=`One window, one picture: every camera’s best moments as a single mosaic.`;function Fo(){let e=I(),[n,i]=D({mode:`closed`}),[a,o]=D(null),[s,c]=D(null),[l,d]=D(null),[f,p]=D(!1),m=C({queryKey:Mo,queryFn:async()=>{let t=fo(await e.trpcClient.addons.custom.mutate({addonId:X,action:Ha,input:{}}));return p(t===null),t}}),h=C({queryKey:No,queryFn:async()=>(await e.trpcClient.deviceManager.listAll.query({projection:`slim`})).filter(e=>e.type===N.Camera).map(e=>({id:e.id,name:e.name})).toSorted((e,t)=>e.name.localeCompare(t.name)),staleTime:6e4}),g=C({queryKey:ci,queryFn:()=>e.trpcClient.notificationOutput.listTargets.query({})}),v=C({queryKey:li,queryFn:()=>e.trpcClient.notificationRules.getConditionCatalog.query({})}),y=O({mutationFn:t=>e.trpcClient.addons.custom.mutate({addonId:X,action:Ua,input:{ruleId:t.ruleId,patch:{enabled:t.enabled}}}),onSuccess:()=>void m.refetch()}),b=O({mutationFn:t=>e.trpcClient.addons.custom.mutate({addonId:X,action:Wa,input:{ruleId:t}}),onSuccess:()=>{o(null),m.refetch()}}),S=O({mutationFn:async t=>po(await e.trpcClient.addons.custom.mutate({addonId:X,action:Ga,input:{ruleId:t,...Oo(Date.now())}})),onSuccess:e=>{c(null),d(e)}}),w=m.data??[],T=(g.data??[]).map(e=>({id:e.id,name:e.name,enabled:e.enabled})),E=new Map(T.map(e=>[e.id,e.name])),A=x(u,{size:`sm`,type:`button`,onClick:()=>i({mode:`form`,rule:null}),"data-testid":`summary-new`,children:[k(Ce,{className:`h-3.5 w-3.5`}),`New summary`]});return m.isLoading?k(z,{icon:Ve,title:`Summaries`,subtitle:Po,children:k(L,{className:`h-5 w-5 animate-spin`})}):m.isError||m.data===null?k(z,{icon:Ve,title:`Summaries`,subtitle:Po,children:k(r,{title:`Summary rules are not available on this hub`,message:f?`The hub answered something this admin build does not understand. Update both and reload.`:`This hub has not been updated to serve summary rules yet. Deploy addon-post-analysis and reload — nothing is lost in the meantime.`})}):x(z,{icon:Ve,title:`Summaries`,subtitle:Po,actions:A,children:[b.isError&&k(r,{title:`Could not delete the rule`,message:String(b.error)}),S.isError&&k(r,{title:`The test run failed`,message:String(S.error)}),l!==null&&x(`div`,{className:`mb-3 rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,"data-testid":`summary-test-outcome`,children:[l.error===void 0?x(`span`,{children:[`Produced `,l.produced,` digest`,l.produced===1?``:`s`,` — `,l.tiles??0,` tile`,(l.tiles??0)===1?``:`s`,` from `,l.cameras??0,` camera`,(l.cameras??0)===1?``:`s`,`, `,l.matched??0,` track`,(l.matched??0)===1?``:`s`,` matched, `,l.enqueued??0,` `,`notification`,(l.enqueued??0)===1?``:`s`,` sent.`]}):x(`span`,{className:`text-warning`,children:[`Nothing was produced: `,l.error]}),k(u,{size:`sm`,variant:`ghost`,type:`button`,className:`ml-2`,onClick:()=>d(null),children:`Dismiss`})]}),w.length===0?k(`div`,{className:`py-16 text-center text-xs text-foreground-subtle`,"data-testid":`summary-empty`,children:`No summary rules yet — create one, and every window it covers arrives as a single picture.`}):k(_,{children:k(t,{columns:Io({nowMs:Date.now(),targetNameById:E,confirmDeleteId:a,deletePending:b.isPending,onToggle:(e,t)=>y.mutate({ruleId:e.id,enabled:t}),onEdit:e=>{$a(e)&&i({mode:`form`,rule:e})},onTest:c,onAskDelete:o,onConfirmDelete:e=>b.mutate(e.id)}),rows:w,rowKey:e=>e.id,minWidthPx:860,bordered:!1})}),n.mode===`form`&&k(jo,{rule:n.rule,cameras:h.data??[],camerasLoading:h.isLoading,targets:T,taxonomy:v.data?.taxonomy,onCancel:()=>i({mode:`closed`}),onSaved:()=>{i({mode:`closed`}),m.refetch()}}),k(_a,{open:s!==null,ruleName:s?.name??``,windowDescription:`the last 3 hours`,targetDescription:`${s?.targets.length??0} target${(s?.targets.length??0)===1?``:`s`}`,pending:S.isPending,onCancel:()=>c(null),onConfirm:()=>{s!==null&&S.mutate(s.id)}})]})}function Io(e){return[{key:`name`,header:`Digest`,render:e=>x(`span`,{className:`flex flex-wrap items-center gap-2`,children:[k(`span`,{className:`truncate text-sm font-medium text-foreground`,children:e.name}),!e.enabled&&k(s,{variant:`warning`,children:`disabled`}),!$a(e)&&k(s,{variant:`warning`,children:`read-only`}),e.hasAi&&k(s,{variant:`info`,children:`AI section`})]})},{key:`cameras`,header:`Cameras`,align:`center`,nowrap:!0,render:e=>k(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.deviceIds.length})},{key:`window`,header:`Window`,render:e=>k(`span`,{className:`text-[11px] text-foreground-subtle`,children:To(e.window)})},{key:`filters`,header:`Keeps`,render:e=>k(`span`,{className:`text-[11px] text-foreground-subtle`,children:Do(e.filters)})},{key:`mosaic`,header:`Mosaic`,nowrap:!0,render:e=>x(`span`,{className:`text-[11px] text-foreground-subtle`,children:[e.maxTiles,` tiles · `,e.rank]})},{key:`targets`,header:`Targets`,render:t=>{let n=t.targets[0],r=n?e.targetNameById.get(n.targetId)??n.targetId:null;return k(`span`,{className:`text-[11px] text-foreground-subtle`,children:t.targets.length===1&&r!==null?r:`${t.targets.length} target${t.targets.length===1?``:`s`}`})}},{key:`lastRun`,header:`Last run`,nowrap:!0,render:t=>k(`span`,{className:`text-[11px] text-foreground-subtle`,"data-testid":`summary-last-${t.id}`,children:Eo(t.generatedAt,e.nowMs)})},{key:`enabled`,header:`On`,align:`center`,nowrap:!0,render:t=>k(p,{checked:t.enabled,disabled:t.readOnly,onCheckedChange:n=>e.onToggle(t,n),"aria-label":`toggle ${t.name}`})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:t=>x(`span`,{className:`flex items-center justify-end gap-1`,children:[k(u,{size:`sm`,variant:`ghost`,type:`button`,disabled:t.readOnly,onClick:()=>e.onTest(t),title:`Produce this digest now and DELIVER it`,"aria-label":`test ${t.name}`,"data-testid":`summary-test-${t.id}`,children:k(ze,{className:`h-3.5 w-3.5`})}),k(u,{size:`sm`,variant:`ghost`,type:`button`,disabled:!$a(t),onClick:()=>e.onEdit(t),"aria-label":`edit ${t.name}`,"data-testid":`summary-edit-${t.id}`,children:k(Se,{className:`h-3.5 w-3.5`})}),e.confirmDeleteId===t.id?x(`span`,{className:`flex items-center gap-1`,children:[k(u,{size:`sm`,variant:`danger`,type:`button`,disabled:e.deletePending,onClick:()=>e.onConfirmDelete(t),"data-testid":`summary-delete-confirm-${t.id}`,children:`Delete`}),k(u,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onAskDelete(null),children:`Cancel`})]}):k(u,{size:`sm`,variant:`ghost`,type:`button`,disabled:t.readOnly,onClick:()=>e.onAskDelete(t.id),"aria-label":`delete ${t.name}`,"data-testid":`summary-delete-${t.id}`,children:k(R,{className:`h-3.5 w-3.5`})})]})}]}var Lo=e=>typeof e==`string`&&e.length>0;function Ro(e){return{levels:e.levels,formats:e.format,bodyMaxLen:e.bodyMaxLen,attachmentSlots:e.attachments.mediaTypes,attachmentMode:e.attachments.mode,attachmentMax:e.attachments.max,attachmentMaxBytes:e.attachments.maxBytes,maxActions:e.actions,showActions:e.actions>0,showClickUrl:e.clickUrl,showSound:e.sound,showTtl:e.ttl,showTag:!0}}function zo(e,t){return e.format.includes(t)?t:e.format[0]??`text`}function Bo(e,t){let n=[];for(let r of e.attachments.mediaTypes){if(n.length>=e.attachments.max)break;let i=t[r];Lo(i)&&n.push({mediaType:r,url:i})}return n}function Vo(e,t){if(e.actions<=0)return[];let n=[];for(let r of t){if(n.length>=e.actions)break;let t=Lo(r.label),i=Lo(r.url);!t&&!i||n.push({id:`test-${n.length+1}`,label:t?r.label:`Action ${n.length+1}`,...i?{url:r.url}:{}})}return n}function Ho(e,t){let n=e.levels.some(e=>e.id===t.level)?t.level:void 0,r=Bo(e,t.attachmentUrls),i=Vo(e,t.actions),a=e.ttl&&Lo(t.ttl)?Number(t.ttl):void 0;return{body:t.body,format:zo(e,t.format),priority:Uo(t.priority),...Lo(t.title)?{title:t.title}:{},...n?{level:n}:{},...r.length>0?{attachments:r}:{},...i.length>0?{actions:i}:{},...e.clickUrl&&Lo(t.clickUrl)?{clickUrl:t.clickUrl}:{},...e.sound&&Lo(t.sound)?{sound:t.sound}:{},...a!==void 0&&Number.isFinite(a)?{ttl:a}:{},...Lo(t.tag)?{tag:t.tag}:{}}}function Uo(e){return Number.isFinite(e)?Math.min(5,Math.max(1,Math.round(e))):3}function Wo(e){return e.levels.find(e=>e.flags?.critical===!0)||e.levels.filter(e=>typeof e.ordinal==`number`).sort((e,t)=>t.ordinal-e.ordinal)[0]}function Go(e){return{level:``,priority:3,format:e.format[0]??`text`,title:``,body:``,attachmentUrls:{},actions:[],clickUrl:``,sound:``,ttl:``,tag:``}}var Ko={image:`/addon/notifiers/samples/image`,video:`/addon/notifiers/samples/video`,gif:`/addon/notifiers/samples/gif`,audio:`/addon/notifiers/samples/audio`,icon:`/addon/notifiers/samples/icon`};function qo(e,t){return e.attachments.max>0&&e.attachments.mediaTypes.includes(t)}function Jo(e){let t=[`text`];for(let n of[`image`,`gif`,`video`,`audio`])qo(e,n)&&t.push(n);return e.actions>0&&t.push(`actions`),e.levels.length>0&&t.push(`critical`),t.push(`overflow`),t}function Yo(e,t,n){let r=Go(e);return qo(e,t)?{...r,body:n,attachmentUrls:{[t]:Ko[t]}}:{...r,body:n}}function Xo(e,t){let n=Go(e);switch(t){case`text`:return{...n,title:`CamStack`,body:`Test notification — text only.`};case`image`:return Yo(e,`image`,`Test notification with an image.`);case`gif`:return Yo(e,`gif`,`Test notification with an animation.`);case`video`:return Yo(e,`video`,`Test notification with a video.`);case`audio`:return Yo(e,`audio`,`Test notification with audio.`);case`actions`:{let t=Array.from({length:e.actions},(e,t)=>({label:`Action ${t+1}`,url:`/`}));return{...n,title:`CamStack`,body:`Test notification with action buttons.`,actions:t,...e.clickUrl?{clickUrl:`/`}:{}}}case`critical`:{let t=Wo(e);return{...n,title:`CamStack`,body:`Critical test notification.`,priority:5,level:t?.id??``}}case`overflow`:return{...n,body:`X`.repeat(e.bodyMaxLen+50)}}}b();var Zo={text:`Text only`,image:`With image`,gif:`With GIF`,video:`With video`,audio:`With audio`,actions:`With buttons`,critical:`Critical`,overflow:`Overflow (advanced)`},Q=`w-full rounded-md border border-border bg-background px-2.5 py-1.5 text-xs text-foreground focus:border-primary focus:ring-1 focus:ring-primary/30 outline-none`,$=`block text-[11px] font-medium text-foreground mb-1`;function Qo({target:e,kind:t,open:n,onClose:r}){let i=I(),o=S(()=>Ro(t.caps),[t.caps]),c=S(()=>Jo(t.caps),[t.caps]),[f,p]=D(()=>Go(t.caps)),[h,_]=D(null),v=S(()=>Ho(t.caps,f),[t.caps,f]),y=f.body.length,b=y>o.bodyMaxLen,C=e=>p(t=>({...t,...e})),w=O({mutationFn:()=>i.trpcClient.notificationOutput.testTarget.mutate({addonId:e.addonId,targetId:e.id,sample:Ho(t.caps,f)}),onMutate:()=>_(null),onSuccess:e=>_(e),onError:e=>_({success:!1,error:e instanceof Error?e.message:`Test failed`})}),T=e=>{p(Xo(t.caps,e)),_(null)},E=(e,t,n)=>{let r=f.actions.length>0?[...f.actions]:[];for(;r.length<=e;)r.push({label:``,url:``});r[e]={...r[e],[t]:n},C({actions:r})};return k(l,{open:n,onOpenChange:e=>!e&&r(),children:x(g,{width:`lg`,className:`!max-w-2xl`,children:[k(d,{children:x(a,{children:[`Test "`,e.name,`" (`,t.label,`)`]})}),x(`div`,{className:`space-y-4 max-h-[60vh] overflow-y-auto pr-1`,children:[k(`div`,{className:`flex flex-wrap gap-1.5`,children:c.map(e=>k(u,{size:`sm`,variant:`outline`,type:`button`,onClick:()=>T(e),children:Zo[e]},e))}),x(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[o.levels.length>0&&x(`div`,{children:[k(`label`,{className:$,children:`Level`}),x(`select`,{className:Q,value:f.level,onChange:e=>C({level:e.target.value}),children:[k(`option`,{value:``,children:`— derive from priority —`}),o.levels.map(e=>x(`option`,{value:e.id,children:[e.label,e.ordinal===null?` (qualitative)`:` (p${e.ordinal})`]},e.id))]}),(()=>{let e=o.levels.find(e=>e.id===f.level);return e?x(`div`,{className:`mt-1 space-y-1`,children:[e.description&&k(`p`,{className:`text-[10px] text-foreground-subtle`,children:e.description}),x(`div`,{className:`flex flex-wrap gap-1`,children:[e.flags?.critical&&k(s,{variant:`danger`,"data-testid":`flag-critical`,children:`critical`}),e.flags?.silent&&k(s,{variant:`info`,children:`silent`}),e.flags?.noPush&&k(s,{variant:`warning`,children:`no-push`})]}),e.requires&&e.requires.length>0&&x(`p`,{className:`text-[10px] text-warning`,children:[`Requires target config: `,e.requires.join(`, `)]})]}):null})()]}),x(`div`,{children:[x(`label`,{className:$,children:[`Priority (ordinal): `,f.priority]}),k(`input`,{type:`range`,min:1,max:5,step:1,value:f.priority,onChange:e=>C({priority:Number(e.target.value)}),className:`w-full accent-primary`,"aria-label":`priority`})]})]}),o.formats.length>0&&x(`div`,{children:[k(`label`,{className:$,children:`Format`}),k(`div`,{className:`flex flex-wrap gap-2`,children:o.formats.map(e=>x(`label`,{className:`flex items-center gap-1.5 text-xs text-foreground cursor-pointer`,children:[k(`input`,{type:`radio`,name:`format`,className:`accent-primary`,checked:f.format===e,onChange:()=>C({format:e})}),e]},e))})]}),x(`div`,{children:[k(`label`,{className:$,children:`Title`}),k(`input`,{className:Q,value:f.title,onChange:e=>C({title:e.target.value})})]}),x(`div`,{children:[x(`label`,{className:$,children:[`Body`,` `,x(`span`,{className:b?`text-danger`:`text-foreground-subtle`,children:[`(`,y,`/`,o.bodyMaxLen,b?` — overflow`:``,`)`]})]}),k(`textarea`,{className:`${Q} min-h-[80px] resize-y`,value:f.body,onChange:e=>C({body:e.target.value})})]}),o.attachmentSlots.length>0&&x(`div`,{children:[x(`label`,{className:$,children:[`Attachments`,` `,x(`span`,{className:`text-foreground-subtle`,children:[`(mode: `,o.attachmentMode,`, max `,o.attachmentMax,o.attachmentMaxBytes?`, ≤${Math.round(o.attachmentMaxBytes/1024/1024)}MB`:``,`)`]})]}),k(`div`,{className:`space-y-1.5`,children:o.attachmentSlots.map(e=>x(`div`,{className:`flex items-center gap-2`,children:[k(`span`,{className:`text-[10px] w-12 shrink-0 text-foreground-subtle`,children:e}),k(`input`,{className:Q,placeholder:`${e} URL`,value:f.attachmentUrls[e]??``,onChange:t=>C({attachmentUrls:{...f.attachmentUrls,[e]:t.target.value}})})]},e))})]}),o.showActions&&x(`div`,{children:[x(`label`,{className:$,children:[`Actions (up to `,o.maxActions,`)`]}),k(`div`,{className:`space-y-1.5`,children:Array.from({length:Math.min(o.maxActions,3)},(e,t)=>x(`div`,{className:`flex items-center gap-2`,children:[k(`input`,{className:Q,placeholder:`label`,value:f.actions[t]?.label??``,onChange:e=>E(t,`label`,e.target.value)}),k(`input`,{className:Q,placeholder:`url`,value:f.actions[t]?.url??``,onChange:e=>E(t,`url`,e.target.value)})]},t))})]}),x(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[o.showClickUrl&&x(`div`,{children:[k(`label`,{className:$,children:`Click URL`}),k(`input`,{className:Q,value:f.clickUrl,onChange:e=>C({clickUrl:e.target.value})})]}),o.showSound&&x(`div`,{children:[k(`label`,{className:$,children:`Sound`}),k(`input`,{className:Q,value:f.sound,onChange:e=>C({sound:e.target.value})})]}),o.showTtl&&x(`div`,{children:[k(`label`,{className:$,children:`TTL (seconds)`}),k(`input`,{className:Q,type:`number`,value:f.ttl,onChange:e=>C({ttl:e.target.value})})]}),o.showTag&&x(`div`,{children:[k(`label`,{className:$,children:`Tag`}),k(`input`,{className:Q,value:f.tag,onChange:e=>C({tag:e.target.value})})]})]}),h&&k($o,{result:h}),x(`details`,{className:`text-[10px]`,children:[k(`summary`,{className:`cursor-pointer text-foreground-subtle`,children:`Payload preview`}),k(`pre`,{className:`mt-1 overflow-x-auto rounded bg-surface p-2 text-foreground-subtle`,children:JSON.stringify(v,null,2)})]})]}),x(m,{children:[k(u,{variant:`secondary`,size:`sm`,type:`button`,onClick:r,children:`Close`}),x(u,{size:`sm`,type:`button`,disabled:w.isPending||f.body.length===0,onClick:()=>w.mutate(),children:[w.isPending?k(L,{className:`h-3.5 w-3.5 animate-spin`}):k(De,{className:`h-3.5 w-3.5`}),`Send test`]})]})]})})}function $o({result:e}){let t=e.renderedAs;return x(`div`,{className:`rounded-md border px-3 py-2 text-xs ${e.success?`border-success/40 bg-success/10`:`border-danger/40 bg-danger/10`}`,"data-testid":`test-result`,children:[x(`div`,{className:`flex items-center gap-2 font-medium`,children:[e.success?k(be,{className:`h-3.5 w-3.5 text-success`}):k(Me,{className:`h-3.5 w-3.5 text-danger`}),k(`span`,{children:e.success?`Delivered`:`Failed`})]}),e.error&&k(`p`,{className:`mt-1 text-danger`,children:e.error}),t&&x(`dl`,{className:`mt-2 grid grid-cols-2 gap-x-3 gap-y-0.5 text-[11px] text-foreground-subtle`,children:[k(`dt`,{children:`Resolved level`}),k(`dd`,{className:`text-foreground`,children:t.level}),k(`dt`,{children:`Format sent`}),k(`dd`,{className:`text-foreground`,children:t.format}),k(`dt`,{children:`Attachments sent`}),k(`dd`,{className:`text-foreground`,children:t.attachmentsSent}),k(`dt`,{children:`Actions sent`}),k(`dd`,{className:`text-foreground`,children:t.actionsSent}),k(`dt`,{children:`Truncated`}),k(`dd`,{className:`text-foreground`,children:t.truncated?`yes`:`no`}),k(`dt`,{children:`Dropped`}),k(`dd`,{className:`text-foreground`,children:t.dropped.length>0?t.dropped.join(`, `):`—`})]})]})}function es(e){let t=[],n=new Map;for(let r of e){let e=n.get(r.addonId);e?e.push(r):(n.set(r.addonId,[r]),t.push(r.addonId))}return t.map(e=>({addonId:e,kinds:n.get(e)??[]}))}function ts(e){let t=[],n=e=>{for(let r of e){if(r.type===`password`){t.push(r.key);continue}if(r.type===`group`){n(r.fields);continue}if(r.type===`sub-tabs`)for(let e of r.tabs)n(e.fields)}};for(let t of e.sections)n(t.fields);return t}function ns(e,t,n){let r=new Set(n),i={};for(let[n,a]of Object.entries(e)){if(!r.has(n)){i[n]=a;continue}a==null||a===``||a!==t[n]&&(i[n]=a)}return i}function rs(e,t){let n=new Set(t),r={};for(let[t,i]of Object.entries(e))r[t]=n.has(t)?``:i;return r}b();var is=[`notificationOutput`,`listTargets`],as=[`notificationOutput`,`listTargetKinds`],os=[`userManagement`,`listUsers`],ss=`ownerUserId`;function cs(e){let t=e.config[ss];return typeof t==`string`&&t.length>0?t:null}function ls(e){return[{key:`name`,header:`Target`,render:t=>{let n=e.kindByKey.get(t.kind);return x(`span`,{className:`flex items-center gap-2`,children:[k(`span`,{className:`flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-surface text-xs`,title:n?.label??t.kind,children:k(us,{kind:n,imgClassName:`h-5 w-5 object-contain`,fallbackClassName:``})}),k(`span`,{className:`truncate text-sm font-medium text-foreground`,children:t.name}),!t.enabled&&k(s,{variant:`warning`,children:`disabled`})]})}},{key:`kind`,header:`Kind`,nowrap:!0,render:t=>k(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.kindByKey.get(t.kind)?.label??t.kind})},{key:`owner`,header:`Owner`,nowrap:!0,render:t=>{let n=cs(t);return n===null?k(s,{variant:`default`,children:`system`}):k(`span`,{className:`text-[11px] text-foreground`,children:e.userNameById.get(n)??n})}},{key:`enabled`,header:`On`,align:`center`,nowrap:!0,render:t=>k(p,{checked:t.enabled,onCheckedChange:n=>e.onToggle(t,n),"aria-label":`toggle ${t.name}`})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:t=>{let n=e.kindByKey.get(t.kind);return x(`span`,{className:`flex items-center justify-end gap-1`,children:[k(u,{size:`sm`,variant:`ghost`,type:`button`,disabled:!n,onClick:()=>e.onTest(t),title:`Test`,children:k(De,{className:`h-3.5 w-3.5`})}),k(u,{size:`sm`,variant:`ghost`,type:`button`,disabled:!n,onClick:()=>n&&e.onEdit(t,n),title:`Edit`,children:k(Se,{className:`h-3.5 w-3.5`})}),k(u,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onDelete(t),title:`Delete`,children:k(R,{className:`h-3.5 w-3.5 text-danger`})})]})}}]}function us({kind:e,imgClassName:t,fallbackClassName:n}){return e?.iconUrl?k(`img`,{src:e.iconUrl,alt:e.label,className:t,loading:`lazy`,draggable:!1}):k(`span`,{className:n,children:e?.icon??`🔔`})}function ds(){let e=I(),[n,i]=D({mode:`closed`}),[a,o]=D(null),s=C({queryKey:is,queryFn:()=>e.trpcClient.notificationOutput.listTargets.query({})}),c=C({queryKey:as,queryFn:async()=>(await e.trpcClient.notificationOutput.listTargetKinds.query({})).map(e=>{let t=e.iconUrl;return{...e,configSchema:e.configSchema,iconUrl:t}})}),l=S(()=>c.data??[],[c.data]),d=S(()=>{let e=new Map;for(let t of l)e.set(t.kind,t);return e},[l]),f=C({queryKey:os,queryFn:()=>e.trpcClient.userManagement.listUsers.query()}),p=S(()=>{let e=new Map;for(let t of f.data??[])e.set(t.id,t.username);return e},[f.data]),m=O({mutationFn:t=>e.trpcClient.notificationOutput.setTargetEnabled.mutate({addonId:t.target.addonId,targetId:t.target.id,enabled:t.enabled}),onSuccess:()=>void s.refetch()}),h=O({mutationFn:t=>e.trpcClient.notificationOutput.deleteTarget.mutate({addonId:t.addonId,targetId:t.id}),onSuccess:()=>void s.refetch()}),g=a?d.get(a.kind):void 0;return x(z,{icon:Ne,title:`Notification Targets`,subtitle:`Deliver notifications to ntfy, Pushover, Telegram, Home Assistant and more. Each target's kind declares its capabilities; the test panel shows exactly what a message degrades to.`,actions:x(u,{size:`sm`,type:`button`,onClick:()=>i({mode:`pick-kind`}),children:[k(Ce,{className:`h-3.5 w-3.5`}),`Add target`]}),children:[s.isLoading&&k(`div`,{className:`flex items-center justify-center py-16`,children:k(L,{className:`h-6 w-6 animate-spin text-primary`})}),s.isError&&!s.isLoading&&k(r,{title:`Failed to load targets`,message:s.error instanceof Error?s.error.message:`Unknown error`,onRetry:()=>void s.refetch()}),!s.isLoading&&!s.isError&&(s.data??[]).length===0&&k(`div`,{className:`text-xs text-foreground-subtle text-center py-16`,children:`No notification targets yet. Click "Add target" to configure one.`}),(s.data??[]).length>0&&k(_,{children:k(t,{columns:ls({kindByKey:d,userNameById:p,onToggle:(e,t)=>m.mutate({target:e,enabled:t}),onTest:o,onEdit:(e,t)=>i({mode:`form`,kind:t,target:e}),onDelete:e=>h.mutate(e)}),rows:s.data??[],rowKey:e=>e.id,minWidthPx:720,bordered:!1})}),n.mode===`pick-kind`&&k(fs,{kinds:l,onCancel:()=>i({mode:`closed`}),onPick:e=>i({mode:`form`,kind:e,target:null})}),n.mode===`form`&&k(ps,{kind:n.kind,target:n.target,users:f.data??[],onCancel:()=>i({mode:`closed`}),onSaved:()=>{i({mode:`closed`}),s.refetch()}}),a&&g&&k(Qo,{target:a,kind:g,open:!0,onClose:()=>o(null)})]})}function fs({kinds:e,onPick:t,onCancel:n}){let r=S(()=>es(e),[e]);return x(_,{className:`p-4 space-y-4`,children:[x(`div`,{className:`flex items-center justify-between`,children:[k(`h3`,{className:`text-sm font-semibold text-foreground`,children:`Choose a notification kind`}),k(u,{size:`sm`,variant:`ghost`,type:`button`,onClick:n,children:`Cancel`})]}),r.length===0&&k(`p`,{className:`text-xs text-foreground-subtle`,children:`No notification providers are installed. Install the notifiers addon (or connect Home Assistant) to add targets.`}),r.map(e=>x(`div`,{children:[k(`div`,{className:`text-[10px] font-semibold uppercase tracking-wider text-foreground-subtle mb-1.5`,children:e.addonId}),k(`div`,{className:`grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-2`,children:e.kinds.map(n=>x(`button`,{type:`button`,onClick:()=>t(n),className:`flex flex-col items-center gap-1.5 rounded-lg border border-border bg-surface px-3 py-3 text-xs hover:border-primary/50 hover:bg-surface-hover transition-colors`,children:[k(us,{kind:n,imgClassName:`h-7 w-7 object-contain`,fallbackClassName:`text-lg leading-7`}),k(`span`,{className:`font-medium text-foreground`,children:n.label}),n.supportsDiscovery&&k(s,{variant:`info`,style:`outline`,children:`discover`})]},`${e.addonId}:${n.kind}`))})]},e.addonId))]})}function ps({kind:e,target:t,users:n,onSaved:r,onCancel:i}){let a=I(),s=S(()=>ts(e.configSchema),[e.configSchema]),c=S(()=>t?.config??{},[t]),[l,d]=D(t?.name??e.label),[f,p]=D(()=>t?rs(t.config,s):{}),[m,h]=D(null),[g,y]=D(null),[b,C]=D(t?cs(t)??``:``),w=O({mutationFn:()=>a.trpcClient.notificationOutput.discoverTargets.query({addonId:e.addonId,kind:e.kind,config:f}),onSuccess:e=>h(e),onError:e=>y(e instanceof Error?e.message:`Discovery failed`)}),T=O({mutationFn:()=>{let{[ss]:n,...r}=ns(f,c,s),i=b===``?r:{...r,[ss]:b},o={id:t?.id??`${e.kind}-${Date.now()}`,name:l,kind:e.kind,addonId:e.addonId,enabled:t?.enabled??!0,config:i};return a.trpcClient.notificationOutput.upsertTarget.mutate({addonId:e.addonId,target:o})},onSuccess:r,onError:e=>y(e instanceof Error?e.message:`Save failed`)}),E=e=>{d(e.suggestedName),p(t=>({...t,...e.config})),h(null)};return x(_,{className:`p-4 space-y-4`,children:[x(`div`,{className:`flex items-center justify-between`,children:[x(`h3`,{className:`text-sm font-semibold text-foreground flex items-center gap-2`,children:[k(us,{kind:e,imgClassName:`h-5 w-5 object-contain`,fallbackClassName:`text-lg`}),t?`Edit ${t.name}`:`Add ${e.label} target`]}),k(u,{size:`sm`,variant:`ghost`,type:`button`,onClick:i,children:`Cancel`})]}),g&&k(`div`,{className:`rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger`,children:g}),x(`div`,{children:[k(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Name`}),k(`input`,{className:`w-full rounded-md border border-border bg-background px-2.5 py-1.5 text-xs text-foreground focus:border-primary focus:ring-1 focus:ring-primary/30 outline-none`,value:l,onChange:e=>d(e.target.value)})]}),x(`div`,{children:[k(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Owner`}),k(o,{value:b,options:[{value:``,label:`System (shared, admin-managed)`},...n.map(e=>({value:e.id,label:e.username}))],onChange:e=>C(e.target.value)}),k(`p`,{className:`mt-0.5 text-[10px] text-foreground-subtle`,children:`A user-owned target belongs to that user: it shows in their viewer and their own rules may deliver to it. System targets stay admin-managed.`})]}),e.supportsDiscovery&&x(`div`,{className:`space-y-2`,children:[x(u,{size:`sm`,variant:`outline`,type:`button`,disabled:w.isPending,onClick:()=>{y(null),w.mutate()},children:[w.isPending?k(L,{className:`h-3.5 w-3.5 animate-spin`}):k(Ee,{className:`h-3.5 w-3.5`}),`Discover`]}),m&&m.length===0&&k(`p`,{className:`text-[11px] text-foreground-subtle`,children:`No candidates discovered.`}),m&&m.length>0&&k(`div`,{className:`rounded-md border border-border divide-y divide-border`,children:m.map((e,t)=>x(`button`,{type:`button`,onClick:()=>E(e),className:`flex w-full items-center justify-between px-3 py-1.5 text-xs hover:bg-surface-hover`,children:[k(`span`,{className:`text-foreground`,children:e.suggestedName}),k(`span`,{className:`text-[10px] text-primary`,children:`use`})]},`${e.suggestedName}-${t}`))})]}),s.length>0&&t&&k(`p`,{className:`text-[10px] text-foreground-subtle`,children:`Secret fields are hidden. Leave them blank to keep the stored value; type a new value to replace it.`}),k(v,{schema:e.configSchema,values:f,onChange:p}),x(`div`,{className:`flex justify-end gap-2`,children:[k(u,{variant:`secondary`,size:`sm`,type:`button`,onClick:i,children:`Cancel`}),x(u,{size:`sm`,type:`button`,disabled:T.isPending||l.trim().length===0,onClick:()=>{y(null),T.mutate()},children:[T.isPending&&k(L,{className:`h-3.5 w-3.5 animate-spin`}),t?`Save changes`:`Create target`]})]})]})}b();var ms=`notificationTexts`,hs=`Every sentence the Notification Center can print — and your wording for it.`;function gs({entry:e,value:t,busy:n,onChange:r,onReset:i}){let a=Va(e),o=e.override!==null;return x(`div`,{className:`flex flex-col gap-1.5 rounded border border-border p-3`,"data-testid":`text-row-${e.key}`,"data-source":e.source,children:[x(`div`,{className:`flex items-center gap-2 flex-wrap`,children:[k(`code`,{className:`text-xs font-medium`,children:e.key}),o?k(s,{variant:`info`,children:`customised`}):null,e.source===`fallback`?k(s,{variant:`warning`,children:`English fallback`}):null]}),x(`div`,{className:`flex items-start gap-2`,children:[k(f,{value:t,disabled:n,onChange:e=>r(e.target.value),className:`flex-1 font-mono text-xs`,"data-testid":`text-input-${e.key}`}),k(u,{variant:`ghost`,size:`sm`,disabled:n||!o&&t===e.shipped,onClick:i,title:`Reset to the shipped wording`,"data-testid":`text-reset-${e.key}`,children:k(Te,{className:`h-3.5 w-3.5`})})]}),x(`p`,{className:`text-xs text-foreground-subtle`,children:[k(`span`,{className:`font-medium`,children:`Shipped:`}),` `,k(`span`,{className:`font-mono`,children:e.shipped})]}),k(`p`,{className:`text-xs text-foreground-subtle`,children:Ba(e)}),a===null?null:k(`p`,{className:`text-xs text-warning`,children:a})]})}function _s(){let e=I(),t=E(),[n,i]=D(null),[a,s]=D(``),[c,l]=D(new Map),[d,p]=D(!1),m=C({queryKey:[ms,n??`hub`],queryFn:async()=>{let t=Fa(await e.trpcClient.addons.custom.mutate({addonId:X,action:Ea,input:n===null?{}:{language:n}}));return p(t===null),t}}),h=()=>{l(new Map),t.invalidateQueries({queryKey:[ms]})},g=O({mutationFn:t=>e.trpcClient.addons.custom.mutate({addonId:X,action:Da,input:{language:t}}),onSuccess:h}),v=O({mutationFn:t=>e.trpcClient.addons.custom.mutate({addonId:X,action:Oa,input:t}),onSuccess:h}),y=m.data??null,b=S(()=>y===null?[]:za(y.entries,a),[y,a]);if(m.isLoading)return k(z,{icon:He,title:`Texts`,subtitle:hs,children:k(L,{className:`h-5 w-5 animate-spin`})});if(m.isError||y===null)return k(z,{icon:He,title:`Texts`,subtitle:hs,children:k(r,{title:`The notification text catalog is not available on this hub`,message:d?`The hub answered something this admin build does not understand. Update both and reload.`:`This hub has not been updated to serve the notification text catalog yet. Deploy addon-post-analysis and reload — nothing is lost in the meantime: notifications keep using the shipped wording.`})});let w=y.language,T=g.isPending||v.isPending,A=La(y.entries,c),j=Ra(y.entries,c),M=y.entries.filter(e=>e.override!==null).length,ee=y.languages.map(e=>({value:e,label:ka[e]})),N=(e,t)=>l(n=>new Map(n).set(e,t)),P=e=>N(e.key,e.shipped);return k(z,{icon:He,title:`Texts`,subtitle:hs,children:x(`div`,{className:`flex flex-col gap-4`,children:[g.isError?k(r,{title:`Could not change the language`,message:String(g.error)}):null,v.isError?k(r,{title:`Could not save`,message:String(v.error)}):null,x(_,{className:`p-4`,children:[x(`div`,{className:`flex flex-wrap items-end gap-6`,children:[x(`div`,{className:`flex flex-col gap-1`,children:[k(`label`,{className:`text-sm font-medium`,children:`Hub language`}),k(`div`,{className:`w-44`,children:k(o,{value:y.activeLanguage,disabled:T,options:ee,onChange:e=>{let t=e.target.value;Aa(t)&&g.mutate(t)},"data-testid":`texts-hub-language`})}),k(`p`,{className:`text-xs text-foreground-subtle`,children:`Every notification is written in this language.`})]}),x(`div`,{className:`flex flex-col gap-1`,children:[k(`label`,{className:`text-sm font-medium`,children:`Editing`}),k(`div`,{className:`w-44`,children:k(o,{value:w,disabled:T,options:ee,onChange:e=>{let t=e.target.value;Aa(t)&&(l(new Map),i(t))},"data-testid":`texts-editing-language`})}),k(`p`,{className:`text-xs text-foreground-subtle`,children:w===y.activeLanguage?`${M} of ${y.entries.length} texts customised.`:`This hub does not speak this language — these words are not in use yet.`})]})]}),k(`p`,{className:`mt-3 text-xs text-foreground-subtle`,children:`A rule that writes its own title or body still overrides everything here — this page is the wording used when a rule does not.`})]}),x(`div`,{className:`flex items-center gap-3`,children:[x(`div`,{className:`relative flex-1`,children:[k(Ee,{className:`absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-foreground-muted`}),k(f,{value:a,placeholder:`Search a key or a sentence…`,onChange:e=>s(e.target.value),className:`pl-7`,"data-testid":`texts-search`})]}),x(`span`,{className:`text-xs text-foreground-subtle whitespace-nowrap`,children:[b.length,` of `,y.entries.length]}),x(u,{disabled:T||j===0,onClick:()=>v.mutate({language:w,overrides:A}),"data-testid":`texts-save`,children:[T?k(L,{className:`h-3.5 w-3.5 animate-spin`}):null,j===0?`Save`:`Save ${j}`]})]}),k(`div`,{className:`flex flex-col gap-2`,"data-testid":`texts-rows`,children:b.length===0?k(`p`,{className:`text-sm text-foreground-subtle`,children:`No text matches that search.`}):b.map(e=>k(gs,{entry:e,value:Ia(e,c),busy:T,onChange:t=>N(e.key,t),onReset:()=>P(e)},e.key))})]})})}var vs=`nc.listTimelapseRules`,ys=`nc.upsertTimelapseRule`,bs=`nc.deleteTimelapseRule`,xs=`nc.testTimelapseRule`,Ss=3600,Cs=3600,ws=30,Ts=1,Es=[`image`,`gif`],Ds={image:`Still frame`,gif:`Short animation (GIF)`},Os=pe({rules:he(se.extend({readOnly:_e().optional()}))});function ks(e){let t=Os.safeParse(e);return t.success?t.data.rules:null}function As(e){return e.readOnly!==!0}var js=pe({produced:me(),exportId:ge().optional(),coveragePercent:me().optional(),enqueued:me().optional(),windowStartMs:me().optional(),windowEndMs:me().optional(),error:ge().optional()});function Ms(e){let t=js.safeParse(e);return t.success?t.data:null}function Ns(){return{name:``,enabled:!0,deviceIds:[],schedule:void 0,cadenceSec:15,framerate:10,denseCadenceSec:void 0,minDwellSec:void 0,targetIds:[],templateTitle:``,templateBody:``,previewText:``,previewTextSet:!1,previewMode:`image`,reportClasses:[],priority:3}}function Ps(e){return{name:e.name,enabled:e.enabled,deviceIds:[...e.deviceIds],schedule:e.schedule,cadenceSec:e.cadenceSec,framerate:e.framerate,denseCadenceSec:e.denseCadenceSec,minDwellSec:e.minDwellSec,targetIds:e.targets.map(e=>e.targetId),templateTitle:e.template?.title??``,templateBody:e.template?.body??``,previewText:e.previewText??``,previewTextSet:e.previewText!==void 0,previewMode:e.previewMode,reportClasses:[...e.reportClasses??[]],priority:e.priority}}var Fs={windows:[{days:[1],startMinute:0,endMinute:60}]};function Is(e){let t=e.templateTitle.trim(),n=e.templateBody.trim();if(!(t.length===0&&n.length===0))return{...t.length>0?{title:t}:{},...n.length>0?{body:n}:{}}}function Ls(e){let t=Is(e);return{name:e.name.trim(),enabled:e.enabled,deviceIds:[...e.deviceIds],schedule:e.schedule??Fs,cadenceSec:e.cadenceSec,framerate:e.framerate,...e.denseCadenceSec===void 0?{}:{denseCadenceSec:e.denseCadenceSec},...e.minDwellSec===void 0?{}:{minDwellSec:e.minDwellSec},targets:Ta(e.targetIds),...t===void 0?{}:{template:t},...e.previewTextSet?{previewText:e.previewText}:{},previewMode:e.previewMode,...e.reportClasses.length>0?{reportClasses:[...e.reportClasses]}:{},priority:e.priority}}function Rs(e,t){let n=Ls(e),r={};return n.name!==t.name&&(r.name=n.name),n.enabled!==t.enabled&&(r.enabled=n.enabled),Y(n.deviceIds,t.deviceIds)||(r.deviceIds=n.deviceIds),Y(n.schedule,t.schedule)||(r.schedule=n.schedule),n.cadenceSec!==t.cadenceSec&&(r.cadenceSec=n.cadenceSec),n.framerate!==t.framerate&&(r.framerate=n.framerate),n.denseCadenceSec!==t.denseCadenceSec&&(r.denseCadenceSec=n.denseCadenceSec??zs(n.cadenceSec)),n.minDwellSec!==t.minDwellSec&&n.minDwellSec!==void 0&&(r.minDwellSec=n.minDwellSec),Y(n.targets,t.targets)||(r.targets=n.targets),Y(n.template,t.template)||(r.template=n.template??null),n.previewText!==t.previewText&&n.previewText!==void 0&&(r.previewText=n.previewText),n.previewMode!==t.previewMode&&(r.previewMode=n.previewMode),Y(n.reportClasses,t.reportClasses)||(r.reportClasses=n.reportClasses??[]),n.priority!==t.priority&&(r.priority=n.priority),r}function zs(e){return Math.max(Ts,e/ws)}function Bs(e,t,n){return t<=0||n<=0?0:e/t/n}function Vs(e,t){return e*t*ce}function Hs(e){let t=[];return e.name.trim().length===0&&t.push(`Give the timelapse a name.`),e.name.length>200&&t.push(`The name is at most 200 characters.`),e.deviceIds.length===0&&t.push(`Pick at least one camera. Each camera renders its own video from its own recorded footage.`),(e.schedule===void 0||e.schedule.windows.length===0)&&t.push(`A timelapse needs at least one time window — the video is assembled and delivered when that window CLOSES, so without one nothing is ever produced.`),e.targetIds.length===0&&t.push(`Pick at least one delivery target, or the video is rendered and never sent.`),(!Number.isInteger(e.cadenceSec)||e.cadenceSec<2||e.cadenceSec>3600)&&t.push(`The cadence is a whole number of seconds between 2 and ${Ss}.`),(!Number.isInteger(e.framerate)||e.framerate<1||e.framerate>60)&&t.push(`The output frame rate is a whole number between 1 and 60 fps.`),e.denseCadenceSec!==void 0&&(e.denseCadenceSec<.1||e.denseCadenceSec>3600?t.push(`The dense cadence is between ${ce}s and ${Cs}s.`):e.denseCadenceSec>=e.cadenceSec&&t.push(`The dense cadence (${e.denseCadenceSec}s) must be strictly smaller than the base cadence (${e.cadenceSec}s) — a dense cadence that is not denser renders a uniform timelapse.`)),e.minDwellSec!==void 0&&(e.minDwellSec<0||e.minDwellSec>60)&&t.push(`The minimum stay is between 0s and 60s.`),e.previewText.length>200&&t.push(`The preview caption is at most 200 characters.`),e.reportClasses.length>20&&t.push(`At most 20 counted classes.`),(e.priority<1||e.priority>5)&&t.push(`Priority is between 1 and 5.`),t}function Us(e){return Hs(e).length===0}function Ws(e){let t=[];if(e.schedule?.invert===!0&&t.push(`This schedule is inverted: the timelapse covers the time OUTSIDE the windows below.`),e.minDwellSec!==void 0&&e.minDwellSec>0){e.denseCadenceSec!==void 0&&t.push(`A minimum stay only ever DENSIFIES: where it needs more frames it samples faster than your dense cadence, which acts as the slowest it will go.`);let n=Vs(e.minDwellSec,e.framerate);n>3&&t.push(`A passage shorter than ${n.toFixed(1)}s can never reach this stay, even at the finest sampling — it is rendered with every frame that exists and no more.`)}return e.previewMode===`gif`&&t.push(`A GIF preview costs a dozen extra seeks and a palette pass per delivery. If it cannot be assembled it degrades to the still — never to nothing.`),t}function Gs(e){return xa(e)}function Ks(e,t){return Sa(e,t,`Never run`)}function qs(e){return e.denseCadenceSec===void 0?{seconds:zs(e.cadenceSec),derived:!0}:{seconds:e.denseCadenceSec,derived:!1}}b();var Js=[`camera`,`rule`,`from`,`to`,`detections`,`detectionSummary`,`count_person`],Ys=7;function Xs(e){return Es.find(t=>t===e)}function Zs({rule:e,cameras:t,camerasLoading:n,targets:r,onSaved:i,onCancel:a}){let s=I(),[c,d]=D(()=>e===null?Ns():Ps(e)),[p,m]=D(null),h=e=>d(t=>({...t,...e})),_=O({mutationFn:async()=>{let t=e===null?{rule:Ls(c)}:{ruleId:e.id,patch:Rs(c,e)};await s.trpcClient.addons.custom.mutate({addonId:X,action:ys,input:t})},onSuccess:i,onError:e=>m(e instanceof Error?e.message:`Save failed`)}),v=Hs(c),y=Ws(c),b=qs(c),S=Bs(Ys,b.seconds,c.framerate),C=Us(c)&&!_.isPending;return k(l,{open:!0,onOpenChange:e=>!e&&a(),children:x(g,{width:`lg`,placement:`sheet-on-mobile`,children:[x(`div`,{className:`mb-3 flex items-center justify-between`,children:[x(`h3`,{className:`flex items-center gap-2 text-sm font-semibold text-foreground`,children:[k(Ae,{className:`h-4 w-4 text-foreground-subtle`}),e===null?`New timelapse`:`Edit ${e.name}`]}),k(u,{size:`sm`,variant:`ghost`,type:`button`,onClick:a,children:`Cancel`})]}),p!==null&&k(`div`,{className:`mb-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger`,children:p}),x(`div`,{className:`max-h-[70vh] space-y-3 overflow-y-auto pr-1`,children:[k(da,{problems:v,testId:`timelapse-problems`}),k(fa,{warnings:y,testId:`timelapse-warnings`}),k(q,{title:`What it is`,hint:`One video per camera, assembled from that camera's RECORDED footage when the window closes.`,children:x(`div`,{className:`flex items-end gap-3`,children:[x(`div`,{className:`min-w-0 flex-1`,children:[k(`label`,{className:K,children:`Name`}),k(f,{value:c.name,onChange:e=>h({name:e.target.value}),placeholder:`e.g. Timelapse ingresso`,"data-testid":`timelapse-name`})]}),k(`div`,{className:`pb-1.5`,children:k(ha,{label:`Enabled`,checked:c.enabled,onChange:e=>h({enabled:e}),testId:`timelapse-enabled`})})]})}),k(q,{title:`Cameras`,children:k(pa,{cameras:t,value:c.deviceIds,loading:n,onChange:e=>h({deviceIds:e}),hint:`Each camera renders and delivers its own video. Recording must be ON for a camera — a timelapse is cut from recorded footage, and the hub refuses a rule for a camera that does not record.`})}),k(q,{title:`When`,children:x(`div`,{children:[k(`label`,{className:K,children:`Weekly windows`}),k(br,{value:c.schedule,onChange:e=>h({schedule:e})}),k(`p`,{className:ua,children:`The video covers exactly one window and is delivered when it CLOSES. A window that crosses midnight (21:00 → 07:00) is the ordinary case for a night timelapse.`})]})}),x(q,{title:`Sampling`,hint:`Two rates: a base rate for the whole window, and a denser one inside the ranges where something was detected.`,children:[x(`div`,{className:`grid grid-cols-2 gap-3`,children:[k(J,{label:`Base cadence (seconds)`,value:c.cadenceSec,min:2,max:Ss,onChange:e=>h({cadenceSec:e??0}),hint:`One frame every N seconds across the quiet parts of the window.`,testId:`timelapse-cadence`}),k(J,{label:`Output frame rate (fps)`,value:c.framerate,min:1,max:60,onChange:e=>h({framerate:e??0}),hint:`How fast the assembled video plays.`,testId:`timelapse-framerate`})]}),x(`div`,{children:[k(`label`,{className:K,children:`Dense cadence, near the detections`}),x(`div`,{className:`flex items-center gap-2`,children:[k(o,{value:c.denseCadenceSec===void 0?`auto`:`explicit`,options:[{value:`auto`,label:`Automatic (${b.seconds}s)`},{value:`explicit`,label:`Set it myself`}],onChange:e=>h({denseCadenceSec:e.target.value===`auto`?void 0:qs(c).seconds}),"data-testid":`timelapse-dense-mode`}),c.denseCadenceSec!==void 0&&k(f,{type:`number`,className:`w-28`,min:.1,step:.1,value:String(c.denseCadenceSec),onChange:e=>{let t=Number(e.target.value);Number.isFinite(t)&&h({denseCadenceSec:t})},"data-testid":`timelapse-dense-seconds`})]}),x(`p`,{className:ua,"data-testid":`timelapse-dense-hint`,children:[`Lower = slower near the detections. At `,b.seconds,`s and `,c.framerate,` fps a`,` `,Ys,`-second passage lasts `,S.toFixed(2),`s on screen; halving the cadence doubles that, and the quiet parts of the night do not change length.`,b.derived?` Automatic keeps tracking the base cadence (base ÷ 30, never below 1s).`:` Fixed at this value — the hub cannot unset the field, so going back to Automatic writes the derived number (${qs({...c,denseCadenceSec:void 0}).seconds}s) explicitly.`]})]}),k(J,{label:`Minimum seconds of video per detection (optional)`,value:c.minDwellSec,min:0,max:60,step:.5,emptyPlaceholder:`no guarantee`,onChange:e=>h({minDwellSec:e}),hint:`State the stay and let the renderer solve for the cadence. It only ever samples DENSER, down to the recording's own frame interval — a passage too short to reach it is rendered with every frame that exists and no more.`,testId:`timelapse-min-dwell`})]}),x(q,{title:`The notification`,children:[k(ma,{targets:r,value:c.targetIds,onChange:e=>h({targetIds:e})}),x(`div`,{className:`grid grid-cols-2 gap-3`,children:[x(`div`,{children:[k(`label`,{className:K,children:`Preview`}),k(o,{value:c.previewMode,options:Es.map(e=>({value:e,label:Ds[e]})),onChange:e=>{let t=Xs(e.target.value);t!==void 0&&h({previewMode:t})},"data-testid":`timelapse-preview-mode`})]}),k(J,{label:`Priority`,value:c.priority,min:1,max:5,onChange:e=>h({priority:e??3}),testId:`timelapse-priority`})]}),x(`div`,{children:[k(`label`,{className:K,children:`Caption on the preview frame`}),k(f,{value:c.previewTextSet?c.previewText:``,placeholder:`${ie} (shipped default)`,onChange:e=>h({previewText:e.target.value,previewTextSet:!0}),"data-testid":`timelapse-preview-text`}),x(`p`,{className:ua,children:[c.previewTextSet&&c.previewText.length===0?`Empty and set: the preview frame carries NO caption.`:`Leave untouched for the shipped caption (${ie}).`,c.previewTextSet&&x(w,{children:[` `,k(`button`,{type:`button`,className:`underline`,onClick:()=>h({previewText:``,previewTextSet:!1}),"data-testid":`timelapse-preview-text-reset`,children:`Back to the shipped caption`})]})]})]}),k(ga,{title:c.templateTitle,body:c.templateBody,onTitleChange:e=>h({templateTitle:e}),onBodyChange:e=>h({templateBody:e}),variables:Js,testIdPrefix:`timelapse-template`}),x(`p`,{className:`text-[10px] text-foreground-subtle`,children:[`With no body of your own the detection summary is appended automatically, and only when the count is non-zero. With one, nothing is appended — ask for it with`,` `,k(`code`,{children:`{{detectionSummary}}`}),`.`]})]})]}),x(`div`,{className:`mt-3 flex justify-end gap-2`,children:[k(u,{size:`sm`,variant:`secondary`,type:`button`,onClick:a,children:`Cancel`}),x(u,{size:`sm`,type:`button`,disabled:!C,onClick:()=>_.mutate(),children:[_.isPending&&k(L,{className:`h-3.5 w-3.5 animate-spin`}),e===null?`Create`:`Save`]})]})]})})}b();var Qs=[`notificationTimelapses`,`listTimelapseRules`],$s=[`deviceManager`,`listAll`,`forTimelapses`],ec=`A night of recorded footage, assembled into one short video per camera.`;function tc(){let e=I(),[n,i]=D({mode:`closed`}),[a,s]=D(null),[c,l]=D(null),[d,f]=D(null),[p,m]=D(!1),h=C({queryKey:Qs,queryFn:async()=>{let t=ks(await e.trpcClient.addons.custom.mutate({addonId:X,action:vs,input:{}}));return m(t===null),t}}),g=C({queryKey:$s,queryFn:async()=>(await e.trpcClient.deviceManager.listAll.query({projection:`slim`})).filter(e=>e.type===N.Camera).map(e=>({id:e.id,name:e.name})).toSorted((e,t)=>e.name.localeCompare(t.name)),staleTime:6e4}),v=C({queryKey:ci,queryFn:()=>e.trpcClient.notificationOutput.listTargets.query({})}),y=O({mutationFn:t=>e.trpcClient.addons.custom.mutate({addonId:X,action:ys,input:{ruleId:t.ruleId,patch:{enabled:t.enabled}}}),onSuccess:()=>void h.refetch()}),b=O({mutationFn:t=>e.trpcClient.addons.custom.mutate({addonId:X,action:bs,input:{ruleId:t}}),onSuccess:()=>{s(null),h.refetch()}}),S=O({mutationFn:async t=>Ms(await e.trpcClient.addons.custom.mutate({addonId:X,action:xs,input:t})),onSuccess:e=>{l(null),f(e)}}),w=h.data??[],T=g.data??[],E=new Map(T.map(e=>[e.id,e.name])),A=(v.data??[]).map(e=>({id:e.id,name:e.name,enabled:e.enabled})),j=new Map(A.map(e=>[e.id,e.name]));return h.isLoading?k(z,{icon:Ae,title:`Timelapses`,subtitle:ec,children:k(L,{className:`h-5 w-5 animate-spin`})}):h.isError||h.data===null?k(z,{icon:Ae,title:`Timelapses`,subtitle:ec,children:k(r,{title:`Timelapse rules are not available on this hub`,message:p?`The hub answered something this admin build does not understand. Update both and reload.`:`This hub has not been updated to serve timelapse rules yet. Deploy addon-post-analysis and reload — the rules themselves are untouched.`})}):x(z,{icon:Ae,title:`Timelapses`,subtitle:ec,actions:x(u,{size:`sm`,type:`button`,onClick:()=>i({mode:`form`,rule:null}),"data-testid":`timelapse-new`,children:[k(Ce,{className:`h-3.5 w-3.5`}),`New timelapse`]}),children:[b.isError&&k(r,{title:`Could not delete the rule`,message:String(b.error)}),S.isError&&k(r,{title:`The test run failed`,message:String(S.error)}),d!==null&&x(`div`,{className:`mb-3 rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,"data-testid":`timelapse-test-outcome`,children:[d.error===void 0?x(`span`,{children:[`Produced `,d.produced,` video`,d.produced===1?``:`s`,d.coveragePercent===void 0?``:` — ${Math.round(d.coveragePercent)}% of the window had footage`,`, `,d.enqueued??0,` notification`,(d.enqueued??0)===1?``:`s`,` sent.`]}):x(`span`,{className:`text-warning`,children:[`Nothing was produced: `,d.error]}),k(u,{size:`sm`,variant:`ghost`,type:`button`,className:`ml-2`,onClick:()=>f(null),children:`Dismiss`})]}),w.length===0?k(`div`,{className:`py-16 text-center text-xs text-foreground-subtle`,"data-testid":`timelapse-empty`,children:`No timelapse rules yet — create one, and each night's recorded footage arrives as a short video.`}):k(_,{children:k(t,{columns:nc({nowMs:Date.now(),cameraNameById:E,targetNameById:j,confirmDeleteId:a,deletePending:b.isPending,onToggle:(e,t)=>y.mutate({ruleId:e.id,enabled:t}),onEdit:e=>i({mode:`form`,rule:e}),onTest:e=>l({rule:e,deviceId:e.deviceIds[0]??null}),onAskDelete:s,onConfirmDelete:e=>b.mutate(e.id)}),rows:w,rowKey:e=>e.id,minWidthPx:900,bordered:!1})}),n.mode===`form`&&k(Zs,{rule:n.rule,cameras:T,camerasLoading:g.isLoading,targets:A,onCancel:()=>i({mode:`closed`}),onSaved:()=>{i({mode:`closed`}),h.refetch()}}),k(_a,{open:c!==null,ruleName:c?.rule.name??``,windowDescription:`its last closed window`,targetDescription:`${c?.rule.targets.length??0} target${(c?.rule.targets.length??0)===1?``:`s`}`,pending:S.isPending,confirmDisabled:c?.deviceId===null,extra:c===null?null:x(`div`,{children:[k(`label`,{className:`mb-1 block text-[11px] font-medium text-foreground`,children:`Which camera`}),k(o,{value:c.deviceId===null?``:String(c.deviceId),options:c.rule.deviceIds.map(e=>({value:String(e),label:E.get(e)??`#${e}`})),onChange:e=>{let t=Number(e.target.value);Number.isFinite(t)&&l({rule:c.rule,deviceId:t})},"data-testid":`timelapse-test-camera`})]}),onCancel:()=>l(null),onConfirm:()=>{c!==null&&c.deviceId!==null&&S.mutate({ruleId:c.rule.id,deviceId:c.deviceId})}})]})}function nc(e){return[{key:`name`,header:`Timelapse`,render:e=>x(`span`,{className:`flex flex-wrap items-center gap-2`,children:[k(`span`,{className:`truncate text-sm font-medium text-foreground`,children:e.name}),!e.enabled&&k(s,{variant:`warning`,children:`disabled`}),!As(e)&&k(s,{variant:`warning`,children:`read-only`})]})},{key:`cameras`,header:`Cameras`,render:t=>k(`span`,{className:`text-[11px] text-foreground-subtle`,children:t.deviceIds.length===1?e.cameraNameById.get(t.deviceIds[0]??-1)??`#${t.deviceIds[0]}`:`${t.deviceIds.length} cameras`})},{key:`schedule`,header:`Window`,render:e=>k(`span`,{className:`text-[11px] text-foreground-subtle`,children:Gs(e.schedule)})},{key:`sampling`,header:`Sampling`,nowrap:!0,render:e=>{let t=qs(Ps(e));return x(`span`,{className:`text-[11px] text-foreground-subtle`,children:[e.cadenceSec,`s · `,e.framerate,`fps · dense `,t.seconds,`s`,t.derived?` (auto)`:``,e.minDwellSec===void 0?``:` · ≥${e.minDwellSec}s/detection`]})}},{key:`targets`,header:`Targets`,render:t=>{let n=t.targets[0],r=n?e.targetNameById.get(n.targetId)??n.targetId:null;return k(`span`,{className:`text-[11px] text-foreground-subtle`,children:t.targets.length===1&&r!==null?r:`${t.targets.length} target${t.targets.length===1?``:`s`}`})}},{key:`lastRun`,header:`Last run`,nowrap:!0,render:t=>k(`span`,{className:`text-[11px] text-foreground-subtle`,"data-testid":`timelapse-last-${t.id}`,children:Ks(t.lastGeneratedAt,e.nowMs)})},{key:`enabled`,header:`On`,align:`center`,nowrap:!0,render:t=>k(p,{checked:t.enabled,disabled:!As(t),onCheckedChange:n=>e.onToggle(t,n),"aria-label":`toggle ${t.name}`})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:t=>x(`span`,{className:`flex items-center justify-end gap-1`,children:[k(u,{size:`sm`,variant:`ghost`,type:`button`,disabled:!As(t),onClick:()=>e.onTest(t),title:`Render this rule's last closed window now and DELIVER it`,"aria-label":`test ${t.name}`,"data-testid":`timelapse-test-${t.id}`,children:k(ze,{className:`h-3.5 w-3.5`})}),k(u,{size:`sm`,variant:`ghost`,type:`button`,disabled:!As(t),onClick:()=>e.onEdit(t),"aria-label":`edit ${t.name}`,"data-testid":`timelapse-edit-${t.id}`,children:k(Se,{className:`h-3.5 w-3.5`})}),e.confirmDeleteId===t.id?x(`span`,{className:`flex items-center gap-1`,children:[k(u,{size:`sm`,variant:`danger`,type:`button`,disabled:e.deletePending,onClick:()=>e.onConfirmDelete(t),"data-testid":`timelapse-delete-confirm-${t.id}`,children:`Delete`}),k(u,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onAskDelete(null),children:`Cancel`})]}):k(u,{size:`sm`,variant:`ghost`,type:`button`,disabled:!As(t),onClick:()=>e.onAskDelete(t.id),"aria-label":`delete ${t.name}`,"data-testid":`timelapse-delete-${t.id}`,children:k(R,{className:`h-3.5 w-3.5`})})]})}]}var rc=`simulate`;function ic(){let[e,t]=je();return k(`div`,{className:`flex flex-col p-4`,children:k(Re,{tabs:[{id:`targets`,label:`Targets`,icon:Ne,content:k(ds,{})},{id:`rules`,label:`Rules`,icon:ye,content:k(mi,{onSimulateRule:n=>{Bi(Ri(n));let r=new URLSearchParams(e);r.set(`tab`,rc),t(r,{replace:!0})}})},{id:rc,label:`Simulate`,icon:ze,content:k(la,{})},{id:`history`,label:`History`,icon:Be,content:k(dt,{})},{id:`alarm`,label:`Alarm`,icon:Fe,content:k(it,{})},{id:`summaries`,label:`Summaries`,icon:Ve,content:k(Fo,{})},{id:`timelapses`,label:`Timelapses`,icon:Ae,content:k(tc,{})},{id:`texts`,label:`Texts`,icon:He,content:k(_s,{})}]})})}export{ic as NotificationsPage,ic as default};
|