@camstack/addon-admin-ui 1.2.318 → 1.2.319
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/{AddonCollectionPage-BN9l7eMZ.js → AddonCollectionPage-BrWgzLIU.js} +1 -1
- package/dist/assets/Addons-DYcAKvwk.js +1 -0
- package/dist/assets/{AdminTabs-lo1nGBvk.js → AdminTabs-ClzbjkxZ.js} +1 -1
- package/dist/assets/AiProfiles-Dov4FVsX.js +3 -0
- package/dist/assets/{BrokerForm-CjGqLtHB.js → BrokerForm-mZwFyC9C.js} +1 -1
- package/dist/assets/Build-60BV1diC.js +375 -0
- package/dist/assets/Calendars-DsHBCFwG.js +1 -0
- package/dist/assets/{Capabilities-Bid9B0aL.js → Capabilities-85W11SU9.js} +1 -1
- package/dist/assets/{CapabilityBadges-CFFfrQgk.js → CapabilityBadges-B6AnXa_t.js} +1 -1
- package/dist/assets/Cluster-qFRM7CZx.js +11 -0
- package/dist/assets/{CompositionEditor-DZT2LotJ.js → CompositionEditor-NRHG8SDd.js} +1 -1
- package/dist/assets/{CompositionEditorPage-DgSroELQ.js → CompositionEditorPage-DdwhEMMN.js} +1 -1
- package/dist/assets/Data-CEGeZLbf.js +1 -0
- package/dist/assets/DetectionIntelligence-BwIpzk1h.js +1 -0
- package/dist/assets/{DeviceAggregateSection-CksIr7a0.js → DeviceAggregateSection-BJDp8r7c.js} +1 -1
- package/dist/assets/DeviceDetail-UwDyYgHs.js +2 -0
- package/dist/assets/DeviceDoActionFields-OJLes8SP.js +1 -0
- package/dist/assets/{Devices-BZ1ju_7C.js → Devices-C7EsO5uT.js} +1 -1
- package/dist/assets/{EmbedPlayerPage-sP8pM1-2.js → EmbedPlayerPage-CLtx1qJu.js} +1 -1
- package/dist/assets/Events-CKB7LKgR.js +1 -0
- package/dist/assets/{FormBuilder-BBaiZSEO.js → FormBuilder-66XFP4SU.js} +1 -1
- package/dist/assets/Identity-B9buxNxL.js +1 -0
- package/dist/assets/IntegrationDetail-B7ZswH_j.js +1 -0
- package/dist/assets/{Integrations-BHzUYG6D.js → Integrations-B4u7dcBy.js} +1 -1
- package/dist/assets/Integrations-BiYfqDqX.js +1 -0
- package/dist/assets/Locations-wmUUv8Qt.js +3 -0
- package/dist/assets/{Logs-BWiH-JhS.js → Logs-8C77vt04.js} +1 -1
- package/dist/assets/{ModelLicenses-CecJNAUn.js → ModelLicenses-BpND7P2W.js} +1 -1
- package/dist/assets/{MotionZonesSettings-CTQLlrhj.js → MotionZonesSettings-BgQQ-nih.js} +1 -1
- package/dist/assets/{MyAccess-BvG_1DW6.js → MyAccess-CfmkGGJr.js} +1 -1
- package/dist/assets/Network-DbOzHm2v.js +1 -0
- package/dist/assets/{NodeAddonsSettingsPanel-D7om0e1q.js → NodeAddonsSettingsPanel-CoGJcleE.js} +1 -1
- package/dist/assets/{NodeInferenceDevices-V0xEVK63.js → NodeInferenceDevices-DEQLoFgS.js} +1 -1
- package/dist/assets/Notifications-q6l-TAXA.js +1 -0
- package/dist/assets/Pipeline-DD8w5812.js +1 -0
- package/dist/assets/{Plates-C8QmsKmj.js → Plates-p-NK9G1T.js} +1 -1
- package/dist/assets/{PrivacyMaskSettings-C9aBSVlv.js → PrivacyMaskSettings-CSIJ2V3u.js} +1 -1
- package/dist/assets/{ProviderIcon-DoIQ7DhJ.js → ProviderIcon-D3iThBBe.js} +1 -1
- package/dist/assets/Recordings-D25IxRNs.js +1 -0
- package/dist/assets/{ScanNetworkModal-C3WijDGp.js → ScanNetworkModal-DKFEtHT3.js} +1 -1
- package/dist/assets/{SceneMonitorEditor-B958o6r1.js → SceneMonitorEditor-DwhUbtzq.js} +1 -1
- package/dist/assets/{Scenes-BQgvgzQs.js → Scenes-D1jX8kn5.js} +1 -1
- package/dist/assets/{Settings-9P3YIZMT.js → Settings-C2BKgOpm.js} +1 -1
- package/dist/assets/{Showroom-BHj5mXWK.js → Showroom-CtqBkiv2.js} +1 -1
- package/dist/assets/{StorageLocationsPanel-DCLsuF-C.js → StorageLocationsPanel-CVjEIApR.js} +1 -1
- package/dist/assets/{Terminal-DoJ_OZH4.js → Terminal-DecFUwef.js} +5 -5
- package/dist/assets/{Viewer-dRJuCLAa.js → Viewer-BPi2u3JT.js} +1 -1
- package/dist/assets/{_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-mIcMabMK.js → _virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-cJ6EU7bN.js} +1 -1
- package/dist/assets/{archive-7wNcK2IS.js → archive-XCiszzxf.js} +1 -1
- package/dist/assets/{authed-media-DyZLbN-o.js → authed-media-DDqmA02K.js} +1 -1
- package/dist/assets/{boxes-DRYKdAp-.js → boxes-D4MIbXht.js} +1 -1
- package/dist/assets/circle-slash-Cy2rn5H3.js +1 -0
- package/dist/assets/{debounced-invalidate-BZmNPMY1.js → debounced-invalidate-Bz2popF9.js} +1 -1
- package/dist/assets/{device-integration-icon-LEPa0YVm.js → device-integration-icon-DzuJgcu0.js} +1 -1
- package/dist/assets/device-picker-model-5vHoWhVP.js +1 -0
- package/dist/assets/{dist-B657U48r.js → dist-BE0-lAbU.js} +1 -1
- package/dist/assets/dist-BlxQFw9d.js +349 -0
- package/dist/assets/{face-bbox-6G4c88_6.js → face-bbox-CQZeT16C.js} +1 -1
- package/dist/assets/{hard-drive-download-BFmQDsVh.js → hard-drive-download-BUvVfeCd.js} +1 -1
- package/dist/assets/{hostInit-CqKhA_sQ.js → hostInit-s2-vIzef.js} +1 -1
- package/dist/assets/index-BBheY5o3.css +2 -0
- package/dist/assets/{index-CwSbxED9.js → index-C1l1qzBm.js} +3 -3
- package/dist/assets/{layers-Nb3R5zd7.js → layers-CtOoDwSD.js} +1 -1
- package/dist/assets/{location-owned-usage-CEaVmhRl.js → location-owned-usage-C5plKvRg.js} +1 -1
- package/dist/assets/{mf-entry-bootstrap-0-b1ec185a.js → mf-entry-bootstrap-0-1c53a077.js} +2 -2
- package/dist/assets/{player-overlays-BcO9fxNP.js → player-overlays-27qhPy_v.js} +1 -1
- package/dist/assets/remoteEntry-C-HUzkdc.js +1 -0
- package/dist/assets/{send-Cxp-ZViK.js → send-BPGjlbSr.js} +1 -1
- package/dist/assets/{settings-2-Bnv0uVAN.js → settings-2-DYo9uOuF.js} +1 -1
- package/dist/assets/{square-check-big-BFhfY6Jd.js → square-check-big-CTL89hi8.js} +1 -1
- package/dist/assets/src-DxIAkBus.js +349 -0
- package/dist/assets/src-IJPkPeFt.js +67 -0
- package/dist/assets/{use-scenes-feed-CzL9nssG.js → use-scenes-feed-CPwa5B1D.js} +1 -1
- package/dist/assets/{use-stationary-objects-Df3ltX40.js → use-stationary-objects-Dq2GsPVr.js} +1 -1
- package/dist/assets/useDevice-CkN93PJ-.js +1 -0
- package/dist/assets/useEventInvalidation-5vHoWhVP.js +1 -0
- package/dist/assets/{useNodeUrlSelection-UzxaMEdr.js → useNodeUrlSelection-CUdqirJf.js} +1 -1
- package/dist/assets/user-round-C3AYvBKo.js +1 -0
- package/dist/assets/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-D3b4GvrC.js → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-yti5GZlu.js} +2 -2
- package/dist/index.html +6 -6
- package/dist/server/addon.js +5246 -4983
- package/package.json +1 -1
- package/dist/assets/Addons-wMbMeQOY.js +0 -1
- package/dist/assets/AiProfiles-Tm1kdnXr.js +0 -3
- package/dist/assets/Build-Dm6CXeaO.js +0 -32
- package/dist/assets/Calendars-BEIjf9xd.js +0 -1
- package/dist/assets/Cluster-DJP3Y97M.js +0 -11
- package/dist/assets/Data-Dmo4xd4g.js +0 -1
- package/dist/assets/DetectionIntelligence-DiHWFh0X.js +0 -1
- package/dist/assets/DeviceDetail-C-VhJOex.js +0 -2
- package/dist/assets/Events-DAb6Xigy.js +0 -1
- package/dist/assets/Identity-Bk15qu5d.js +0 -1
- package/dist/assets/IntegrationDetail-wcjbkQUB.js +0 -1
- package/dist/assets/Integrations-BkvkGuwJ.js +0 -1
- package/dist/assets/Locations-BSfdvsGe.js +0 -3
- package/dist/assets/Network-BhsxhFjD.js +0 -1
- package/dist/assets/Notifications-D5dhr2wH.js +0 -1
- package/dist/assets/Pipeline-lo8pqs0O.js +0 -1
- package/dist/assets/Recordings-C_KplJ3-.js +0 -1
- package/dist/assets/circle-slash-Jvk_TWqc.js +0 -1
- package/dist/assets/device-picker-model-DXiaooJB.js +0 -1
- package/dist/assets/dist-B1YvGzuM.js +0 -349
- package/dist/assets/index-DZYv56ZC.css +0 -2
- package/dist/assets/remoteEntry-CUHUArg_.js +0 -1
- package/dist/assets/src-BVYExcrk.js +0 -349
- package/dist/assets/src-C2nRzmKs.js +0 -67
- package/dist/assets/useDevice-CbY0qewJ.js +0 -1
- package/dist/assets/useEventInvalidation-DXiaooJB.js +0 -1
- package/dist/assets/user-round-BzsknipD.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{K as e,Q as t,S as n,W as r,a as i,b as a,i as o,o as s,p as c,q as l,t as u,x as d,z as f}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-DhP-Lgiq.js";import{Z as p,_t as m,at as h,lt as g,st as _,yt as v}from"./player-overlays-27qhPy_v.js";import{B as y,Bn as b,Cd as x,Fn as S,Ft as C,Gt as w,Hn as T,It as E,Kt as D,Ld as O,M as k,Nl as A,Nn as j,Nt as ee,Pt as M,Pu as N,Q as P,Qt as F,Sa as te,Sd as ne,Sn as I,So as re,Tt as ie,Us as ae,Uu as oe,Vi as se,Vn as L,Vs as R,Vu as ce,Xt as le,Yr as ue,Yt as de,Zl as fe,Zt as pe,_ as me,_l as z,_o as he,_u as ge,bo as _e,d as ve,dd as ye,ed as be,en as B,f as V,g as xe,gn as H,h as Se,hn as U,hu as W,ku as G,ln as K,lu as Ce,m as we,nu as Te,p as Ee,qt as De,ud as Oe,uu as ke,v as Ae,vl as je,vo as Me,wd as Ne,wt as Pe,xn as q,yn as J,zn as Fe}from"./src-IJPkPeFt.js";import{t as Ie}from"./send-BPGjlbSr.js";import{$ as Le,A as Re,B as ze,C as Be,D as Ve,E as He,F as Ue,G as We,H as Ge,I as Ke,J as qe,K as Je,L as Ye,M as Xe,Nt as Ze,O as Qe,P as $e,Q as et,R as tt,S as nt,T as rt,U as it,V as at,W as ot,X as st,Y as ct,Z as lt,_ as ut,at as dt,b as ft,c as pt,ct as mt,d as ht,dn as gt,dt as _t,et as vt,f as yt,fn as bt,ft as xt,g as St,h as Ct,it as wt,j as Tt,k as Et,l as Dt,lt as Ot,m as kt,nt as At,ot as jt,p as Mt,pn as Nt,q as Pt,qn as Ft,rt as It,st as Lt,tt as Rt,u as zt,un as Bt,ut as Vt,v as Ht,w as Ut,x as Wt,y as Gt,z as Kt}from"./src-DxIAkBus.js";import{D as qt,M as Jt,O as Yt,v as Xt,y as Zt}from"./__vite-browser-external-Cc3gW-QT.js";import{c as Qt,d as $t,l as en,m as tn}from"./index-C1l1qzBm.js";import{t as nn}from"./AdminPage-CiKtOLQm.js";import{t as rn}from"./DeviceDoActionFields-OJLes8SP.js";import"./device-picker-model-5vHoWhVP.js";import{t as an}from"./AdminTabs-ClzbjkxZ.js";import{t as on}from"./use-scenes-feed-CPwa5B1D.js";var sn=v(`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`}]]),cn=v(`images`,[[`path`,{d:`m22 11-1.296-1.296a2.4 2.4 0 0 0-3.408 0L11 16`,key:`9kzy35`}],[`path`,{d:`M4 8a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2`,key:`1t0f0t`}],[`circle`,{cx:`13`,cy:`7`,r:`1`,fill:`currentColor`,key:`1obus6`}],[`rect`,{x:`8`,y:`2`,width:`14`,height:`14`,rx:`2`,key:`1gvhby`}]]),ln=v(`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`}]]),un=v(`list-ordered`,[[`path`,{d:`M11 5h10`,key:`1cz7ny`}],[`path`,{d:`M11 12h10`,key:`1438ji`}],[`path`,{d:`M11 19h10`,key:`11t30w`}],[`path`,{d:`M4 4h1v5`,key:`10yrso`}],[`path`,{d:`M4 9h2`,key:`r1h2o0`}],[`path`,{d:`M6.5 20H3.4c0-1 2.6-1.925 2.6-3.5a1.5 1.5 0 0 0-2.6-1.02`,key:`xtkcd5`}]]);t();var dn={home:`Home`,away:`Away`,night:`Night`};function fn(e){return dn[e]??e}function pn(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 mn(e,t){if(e.ruleCount===0)return`Arms nothing — no enabled rule is gated on this mode.`;if(e.allDevices&&e.allDevicesExcept.length>0){let n=e.allDevicesExcept.map(t);return`All devices except ${n.length}: ${n.join(`, `)}`}return e.allDevices?`Every device — ${vn(e.ruleCount,`rule`)} with no device scope.`:e.deviceIds.length===0?`${vn(e.ruleCount,`rule`)}, no device restriction.`:e.deviceIds.map(t).join(`, `)}function hn(e,t){if(e.length===0)return``;let n=e.map(e=>`${t(e.deviceId)} (${gn[e.reason]})`);return`${e.length} excluded: ${n.join(`, `)}`}var gn={muted:`notifications muted`,"detection-off":`detection off`,offline:`offline`};function _n(e){return e.ruleCount===0}function vn(e,t){return e===1?`1 ${t}`:`${e} ${t}s`}function yn(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 bn=2e3,xn=15e3,Sn=new Set([`arming`,`pending`,`triggered`]);function Cn(e){return e!==void 0&&Sn.has(e)?bn:xn}var wn={disarmed:`Disarmed`,armed_home:`Armed`,armed_away:`Armed`,armed_night:`Armed`,armed_vacation:`Armed`,armed_custom_bypass:`Armed`,arming:`Arming`,disarming:`Disarming`,pending:`Entry delay`,triggered:`Triggered`};function Tn(e){let t=wn[e.state];return e.state===`disarmed`||e.targetMode===null?t:`${t} — ${fn(e.targetMode)}`}function En(e){return e!==`disarmed`}function Dn(e){return e===`open`?`ignored until it closes`:`closed — monitored at next open`}function On(e,t){return(e.nonBlocking??[]).find(e=>e.mode===t)?.deviceIds??[]}function kn(e,t){return(e.blocking??[]).find(e=>e.mode===t)?.deviceIds??[]}function An(e,t){return(e.secureOnArmOff??[]).find(e=>e.mode===t)?.deviceIds??[]}function jn(e,t,n){let r=(e.modeDelays??[]).find(e=>e.mode===t);switch(n){case`exitDelaySec`:return r?.exitDelaySec;case`entryDelaySec`:return r?.entryDelaySec;case`triggeredDurationSec`:return r?.triggeredDurationSec}}function Mn(e,t,n){switch(t){case`exitDelaySec`:return{mode:e,exitDelaySec:n};case`entryDelaySec`:return{mode:e,entryDelaySec:n};case`triggeredDurationSec`:return{mode:e,triggeredDurationSec:n}}}function Nn(e,t,n,r){let i=jn(e,t,n);return r==="default"?i===void 0?null:Mn(t,n,null):i===r?null:Mn(t,n,r)}function Pn(e,t){let n=e.openings.find(e=>e.mode===t);if(n===void 0)return null;let r=n.devices.filter(e=>e.blocking).length;return{blocking:r,nonBlocking:n.devices.length-r,unknown:n.unknown.length}}var Fn=[`unknown-refusal`,`stale`,`expired`,`used`];function In(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ln(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(!In(n))return null;let{deviceId:e,name:r,state:i}=n;if(typeof e!=`number`||typeof r!=`string`||typeof i!=`string`)return null;t.push({deviceId:e,name:r,state:i})}return t}function Rn(e){if(!In(e))return null;let t=e.outcome;if(t===`armed`||t===`arming`){let n=Ln(e.excluded);return n===null?null:{outcome:t,excluded:n}}if(t===`refused`){let n=Ln(e.blocking),r=e.refusalId;return n===null||typeof r!=`string`||r===``?null:{outcome:t,refusalId:r,blocking:n}}if(t===`rejected`){let n=Fn.find(t=>t===e.reason);return n===void 0?null:{outcome:t,reason:n}}return null}var zn={"unknown-refusal":`the hub no longer knows that refusal`,stale:`the panel changed since it refused — arm again`,expired:`the refusal expired — arm again`,used:`that refusal was already used`};function Bn(e){return zn[e]}var Vn=[{field:`exitDelaySec`,key:`exit`,label:`Exit delay`,hint:`Time between arming and the mode taking effect — long enough to leave.`,max:600,zeroMeans:`arms immediately`},{field:`entryDelaySec`,key:`entry`,label:`Entry delay`,hint:`Time between a trigger and the alarm firing — long enough to reach the keypad.`,max:600,zeroMeans:`fires immediately`},{field:`triggeredDurationSec`,key:`siren`,label:`Triggered for`,hint:`How long the alarm stays triggered before re-arming itself.`,max:Bt,zeroMeans:`until disarmed`}];function Hn(e){return`Enter a whole number of seconds from 0 to ${e}.`}function Un(e,t){let n=e.trim();return`${n===``?`Nothing was entered, so nothing was saved`:`${n} was not saved`} — ${Hn(t)}`}function Wn({label:e,value:t,max:r,zeroMeans:i,disabled:a,testId:o,hint:s,adornment:c,onCommit:u}){let[f,p]=l(null),[m,h]=l(null),g=f??String(t),_=f!==null&&f.trim()!==``&&yn(f,r)===null,v=pn(t,i),y=()=>{let e=f===null?null:yn(f,r);p(null),e===null?f!==null&&h(f):(h(null),u(e))};return n(k,{label:e,...s===void 0?{}:{description:s},..._?{error:Hn(r)}:m===null?{}:{error:Un(m,r)},children:[n(`div`,{className:`flex items-center gap-2`,children:[d(B,{type:`number`,min:0,max:r,value:g,disabled:a,state:_||m!==null?`error`:`default`,"aria-label":e,onChange:e=>{h(null),p(e.target.value)},onBlur:y,className:`w-20`,"data-testid":o}),d(`span`,{className:`text-xs text-foreground-subtle`,children:`s`}),c]}),v===`${t} s`?null:d(`span`,{className:`text-[10px] text-foreground-subtle`,children:v})]})}var Gn=[`contact`,`cover`,`lock-control`,`switch`];function Kn(e){let t=new Set;for(let n of e?.openings??[]){for(let e of n.devices)t.add(e.deviceId);for(let e of n.unknown)t.add(e)}return t}function qn(e){let t=new Set(Kn(e.live));for(let n of e.openingIds??[])t.add(n);for(let n of e.listed)t.add(n);return{ids:[...t].toSorted((e,t)=>e-t),unresolved:e.openingIds===null}}function Jn(e){return e.ids.length>0||e.unresolved?null:`no-opening`}function Yn(e,t,n=new Map){let r=[...e].map(([e,t])=>({id:e,name:t})),i=e=>{let t=n.get(e)?.trim();return t===void 0||t===``?null:t},a=e=>Se([e],r,t)[0];return{nameOf:e=>{let t=a(e);return i(e)??(t===void 0?`Device #${String(e)}`:Ee(t))},isRemoved:e=>i(e)===null&&a(e)?.removed===!0}}function Xn(e){let t=e.name.trim();return t===``?`Device #${String(e.deviceId)}`:t}function Zn(e){return e===0?`Not armed — the hub refused without naming an open device.`:`Not armed — these are open:`}t();var Qn=`pipeline-analytics`,$n=`The hub answered something this build cannot read — refresh after updating.`;function er(e){return e instanceof Error?e.message:String(e)}function tr(e){return e.map(e=>`${Xn(e)} (${e.state})`).join(`, `)}function nr({live:e,onChanged:t}){let r=h(),[i,a]=l(null),[o,s]=l(null),[c,f]=l(null),p=(e,t)=>r.trpcClient.addons.custom.mutate({addonId:Qn,action:e,input:t}),m=e=>{if(e===null){s($n);return}if(e.outcome===`refused`){a({refusalId:e.refusalId,blocking:e.blocking});return}if(a(null),e.outcome===`rejected`){s(`Arm anyway was not accepted: ${Bn(e.reason)}.`);return}let t=e.outcome===`armed`?`Armed`:`Arming`;f(e.excluded.length===0?`${t}.`:`${t} — excluded: ${tr(e.excluded)}.`)},g=()=>{s(null),f(null)},_=u({mutationFn:async e=>Rn(await p(`nc.armAlarm`,{mode:e})),onMutate:g,onSuccess:m,onError:e=>s(er(e)),onSettled:t}),v=u({mutationFn:async e=>Rn(await p(`nc.armAlarmAnyway`,{refusalId:e})),onMutate:g,onSuccess:m,onError:e=>s(er(e)),onSettled:t}),y=u({mutationFn:async()=>p(`nc.disarmAlarm`,{}),onMutate:()=>{g(),a(null)},onSuccess:()=>f(`Disarmed.`),onError:e=>s(er(e)),onSettled:t});if(e===void 0)return n(H,{className:`p-4`,children:[d(`h3`,{className:`text-sm font-semibold mb-1`,children:`Panel`}),d(`p`,{className:`text-sm text-foreground-subtle`,children:`This hub does not report the panel's live state yet — update it to arm from here.`})]});let b=_.isPending||v.isPending||y.isPending;return n(H,{className:`p-4`,children:[n(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[n(`div`,{children:[d(`h3`,{className:`text-sm font-semibold`,children:`Panel`}),d(`p`,{className:`text-lg font-medium`,"data-testid":`alarm-state`,children:Tn(e)})]}),n(`div`,{className:`flex flex-wrap items-center gap-2`,children:[b?d(G,{className:`h-4 w-4 animate-spin`}):null,e.availableModes.map(e=>n(I,{type:`button`,size:`md`,variant:`outline`,disabled:b,onClick:()=>_.mutate(e),"data-testid":`alarm-arm-${e}`,children:[`Arm `,fn(e)]},e)),d(I,{type:`button`,size:`md`,variant:En(e.state)?`danger`:`secondary`,disabled:b,onClick:()=>y.mutate(),"data-testid":`alarm-disarm`,children:`Disarm`})]})]}),o===null?null:d(`div`,{className:`mt-3`,children:d(J,{title:`The panel did not do that`,message:o})}),c===null?null:d(`p`,{className:`mt-3 text-sm text-foreground-subtle`,children:c}),i===null?null:n(`div`,{className:`mt-3 rounded border border-warning p-3`,"data-testid":`alarm-refused`,children:[d(`p`,{className:`text-sm font-medium`,children:Zn(i.blocking.length)}),i.blocking.length>0?d(`ul`,{className:`mt-1 list-disc pl-5 text-sm`,children:i.blocking.map(e=>n(`li`,{children:[Xn(e),` `,n(`span`,{className:`text-foreground-subtle`,children:[`(`,e.state,`)`]})]},e.deviceId))}):null,n(`div`,{className:`mt-2 flex flex-wrap items-center gap-2`,children:[d(I,{type:`button`,size:`md`,variant:`danger`,disabled:b,onClick:()=>v.mutate(i.refusalId),children:`Arm anyway`}),d(`span`,{className:`text-xs text-foreground-subtle`,children:`Each open device is ignored until it closes, then monitored again.`})]})]}),n(`div`,{className:`mt-4`,"data-testid":`alarm-exclusions`,children:[d(`h4`,{className:`text-xs font-semibold uppercase text-foreground-subtle`,children:`Excluded sensors`}),e.exclusions.length===0?d(`p`,{className:`text-sm text-foreground-subtle`,children:`No sensor is excluded.`}):d(`ul`,{className:`mt-1 flex flex-col gap-1 text-sm`,children:e.exclusions.map(e=>n(`li`,{children:[Xn(e),` —`,` `,d(`span`,{className:`text-foreground-subtle`,children:Dn(e.phase)})]},e.deviceId))})]})]})}function rr(e,t){let n=e?.trim()??``;if(n===``)return``;if(t.state===`answered`){let e=Ae(n),r=t.zones.find(t=>t.locationKeys.includes(e));if(r!==void 0)return`${r.label} · ${n}`}return n}function ir(e){switch(e.kind){case`checking`:return{word:`Checking…`,note:null};case`hub-too-old`:return{word:`Unknown`,note:`This hub does not report sensor states — update the hub`};case`read-failed`:return{word:`Unknown`,note:`Could not read: ${e.error}`};case`open`:case`closed`:return{word:e.word,note:e.offline?`Offline — last known`:null};case`unknown`:return{word:`Unknown`,note:e.why===`not-answered`?`Not answered`:e.why===`read-failed`?`Could not read`:`No state reported`};case`not-opening`:return{word:`Not an opening`,note:null};case`removed`:return{word:`Removed`,note:`No longer in the device list`}}}var ar=`Not checked by this mode — switch on to remove the entry`;function or(e){return e.listedUncovered?{word:`No`,note:ar}:sr(e.coverage)}function sr(e){switch(e.kind){case`arm-checked`:return{word:`Yes`,note:null};case`arm-checked-skipped`:return{word:`Skipped`,note:`Blocks arming; notifications skipped: ${e.reason===`detection-off`?`detection off`:e.reason}`};case`unscoped`:return{word:`All-devices`,note:`Never blocks this mode`};case`not-covered`:return{word:`No`,note:`Never blocks this mode`}}}function cr(e){switch(e.kind){case`open`:case`read-failed`:case`hub-too-old`:case`removed`:return`warning`;case`closed`:case`checking`:case`unknown`:case`not-opening`:return`default`}}function lr(e){if(e.listedUncovered)return`default`;switch(e.coverage.kind){case`arm-checked`:return`success`;case`arm-checked-skipped`:return`warning`;case`unscoped`:case`not-covered`:return`default`}}function ur({name:e,variant:t,words:r}){return n(`span`,{"data-testid":`alarm-cell-${e}`,className:`flex flex-col items-start gap-0.5`,children:[d(U,{variant:t,"data-testid":`alarm-cell-${e}-badge`,children:r.word}),r.note===null?null:d(`span`,{className:`text-[10px] text-foreground-subtle`,"data-testid":`alarm-cell-${e}-note`,children:r.note})]})}var dr=`hidden sm:table-cell`;function fr(e){let{mode:t,inFlight:r,onSwitch:i,zones:a,disabled:o}=e;return[{key:`name`,header:`Name`,cell:e=>{let t=rr(e.device.location,a);return n(`span`,{className:`flex min-w-0 flex-col`,"data-testid":`alarm-cell-name`,"data-muted":e.listedUncovered?`true`:void 0,children:[d(`span`,{className:`truncate text-xs font-medium text-foreground`,children:e.device.name}),t===``?null:d(`span`,{className:`truncate text-[10px] text-foreground-subtle`,"data-testid":`alarm-cell-zone`,children:t})]})}},{key:`type`,header:`Type`,headerClassName:dr,cellClassName:`${dr} text-[11px] text-foreground-subtle`,cell:e=>me(e.device.type??null)},{key:`state`,header:`State`,cell:e=>d(ur,{name:`state`,variant:cr(e.cell),words:ir(e.cell)})},{key:`coverage`,header:`Checked when arming`,headerClassName:dr,cellClassName:dr,cell:e=>d(ur,{name:`coverage`,variant:lr(e),words:or(e)})},{key:`blocks`,header:`Blocks arming`,headerClassName:`text-right`,cellClassName:`text-right`,cell:e=>{let a=r!==null&&r.mode===t&&r.deviceId===e.device.id&&r.kind===`blocks`,s=r!==null&&!a;return n(`span`,{className:`inline-flex items-center justify-end gap-1`,children:[a?d(G,{className:`h-3 w-3 animate-spin`}):null,d(F,{checked:e.blocks,onCheckedChange:t=>i(e,`blocks`,t),disabled:o,"data-device-id":String(e.device.id),"data-testid":`alarm-switch-blocks`,"aria-label":`Blocks arming: ${e.device.name}`,"aria-busy":a?!0:void 0,"aria-disabled":s?!0:void 0,className:s?`opacity-50`:void 0})]})}},{key:`secure`,header:`Secure on arm`,headerClassName:`text-right`,cellClassName:`text-right`,cell:e=>{if(!e.controllable)return d(`span`,{className:`text-[10px] text-foreground-subtle`,children:`—`});let a=r!==null&&r.mode===t&&r.deviceId===e.device.id&&r.kind===`secureOnArm`,s=r!==null&&!a;return n(`span`,{className:`inline-flex items-center justify-end gap-1`,children:[a?d(G,{className:`h-3 w-3 animate-spin`}):null,d(F,{checked:e.secureOnArm,onCheckedChange:t=>i(e,`secureOnArm`,t),disabled:o,"data-device-id":String(e.device.id),"data-testid":`alarm-switch-secure`,"aria-label":`Secure on arm: ${e.device.name}`,"aria-busy":a?!0:void 0,"aria-disabled":s?!0:void 0,className:s?`opacity-50`:void 0})]})}}]}function pr(e){let{mode:t,rows:r,sensorsRetry:i,zones:a}=e;return n(`div`,{className:`space-y-2`,"data-testid":`alarm-sensors-${t}`,children:[i===null?null:n(`div`,{className:`flex items-center gap-2 text-xs text-warning`,"data-testid":`alarm-sensors-failed`,children:[d(`span`,{children:`Could not read the sensor states.`}),d(I,{type:`button`,size:`sm`,variant:`outline`,onClick:i,children:`Retry`})]}),d(y,{mode:`generic`,items:r,getKey:e=>String(e.device.id),getSearchText:e=>[e.device.name,rr(e.device.location,a),me(e.device.type??null)].join(` `),getFilterType:e=>me(e.device.type??null),columns:fr(e),rowClassName:e=>e.listedUncovered?`opacity-60`:``,searchPlaceholder:`Search sensors`,emptyLabel:`No sensor matches.`})]})}var mr=[/has no (?:handler for )?custom action ["']nc\.getAlarmSensors["']/,/No "query"-procedure on path "notificationRules\.getAlarmSensors"/,/method 'getAlarmSensors' not found on provider 'notification-rules'/];function hr(e){return mr.some(t=>t.test(e))}function gr(e,t,n){if(n)return{kind:`removed`};if(e.status===`pending`)return{kind:`checking`};if(e.status===`failed`)return hr(e.error)?{kind:`hub-too-old`}:{kind:`read-failed`,error:e.error};let r=e.sensors.find(e=>e.deviceId===t);if(r===void 0)return{kind:`unknown`,why:`not-answered`};switch(r.reading){case`unknown`:return{kind:`unknown`,why:r.unknownWhy??`read-failed`};case`open`:return{kind:`open`,word:r.state??r.reading,offline:r.online===!1};case`closed`:return{kind:`closed`,word:r.state??r.reading,offline:r.online===!1};case`not-opening`:return{kind:`not-opening`}}}function _r(e,t,n,r){if(n)return!1;if(e.status===`answered`){let n=e.sensors.find(e=>e.deviceId===t);if(n!==void 0)return n.controllable===!0}let i=(r??``).toLowerCase();return i===`cover`||i===`lock`||i===`switch`}function vr(e,t){if(e.deviceIds.includes(t)){let n=e.skippedDevices.find(e=>e.deviceId===t);return n===void 0?{kind:`arm-checked`}:{kind:`arm-checked-skipped`,reason:n.reason}}return e.allDevices&&!e.allDevicesExcept.includes(t)?{kind:`unscoped`}:{kind:`not-covered`}}function yr(e){return e.kind===`unscoped`||e.kind===`not-covered`}function br(e){let t=[...e.candidates].sort((e,t)=>e.name.localeCompare(t.name)||e.id-t.id),n=[];for(let r of t){let t=e.removedIds.has(r.id),i=vr(e.coverage,r.id),a=_r(e.sensors,r.id,t,r.type),o=Tt({controllable:a,deviceId:r.id,nonBlocking:e.nonBlocking,blocking:e.blocking}),s=Xe({controllable:a,deviceId:r.id,secureOnArmOff:e.secureOnArmOff}),c=e.nonBlocking.includes(r.id)||e.blocking.includes(r.id)||e.secureOnArmOff.includes(r.id),l=!t&&yr(i)&&(!o||c)&&c;!t&&yr(i)&&!c||n.push({device:r,removed:t,cell:gr(e.sensors,r.id,t),coverage:i,controllable:a,blocks:o,secureOnArm:s,listedUncovered:l})}return n}function xr(e){return e.rowCount>0?`rows`:e.candidatesComplete?`none`:`pending`}function Sr(e,t){if(!Number.isInteger(t)||t<1)throw Error(`alarmSensorReadChunks: the bound must be an integer >= 1, got ${t}`);let n=[...new Set(e)].sort((e,t)=>e-t),r=[];for(let e=0;e<n.length;e+=t)r.push(n.slice(e,e+t));return r}function Cr(e,t,n,r,i){return e===null?{kind:`start`,write:{mode:t,deviceId:n.device.id,name:n.device.name,kind:r,nextValue:i,controllable:n.controllable}}:{kind:`refused`,inFlight:e}}function wr(e){return e.kind===`secureOnArm`?{secureOnArmEdit:{mode:e.mode,deviceId:e.deviceId,secureOnArm:e.nextValue}}:e.controllable?{blockingEdit:{mode:e.mode,deviceId:e.deviceId,blocking:e.nextValue}}:{nonBlockingEdit:{mode:e.mode,deviceId:e.deviceId,nonBlocking:!e.nextValue}}}function Tr(e,t){return Et(wr(e),t)?{kind:`landed`}:{kind:`not-landed`}}function Er({coverage:e,live:t,rows:r,names:i}){let a=r.filter(e=>e.coverage.kind.startsWith(`arm-checked`)).length,o=t===void 0?null:Pn(t,e.mode),s=mn(e,i.nameOf);return n(`div`,{className:`flex flex-wrap items-center gap-1.5`,"data-testid":`alarm-badges-${e.mode}`,children:[_n(e)?d(U,{variant:`warning`,title:s,"data-testid":`alarm-arms-nothing`,children:`Arms nothing — no enabled rule is gated on this mode`}):n(U,{variant:`default`,title:s,"data-testid":`alarm-covers`,children:[`Checks `,a,` `,a===1?`sensor`:`sensors`]}),o!==null&&o.blocking>0?n(U,{variant:`warning`,"data-testid":`alarm-openings-${e.mode}`,children:[o.blocking,` open — `,o.blocking===1?`refuses`:`refuse`,` the arm`]}):null,o!==null&&o.unknown>0?n(U,{variant:`default`,children:[o.unknown,` unreadable`]}):null,e.skippedDevices.length>0?n(U,{variant:`warning`,title:hn(e.skippedDevices,i.nameOf),"data-testid":`alarm-skipped`,children:[e.skippedDevices.length,` not notified`]}):null]})}function Dr(e){return e.status===`answered`?e.openingIds:null}function Or({check:e,view:t}){return t.unresolved?e.status===`pending`?n(`p`,{className:`flex items-center gap-1 text-xs text-foreground-subtle`,"data-testid":`alarm-openings-checking`,children:[d(G,{className:`h-3 w-3 animate-spin`}),`Checking which devices are openings…`]}):e.status===`failed`?n(`div`,{className:`flex flex-wrap items-center gap-2 text-xs text-warning`,"data-testid":`alarm-openings-check-failed`,children:[n(`span`,{children:[`Couldn't check which devices are openings (`,e.error,`).`]}),d(I,{type:`button`,size:`sm`,variant:`outline`,onClick:e.retry,children:`Retry`})]}):null:null}function kr({coverage:e,settings:t,disabled:n,onDelayEdit:r}){let i=e.mode,a=Re(t,i);return d(`div`,{className:`grid grid-cols-3 gap-3`,"data-testid":`alarm-delays-${i}`,children:Vn.map(e=>{let o=a.source[e.field]==="default";return d(Wn,{label:e.label,value:a[e.field],max:e.max,zeroMeans:e.zeroMeans,disabled:n,testId:`alarm-delay-${i}-${e.key}`,onCommit:t=>r(e.field,t),adornment:o?d(U,{variant:`default`,title:`Uses the default (${t[e.field]} s)`,children:`Default`}):d(I,{type:`button`,size:`sm`,variant:`ghost`,disabled:n,title:`Use the default`,"aria-label":`${e.label}: use the default`,onClick:()=>r(e.field,`default`),"data-testid":`alarm-delay-${i}-${e.key}-default`,children:d(g,{className:`h-3.5 w-3.5`})})},e.field)})})}var Ar={"no-opening":`This household has no contact, cover or lock.`};function jr({coverage:e,live:t,settings:r,names:i,openingsCheck:a,rows:o,sensorsRetry:s,inFlight:c,onSwitch:l,zones:u,onDelayEdit:f,disabled:p}){let m=qn({live:t,listed:On(r,e.mode),openingIds:Dr(a)}),h=Jn(m),g=xr({rowCount:o.length,candidatesComplete:!m.unresolved});return n(`div`,{className:`flex flex-col gap-3`,"data-mode":e.mode,"data-empty":_n(e)?`true`:`false`,children:[d(Er,{coverage:e,live:t,rows:o,names:i}),d(kr,{coverage:e,settings:r,disabled:p,onDelayEdit:f}),n(`div`,{className:`flex flex-col gap-2`,"data-testid":`alarm-nonblocking-${e.mode}`,children:[d(Or,{check:a,view:m}),h===null?null:d(`p`,{className:`text-xs text-foreground-subtle`,children:Ar[h]}),g===`none`&&h===null?d(`p`,{className:`text-xs text-foreground-subtle`,"data-testid":`alarm-sensors-none`,children:`No sensor is covered by a rule of this mode.`}):null,g===`rows`?d(pr,{mode:e.mode,rows:o,sensorsRetry:s,inFlight:c,onSwitch:l,zones:u,disabled:p}):null]})]})}t();function Mr({profiles:e,busy:t,onActivate:r,onCreate:i,onClone:o,onRename:s,onDelete:c}){let[u,f]=l(``),[p,m]=l(!1),h=e.items.find(t=>t.id===e.activeId)??e.items[0],g=h!==void 0&&!h.isDefault,v=u.trim(),y=()=>{v.length!==0&&(i(v),f(``))},b=()=>{v.length===0||h===void 0||(o(h.id,v),f(``))},x=()=>{v.length===0||h===void 0||(s(h.id,v),f(``),m(!1))};return n(`div`,{className:`flex flex-col gap-2 rounded-md border border-border bg-surface-1 p-3`,"data-testid":`alarm-profiles`,children:[n(`div`,{className:`flex flex-wrap items-center gap-2`,children:[d(`label`,{className:`text-xs font-medium text-foreground-muted`,htmlFor:`alarm-profile-select`,children:`Profile`}),d(`select`,{id:`alarm-profile-select`,className:`h-8 min-w-[10rem] rounded-md border border-border bg-background px-2 text-sm`,"data-testid":`alarm-profile-select`,disabled:t,value:e.activeId,onChange:e=>r(e.target.value),children:e.items.map(e=>n(`option`,{value:e.id,children:[e.name,e.isDefault?` (default)`:``]},e.id))}),g?d(I,{type:`button`,variant:`ghost`,size:`sm`,disabled:t,"data-testid":`alarm-profile-delete`,title:`Delete this profile`,onClick:()=>{h!==void 0&&c(h.id)},children:d(_,{className:`h-3.5 w-3.5`})}):null]}),n(`div`,{className:`flex flex-wrap items-center gap-2`,children:[d(B,{className:`h-8 max-w-[14rem]`,"data-testid":`alarm-profile-name`,placeholder:p?`New name`:`New profile name`,value:u,disabled:t,onChange:e=>f(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(p?x():y())}}),p?n(a,{children:[d(I,{type:`button`,size:`sm`,disabled:t||v.length===0,"data-testid":`alarm-profile-rename-save`,onClick:x,children:`Rename`}),d(I,{type:`button`,variant:`ghost`,size:`sm`,disabled:t,"data-testid":`alarm-profile-rename-cancel`,onClick:()=>{m(!1),f(``)},children:`Cancel`})]}):n(a,{children:[n(I,{type:`button`,size:`sm`,disabled:t||v.length===0,"data-testid":`alarm-profile-create`,title:`Create with system defaults`,onClick:y,children:[d(W,{className:`mr-1 h-3.5 w-3.5`}),`Create`]}),n(I,{type:`button`,size:`sm`,variant:`secondary`,disabled:t||v.length===0||h===void 0,"data-testid":`alarm-profile-clone`,title:`Clone the selected profile`,onClick:b,children:[d(be,{className:`mr-1 h-3.5 w-3.5`}),`Clone`]}),d(I,{type:`button`,size:`sm`,variant:`ghost`,disabled:t||h===void 0,"data-testid":`alarm-profile-rename`,onClick:()=>{m(!0),f(h?.name??``)},children:`Rename`})]})]}),d(`p`,{className:`text-[11px] text-foreground-subtle`,children:`Create starts from system defaults. Clone copies the selected profile (sensors, secure-on-arm, delays). Switching applies that profile for the next arm.`})]})}var Nr=/\{\{\s*(\w+)\s*\}\}/g,Pr=[`subject`,`place`,`time`,`rule`,`occupancy`,`sound`,`sensor`,`system`,`digest`,`ai`];function Fr(e,t,n){let r=Math.min(Math.max(t.start,0),e.length),i=Math.min(Math.max(t.end,r),e.length);return{value:e.slice(0,r)+n+e.slice(i),cursor:r+n.length}}function Ir(e){let t=`{{${e.name}}}`;return{text:t,cursorOffset:e.dynamic?t.length-2:t.length}}function Lr(e){return[...e.matchAll(Nr)].map(e=>e[1]??``).filter(e=>e.length>0)}function Rr(e,t){return t.some(t=>t.dynamic?e.startsWith(t.dynamic.prefix)&&e.length>t.dynamic.prefix.length:t.name===e)}function zr(e,t){return[...new Set(Lr(e))].filter(e=>!Rr(e,t))}var Br={previewText:[`camera`,`rule`,`from`,`to`],captionText:[`rule`,`from`,`to`]};function Vr(e){return e.map(e=>{let t=nt.find(t=>t.name===e.name),n=e.systemEventKinds;if(t?.systemEventKinds===void 0||n===void 0)return e;let r=t.systemEventKinds.filter(e=>n.includes(e)||Wt.includes(e)),i=n.filter(e=>!r.includes(e));return{...e,systemEventKinds:[...r,...i]}})}function Hr(e){let t=new Set(e.map(e=>e.name)),n=nt.filter(e=>Be(e)&&!t.has(e.name));return[...e,...n]}function Ur(e,t){if(t.field===`previewText`||t.field===`captionText`){let n=Br[t.field];return e.filter(e=>e.families.includes(t.family)&&n.includes(e.name)&&!e.dynamic)}return e.filter(e=>!e.families.includes(t.family)||e.fields&&!e.fields.includes(t.field)||!rt(e.kinds,t.kind)||e.deliveries&&t.delivery!==void 0&&!e.deliveries.includes(t.delivery)?!1:He(e,t)&&Ut(e,t))}function Wr(e){return Pr.map(t=>({group:t,vars:e.filter(e=>e.group===t)})).filter(e=>e.vars.length>0)}var Gr=[`nc`,`template-catalog`],Kr=400;function qr(){let e=h();return i({queryKey:Gr,staleTime:5*6e4,queryFn:async()=>Hr(Vr((await e.trpcClient.notificationRules.getTemplateCatalog.query({})).vars))})}function Jr(e,t,n){let r=h(),a=P(t.title??``,Kr),o=P(t.body??``,Kr);return i({queryKey:[`nc`,`template-preview`,e,a,o],enabled:n&&(a.length>0||o.length>0),staleTime:3e4,queryFn:()=>r.trpcClient.notificationRules.previewTemplate.mutate({context:e,template:{...a?{title:a}:{},...o?{body:o}:{}}})})}t();var Yr={subject:`Subject`,place:`Place`,time:`Time`,rule:`Rule`,occupancy:`Occupancy`,sound:`Sound`,sensor:`Sensor`,system:`System event`,digest:`Digest`,ai:`AI`},Xr=`block text-[11px] font-medium text-foreground mb-1`,Zr=`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`;function Qr({label:t,value:r,onChange:i,vars:a,multiline:o=!1,placeholder:s,disabled:c=!1,testId:l}){let u=e(null),f=e(null),p=a?zr(r,a):[],m=e=>{let t=o?f.current:u.current,n={start:t?.selectionStart??r.length,end:t?.selectionEnd??r.length},a=Ir(e),s=Fr(r,n,a.text);i(s.value);let c=s.cursor-a.text.length+a.cursorOffset;requestAnimationFrame(()=>{t?.focus(),t?.setSelectionRange(c,c)})},h=e=>i(e.target.value);return n(`div`,{className:`space-y-1`,children:[d(`label`,{className:Xr,children:t}),o?d(`textarea`,{ref:f,value:r,rows:2,disabled:c,placeholder:s,onChange:h,className:Zr,"data-testid":`${l}-input`}):d(B,{ref:u,value:r,disabled:c,placeholder:s,onChange:h,"data-testid":`${l}-input`}),a&&a.length===0?d(`p`,{className:`text-[10px] text-foreground-subtle`,children:`No variables for this field.`}):null,a&&a.length>0?d(`div`,{className:`flex flex-wrap gap-x-3 gap-y-1`,children:Wr(a).map(e=>n(`div`,{className:`flex flex-wrap items-center gap-1`,"data-testid":`${l}-group-${e.group}`,children:[d(`span`,{className:`text-[10px] uppercase text-foreground-subtle`,children:Yr[e.group]}),e.vars.map(e=>d(`button`,{type:`button`,disabled:c,onMouseDown:e=>e.preventDefault(),onClick:()=>m(e),title:`${e.description??e.label} — e.g. "${e.example}"`,className:`rounded border border-border px-1.5 py-0.5 font-mono text-[10px] text-foreground hover:bg-surface-hover`,"data-testid":`${l}-chip-${e.name}`,children:e.dynamic?`${e.name}<class>`:e.name},e.name))]},e.group))}):null,p.length>0?n(`p`,{className:`flex items-center gap-1 text-[10px] text-warning`,"data-testid":`${l}-unknown`,children:[d(A,{className:`h-3 w-3`}),p.map(e=>`{{${e}}}`).join(` `),` will be empty in this notification.`]}):null]})}function $r({context:e,title:t,body:r,testId:i}){let a=Jr(e,{title:t,body:r},!0);return a.data?n(`div`,{className:`rounded-md border border-border bg-surface-subtle px-2.5 py-1.5 text-xs`,"data-testid":i,children:[d(`p`,{className:`text-[10px] uppercase text-foreground-subtle`,children:`Preview (example values)`}),a.data.title===null?null:d(`p`,{className:`font-medium`,children:a.data.title}),a.data.body===null?null:d(`p`,{className:`whitespace-pre-wrap`,children:a.data.body})]}):null}var Y=`block text-[11px] font-medium text-foreground mb-1`,ei=`mt-1 text-[10px] text-foreground-subtle`;function ti({title:e,hint:t,children:r}){return n(`div`,{className:`rounded-md border border-border px-3 py-3`,children:[d(`div`,{className:`mb-2 text-[11px] font-semibold text-foreground`,children:e}),t!==void 0&&d(`p`,{className:`mb-2 text-[10px] text-foreground-subtle`,children:t}),d(`div`,{className:`space-y-3`,children:r})]})}function ni({problems:e,testId:t=`digest-problems`}){return e.length===0?null:n(`div`,{className:`rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-[11px] text-danger`,"data-testid":t,children:[n(`div`,{className:`mb-1 flex items-center gap-1.5 font-medium`,children:[d(A,{className:`h-3.5 w-3.5`}),`This rule could never produce anything, so it cannot be saved:`]}),d(`ul`,{className:`list-disc space-y-0.5 pl-4`,children:e.map(e=>d(`li`,{children:e},e))})]})}function ri({warnings:e,testId:t=`digest-warnings`}){return e.length===0?null:n(`div`,{className:`rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-[11px] text-warning`,"data-testid":t,children:[n(`div`,{className:`mb-1 flex items-center gap-1.5 font-medium`,children:[d(N,{className:`h-3.5 w-3.5`}),`Worth knowing:`]}),d(`ul`,{className:`list-disc space-y-0.5 pl-4`,children:e.map(e=>d(`li`,{children:e},e))})]})}function ii({cameras:e,value:t,onChange:r,fleet:i,hint:a}){return n(`div`,{className:`space-y-1`,children:[d(V,{devices:e,listState:i.state,fleet:i,value:t,onChange:r,emptyLabel:`No camera selected`,testId:`digest-camera-picker`}),a!==void 0&&d(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:a})]})}function ai({targets:e,value:t,onChange:r,disabled:i=!1,testIdPrefix:a=`digest-target`,emptyMessage:o=`No delivery target is configured. Add one on the Targets tab first — without one the artefact is rendered and thrown away.`}){let s=e=>r(t.includes(e)?t.filter(t=>t!==e):[...t,e]);return e.length===0?d(`p`,{className:`text-[11px] text-foreground-subtle`,children:o}):d(`div`,{className:`divide-y divide-border rounded-md border border-border`,"data-testid":`${a}s`,children:e.map(e=>n(`label`,{className:[`flex items-center gap-2.5 px-3 py-1.5 text-xs text-foreground`,i?`cursor-not-allowed opacity-60`:`cursor-pointer hover:bg-surface-hover`].join(` `),children:[d(`input`,{type:`checkbox`,checked:t.includes(e.id),onChange:()=>s(e.id),disabled:i,className:`accent-primary`,"data-testid":`${a}-${e.id}`}),d(`span`,{className:`flex-1 truncate`,children:e.name}),!e.enabled&&d(U,{variant:`warning`,children:`disabled`})]},e.id))})}function oi({label:e,value:t,onChange:r,min:i,max:a,step:o,hint:s,emptyPlaceholder:c,testId:l,disabled:u=!1}){return n(`div`,{children:[d(`label`,{className:Y,children:e}),d(B,{type:`number`,value:t===void 0?``:String(t),disabled:u,...i===void 0?{}:{min:i},...a===void 0?{}:{max:a},...o===void 0?{}:{step:o},...c===void 0?{}:{placeholder:c},...l===void 0?{}:{"data-testid":l},onChange:e=>{let t=e.target.value.trim();if(t.length===0){r(void 0);return}let n=Number(t);Number.isFinite(n)&&r(n)}}),s!==void 0&&d(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:s})]})}function si({label:e,checked:t,onChange:r,hint:i,testId:a}){return n(`div`,{children:[n(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[d(F,{checked:t,onCheckedChange:r,"aria-label":e,...a===void 0?{}:{"data-testid":a}}),e]}),i!==void 0&&d(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:i})]})}function ci({title:e,body:t,onTitleChange:r,onBodyChange:i,family:a,testIdPrefix:o}){let s=qr(),c=e=>s.data?Ur(s.data,{family:a,field:e}):void 0;return n(`div`,{className:`space-y-2`,children:[d(Qr,{label:`Notification title`,value:e,onChange:r,vars:c(`title`),testId:`${o}-title`}),d(Qr,{label:`Notification body`,value:t,onChange:i,vars:c(`body`),multiline:!0,testId:`${o}-body`}),d(`p`,{className:`text-[10px] text-foreground-subtle`,children:`Leave both blank to use the hub's own wording (editable on the Texts tab).`}),d($r,{context:{family:a,field:`body`},title:e,body:t,testId:`${o}-preview`})]})}function li({open:e,ruleName:t,windowDescription:r,targetDescription:i,pending:a,onConfirm:o,onCancel:s,extra:c,confirmDisabled:l=!1}){return e?d(w,{open:!0,onOpenChange:e=>!e&&s(),children:d(De,{width:`sm`,children:n(`div`,{className:`space-y-3`,"data-testid":`digest-test-confirm`,children:[n(`h3`,{className:`flex items-center gap-2 text-sm font-semibold text-foreground`,children:[d(Ie,{className:`h-4 w-4 text-warning`}),`Send a real notification now?`]}),n(`p`,{className:`text-xs text-foreground-subtle`,children:[`"`,t,`" will be produced over `,r,` and DELIVERED to`,` `,i,` — on every phone that target reaches, right now. This is not a dry run.`]}),d(`p`,{className:`text-[11px] text-foreground-subtle`,children:`It does not consume the schedule: the next scheduled run still happens.`}),c,n(`div`,{className:`flex justify-end gap-2`,children:[d(I,{size:`sm`,variant:`secondary`,type:`button`,onClick:s,children:`Cancel`}),d(I,{size:`sm`,type:`button`,disabled:a||l,onClick:o,"data-testid":`digest-test-confirm-send`,children:a?`Sending…`:`Produce and send`})]})]})})}):null}t();var ui=[`notificationRules`,`getAlarmConfig`],di=[`notificationOutput`,`listTargets`],fi=[`notificationRules`,`getAlarmSensors`],pi=[`deviceManager`,`listDeviceIdsByCaps`,`alarm-openings`],mi=6e4;function hi(e){return e instanceof Error?e.message:String(e)}function gi({notice:e}){switch(e.kind){case`refused`:return n(`p`,{className:`text-xs text-warning`,role:`alert`,"data-testid":`alarm-switch-refused`,children:[`Saving `,e.inFlight.name,` (`,fn(e.inFlight.mode),`) — wait for it to finish.`]});case`not-landed`:return n(`p`,{className:`text-xs text-warning`,role:`alert`,"data-testid":`alarm-switch-not-landed`,children:[`The hub did not apply this change — another editor may have changed it, or the hub needs an update (`,e.write.name,`, `,fn(e.write.mode),`).`]});case`failed`:return d(`p`,{className:`text-xs text-danger`,role:`alert`,"data-testid":`alarm-switch-failed`,children:`Could not change ${e.write.name} for ${fn(e.write.mode)}: ${e.error}`})}}function _i(){let t=h(),a=s(),o=i({queryKey:ui,queryFn:async()=>t.trpcClient.notificationRules.getAlarmConfig.query({}),refetchInterval:e=>Cn(e.state.data?.live?.state)}),f=i({queryKey:di,queryFn:async()=>(await t.trpcClient.notificationOutput.listTargets.query({})).map(e=>({id:e.id,name:e.name,enabled:e.enabled}))}),p=se({projection:`slim`}),[m,g]=l(!1),_=u({mutationFn:e=>t.trpcClient.notificationRules.setAlarmConfig.mutate({patch:e}),onSuccess:(e,t)=>{a.setQueryData(ui,e),g(!Et(t,e.settings))}}),v=u({mutationFn:async e=>{switch(e.kind){case`activate`:return t.trpcClient.notificationRules.activateAlarmProfile.mutate({id:e.id});case`create`:return t.trpcClient.notificationRules.createAlarmProfile.mutate({name:e.name});case`clone`:return t.trpcClient.notificationRules.createAlarmProfile.mutate({name:e.name,cloneFromId:e.fromId});case`rename`:return t.trpcClient.notificationRules.renameAlarmProfile.mutate({id:e.id,name:e.name});case`delete`:return t.trpcClient.notificationRules.deleteAlarmProfile.mutate({id:e.id})}},onSuccess:e=>{a.setQueryData(ui,e),g(!1)}}),y=()=>a.invalidateQueries({queryKey:ui}),b=r(()=>{let e=new Map;for(let t of p.data??[])e.set(t.id,t.name);return e},[p.data]),x=o.data?.live,S=i({queryKey:pi,staleTime:mi,queryFn:async()=>new Set(await t.trpcClient.deviceManager.listDeviceIdsByCaps.query({capNames:[...Gn]}))}),w=r(()=>(p.data??[]).map(e=>({id:e.id,name:e.name,type:String(e.type),location:e.location??null})),[p.data]),T=r(()=>new Map(w.map(e=>[e.id,e])),[w]),D=S.isError?{status:`failed`,error:S.error instanceof Error?S.error.message:String(S.error),retry:()=>void S.refetch()}:S.data===void 0?{status:`pending`}:{status:`answered`,openingIds:S.data},O=r(()=>{let e=new Map;for(let t of x?.openings??[])for(let n of t.devices)e.set(n.deviceId,Xn(n));return Yn(b,we(p),e)},[x,b,p]),k=xe(!0),[A,j]=l(null),M=r(()=>{let e=new Map,t=o.data;if(t===void 0)return e;for(let n of t.coverage)e.set(n.mode,qn({live:t.live,listed:On(t.settings,n.mode),openingIds:S.data??null}).ids);return e},[o.data,S.data]),N=r(()=>{let e=new Set;for(let t of M.values())for(let n of t)O.isRemoved(n)||e.add(n);return[...e].toSorted((e,t)=>e-t)},[M,O]),P=i({queryKey:[...fi,N],enabled:N.length>0,placeholderData:c,refetchInterval:e=>e.state.error!==null&&hr(hi(e.state.error))?!1:x!==void 0&&En(x.state)?5e3:15e3,retry:(e,t)=>!hr(hi(t))&&e<2,queryFn:async()=>{let e=[];for(let n of Sr(N,500))e.push(await t.trpcClient.notificationRules.getAlarmSensors.query({deviceIds:[...n]}));return{sensors:e.flatMap(e=>e.sensors),readAt:Math.min(...e.map(e=>e.readAt))}}}),F=P.isError?{status:`failed`,error:hi(P.error)}:P.data===void 0?{status:`pending`}:{status:`answered`,sensors:P.data.sensors},te=e(null),[ne,I]=l(null),[re,ie]=l(null),ae=async e=>{try{let n=await t.trpcClient.notificationRules.setAlarmConfig.mutate({patch:wr(e)});Tr(e,n.settings).kind===`landed`?a.setQueryData(ui,n):(ie({kind:`not-landed`,write:e}),a.invalidateQueries({queryKey:ui}))}catch(t){ie({kind:`failed`,write:e,error:hi(t)}),a.invalidateQueries({queryKey:ui})}finally{te.current=null,I(null),ie(e=>e?.kind===`refused`?null:e)}},oe=(e,t,n,r)=>{let i=Cr(te.current,e,t,n,r);if(i.kind===`refused`){ie({kind:`refused`,inFlight:i.inFlight});return}te.current=i.write,I(i.write),ie(null),ae(i.write)};if(o.isLoading)return d(nn,{icon:fe,title:`Alarm`,subtitle:`Panel delays and mode coverage.`,children:d(G,{className:`h-5 w-5 animate-spin`})});let L=o.data;if(L===void 0||o.isError)return d(nn,{icon:fe,title:`Alarm`,subtitle:`Panel delays and mode coverage.`,children:d(J,{title:`Alarm settings are not available`,message:`This hub has not been updated to serve the alarm configuration yet.`})});if(L.deviceId===null)return d(nn,{icon:fe,title:`Alarm`,subtitle:`Panel delays and mode coverage.`,children:d(H,{className:`p-4`,children:d(`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 R=L.settings,ce=_.isPending||v.isPending,le=R.announceTargets,ue=e=>{g(!1),_.mutate(e)},de=(e,t)=>{switch(e){case`exitDelaySec`:return ue({exitDelaySec:t});case`entryDelaySec`:return ue({entryDelaySec:t});case`triggeredDurationSec`:return ue({triggeredDurationSec:t})}},pe=(e,t,n)=>{let r=Nn(R,e,t,n);r!==null&&ue({modeDelays:[r]})},me=new Map(L.coverage.map(e=>[e.mode,br({candidates:(M.get(e.mode)??[]).map(e=>({...T.get(e),id:e,name:O.nameOf(e)})),removedIds:new Set((M.get(e.mode)??[]).filter(O.isRemoved)),coverage:e,nonBlocking:On(R,e.mode),blocking:kn(R,e.mode),secureOnArmOff:An(R,e.mode),sensors:F})])),z=L.coverage.find(e=>e.mode===A)??L.coverage.find(e=>(me.get(e.mode)?.length??0)>0)??L.coverage[0],he=z?.mode??``;return n(nn,{icon:fe,title:`Alarm`,subtitle:`The panel, what each mode arms, and who hears about it.`,children:[_.isError?d(J,{title:`Could not save`,message:String(_.error)}):null,v.isError?d(J,{title:`Could not update profile`,message:String(v.error)}):null,m?d(`div`,{"data-testid":`alarm-save-not-landed`,children:d(J,{variant:`warning`,title:`Not applied`,message:`The hub did not apply this change — another editor may have changed it, or the hub needs an update`})}):null,L.profiles===void 0?null:d(Mr,{profiles:L.profiles,busy:ce,onActivate:e=>v.mutate({kind:`activate`,id:e}),onCreate:e=>v.mutate({kind:`create`,name:e}),onClone:(e,t)=>v.mutate({kind:`clone`,fromId:e,name:t}),onRename:(e,t)=>v.mutate({kind:`rename`,id:e,name:t}),onDelete:e=>v.mutate({kind:`delete`,id:e})}),d(nr,{live:L.live,onChanged:y}),n(H,{className:`p-4`,"data-testid":`alarm-coverage`,children:[d(ee,{value:he,onValueChange:e=>{let t=L.coverage.find(t=>t.mode===e);t!==void 0&&j(t.mode)},children:d(C,{className:`mb-3`,children:L.coverage.map(e=>n(E,{value:e.mode,"data-testid":`alarm-tab-${e.mode}`,children:[fn(e.mode),d(`span`,{className:`ml-1.5 text-[10px] text-foreground-subtle`,children:me.get(e.mode)?.length??0})]},e.mode))})}),re===null?null:d(gi,{notice:re}),z===void 0?null:d(jr,{coverage:z,live:L.live,settings:R,names:O,openingsCheck:D,rows:me.get(z.mode)??[],sensorsRetry:F.status===`failed`&&!hr(F.error)?()=>void P.refetch():null,inFlight:ne,onSwitch:(e,t,n)=>oe(z.mode,e,t,n),zones:k,onDelayEdit:(e,t)=>pe(z.mode,e,t),disabled:ce},z.mode)]}),n(H,{className:`p-4`,"data-testid":`alarm-default-delays`,children:[d(`h3`,{className:`mb-3 text-sm font-semibold`,title:`A mode without its own value uses these.`,children:`Default delays`}),d(`div`,{className:`grid grid-cols-3 gap-3`,children:Vn.map(e=>d(Wn,{label:e.label,value:R[e.field],max:e.max,zeroMeans:e.zeroMeans,disabled:ce,testId:`alarm-delay-${e.label.toLowerCase().replace(/\s+/g,`-`)}`,onCommit:t=>{t!==R[e.field]&&de(e.field,t)}},e.field))})]}),n(H,{className:`p-4`,"data-testid":`alarm-recipients`,children:[d(`h3`,{className:`mb-3 text-sm font-semibold`,title:`Every alarm change is sent to these targets.`,children:`Recipients`}),n(`div`,{className:`flex flex-col gap-2`,children:[d(vi,{query:f,selected:le,disabled:ce,onChange:e=>ue({announceTargets:e})}),le.length===0?d(`p`,{className:`text-xs text-warning`,"data-testid":`alarm-no-recipient`,children:`No recipient selected — alarm changes are not sent to anyone.`}):null]})]})]})}function vi({query:e,selected:t,disabled:n,onChange:r}){return e.isPending?d(G,{className:`h-4 w-4 animate-spin`}):e.isError?d(J,{title:`Targets could not be read`,message:String(e.error)}):d(`div`,{className:`max-h-56 overflow-y-auto`,children:d(ai,{targets:e.data,value:t,onChange:r,disabled:n,testIdPrefix:`alarm-target`,emptyMessage:`No notification targets are configured — nothing can be sent.`})})}var yi=`history`,bi=`ruleId`,xi=[bi],Si=24,Ci=0,wi=100;function Ti(e,t){let n=new URLSearchParams(e);return n.set(`tab`,yi),n.set(bi,t),n}function Ei(e,t){let n=new URLSearchParams(e);return t===``?n.delete(bi):n.set(bi,t),n}function Di(e){let t=e.get(`ruleId`)??``;return{ruleId:t,deviceId:``,status:``,windowHours:t===``?Si:Ci,limit:wi}}function Oi(e){let t=e.rules.map(e=>({value:e.id,label:e.name})),n=e.selected!==``&&!e.rules.some(t=>t.id===e.selected)?[{value:e.selected,label:e.answered?`Deleted rule (${e.selected})`:e.selected}]:[];return[{value:``,label:`All rules`},...t,...n]}t();var ki=[{value:1,label:`Last hour`},{value:24,label:`Last 24 hours`},{value:168,label:`Last 7 days`},{value:0,label:`All time`}],Ai=[{value:``,label:`Any status`},{value:`pending`,label:`Pending`},{value:`sent`,label:`Sent`},{value:`dead`,label:`Dead`}],ji=[50,100,250,500];function Mi(e){return e===`pending`||e===`sent`||e===`dead`?e:void 0}function Ni(e){switch(e){case`pending`:return`info`;case`sent`:return`success`;case`dead`:return`danger`}}function Pi(){let e=h(),[t,a]=tn(),[o,s]=l(()=>Di(t)),c=e=>s(t=>({...t,...e})),u=e=>{c({ruleId:e}),a(Ei(t,e),{replace:!0})},f=i({queryKey:[`notificationRules`,`listRules`,`forHistory`],queryFn:async()=>(await e.trpcClient.notificationRules.listRules.query({})).rules}),p=se({projection:`slim`}),m=Date.now(),g=i({queryKey:[`notificationRules`,`getHistory`,o],retry:!1,queryFn:async()=>{let t=o.windowHours>0?m-o.windowHours*36e5:void 0;return(await e.trpcClient.notificationRules.getHistory.query({filter:{limit:o.limit,...o.ruleId?{ruleId:o.ruleId}:{},...o.deviceId?{deviceId:Number(o.deviceId)}:{},...Mi(o.status)?{status:Mi(o.status)}:{},...t===void 0?{}:{since:t}}})).entries}}),_=r(()=>{let e=new Map;for(let t of p.data??[])t.type===Ft.Camera&&e.set(t.id,t.name);return e},[p.data]),v=e=>_.get(e)??`Camera #${String(e)}`,y=g.data??[],b=g.isError;return n(nn,{icon:sn,title:`Delivery history`,subtitle:`A searchable log of every notification the rules delivered (or failed to deliver).`,children:[n(`div`,{className:`mb-4 grid grid-cols-2 gap-2 sm:grid-cols-5`,children:[n(`div`,{children:[d(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:`Rule`}),d(q,{"data-testid":`history-rule-filter`,value:o.ruleId,onChange:e=>u(e.target.value),options:[...Oi({rules:f.data??[],answered:f.isSuccess,selected:o.ruleId})]})]}),n(`div`,{children:[d(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:`Camera`}),d(q,{value:o.deviceId,onChange:e=>c({deviceId:e.target.value}),options:[{value:``,label:`All cameras`},...(p.data??[]).map(e=>({value:String(e.id),label:e.name}))]})]}),n(`div`,{children:[d(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:`Status`}),d(q,{value:o.status,onChange:e=>c({status:e.target.value}),options:Ai.map(e=>({value:e.value,label:e.label}))})]}),n(`div`,{children:[d(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:`Window`}),d(q,{value:String(o.windowHours),onChange:e=>c({windowHours:Number(e.target.value)}),options:ki.map(e=>({value:String(e.value),label:e.label}))})]}),n(`div`,{children:[d(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:`Limit`}),d(q,{value:String(o.limit),onChange:e=>c({limit:Number(e.target.value)}),options:ji.map(e=>({value:String(e),label:String(e)}))})]})]}),g.isLoading&&d(`div`,{className:`flex items-center justify-center py-16`,children:d(G,{className:`h-6 w-6 animate-spin text-primary`})}),b&&!g.isLoading&&d(H,{children:n(`div`,{className:`flex flex-col items-center gap-2 px-4 py-14 text-center`,children:[d(sn,{className:`h-6 w-6 text-foreground-subtle`}),d(`div`,{className:`text-sm font-medium text-foreground`,children:`Delivery history requires a server update`}),d(`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.`}),n(`button`,{type:`button`,onClick:()=>void g.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:[d(Ce,{className:`h-3 w-3`}),` Retry`]})]})}),!b&&!g.isLoading&&y.length===0&&d(`div`,{className:`py-16 text-center text-xs text-foreground-subtle`,children:`No deliveries match these filters.`}),!b&&y.length>0&&d(H,{children:d(Pe,{columns:Fi(v),rows:y,rowKey:e=>e.id,minWidthPx:720,bordered:!1,mobileMode:`scroll`,maxBodyHeight:`max-h-[60vh]`})})]})}function Fi(e){return[{key:`when`,header:`When`,nowrap:!0,render:e=>d(`span`,{className:`text-[11px] text-foreground-subtle`,children:new Date(e.createdAt).toLocaleString()})},{key:`rule`,header:`Rule`,render:e=>d(`span`,{className:`text-xs font-medium text-foreground`,children:e.ruleName})},{key:`camera`,header:`Camera`,nowrap:!0,render:t=>d(`span`,{className:`text-[11px] text-foreground-subtle`,children:e(t.deviceId)})},{key:`subject`,header:`Subject`,render:e=>n(`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=>n(`span`,{className:`flex items-center gap-1.5`,children:[d(U,{variant:Ni(e.status),children:e.status}),e.attempts>1?n(`span`,{className:`text-[10px] text-foreground-subtle`,children:[`×`,e.attempts]}):null]})},{key:`error`,header:`Detail`,render:e=>e.error?d(`span`,{className:`text-[11px] text-danger`,children:e.error}):d(`span`,{className:`text-[11px] text-foreground-subtle`,children:`—`})}]}var Ii=[`onActivation`,`onDeactivation`,`onTrigger`,`onTriggerOff`],Li={onActivation:{title:`On activation`,hint:`Runs when the rule is turned on.`},onDeactivation:{title:`On deactivation`,hint:`Runs when the rule is turned off.`},onTrigger:{title:`On trigger`,hint:`Runs on a positive / raised match.`},onTriggerOff:{title:`On trigger off`,hint:`Runs on a clear / leave match. Delivery types without a clear edge never fire this.`}},Ri={onActivation:[],onDeactivation:[],onTrigger:[],onTriggerOff:[],buttons:[]};function zi(e){return e===void 0?Ri:{onActivation:[...e.onActivation??[]],onDeactivation:[...e.onDeactivation??[]],onTrigger:[...e.onTrigger??[]],onTriggerOff:[...e.onTriggerOff??[]],buttons:[...e.buttons??[]]}}function Bi(e){let t=e.buttons.filter(e=>e.id.trim()!==``&&e.label.trim()!==``&&e.sequenceId.trim()!==``),n={onActivation:e.onActivation,onDeactivation:e.onDeactivation,onTrigger:e.onTrigger,onTriggerOff:e.onTriggerOff};if(!(!Ii.some(e=>n[e].length>0)&&t.length===0))return{...n.onActivation.length>0?{onActivation:[...n.onActivation]}:{},...n.onDeactivation.length>0?{onDeactivation:[...n.onDeactivation]}:{},...n.onTrigger.length>0?{onTrigger:[...n.onTrigger]}:{},...n.onTriggerOff.length>0?{onTriggerOff:[...n.onTriggerOff]}:{},...t.length>0?{buttons:t}:{}}}function Vi(e,t){let n=[];for(let r of Ii){let i=e[r];i.length>4&&n.push({kind:`too-many`,message:`${Li[r].title} has more than 4 bindings.`});for(let e of i)e.kind===`sequence`&&!t.has(e.sequenceId)&&n.push({kind:`unknown-sequence`,message:`${Li[r].title} points at a sequence that does not exist.`})}let r=new Set;for(let i of e.buttons){let e=i.id.trim();e!==``&&(r.has(e)&&n.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),t.has(i.sequenceId.trim())||n.push({kind:`unknown-sequence`,message:`"${i.label||e}" points at a sequence that does not exist. It would never appear on a notification.`}))}return n}function Hi(e,t){return{id:`action-${String(e+1)}`,label:`Action`,sequenceId:t}}function Ui(){return{kind:`do`,action:{kind:`wait`,seconds:5}}}function Wi(e){return{kind:`sequence`,sequenceId:e}}function Gi(){return{kind:`wait`,seconds:5}}var Ki=[{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`}];function qi(e){let t=[],n=e.find(e=>e.type===Ft.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`,actions:[{kind:`cap`,deviceId:n.id,cap:`alarm-panel`,method:`trigger`,args:{}}]})});for(let n of e.filter(e=>e.type===Ft.Siren))t.push({id:`siren-${String(n.id)}`,label:`Sound ${n.name}`,hint:`On, 30 seconds, off.`,build:()=>({name:`sound ${n.name}`.toLowerCase(),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 Ji(e,t){return e.onTrigger.length>=4?e:{...e,onTrigger:[...e.onTrigger,{kind:`sequence`,sequenceId:t}]}}var Yi=`mt-1 w-full rounded border border-border bg-background px-2 py-1 text-xs`,Xi=`block text-[11px] font-medium text-foreground`;function Zi({title:e,description:t,children:r}){return n(`div`,{className:`flex flex-col gap-2`,children:[n(`div`,{children:[d(`h4`,{className:`text-xs font-semibold text-foreground`,children:e}),d(`p`,{className:`text-[11px] text-foreground-subtle`,children:t})]}),r!==void 0&&d(`div`,{className:`flex flex-wrap items-center gap-1`,children:r})]})}function Qi({value:e,onChange:t,devices:r,devicesState:i,sequences:a=[],onCreateSequence:o}){let s=Vi(e,new Set(a.map(e=>e.id))),c=qi(r),l=(n,r)=>t({...e,[n]:r}),u=(n,r)=>t({...e,buttons:e.buttons.map((e,t)=>t===n?r:e)});return n(`div`,{className:`space-y-4`,children:[s.length>0&&d(`div`,{className:`space-y-1 rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-[11px] text-warning`,children:s.map(e=>d(`p`,{children:e.message},e.message))}),c.length>0&&o!==void 0&&d(`section`,{className:`space-y-2`,children:d(Zi,{title:`Quick add`,description:`Creates a shared sequence and binds it to On trigger.`,children:c.map(r=>n(I,{size:`sm`,variant:`ghost`,type:`button`,title:r.hint,className:`min-w-0 max-w-full`,onClick:()=>{(async()=>{let n=r.build();t(Ji(e,await o({name:n.name,...n.minDelaySec===void 0?{}:{minDelaySec:n.minDelaySec},actions:[...n.actions]})))})()},children:[d(z,{className:`h-3.5 w-3.5 shrink-0`}),d(`span`,{className:`truncate`,children:r.label})]},r.id))})}),Ii.map(t=>d($i,{hookKey:t,bindings:e[t],sequences:a,devices:r,devicesState:i,onChange:e=>l(t,e)},t)),n(`section`,{className:`space-y-2`,children:[d(Zi,{title:`Buttons on the notification`,description:`Each button runs one shared sequence when tapped.`,children:n(I,{size:`sm`,variant:`ghost`,type:`button`,disabled:a.length===0,onClick:()=>t({...e,buttons:[...e.buttons,Hi(e.buttons.length,a[0]?.id??``)]}),children:[d(W,{className:`h-3.5 w-3.5 shrink-0`}),` Button`]})}),e.buttons.length>0&&n(`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:[d(A,{className:`mt-0.5 h-3.5 w-3.5 shrink-0`}),n(`span`,{children:[`A button's link travels inside the notification. The link is the only authority: anyone holding the notification can run the button `,d(`strong`,{children:`once`}),`, within 15 minutes.`]})]}),a.length===0?d(`p`,{className:`rounded border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:`Create a sequence on the Sequences tab first — a button runs one, it does not define its own steps.`}):e.buttons.length===0?d(`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)=>d(na,{button:n,sequences:a,onChange:e=>u(r,e),onRemove:()=>t({...e,buttons:e.buttons.filter((e,t)=>t!==r)})},`btn-${String(r)}`))]})]})}function $i({hookKey:e,bindings:t,sequences:r,devices:i,devicesState:a,onChange:o}){let s=Li[e];return n(`section`,{className:`space-y-2`,children:[n(Zi,{title:s.title,description:s.hint,children:[n(I,{size:`sm`,variant:`ghost`,type:`button`,disabled:t.length>=4||r.length===0,onClick:()=>o([...t,Wi(r[0]?.id??``)]),children:[d(W,{className:`h-3.5 w-3.5`}),` Sequence`]}),n(I,{size:`sm`,variant:`ghost`,type:`button`,disabled:t.length>=4,onClick:()=>o([...t,Ui()]),children:[d(W,{className:`h-3.5 w-3.5`}),` Single action`]})]}),t.length===0?d(`p`,{className:`rounded border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:`Nothing on this edge.`}):t.map((n,s)=>d(ea,{binding:n,sequences:r,devices:i,devicesState:a,onChange:e=>o(t.map((t,n)=>n===s?e:t)),onRemove:()=>o(t.filter((e,t)=>t!==s))},`${e}-${String(s)}`))]})}function ea({binding:e,sequences:t,devices:r,devicesState:i,onChange:a,onRemove:o}){return d(`div`,{className:`space-y-2 rounded-md border border-border p-3`,children:n(`div`,{className:`flex flex-wrap items-end gap-2`,children:[n(`div`,{className:`w-32`,children:[d(`label`,{className:Xi,children:`Kind`}),n(`select`,{className:Yi,value:e.kind,onChange:e=>a(e.target.value===`sequence`?Wi(t[0]?.id??``):Ui()),children:[d(`option`,{value:`sequence`,children:`Sequence`}),d(`option`,{value:`do`,children:`Single action`})]})]}),e.kind===`sequence`?n(`div`,{className:`min-w-0 flex-1`,children:[d(`label`,{className:Xi,children:`Sequence`}),d(`select`,{className:Yi,value:e.sequenceId,onChange:e=>a({kind:`sequence`,sequenceId:e.target.value}),children:t.map(e=>d(`option`,{value:e.id,children:e.name},e.id))})]}):d(ta,{action:e.action,devices:r,devicesState:i,onChange:e=>a({kind:`do`,action:e})}),d(I,{size:`sm`,variant:`ghost`,type:`button`,onClick:o,title:`Remove`,children:d(_,{className:`h-3.5 w-3.5`})})]})})}function ta({action:e,devices:t,devicesState:r,onChange:i}){return n(`div`,{className:`flex min-w-0 flex-1 flex-col gap-2`,children:[n(`div`,{className:`w-24`,children:[d(`label`,{className:Xi,children:`Step`}),n(`select`,{className:Yi,value:e.kind,onChange:e=>i(e.target.value===`wait`?{kind:`wait`,seconds:5}:{kind:`cap`,deviceId:t[0]?.id??0,cap:``,method:``}),children:[d(`option`,{value:`cap`,children:`Do`}),d(`option`,{value:`wait`,children:`Wait`})]})]}),e.kind===`wait`?n(`div`,{className:`w-28`,children:[d(`label`,{className:Xi,children:`Seconds`}),d(`input`,{type:`number`,min:0,max:300,className:Yi,value:e.seconds,onChange:e=>i({kind:`wait`,seconds:Number(e.target.value)})})]}):d(rn,{value:e,devices:t,listState:r,onChange:e=>{i({kind:`cap`,deviceId:typeof e.deviceId==`number`?e.deviceId:0,cap:e.cap,method:e.method,...e.args===void 0?{}:{args:{...e.args}}})}})]})}function na({button:e,sequences:t,onChange:r,onRemove:i}){return n(`div`,{className:`flex flex-wrap items-end gap-2 rounded-md border border-border p-3`,children:[n(`div`,{className:`w-28`,children:[d(`label`,{className:Xi,children:`Id`}),d(B,{className:`mt-1`,value:e.id,onChange:t=>r({...e,id:t.target.value})})]}),n(`div`,{className:`min-w-0 flex-1`,children:[d(`label`,{className:Xi,children:`Label`}),d(B,{className:`mt-1`,value:e.label,onChange:t=>r({...e,label:t.target.value})})]}),n(`div`,{className:`min-w-0 flex-1`,children:[d(`label`,{className:Xi,children:`Sequence`}),d(`select`,{className:Yi,value:e.sequenceId,onChange:t=>r({...e,sequenceId:t.target.value}),children:t.map(e=>d(`option`,{value:e.id,children:e.name},e.id))})]}),n(`div`,{className:`w-32`,children:[d(`label`,{className:Xi,children:`Icon`}),n(`select`,{className:Yi,value:e.icon??``,onChange:t=>{let n={...e};t.target.value===``?delete n.icon:n.icon=t.target.value,r(n)},children:[d(`option`,{value:``,children:`—`}),Ki.map(e=>d(`option`,{value:e.value,children:e.label},e.value))]})]}),d(I,{size:`sm`,variant:`ghost`,type:`button`,onClick:i,title:`Remove`,children:d(_,{className:`h-3.5 w-3.5`})})]})}function ra(e){return t=>Object.prototype.hasOwnProperty.call(e,t)}var ia=ra({devices:!0}),aa=ra({classes:!0,classesExclude:!0,labelEquals:!0,identities:!0,identitiesExclude:!0,eventTypeTokens:!0,sensorKinds:!0}),oa=ra({minConfidence:!0,minImportance:!0,minLabelConfidence:!0}),sa=ra({minDwellSeconds:!0}),ca=ra({source:!0}),la=ra({crossing:!0}),ua=ra({packagePhase:!0}),da=ra({sensorTransition:!0}),fa=ra({plates:!0}),pa=ra({occupancy:!0}),ma=ra({audio:!0}),ha=ra({systemEvent:!0}),ga=ra({deviceState:!0}),_a=ra({scene:!0});function va(e,t){let n=e[t];return Array.isArray(n)?n:[]}function ya(e,t){let n=e[t];return typeof n==`number`?n:void 0}t();function ba(e,t){let n=h().trpcClient,i=o({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 r(()=>{let e=[],n=new Set;for(let r of i){if(!r.data)continue;let i=t.find(e=>e.id===r.data.deviceId)?.name;for(let t of r.data.zones)n.has(t.id)||(n.add(t.id),e.push({value:t.id,label:t.name,...i===void 0?{}:{hint:i}}))}return{options:e,loading:i.some(e=>e.isLoading),failed:i.some(e=>e.isError)}},[i,t])}function xa(e){let t=h().trpcClient,n=o({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 r(()=>{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 Sa(){let e=te();return r(()=>({options:(e.data??[]).map(e=>({value:e.id,label:e.name})),loading:e.isLoading,failed:e.isError===!0}),[e.data,e.isLoading,e.isError])}function Ca(){let e=R({limit:200}),t=ae();return r(()=>{let n=new Set;for(let e of t.data??[])e.name.trim().length>0&&n.add(e.name);let r=new Set;for(let t of e.data??[])t.text.trim().length>0&&r.add(t.text);return[...[...n].sort(),...[...r].sort()]},[e.data,t.data])}function wa({options:e,value:t,onChange:i,loading:a,emptyHint:o,placeholder:s,noFreeText:c=!1}){let[u,f]=l(``),p=r(()=>new Set(e.map(e=>e.value)),[e]),m=r(()=>new Set(t),[t]),h=t.filter(e=>!p.has(e)),g=e=>{i(m.has(e)?t.filter(t=>t!==e):[...t,e])},_=()=>{let e=u.trim();e.length===0||t.includes(e)||(i([...t,e]),f(``))};return n(`div`,{className:`mt-1 space-y-1.5`,children:[h.length>0&&d(`div`,{className:`flex flex-wrap gap-1`,children:h.map(e=>n(`button`,{type:`button`,onClick:()=>i(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?d(`div`,{className:`max-h-40 overflow-y-auto rounded-md border border-border divide-y divide-border`,children:e.map(e=>n(`label`,{className:`flex items-center gap-2.5 px-3 py-1.5 text-xs text-foreground cursor-pointer hover:bg-surface-hover`,children:[d(`input`,{type:`checkbox`,checked:m.has(e.value),onChange:()=>g(e.value),className:`accent-primary`}),d(`span`,{className:`flex-1 truncate`,children:e.label}),e.hint!==void 0&&d(`span`,{className:`text-[10px] text-foreground-subtle`,children:e.hint})]},e.value))}):d(`p`,{className:`text-[10px] text-foreground-subtle`,children:a===!0?`Loading…`:o}),!c&&d(`input`,{value:u,onChange:e=>f(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),_())},placeholder:s,className:`w-full rounded-md border border-border bg-background px-2 py-1 text-xs text-foreground placeholder:text-foreground-subtle`})]})}var Ta=[{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.`}],Ea=`Immediate, grouped`,Da=Ta.flatMap(e=>e.value===`immediate`?[e,{value:`immediate-grouped`,label:Ea,hint:`Waits for subjects to be recognised, then sends one message with a mosaic, one picture per subject.`}]:[e]);function Oa(e){return e.groupingSec!==void 0&&Ge(e)?`immediate-grouped`:e.delivery}function ka(e){let t=(e.delivery===`immediate`||e.delivery===`track-end`)&&Ge({delivery:`immediate`,conditions:e.conditions});return Da.filter(e=>e.value!==`immediate-grouped`||t)}function Aa(e){return Da.find(t=>t.value===e)?.value}function ja(e,t=Ea){return Oa(e)===`immediate-grouped`?`${t} · ${String(e.groupingSec)} s`:Na(e.delivery)}function Ma(e){if(e.trim().length===0)return;let t=Number(e);return Number.isFinite(t)&&t>=0?Math.trunc(t):void 0}function Na(e){return Ta.find(t=>t.value===e)?.label??e}function Pa(e){return Ta.some(t=>t.value===e)}var Fa=[{key:`all`,label:`All rules`,blurb:`Every event-driven notification rule. Summaries and Timelapses live in their own tabs on this same Rules page — pick the type under New rule when creating from here.`,newRuleLabel:`New rule`,emptyHint:`No event-driven rules yet. Click "New rule" and pick Rule, Summary or Timelapse.`,creatable:!0},{key:`detection`,label:`Detections`,blurb:`Rules driven by what the cameras SEE — detections, tracks and package events. Doorbell presses and other sensor changes have their own section now (operator ruling, 2026-10-01).`,newRuleLabel:`New detection rule`,emptyHint:`No detection rules yet. Click "New detection rule" to author one.`,creatable:!0},{key:`sensor`,label:`Sensors`,blurb:`Rules driven by a device or sensor CHANGING STATE — a doorbell press, a linked sensor opening or closing. The picture is one snapshot of the camera the sensor is attributed to; there is no media choice to make.`,newRuleLabel:`New sensor rule`,emptyHint:`No sensor rules yet. Click "New sensor rule" to be told when a doorbell is pressed or a linked sensor changes.`,creatable:!0},{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.`,creatable:!0},{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.`,creatable:!0},{key:`device-events`,label:`Device events`,blurb:`Rules about your devices: offline or back, switched off or on, a stream dropping, a battery or consumable running low, a camera detecting nothing. These carry no image.`,newRuleLabel:`New device-event rule`,emptyHint:`No device-event rules yet. Click "New device-event rule" to be told when a device drops, a battery runs low or a camera goes blind.`,creatable:!0},{key:`system`,label:`System events`,blurb:`Rules about the installation itself: a node leaving the cluster, an addon crash-looping, an update available or installed, a backup or export finishing. These carry no image and are not tied to a detection.`,newRuleLabel:`New system rule`,emptyHint:`No system rules yet. Click "New system rule" to be told when a node leaves, an update lands or a backup finishes.`,creatable:!0},{key:`alarm`,label:`Alarm`,blurb:`Rules about the alarm panel: arming, armed, triggered, disarmed, and the refusals in between.`,newRuleLabel:`New alarm rule`,emptyHint:`No alarm rules yet. Click "New alarm rule" to be told when the alarm arms, goes off or is disarmed.`,creatable:!0},{key:`mixed`,label:`To recreate`,blurb:`System rules authored before the three families existed. Each mixes families and keeps firing as it is, but it cannot be edited: recreate it as one rule per family (Device events, System events, Alarm). Open none of them: Delete each once its replacements exist.`,newRuleLabel:`New rule`,emptyHint:`Nothing to recreate.`,creatable:!1}];function Ia(e){return ot(it(e)).editable}function La(e){return Kt(Ra(e))}function Ra(e){switch(e){case`device-events`:case`system`:case`alarm`:case`mixed`:return e;default:return}}var za=new Map([[0,`No cooldown`],[60,`1 minute`],[3600,`1 hour`]]),Ba=86400;function Va(e){let t=za.get(e);return t===void 0?e%3600==0?`${e/3600} hours`:e%60==0?`${e/60} minutes`:`${e} seconds`:t}function Ha(e){if(e.trim().length===0)return;let t=Number(e);return Number.isFinite(t)&&t>=0?Math.trunc(t):void 0}var Ua=[{value:`rule-device`,label:`Per device`},{value:`rule`,label:`Whole rule (one window for every device)`}];function Wa(e){return Ua.find(t=>t.value===e)?.value}var Ga=[{value:`per-class`,label:`Separate windows per class (default)`},{value:`shared`,label:`Shared across classes`}];function Ka(e){return Ga.find(t=>t.value===e)?.value}var qa=[{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 Ja(e){return qa.find(t=>t.value===e)?.value}var Ya=[{value:``,label:`Automatic`},{value:`cropped`,label:`Cropped on the subject`},{value:`full`,label:`Full frame`},{value:`boxed`,label:`Full frame with boxes`}];function Xa(e){let t=Ya.find(t=>t.value===e)?.value;return t===``?void 0:t}var Za=[{value:``,label:`Mosaic of every linked camera (default)`},{value:`mosaic`,label:`Mosaic of every linked camera`},{value:`each`,label:`One image per camera (first camera where only one is allowed)`}];function Qa(e){let t=Za.find(t=>t.value===e)?.value;return t===``?void 0:t}var $a=[{value:``,label:`Lowest available`},{value:`low`,label:`Low`},{value:`mid`,label:`Medium`},{value:`high`,label:`High`}];function eo(e){let t=$a.find(t=>t.value===e)?.value;return t===``?void 0:t}var to=[{value:`any`,label:`Any source`},{value:`pipeline`,label:`Pipeline`},{value:`onboard`,label:`Onboard (camera)`},{value:`sensor`,label:`Sensor`}],no=[{value:`delivered`,label:`Delivered`},{value:`picked-up`,label:`Picked up`},{value:`both`,label:`Both`}],ro=[{value:``,label:`It triggers and when it clears`},{value:`raised`,label:`Only when it triggers`},{value:`cleared`,label:`Only when it clears`}];function io(e){return e===`raised`||e===`cleared`?e:void 0}function ao(e,t){return e===`sensorTransition`?Qe(t.sensorKinds):!0}var oo=[{value:`enter`,label:`Entering`},{value:`exit`,label:`Leaving`},{value:`any`,label:`Entering or leaving`}],so=`enter`;function co(e){return e===`exit`||e===`any`?e:void 0}var lo=[{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`}];function uo(e,t){return e.options&&e.options.length>0?e.options:t}var fo=[{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 po(e){if(e===``)return;let t=Number(e);return Number.isFinite(t)&&t>=1&&t<=8?t:void 0}var mo=new Map(Object.entries({"device-offline":`Device offline`,"device-online":`Device online`,"device-disabled":`Device switched off`,"device-enabled":`Device switched on`,"stream-offline":`Stream offline`,"stream-online":`Stream online`,"device-battery-low":`Battery low`,"device-battery-normal":`Battery back to normal`,"device-consumable-low":`Consumable low`,"device-consumable-normal":`Consumable back to normal`,"device-tank-low":`Tank low (water, detergent)`,"device-tank-full":`Tank full (dirty water, dust)`,"device-tank-normal":`Tank back to normal`,"detection-blind":`Camera detecting nothing`,"node-offline":`Node offline`,"node-online":`Node online`,"node-inference-unavailable":`Node has no usable inference device`,"addon-crash-loop":`Addon stopped after repeated crashes`,"addon-update-available":`Addon update available`,"addon-updated":`Addons updated`,"server-update-available":`Server update available`,"server-updated":`Server updated`,"wrapper-update-available":`Container / app update available`,"export-completed":`Export completed`,"backup-completed":`Backup completed`,"alarm-arm-refused":`Alarm arm refused (something is open)`,"alarm-check-failed":`Alarm check failed (armed anyway)`,"alarm-arming":`Alarm arming (exit delay)`,"alarm-armed":`Alarm armed`,"alarm-pending":`Alarm entry delay started`,"alarm-triggered":`Alarm triggered`,"alarm-rearmed":`Alarm re-armed after siren`,"alarm-sensor-bypass":`Alarm sensor bypass`,"alarm-disarmed":`Alarm disarmed`}));function ho(e){return mo.get(e)}var go={"device-state":`A device the hub can no longer reach, or that came back. Switched off / on is a device an operator turned off or back on — not a fault, a choice.`,streams:`A stream that stopped or came back.`,battery:`A battery below the cluster threshold, and (optionally) its return to normal. Devices with a binary low-battery indicator are judged by the indicator, not by the percentage.`,consumables:`A consumable — filter, brush, bag — at or below this rule’s threshold, or that the device reports as due for replacement, and (optionally) its return to normal after a change. A device that only says "replace" is judged by that, not by a percentage.`,tanks:`A robot vacuum tank the device reports as running low (clean water, detergent) or full (dirty water, dust bin), and (optionally) its return to normal once refilled or emptied.`,"detection-blind":`A camera that is running and being analysed, but detects nothing — up, and producing no work.`,nodes:`An agent or worker node joining or leaving the cluster, or an online node whose inference devices all went away.`,addons:`An addon the hub has stopped restarting after repeated crashes, a newer version of an addon, or an addon update that just finished.`,updates:`A newer version of the server itself, or of the container / app the node runs inside, is available — or a server update just finished.`,"backups-exports":`A scheduled or manual backup of the hub finished, or a footage export finished rendering.`,alarm:`The alarm panel refusing to arm, arming, armed, counting down to a siren, going off, re-arming, excluding an open sensor, or being disarmed.`},_o=lt.map(e=>({id:e.id,family:e.family,label:e.label,hint:go[e.id]??``,kinds:e.kinds.flatMap(e=>{let t=ho(e);return t===void 0?[]:[{value:e,label:t}]})}));function vo(e){return _o.filter(t=>t.family===e)}function yo(e){let t=Je(e).conditions.systemEvent;return t===void 0?{kinds:(vo(e)[0]?.kinds??[]).map(e=>e.value)}:{...t,kinds:[...t.kinds]}}var bo=_o.flatMap(e=>e.kinds);function xo(e){return bo.find(t=>t.value===e)?.label??e}function So(e){return{devices:Le(e,`deviceIds`),deviceTypes:Le(e,`deviceTypes`),nodes:Le(e,`nodeIds`),packages:Le(e,`packageNames`),consumableThreshold:Le(e,`consumableLowPercent`)}}function Co(e,t){let n=st[e],r=So(t);return{devices:n.includes(`deviceIds`)&&r.devices,excludeDevices:n.includes(`excludeDeviceIds`)&&r.devices,deviceTypes:n.includes(`deviceTypes`)&&r.deviceTypes,nodes:n.includes(`nodeIds`)&&r.nodes,packages:n.includes(`packageNames`)&&r.packages,consumableThreshold:n.includes(`consumableLowPercent`)&&r.consumableThreshold}}var wo=Object.values(Ft).map(e=>({value:e,label:To(e)})).toSorted((e,t)=>e.label.localeCompare(t.label));function To(e){let t=e.replaceAll(`-`,` `);return t.charAt(0).toUpperCase()+t.slice(1)}function Eo(e,t,n){if(!vo(n).some(e=>e.kinds.some(e=>e.value===t)))return e;let r=e?.kinds??[];return r.length===1&&r[0]===t?e:Ao(e,r.includes(t)?r.filter(e=>e!==t):bo.filter(e=>e.value===t||r.includes(e.value)).map(e=>e.value),n)}function Do(e,t){return t===void 0?void 0:Ao(t,t.kinds,e)}function Oo(e,t){let n=e?.kinds??[];if(n.length===0)return;let r=ko(t,`deviceIds`,e?.deviceIds),i=ko(t,`excludeDeviceIds`,e?.excludeDeviceIds),a=ko(t,`deviceTypes`,e?.deviceTypes),o=ko(t,`nodeIds`,e?.nodeIds),s=ko(t,`packageNames`,e?.packageNames),c=Object.prototype.hasOwnProperty.call(t,`consumableLowPercent`)?t.consumableLowPercent:e?.consumableLowPercent;return{kinds:[...n],...r===void 0?{}:{deviceIds:[...r]},...i===void 0?{}:{excludeDeviceIds:[...i]},...a===void 0?{}:{deviceTypes:[...a]},...o===void 0?{}:{nodeIds:[...o]},...s===void 0?{}:{packageNames:[...s]},...c===void 0?{}:{consumableLowPercent:c}}}function ko(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 Ao(e,t,n){let r=Co(n,t),i=r.devices?e?.deviceIds:void 0,a=r.excludeDevices?e?.excludeDeviceIds:void 0,o=r.deviceTypes?e?.deviceTypes:void 0,s=r.nodes?e?.nodeIds:void 0,c=r.packages?e?.packageNames:void 0,l=r.consumableThreshold?e?.consumableLowPercent:void 0;return{kinds:[...t],...i&&i.length>0?{deviceIds:[...i]}:{},...a&&a.length>0?{excludeDeviceIds:[...a]}:{},...o&&o.length>0?{deviceTypes:[...o]}:{},...s&&s.length>0?{nodeIds:[...s]}:{},...c&&c.length>0?{packageNames:[...c]}:{},...l===void 0?{}:{consumableLowPercent:l}}}var jo=95;function Mo(e){let t=e.trim();if(t===``)return{kind:`clear`};let n=Number(t);return Number.isInteger(n)&&n>=1&&n<=jo?{kind:`set`,value:n}:{kind:`invalid`}}function No(e,t=2){if(e===void 0||e.length===0)return`No event selected`;let n=e.slice(0,t).map(xo).join(`, `),r=e.length-Math.min(t,e.length);return r>0?`${n} +${r}`:n}function Po(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,o=e.excludeDeviceIds?.length??0;r>0&&t.push(e.deviceTypes?.map(To).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`}`);let s=o>0?`except ${o} device${o===1?``:`s`}`:null,c=e.consumableLowPercent===void 0?[]:[`consumables at ${e.consumableLowPercent}%`];return t.length===0?[s===null?`Everything`:`Everything ${s}`,...c].join(` · `):[...t,...s===null?[]:[s],...c].join(` · `)}function Fo(e){return e===void 0||(e.deviceTypes?.length??0)===0?!1:e.kinds.some(e=>gt.includes(e))}var Io=[`all`,`only`,`except`];function Lo(e,t){return(e??[]).length>0?`only`:(t??[]).length>0?`except`:`all`}function Ro(e,t){let n=[...e??[]],r=[...t??[]];return{mode:Lo(n,r),include:n,exclude:r,legacyBoth:n.length>0&&r.length>0}}function zo(e,t){return{...e,mode:t}}function Bo(e){switch(e.mode){case`only`:return e.include;case`except`:return e.exclude;case`all`:return[]}}function Vo(e,t){switch(e.mode){case`only`:return{...e,include:[...t]};case`except`:return{...e,exclude:[...t]};case`all`:return e}}function Ho(e){return e.mode===`only`&&e.legacyBoth?e.exclude:[]}function Uo(e){return{...e,exclude:[],legacyBoth:!1}}function Wo(e){switch(e.mode){case`all`:return{};case`except`:return e.exclude.length>0?{exclude:[...e.exclude]}:{};case`only`:{let t=Ho(e);return{...e.include.length>0?{include:[...e.include]}:{},...t.length>0?{exclude:[...t]}:{}}}}}function Go(e){let t=Wo(e),n=t.include??[],r=t.exclude??[];return[...e.include.filter(e=>!n.includes(e)),...e.exclude.filter(e=>!r.includes(e))]}var Ko=[10,30,60],qo=[5,10,15,30,60,120,240,480];function Jo(e){return e>=60&&e%60==0?`${e/60} h`:`${e} min`}var Yo=new Set([`alarm-arm-refused`,`alarm-check-failed`,`alarm-arming`,`alarm-armed`,`alarm-pending`,`alarm-triggered`,`alarm-rearmed`,`alarm-sensor-bypass`,`alarm-disarmed`]),Xo=`alarm-panel`;function Zo(e,t){for(let t of e.systemEvent?.kinds??[])if(Yo.has(t))return!0;for(let e of t)if(e.kind===`cap`&&e.cap===Xo)return!0;return!1}function Qo(e,t){let n=new Map(t.map(e=>[e.id,e])),r=[];for(let t of[`onActivation`,`onDeactivation`,`onTrigger`,`onTriggerOff`])for(let i of e[t])if(i.kind===`do`)r.push(i.action);else{let e=n.get(i.sequenceId);e!==void 0&&r.push(...e.actions)}for(let t of e.buttons){let e=n.get(t.sequenceId);e!==void 0&&r.push(...e.actions)}return r}function $o(e){let{devices:t,devicesExclude:n,classes:r,classesExclude:i,...a}=e;return{conditions:a,deviceScope:Ro(t,n),classScope:Ro(r,i)}}function es(e){let t=Wo(e.deviceScope),n=Wo(e.classScope);return{...e.conditions,...t.include===void 0?{}:{devices:[...t.include]},...t.exclude===void 0?{}:{devicesExclude:[...t.exclude]},...n.include===void 0?{}:{classes:[...n.include]},...n.exclude===void 0?{}:{classesExclude:[...n.exclude]}}}function ts(e){return e.deviceScope.mode===`only`?e.deviceScope.include:[]}function ns(e,t,n){let r=it(n);return e.some(e=>e.id===t&&Ke(e,n.delivery,r))}function rs(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,mediaLinkedCameras:void 0,templateTitle:``,templateBody:``,...$o(t),schedule:void 0,systemEventDelivery:void 0,snoozeAllowGlobal:!1,groupingSec:void 0,snoozeOptions:void 0,actions:Ri,cooldownSec:30,cooldownScope:`rule-device`,cooldownGranularity:void 0}}function is(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,mediaLinkedCameras:e.media.linkedCameras,templateTitle:e.template?.title??``,templateBody:e.template?.body??``,...$o(e.conditions),schedule:e.schedule,systemEventDelivery:e.systemEventDelivery,snoozeAllowGlobal:e.snoozeAllowGlobal===!0,groupingSec:e.groupingSec,snoozeOptions:e.snoozeOptions,actions:zi(e.actions),cooldownSec:e.throttle.cooldownSec,cooldownScope:e.throttle.scope,cooldownGranularity:e.throttle.granularity}}function as(e,t){let n=[];if(fs(e)){let r=e.groupingSec;r!==void 0&&(!Number.isInteger(r)||r<5||r>60)&&n.push(`The grouping window is a whole number of seconds between 5 and 60.`);let i=t?.confirm;i?.enabled===!0&&i.expect!==void 0&&!ps(i.expect)&&n.push(`This rule’s AI confirm expects more than one subject, but a grouped message judges one picture per subject, so it would never send. Remove the confirm expectation (viewer or API), or choose Immediate.`)}if(jt(e.conditions.audio)&&n.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.`),(!Number.isInteger(e.cooldownSec)||e.cooldownSec<0||e.cooldownSec>86400)&&n.push(`The cooldown is a whole number of seconds between 0 and ${String(Ba)} (24 hours). 0 means every match is delivered.`),cs(e))for(let t of Ht({delivery:e.delivery,conditions:e.conditions,...e.systemEventDelivery===void 0?{}:{systemEventDelivery:e.systemEventDelivery},...Bi(e.actions)===void 0?{}:{actions:Bi(e.actions)}}))n.push(Ct(t));return n}function os(e){let t=e.systemEventDelivery;return t===void 0?{}:tt(e.delivery)?{systemEventDelivery:t}:t.mode===`summary`?{systemEventDelivery:{mode:`instant`}}:{}}function ss(e){if(!cs(e))return null;if(!ft(e.templateBody))return`This body names none of the summary ({{summaryText}} or a section variable) — the hub appends {{summaryText}} to it when it sends.`;let t=e.templateBody;return(e.systemEventDelivery?.mode===`summary`?e.systemEventDelivery.split:void 0)===`section`&&t.trim().length>0&&!/\{\{\s*summaryText\s*\}\}/.test(t)?`Sent one per category: this body names no {{summaryText}}, so on every other category’s notification the hub appends {{summaryText}} (that category’s lines).`:null}function cs(e){return tt(e.delivery)&&e.systemEventDelivery?.mode===`summary`}function ls(e,t,n=new Set){return as(e,t).length===0&&Pa(e.delivery)&&(!tt(e.delivery)||_s(e)>0)&&it(e)!==`mixed`&&e.name.trim().length>0&&(e.targetIds.length>0||e.targetUsers.length>0)&&Vi(e.actions,n).length===0}function us(e,t){let n=hs(e.conditions,t);return tt(t)&&(n.systemEvent?.kinds.length??0)===0?{...e,delivery:t,conditions:{...n,systemEvent:yo(`device-events`)}}:{...e,delivery:t,conditions:n}}function ds(e,t){return t===`immediate-grouped`?{...us(e,`immediate`),groupingSec:e.groupingSec??20}:{...us(e,t),groupingSec:void 0}}function fs(e){return e.groupingSec!==void 0&&Ge(e)}function ps(e){switch(e.op){case`>`:return 1>e.count;case`<=`:return 1<=e.count;case`<`:return 1<e.count;case`==`:return e.count===1;default:return 1>=e.count}}var ms=new Set([`immediate`,`track-end`,`package-event`]);function hs(e,t){if(e.source!==`pipeline`||ms.has(t))return e;let{source:n,...r}=e;return r}function gs(e,t){return qe(e.conditions.systemEvent)===t?e:{...e,conditions:{...e.conditions,systemEvent:yo(t)}}}function _s(e){return e.conditions.systemEvent?.kinds.length??0}function vs(e,t){return e.appliesTo.includes(t)}var ys={source:`any`};function bs(e,t){if(t==null)return!0;if(Array.isArray(t))return t.length===0;if(typeof t==`string`)return t.length===0||ys[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 xs=bt.filter(e=>e.id===`audio`);function Ss(e){if(e.length===0)return e;let t=new Set(e.map(e=>e.id)),n=xs.filter(e=>!t.has(e.id));return n.length===0?e:[...e,...n]}function Cs(e,t,n,r=it({delivery:t,conditions:e})){let i=n.length===0?null:new Set(n.filter(e=>e.id!==`schedule`&&Ke(e,t,r)).map(e=>e.id)),a={};for(let[t,n]of Object.entries(e))i!==null&&!i.has(t)||ao(t,e)&&(bs(t,n)||(a[t]=n));return a}function ws(e,t){if(e===void 0)return{};let n=Do(e,t.systemEvent);return n===void 0?{}:{systemEvent:n}}function Ts(e){return e!==void 0&&e.windows.length>0}function Es(e){let t={...e.clipPreRollSec===void 0?{}:{clipPreRollSec:e.clipPreRollSec},...e.clipPostRollSec===void 0?{}:{clipPostRollSec:e.clipPostRollSec}};return Object.keys(t).length>0?t:void 0}function Ds(e){let t=Es(e.media);return{...e.confirm===void 0?{}:{confirm:e.confirm},...t===void 0?{}:{media:t}}}function Os(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=Bi(e.actions),s=it(e),c=ot(s),l=Pt(s),u=n.length===0?!0:n.some(t=>t.id===`schedule`&&vs(t,e.delivery)),d=!cs(e)&&u&&Ts(e.schedule)?e.schedule:void 0,f=n.length===0?!0:n.some(t=>t.id===`devices`&&vs(t,e.delivery)),p=n.length===0?!0:n.some(t=>t.id===`devicesExclude`&&vs(t,e.delivery)),{devices:m,devicesExclude:h,...g}=es(e);return{name:e.name.trim(),enabled:e.enabled,delivery:e.delivery,conditions:{...Cs(g,e.delivery,n,s),...f&&m!==void 0?{devices:m}:{},...p&&h!==void 0?{devicesExclude:h}:{},...ws(l,e.conditions)},...d?{schedule:d}:{},...os(e),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:c.carriesMedia?{attach:e.mediaAttach,...c.carriesSubjectCrop&&e.mediaZoneCrop?{zoneCrop:!0}:{},...c.carriesSubjectCrop&&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},...s===`sensor`&&e.mediaAttach!==`none`&&e.mediaLinkedCameras!==void 0?{linkedCameras:e.mediaLinkedCameras}:{},...(e.mediaGif||e.mediaClip)&&t?.media?.clipPreRollSec!==void 0?{clipPreRollSec:t.media.clipPreRollSec}:{},...(e.mediaGif||e.mediaClip)&&t?.media?.clipPostRollSec!==void 0?{clipPostRollSec:t.media.clipPostRollSec}:{}}:{attach:`none`},throttle:{cooldownSec:e.cooldownSec,scope:e.cooldownScope,...e.cooldownGranularity===void 0?{}:{granularity:e.cooldownGranularity}},priority:e.priority,...a?{template:a}:{},...e.snoozeAllowGlobal?{snoozeAllowGlobal:!0}:{},...fs(e)?{groupingSec:e.groupingSec}:{},...e.snoozeOptions===void 0?{}:{snoozeOptions:[...e.snoozeOptions]},...t?.confirm===void 0?{}:{confirm:t.confirm},...o===void 0?{}:{actions:o}}}function ks(e,t){let n=Os(e,void 0,t);return[`template`,`schedule`,`targetUsers`,`snoozeOptions`,`snoozeAllowGlobal`,`groupingSec`,`actions`].filter(e=>n[e]===void 0)}var As=[{key:`rule`,label:`Rule`,fields:[`name`,`enabled`,`delivery`,`groupingSec`,`targetIds`,`targetUsers`,`targetParams`]},{key:`devices`,label:`Devices`,fields:[`deviceScope`]},{key:`conditions`,label:`Conditions`,fields:[`conditions`,`classScope`,`schedule`,`systemEventDelivery`]},{key:`notification`,label:`Notification`,fields:[`priority`,`mediaAttach`,`mediaFrame`,`mediaZoneCrop`,`mediaGif`,`mediaClip`,`mediaProfile`,`mediaClipSpeed`,`mediaLinkedCameras`,`templateTitle`,`templateBody`]},{key:`actions`,label:`Actions`,fields:[`actions`]},{key:`advanced`,label:`Advanced`,fields:[`snoozeAllowGlobal`,`snoozeOptions`,`cooldownSec`,`cooldownScope`,`cooldownGranularity`]}];function js(e,t={}){let n=it({delivery:e,conditions:t}),r=ot(n),i=As.map(e=>e.key===`conditions`?{...e,label:r.label}:e);return Kt(n)?i.filter(e=>e.key!==`devices`):i}function Ms(e){if(e.audio!==void 0)return`Sound`;if(e.occupancy!==void 0)return`Occupancy`}function Ns(e){let t=it(e),n=Ye(es(e),t);return t===`sensor`&&e.conditions.sensorTransition!==void 0&&!ao(`sensorTransition`,e.conditions)?[...n,{conditionId:`sensorTransition`,reason:Ve}]:n}var Ps=`rule`;function Fs(e){return As.find(t=>t.key===e)?.key}function Is(e){return e?.toLowerCase().startsWith(`it`)===!0?`it`:`en`}function Ls(){let{i18n:e}=en(),t=Is(e.language);return e=>ht(e,t)}t();var X=`block text-[11px] font-medium text-foreground`,Z=`text-[10px] text-foreground-subtle mt-0.5`;function Rs({cameras:e,fleet:t,value:n,onChange:r,emptyMeansAll:i=!1,savedHadDevices:a=!1}){return d(V,{devices:e,listState:t.state,fleet:t,value:n,onChange:r,emptyMeansAll:i,savedHadDevices:a})}function zs({value:e,placeholder:t,onChange:r}){let[i,a]=l(``),o=()=>{let t=i.trim();if(t.length===0||e.includes(t)){a(``);return}r([...e,t]),a(``)},s=t=>r(e.filter(e=>e!==t));return n(`div`,{className:`mt-1 space-y-1.5`,children:[e.length>0&&d(`div`,{className:`flex flex-wrap gap-1`,children:e.map(e=>n(`span`,{className:`inline-flex items-center gap-1 rounded bg-surface-hover px-1.5 py-0.5 text-[11px] text-foreground`,children:[e,d(`button`,{type:`button`,onClick:()=>s(e),"aria-label":`remove ${e}`,className:`text-foreground-subtle hover:text-danger`,children:d(je,{className:`h-3 w-3`})})]},e))}),d(B,{value:i,placeholder:t,onChange:e=>a(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),o())},onBlur:o})]})}function Bs({picker:e,value:t,onChange:i}){let a=r(()=>vt(e),[e]),o=r(()=>new Set(t),[t]),s=t.filter(e=>!a.has(e)),c=e=>{i(o.has(e)?t.filter(t=>t!==e):[...t,e])};return n(`div`,{className:`space-y-2`,children:[s.length>0&&d(`div`,{className:`flex flex-wrap gap-1`,children:s.map(e=>n(`button`,{type:`button`,onClick:()=>i(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=>n(`div`,{children:[d(`div`,{className:`text-[10px] uppercase tracking-wide text-foreground-muted mb-1`,children:e.fallbackLabel}),d(`div`,{className:`flex flex-wrap gap-1`,children:e.options.map(e=>{let t=o.has(e.value);return d(`button`,{type:`button`,"aria-pressed":t,onClick:()=>c(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 Vs({value:e,min:t,max:r,step:i,onChange:a}){return n(`div`,{className:`mt-1 flex items-center gap-2`,children:[d(B,{type:`number`,value:e??``,min:t,max:r,step:i,className:`max-w-[8rem]`,onChange:e=>{let t=e.target.value;if(t===``){a(void 0);return}let n=Number(t);a(Number.isFinite(n)?n:void 0)}}),e!==void 0&&r!==void 0&&d(`input`,{type:`range`,min:t,max:r,step:i,value:e,onChange:e=>a(Number(e.target.value)),className:`flex-1 accent-primary`,"aria-label":`value`})]})}function Hs({value:e,onChange:t,options:r}){let{t:i}=en(),a=Us(r??[]),o=a.length>0?a:oo;return n(`div`,{className:`mt-1 space-y-1`,children:[d(q,{value:e??`enter`,options:o.map(e=>({value:e.value,label:i(`notificationRules.crossing.${e.value}`,e.label)})),onChange:e=>t(co(e.target.value))}),d(`p`,{className:Z,children:i(`notificationRules.crossing.hint`,`Which way the subject crosses the zone.`)})]})}function Us(e){let t=[];for(let n of e){let e=n.value===``||n.value===`enter`?so:co(n.value);e===void 0||t.some(t=>t.value===e)||t.push({value:e,label:n.label})}return t}function Ws({deviceIds:e,cameras:t,value:n,onChange:r}){let{options:i,loading:a}=ba(e,t);return d(wa,{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 Gs({deviceIds:e,value:t,onChange:n}){let{options:r,loading:i}=xa(e);return d(wa,{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 Ks=[{value:`became-occupied`,label:`Became occupied`},{value:`became-free`,label:`Became free`},{value:`>=`,label:`Count ≥`},{value:`<=`,label:`Count ≤`}];function qs(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 Js({deviceIds:e,cameras:t,classOptions:r,value:i,onChange:a}){let{options:o,loading:s}=ba(e,t),c=i??Ue,l=e=>a({...c,...e}),u=c.op===`became-occupied`||c.op===`became-free`,f=qs(r,c.className);return n(`div`,{className:`mt-1 space-y-1.5`,children:[n(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[d(`div`,{className:`min-w-[10rem]`,children:d(q,{value:c.zoneId??``,options:[{value:``,label:s?`Loading zones…`:`— whole frame —`},...o.map(e=>({value:e.value,label:e.label}))],onChange:e=>l({zoneId:e.target.value===``?void 0:e.target.value})})}),d(`div`,{className:`min-w-[9rem]`,children:d(q,{value:c.className??``,options:[{value:``,label:`— any class —`},...f],onChange:e=>l({className:e.target.value===``?void 0:e.target.value})})}),d(`div`,{className:`min-w-[9rem]`,children:d(q,{value:c.op,options:Ks.map(e=>({value:e.value,label:e.label})),onChange:e=>{let t=Ks.find(t=>t.value===e.target.value);t&&l({op:t.value})}})})]}),n(`div`,{className:`flex flex-wrap items-center gap-3 text-xs text-foreground-subtle`,children:[n(`label`,{className:`flex items-center gap-1`,children:[u?`Threshold`:`Count`,d(B,{type:`number`,min:0,className:`w-16`,value:String(c.count),onChange:e=>l({count:Math.max(0,Number(e.target.value)||0)})})]}),n(`label`,{className:`flex items-center gap-1`,children:[`Hold for`,d(B,{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`]}),i===void 0?null:d(`button`,{type:`button`,onClick:()=>a(void 0),className:`underline hover:text-foreground`,children:`Clear`})]}),e.length===0&&d(`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.`}),d(`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.`})]})}var Ys=[{value:`label`,label:`Sounds — fires at once`,Icon:Te},{value:`level`,label:`Volume — over a window`,Icon:O}];function Xs({taxonomy:e,value:t,onChange:r}){let i=Ot(t),o=e=>r(_t(t,e)),{choices:s,unknownLabels:c}=Lt(e,i.labels),l=mt(t)??`label`;return n(`div`,{className:`mt-1 space-y-2`,children:[n(`div`,{className:`flex flex-wrap items-center gap-1`,children:[Ys.map(e=>d(`button`,{type:`button`,"aria-pressed":l===e.value,onClick:()=>o({mode:e.value}),className:`rounded border px-2 py-0.5 text-[11px] ${l===e.value?`border-primary bg-primary/15 text-foreground`:`border-border text-foreground-subtle hover:bg-surface-hover`}`,children:n(`span`,{className:`inline-flex items-center gap-1`,children:[d(e.Icon,{className:`h-3 w-3`}),e.label]})},e.value)),t===void 0?null:d(`button`,{type:`button`,onClick:()=>r(void 0),className:`ml-1 text-xs text-foreground-subtle underline hover:text-foreground`,children:`Clear`})]}),l===`label`?n(a,{children:[d(`div`,{className:`flex flex-wrap gap-1`,children:s.map(e=>{let t=Vt(i.labels,e.value),r=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 d(`button`,{type:`button`,"aria-pressed":t,title:e.unknown?`Stored by the rule — not offered by this hub`:void 0,onClick:()=>o({labels:xt(i.labels,e.value)}),className:`rounded border px-1.5 py-0.5 text-[10px] ${r}`,children:n(`span`,{className:`inline-flex items-center gap-1`,children:[d(S,{iconId:e.iconId,size:12}),e.label]})},e.value)})}),c.length>0&&n(`p`,{className:`text-[10px] text-warning`,children:[`Kept from the rule, unknown to this hub: `,c.join(`, `)]}),n(`div`,{className:`flex flex-wrap items-center gap-3 text-xs text-foreground-subtle`,children:[n(`label`,{className:`flex items-center gap-1`,children:[`Confirm after`,d(B,{type:`number`,min:1,max:20,step:1,className:`w-16`,value:String(i.confirmHits??2),onChange:e=>o({confirmHits:Number(e.target.value)})}),`frames`]}),n(`label`,{className:`flex items-center gap-1`,children:[`within`,d(B,{type:`number`,min:1,max:60,step:1,className:`w-16`,value:String(i.confirmWindowSec??5),onChange:e=>o({confirmWindowSec:Number(e.target.value)})}),`s`]})]}),n(`p`,{className:`text-[11px] text-foreground-subtle`,children:[`Fires when that many labelled frames land inside the window (default`,` `,2,` in `,5,` s). A single-frame false positive never reaches 2; a real episode usually labels two or three frames. The rule's cooldown is the other throttle.`]})]}):n(a,{children:[d(`div`,{className:`flex flex-wrap items-center gap-3 text-xs text-foreground-subtle`,children:n(`label`,{className:`flex items-center gap-1`,children:[`Louder than`,d(B,{type:`number`,min:It,max:0,step:3,className:`w-20`,value:String(i.dbThreshold??wt),onChange:e=>o({dbThreshold:Number(e.target.value)})}),`dBFS`]})}),n(`div`,{className:`flex flex-wrap items-center gap-3 text-xs text-foreground-subtle`,children:[n(`label`,{className:`flex items-center gap-1`,children:[`Hits`,d(B,{type:`number`,min:1,max:100,step:5,className:`w-16`,value:String(i.hitPercent),onChange:e=>o({hitPercent:Number(e.target.value)})}),`% (default `,dt.hitPercent,`)`]}),n(`label`,{className:`flex items-center gap-1`,children:[`over`,d(B,{type:`number`,min:1,max:300,step:5,className:`w-16`,value:String(i.samplingSeconds),onChange:e=>o({samplingSeconds:Number(e.target.value)})}),`s (default `,dt.samplingSeconds,`)`]})]}),n(`p`,{className:`text-[11px] text-foreground-subtle`,children:[`dBFS is negative-going: 0 is full scale, `,It,` is silence — so a HIGHER number is a narrower filter. Measured on this hub, a baby crying reads `,`−`,`55 to `,`−`,`26 dBFS, so a floor above `,`−`,`55 excludes most of it. The window must be FULL before it can match.`]})]}),jt(t)?d(`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]})}function Zs({value:e,onChange:t}){let r=e?.values??[],i=e?.maxDistance??1,a=e=>t(e.length>0?{values:e,maxDistance:i}:void 0),o=e=>t(r.length>0?{values:r,maxDistance:e}:void 0),s=Ca().filter(e=>!r.includes(e));return n(`div`,{className:`mt-1 space-y-1.5`,children:[d(zs,{value:r,placeholder:`Plate text…`,onChange:a}),s.length>0&&n(`div`,{className:`flex flex-wrap items-center gap-1`,children:[d(`span`,{className:`text-[10px] text-foreground-subtle`,children:`Seen:`}),s.slice(0,12).map(e=>d(`button`,{type:`button`,onClick:()=>a([...r,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))]}),n(`label`,{className:`flex items-center gap-2 text-[11px] text-foreground-subtle`,children:[`Max distance`,d(B,{type:`number`,min:0,max:3,step:1,value:i,className:`max-w-[5rem]`,onChange:e=>{let t=Number(e.target.value);o(Number.isFinite(t)?Math.max(0,Math.min(3,t)):1)}})]})]})}function Qs({gateable:e,value:t,onChange:r}){let i=Ls(),a=e.find(e=>e.id===t?.deviceId),o=new Set(t?.states??[]),s=e=>{let t=Number(e);if(!Number.isFinite(t)||t===0)return r(void 0);r({deviceId:t,states:[]})},c=e=>{if(t===void 0)return;let n=new Set(o);n.has(e)?n.delete(e):n.add(e),r(n.size===0?void 0:{deviceId:t.deviceId,states:[...n]})};return n(`div`,{className:`mt-1 space-y-2`,children:[d(q,{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=>s(e.target.value)}),a!==void 0&&d(`div`,{className:`flex flex-wrap gap-1.5`,children:a.states.map(e=>d(`button`,{type:`button`,onClick:()=>c(e),className:o.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:i(e)},e))}),a!==void 0&&a.states.length===0&&d(`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&&d(`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.`})]})}function $s(e,t){let n=t(e.verdict);return e.latched?`${n} · ${t(`latched`)}`:n}function ec({scenes:e,value:t,onChange:r}){let{t:i}=en(),a=Ls(),o=e.find(e=>e.sceneId===t?.sceneId),s=n=>{if(n===``)return r(void 0);let i=e.find(e=>e.sceneId===n);if(i===void 0)return r(void 0);r({sceneId:n,deviceId:i.deviceId,requiredState:t?.requiredState??`diverged`,...t?.latched===void 0?{}:{latched:t.latched}})},c=e=>{t!==void 0&&r({...t,requiredState:e===`matched`?`matched`:`diverged`})},l=e=>{if(t!==void 0){if(e===``){let{latched:e,...n}=t;return r(n)}r({...t,latched:e===`latched`})}};return e.length===0?d(`p`,{className:Z,children:i(`notificationRules.scene.none`,`No scenes yet — create one on the Scenes page.`)}):n(`div`,{className:`mt-1 space-y-2`,children:[d(q,{value:t?.sceneId??``,options:[{value:``,label:i(`notificationRules.scene.noGate`,`— no scene gate —`)},...e.map(e=>({value:e.sceneId,label:`${e.cameraName} · ${e.label} — ${$s(e,a)}`}))],onChange:e=>s(e.target.value)}),t!==void 0&&n(`div`,{className:`flex flex-wrap items-center gap-2`,children:[n(`label`,{className:`flex items-center gap-2 text-[11px] text-foreground-subtle`,children:[i(`notificationRules.scene.onlyWhile`,`Only while it is`),d(q,{value:t.requiredState,options:[{value:`diverged`,label:a(`diverged`)},{value:`matched`,label:a(`matched`)}],onChange:e=>c(e.target.value)})]}),n(`label`,{className:`flex items-center gap-2 text-[11px] text-foreground-subtle`,children:[i(`notificationRules.scene.read`,`Read`),d(q,{value:t.latched===void 0?``:t.latched?`latched`:`live`,options:[{value:``,label:o===void 0?i(`notificationRules.scene.readOwn`,`The scene's own setting`):`${i(`notificationRules.scene.readOwn`,`The scene's own setting`)} (${a(o.emit)})`},{value:`latched`,label:a(`latched`)},{value:`live`,label:a(`live`)}],onChange:e=>l(e.target.value)})]})]}),o!==void 0&&n(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:[i(`notificationRules.scene.rightNow`,`Right now:`),` `,$s(o,a)]}),t!==void 0&&o===void 0&&d(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:i(`notificationRules.scene.missing`,`This scene no longer exists — pick another or remove the gate.`)})]})}var tc=new Set([`devices`,`devicesExclude`,`customZones`,`source`,`crossing`]),nc=[[`classes`,`classesExclude`],[`zones`,`zonesExclude`],[`identities`,`identitiesExclude`]],rc={minConfidence:`class`},ic=[{id:`system`,label:`System events`},{id:`class`,label:`Detections`},{id:`zones`,label:`Zones`},{id:`label`,label:`Faces, plates & labels`},{id:`quality`,label:`Quality`},{id:`scope`,label:`Only while`},{id:`device`,label:`Device event`},{id:`package`,label:`Package`},{id:`occupancy`,label:`Occupancy`},{id:`audio`,label:`Sound`},{id:`schedule`,label:`Schedule`}];function ac(e){let t=new Set(e.map(e=>e.id)),n=new Set;for(let[e,r]of nc)t.has(e)&&n.add(r);return n}function oc(e){return rc[e.id]??e.group}function sc(e){let t=e.replace(/[-_]/g,` `);return t.charAt(0).toUpperCase()+t.slice(1)}function cc(e){let t=ac(e),n=e.filter(e=>!tc.has(e.id)&&!t.has(e.id)),r=new Set(ic.map(e=>e.id)),i=[],a=e=>n.filter(t=>oc(t)===e);for(let e of ic){let t=a(e.id);t.length>0&&i.push({id:e.id,label:e.label,descriptors:t})}let o=[];for(let e of n){let t=oc(e);!r.has(t)&&!o.includes(t)&&o.push(t)}for(let e of o)i.push({id:e,label:sc(e),descriptors:a(e)});return i}function lc(e,t){switch(e){case`zones`:return Ro(t.zones?.ids,t.zonesExclude);case`labels`:return Ro(t.labelEquals,void 0);case`identities`:return uc(t)}}function uc(e){let t=e.identities,n=[...e.identitiesExclude??[]];return t===void 0?Ro(void 0,n):{mode:`only`,include:[...t],exclude:n,legacyBoth:n.length>0}}function dc(e,t,n){switch(e){case`zones`:return fc(t,n);case`labels`:return pc(t,n);case`identities`:return mc(t,n)}}function fc(e,t){let{zones:n,zonesExclude:r,...i}=e,a=Wo(t);return{...i,...a.include===void 0?{}:{zones:{ids:[...a.include]}},...a.exclude===void 0?{}:{zonesExclude:[...a.exclude]}}}function pc(e,t){let{labelEquals:n,...r}=e,i=Wo(t);return{...r,...i.include===void 0?{}:{labelEquals:[...i.include]}}}function mc(e,t){let{identities:n,identitiesExclude:r,...i}=e;if(t.mode===`only`){let e=Ho(t);return{...i,identities:[...t.include],...e.length>0?{identitiesExclude:[...e]}:{}}}let a=Wo(t);return{...i,...a.exclude===void 0?{}:{identitiesExclude:[...a.exclude]}}}var hc={all:`All`,only:`Only these`,except:`All except these`},gc={devices:{items:`devices`,every:`Every device — no restriction.`},classes:{items:`classes`,every:`Every class — no restriction.`},zones:{items:`zones`,every:`Every zone — no restriction.`},faces:{items:`faces`,every:`Every face — no restriction.`},labels:{items:`labels`,every:`Every label — no restriction.`},calendars:{items:`calendars`,every:`Every calendar — no restriction.`}};function _c({draft:e,onChange:t,exceptOffered:r,plural:i,renderPicker:a,describe:o,testId:s}){let{t:c}=en(),l=(e,t,n)=>c(e,{items:n,defaultValue:t}).replaceAll(`{{items}}`,n),u=c(`ruleScope.items.${i}`,gc[i].items),f=Io.filter(t=>t!==`except`||r||e.mode===`except`),p=Ho(e),m=Go(e),h=e.mode===`all`?null:e.mode;return n(`div`,{className:`mt-1 space-y-1.5`,"data-testid":s,children:[d(`div`,{role:`radiogroup`,"aria-label":l(`ruleScope.which`,`Which {{items}}`,u),className:`inline-flex flex-wrap items-center gap-1`,children:f.map(n=>{let r=n===e.mode;return d(`button`,{type:`button`,role:`radio`,"aria-checked":r,"data-testid":`scope-mode-${n}`,onClick:()=>t(zo(e,n)),className:r?`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 hover:bg-surface-hover`,children:c(`ruleScope.mode.${n}`,hc[n])},n)})}),h===null?d(`p`,{className:`text-[11px] text-foreground-subtle`,children:c(`ruleScope.every.${i}`,gc[i].every)}):a(Bo(e),n=>t(Vo(e,n)),h),p.length>0&&n(`p`,{className:`text-[11px] text-warning`,"data-testid":`scope-legacy-exclusions`,children:[l(`ruleScope.legacy`,`This rule also excludes {{items}} — kept when you save.`,p.map(o).join(`, `)),` `,d(`button`,{type:`button`,className:`underline hover:no-underline`,onClick:()=>t(Uo(e)),children:c(`ruleScope.removeExclusions`,`Remove exclusions`)})]}),m.length>0&&d(`p`,{className:`text-[11px] text-foreground-subtle`,"data-testid":`scope-cleared-on-save`,children:l(`ruleScope.cleared`,`Saving in this mode clears {{items}} from the rule.`,m.map(o).join(`, `))})]})}function vc(e,t){let n=t.map(e=>e.id);switch(e.mode){case`only`:{let t=new Set(e.include);return n.filter(e=>t.has(e))}case`except`:{let t=new Set(e.exclude);return n.filter(e=>!t.has(e))}case`all`:return n}}function yc(e){return e.map(e=>e.hint===void 0?{id:e.value,name:e.label}:{id:e.value,name:`${e.hint}:${e.label}`,type:e.hint})}t();function bc(e,t,n){let[r,i]=l(()=>lc(e,t));return[r,r=>{i(r),n(dc(e,t,r))}]}function xc(e,t){return t?`failed`:e?`pending`:`answered`}function Sc({conditions:e,onConditionsChange:t,exceptOffered:n,cameraIds:i,cameras:a}){let{t:o}=en(),[s,c]=bc(`zones`,e,t),{options:l,loading:u,failed:f}=ba(i,a),p=r(()=>yc(l),[l]),m=xc(u,!1),h=f?{state:`failed`,devices:void 0}:{state:m,devices:m===`answered`?p:void 0},g=r(()=>new Map(p.map(e=>[e.id,e.name])),[p]);return d(_c,{draft:s,onChange:c,exceptOffered:n,plural:`zones`,describe:e=>g.get(e)??e,testId:`rule-zone-scope`,renderPicker:(e,t,n)=>i.length===0?d(`p`,{className:Z,children:o(`notificationRules.zones.noCameras`,`This rule covers no camera, so it has no zones.`)}):d(V,{devices:p,listState:m,fleet:h,value:e,onChange:t,emptyMeansAll:!0,noun:`zone`,groupTitle:e=>e.type??o(`notificationRules.zones.group`,`Zones`),testId:`zone-picker`},n)})}function Cc({conditions:e,onConditionsChange:t,exceptOffered:n}){let{t:i}=en(),[a,o]=bc(`identities`,e,t),{options:s,loading:c,failed:l}=Sa(),u=r(()=>s.map(e=>({id:e.value,name:e.label})),[s]),f=r(()=>new Map(u.map(e=>[e.id,e.name])),[u]);return d(_c,{draft:a,onChange:o,exceptOffered:n,plural:`faces`,describe:e=>f.get(e)??e,testId:`rule-identity-scope`,renderPicker:(e,t,n)=>d(V,{devices:u,listState:xc(c,l),value:e,onChange:t,emptyMeansAll:n===`except`,...n===`only`?{emptyLabel:i(`notificationRules.faces.anyKnown`,`Any known face — nobody in particular`)}:{},noun:`face`,groupTitle:()=>i(`notificationRules.faces.group`,`Known faces`),testId:`identity-picker`},n)})}function wc({conditions:e,onConditionsChange:t}){let{t:n}=en(),[r,i]=bc(`labels`,e,t);return d(_c,{draft:r,onChange:i,exceptOffered:!1,plural:`labels`,describe:e=>e,testId:`rule-label-scope`,renderPicker:(e,t)=>d(zs,{value:e,placeholder:n(`notificationRules.labels.add`,`Add a label…`),onChange:t})})}function Tc(e){let t=At(e);return t===null?null:t.groups.flatMap(e=>e.options.map(t=>({id:t.value,name:t.label,type:e.fallbackLabel})))}function Ec(e){return e.type??`Other`}t();function Dc({taxonomy:e,scope:t,onChange:n,exceptOffered:i}){let a=r(()=>Tc(e),[e]),o=r(()=>new Map((a??[]).map(e=>[e.id,e.name])),[a]);return d(_c,{draft:t,onChange:n,exceptOffered:i,plural:`classes`,describe:e=>o.get(e)??e,testId:`rule-class-scope`,renderPicker:(e,t,n)=>a===null?d(zs,{value:e,placeholder:`Add value…`,onChange:t}):d(V,{devices:a,listState:`answered`,value:e,onChange:t,emptyMeansAll:!0,noun:`class`,groupTitle:Ec,testId:`class-picker`},n)})}var Oc=[{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 kc(e){let t=Math.floor(e/60),n=e%60;return`${String(t).padStart(2,`0`)}:${String(n).padStart(2,`0`)}`}function Ac(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 jc(){return{days:[1,2,3,4,5],startMinute:540,endMinute:1080}}function Mc({value:e,onChange:t}){let r=e?.windows??[],i=e?.invert??!1,a=(n,r)=>{if(n.length===0){t(void 0);return}t({windows:n,...r?{invert:!0}:{},...e?.timezone?{timezone:e.timezone}:{}})},o=()=>a([...r,jc()],i),s=e=>a(r.filter((t,n)=>n!==e),i),c=(e,t)=>a(r.map((n,r)=>r===e?t:n),i);return n(`div`,{className:`mt-1 space-y-2`,children:[r.length===0?d(`p`,{className:Z,children:`Always active — add a window to restrict when the rule fires.`}):r.map((e,t)=>d(Nc,{window:e,onChange:e=>c(t,e),onRemove:()=>s(t)},t)),n(`div`,{className:`flex items-center gap-3`,children:[n(`button`,{type:`button`,onClick:o,className:`flex items-center gap-1 rounded-md bg-surface-hover px-2 py-1 text-[11px] text-foreground-subtle hover:text-foreground`,children:[d(W,{className:`h-3 w-3`}),` Add window`]}),r.length>0&&n(`label`,{className:`flex items-center gap-1.5 text-[11px] text-foreground-subtle`,children:[d(`input`,{type:`checkbox`,checked:i,onChange:e=>a([...r],e.target.checked),className:`accent-primary`}),`Active outside the windows`]})]})]})}function Nc({window:e,onChange:t,onRemove:r}){let i=n=>{let r=e.days.includes(n)?e.days.filter(e=>e!==n):[...e.days,n];r.length!==0&&t({...e,days:r})};return n(`div`,{className:`space-y-1.5 rounded-md border border-border p-2`,children:[n(`div`,{className:`flex items-center gap-2 text-xs`,children:[d(`input`,{type:`time`,value:kc(e.startMinute),onChange:n=>t({...e,startMinute:Ac(n.target.value)}),className:`rounded-md border border-border bg-background px-1 py-0.5`}),d(`span`,{className:`text-foreground-subtle`,children:`→`}),d(`input`,{type:`time`,value:kc(e.endMinute),onChange:n=>t({...e,endMinute:Ac(n.target.value)}),className:`rounded-md border border-border bg-background px-1 py-0.5`}),d(`span`,{className:`flex-1`}),d(`button`,{type:`button`,onClick:r,"aria-label":`Remove window`,className:`text-foreground-subtle hover:text-danger`,children:d(_,{className:`h-3.5 w-3.5`})})]}),d(`div`,{className:`flex flex-wrap gap-1`,children:Oc.map(t=>d(`button`,{type:`button`,onClick:()=>i(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))})]})}function Pc(e){return{id:e.id,name:e.name,type:e.type,location:e.location,...e.parentName===void 0?{}:{detail:e.parentName}}}function Fc({devices:e,value:t,onChange:n,listState:r,savedHadDevices:i}){return d(V,{devices:e.map(Pc),listState:r,value:t,onChange:n,emptyMeansAll:!0,savedHadDevices:i,noun:`device`,showAll:!0})}function Ic({devices:e,scope:t,onChange:n,listState:r,savedScope:i,exceptOffered:a}){let o=new Map(e.map(e=>[e.id,e.name]));return d(_c,{draft:t,onChange:n,exceptOffered:a,plural:`devices`,describe:e=>o.get(e)??`Device #${String(e)}`,testId:`rule-device-scope`,renderPicker:(t,n,a)=>d(Fc,{devices:e,value:t,onChange:n,listState:r,savedHadDevices:(a===`only`?i.include:i.exclude).length>0},a)})}function Lc(e){return e.data===void 0?e.isError?`failed`:`pending`:`answered`}function Rc(e,t){return t===`answered`?e?.complete===!0?`answered`:`failed`:t}function zc(e){let t=Lc(e),n=e.data===void 0?[]:yt(e.data.nodes),r=Rc(e.data,t);return{items:n,listState:t,fleet:{state:r,devices:r===`answered`?n:void 0}}}function Bc(e){let t=Lc(e),n=e.data===void 0?[]:Mt(e.data);return{items:n,listState:t,fleet:{state:t,devices:t===`answered`?n:void 0}}}var Vc=[`nc-pickers`,`node-directory`],Hc=[`nc-pickers`,`package-list`],Uc=6e4,Wc={hub:`Hub`,agent:`Agents`},Gc={server:`Server`,framework:`Framework`,wrapper:`Wrapper`,addon:`Addons`};function Kc(e){let t=Wc[e.type??``]??`Nodes`;return e.location===`offline`?`${t} · offline`:t}function qc(e){return Gc[e.type??``]??`Packages`}function Jc({value:e,onChange:t,testId:r}){let a=h().trpcClient,o=i({queryKey:Vc,staleTime:Uc,queryFn:()=>a.nodes.directory.query()}),s=zc(o);return n(`div`,{children:[d(V,{devices:s.items,listState:s.listState,fleet:s.fleet,value:e,onChange:t,emptyMeansAll:!0,noun:`node`,groupTitle:Kc,...r===void 0?{}:{testId:r}}),o.data?.complete===!1&&d(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,"data-testid":`node-directory-incomplete`,children:`The node history could not be read — offline nodes may be missing from this list.`})]})}function Yc({value:e,onChange:t,testId:n}){let r=h().trpcClient,a=Bc(i({queryKey:Hc,staleTime:Uc,queryFn:()=>r.addons.listPackages.query()}));return d(V,{devices:a.items,listState:a.listState,fleet:a.fleet,value:e,onChange:t,emptyMeansAll:!0,noun:`package`,groupTitle:qc,...n===void 0?{}:{testId:n}})}var Xc={context:{family:`rule`,field:`body`,kind:`device-events`,systemEventKinds:[`device-tank-low`]},template:{body:`{{deviceName}}`}};function Zc(e){if(typeof e!=`object`||!e||!(`data`in e))return;let t=e.data;if(!(typeof t!=`object`||!t||!(`code`in t)))return typeof t.code==`string`?t.code:void 0}function Qc(e,t){return e===`pending`?`pending`:e===`success`?`current`:Zc(t)===`BAD_REQUEST`?`outdated`:`unknown`}function $c(e){let t=h(),n=i({queryKey:[`nc`,`hub-rule-schema-probe`],enabled:e,staleTime:5*6e4,retry:!1,queryFn:()=>t.trpcClient.notificationRules.previewTemplate.mutate(Xc)});return e?Qc(n.status,n.error):`pending`}t();var el=`/system/settings`,tl=`/system/notifications?tab=alarm`,nl=`text-primary underline-offset-2 hover:underline`;function rl({family:e,value:t,cameras:i,allDevices:a,fleet:o,savedHadDevices:s,onChange:c}){let l=r(()=>t?.kinds??[],[t]),u=r(()=>a===void 0?i:a.map(Pc),[a,i]),f=Co(e,l),p=$c(e===`device-events`),m=e===`alarm`;return n(`div`,{className:`mt-1 space-y-3`,"data-testid":`system-event-field`,children:[vo(e).map(r=>n(`div`,{children:[d(`div`,{className:`text-[10px] font-semibold uppercase tracking-wide text-foreground-subtle`,children:r.label}),d(`div`,{className:`mt-1 flex flex-wrap gap-1.5`,children:r.kinds.map(n=>{let r=l.includes(n.value);return d(`button`,{type:`button`,role:`checkbox`,"aria-checked":r,"aria-label":n.label,onClick:()=>c(Eo(t,n.value,e)),className:r?`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:n.label},n.value)})}),d(`p`,{className:Z,children:r.hint})]},r.id)),e===`device-events`&&n(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,"data-testid":`system-event-device-alert-settings`,children:[`The battery threshold and the reminder interval are cluster settings (the consumable threshold is this rule’s own, below):`,` `,d($t,{to:el,target:`_blank`,rel:`noreferrer`,className:nl,children:`Settings → Battery & offline alerts`}),`.`]}),e===`alarm`&&n(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,"data-testid":`system-event-alarm-settings`,children:[d($t,{to:tl,target:`_blank`,rel:`noreferrer`,className:nl,children:`Alarm settings`}),l.includes(`alarm-triggered`)&&` — when a rule sets the alarm off, this notification carries that rule's pictures.`]}),p===`outdated`&&n(`p`,{className:`rounded-md border border-warning/40 bg-warning/10 px-2.5 py-1.5 text-[11px] text-warning`,"data-testid":`system-event-hub-outdated`,children:[`This hub’s server predates per-rule consumable thresholds and tank alerts: it drops a rule’s threshold when the rule is saved (the rule then judges at`,` `,15,`%) and refuses tank events. Update the server (@camstack/server) on every node first.`]}),p===`unknown`&&d(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,"data-testid":`system-event-hub-unchecked`,children:`Could not check whether this hub’s server knows per-rule consumable thresholds and tank alerts.`}),f.consumableThreshold&&n(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground`,htmlFor:`system-event-consumable-threshold`,children:`Consumable low at (%)`}),d(B,{id:`system-event-consumable-threshold`,"data-testid":`system-event-consumable-threshold`,type:`number`,min:1,max:jo,step:1,placeholder:`15`,value:t?.consumableLowPercent??``,className:`mt-1 max-w-[8rem]`,onChange:e=>{let n=Mo(e.target.value);n.kind!==`invalid`&&c(Oo(t,{consumableLowPercent:n.kind===`set`?n.value:void 0}))}}),n(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:[`This rule is told when a consumable’s remaining life reaches this percentage (empty = `,15,`%). Another rule may use its own number — each is told at its own threshold. A device that reports “replace” is announced whatever this says.`]})]}),f.deviceTypes&&n(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground`,children:`Only these device types (optional)`}),d(wa,{options:wo,value:t?.deviceTypes??[],onChange:e=>c(Oo(t,{deviceTypes:e})),emptyHint:`No device types listed — the rule watches every type.`,placeholder:`Device type…`}),d(`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.`})]}),Fo(t)&&d(`p`,{className:`rounded-md border border-warning/40 bg-warning/10 px-2.5 py-1.5 text-[11px] text-warning`,"data-testid":`battery-device-types-warning`,children:`Battery and consumable alerts are narrowed by device type here. Batteries and consumables belong to sensors, containers, vacuums and mowers — rarely to a camera — so a type filter meant for liveness silences them. Leave the types empty, or put these kinds in a rule of their own.`}),f.devices&&n(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground`,children:m?`Only when triggered by these cameras (optional)`:`Only these devices (optional)`}),d(V,{devices:m?i:u,listState:o.state,fleet:o,emptyMeansAll:!0,savedHadDevices:s,noun:m?`camera`:`device`,value:t?.deviceIds??[],onChange:e=>c(Oo(t,{deviceIds:e})),testId:`system-event-include`}),d(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:m?`An alarm is narrowed to the camera whose rule set it off. Leave it empty for every camera.`:`Leave it empty to watch every device.`})]}),f.excludeDevices&&n(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground`,children:`Never these devices (optional)`}),d(V,{devices:u,listState:o.state,fleet:o,noun:`device`,emptyLabel:`No device excluded`,value:t?.excludeDeviceIds??[],onChange:e=>c(Oo(t,{excludeDeviceIds:e})),testId:`system-event-exclude`}),d(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:`Applied after the list above: a device here is never reported, whatever else matches — "every battery except the thermometer that always reads 0 %".`})]}),f.nodes&&n(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground`,children:`Only these nodes (optional)`}),d(Jc,{value:t?.nodeIds??[],onChange:e=>c(Oo(t,{nodeIds:e})),testId:`system-event-nodes`}),d(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:`Leave it empty to watch every node.`})]}),f.packages&&n(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground`,children:`Only these packages (optional)`}),d(Yc,{value:t?.packageNames??[],onChange:e=>c(Oo(t,{packageNames:e})),testId:`system-event-packages`}),d(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:`Leave it empty to be told about every addon, server and container update.`})]})]})}function il({value:e}){let t=e?.kinds??[];return n(`div`,{className:`mt-1 rounded-md border border-warning/40 bg-warning/10 px-2.5 py-1.5 text-[11px] text-warning`,"data-testid":`system-event-mixed`,children:[d(`p`,{children:`This rule is not one kind of system rule — its events span device events, system and alarm, or it names none. It keeps firing as it is, but it cannot be edited here: recreate it as one rule per kind.`}),t.length>0&&d(`p`,{className:`mt-1 text-foreground`,children:t.map(xo).join(`, `)})]})}function al({family:e,onChange:t}){return n(`div`,{"data-testid":`system-family-select`,children:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Kind of system rule`}),d(q,{value:e,"aria-label":`Kind of system rule`,onChange:e=>{let n=e.target.value;et(n)&&t(n)},options:ct.map(e=>({value:e,label:ot(e).label}))}),d(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:`One rule answers one question: about devices, about the installation, or about the alarm. Changing it starts the event list over.`})]})}t();function ol({catalog:e,taxonomy:t,delivery:i,conditions:a,classScope:o,onClassScopeChange:s,actions:c,sequenceActionsOf:l,savedConditions:u,schedule:f,deviceIds:p,zoneCameraIds:m,cameras:h,fleet:g,allDevices:_,gateable:v,gateableScenes:y,onConditionsChange:b,onScheduleChange:x}){let{t:S}=en(),C=(e,t)=>{let n={...a};t===void 0?delete n[e]:n[e]=t,b(n)},w=it({delivery:i,conditions:a}),T=r(()=>e.filter(e=>Ke(e,i,w)&&ao(e.id,a)),[e,i,w,a]),E=r(()=>cc(T),[T]),D=e=>T.some(t=>t.id===e),O=e=>sl.has(e.id)?d(Dc,{taxonomy:t,scope:o,onChange:s,exceptOffered:D(`classesExclude`)}):cl.has(e.id)?d(Sc,{conditions:a,onConditionsChange:b,exceptOffered:D(`zonesExclude`),cameraIds:m??p,cameras:h}):ll.has(e.id)?d(Cc,{conditions:a,onConditionsChange:b,exceptOffered:D(`identitiesExclude`)}):e.id===`labelEquals`?d(wc,{conditions:a,onConditionsChange:b}):null;return d(`div`,{className:`space-y-4`,children:E.map(e=>n(`div`,{className:`space-y-2.5`,"data-testid":`condition-group-${e.id}`,children:[d(`div`,{className:`text-[11px] font-semibold uppercase tracking-wide text-foreground-subtle`,children:S(`notificationRules.groups.${e.id}`,e.label)}),e.descriptors.map(e=>{let r=O(e);return n(`div`,{"data-testid":`condition-${e.id}`,children:[d(`label`,{className:X,children:ul(e,S)}),r??d(pl,{descriptor:e,kind:w,taxonomy:t,conditions:a,actions:c,sequenceActionsOf:l,savedConditions:u,schedule:f,deviceIds:p,cameras:h,fleet:g,..._===void 0?{}:{allDevices:_},gateable:v,gateableScenes:y,onFieldChange:C,onScheduleChange:x}),dl(e,S)!==void 0&&d(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:dl(e,S)})]},e.id)})]},e.id))})}var sl=new Set([`classes`,`classesExclude`]),cl=new Set([`zones`,`zonesExclude`]),ll=new Set([`identities`,`identitiesExclude`]);function ul(e,t){return sl.has(e.id)?t(`notificationRules.labels.classes`,`Object classes`):cl.has(e.id)?t(`notificationRules.labels.zones`,`Zones`):ll.has(e.id)?t(`notificationRules.labels.faces`,`Known faces`):e.id===`labelEquals`?t(`notificationRules.labels.labels`,`Labels`):e.id===`crossing`?t(`notificationRules.labels.crossing`,`Zone crossing`):e.id===`source`?t(`notificationRules.labels.source`,`Detection source`):e.label}function dl(e,t){if(!fl.has(e.id))return e.id===`scene`?t(`notificationRules.scene.hint`,`Only fire while a scene is matched or diverged.`):e.description}var fl=new Set([...sl,...cl,...ll,`labelEquals`,`crossing`]);function pl({descriptor:e,kind:t,taxonomy:r,conditions:i,actions:o,sequenceActionsOf:s,savedConditions:c,schedule:l,deviceIds:u,cameras:f,fleet:p,allDevices:m,gateable:h,gateableScenes:g,onFieldChange:_,onScheduleChange:v}){switch(e.valueType){case`deviceIdList`:{if(!ia(e.id))break;let t=e.id,n=i[t]??[];return d(Rs,{cameras:f,fleet:p,emptyMeansAll:!0,savedHadDevices:(c?.[t]?.length??0)>0,value:n,onChange:e=>_(t,e.length>0?e:void 0)})}case`stringList`:{if(!aa(e.id))break;let t=e.id,n=e=>_(t,e.length>0?e:void 0);if(t===`eventTypeTokens`)return d(Gs,{deviceIds:u,value:va(i,t),onChange:n});let a=Rt(t,r);return a===null?d(zs,{value:va(i,t),placeholder:`Add value…`,onChange:n}):d(Bs,{picker:a,value:va(i,t),onChange:n})}case`number01`:{if(!oa(e.id))break;let t=e.id;return d(Vs,{value:ya(i,t),min:0,max:1,step:.05,onChange:e=>_(t,e)})}case`number`:{if(!sa(e.id))break;let t=e.id;return d(Vs,{value:ya(i,t),min:0,step:1,onChange:e=>_(t,e)})}case`sourceSelect`:{if(!ca(e.id))break;let t=e.id;return vl(e,i[t],e=>_(t,e))}case`systemEvent`:{if(!ha(e.id))break;let n=e.id,r=Pt(t);return r===void 0?d(il,{value:i[n]}):d(rl,{family:r,value:i[n],cameras:f,fleet:p,...m===void 0?{}:{allDevices:m},savedHadDevices:(c?.[n]?.deviceIds?.length??0)>0,onChange:e=>_(n,e)})}case`deviceState`:if(!ga(e.id))break;return d(Qs,{gateable:h,value:i.deviceState,onChange:e=>_(`deviceState`,e)});case`scene`:if(!_a(e.id))break;return d(ec,{scenes:g,value:i.scene,onChange:e=>_(`scene`,e)});case`crossingSelect`:{if(!la(e.id))break;let t=e.id;return yl(e,i[t],e=>_(t,e))}case`packagePhase`:{if(!ua(e.id))break;let t=e.id;return d(q,{value:i[t]??``,options:[{value:``,label:`— any phase —`},...uo(e,no).map(e=>({value:e.value,label:e.label}))],onChange:e=>_(t,_l(e.target.value))})}case`sensorTransition`:{if(!da(e.id))break;let t=e.id,r=$e({conditions:i,...o===void 0?{}:{actions:o},...s===void 0?{}:{sequenceActionsOf:s}});return n(a,{children:[d(q,{value:i[t]??``,options:uo(e,ro).map(e=>({value:e.value,label:e.label})),onChange:e=>_(t,io(e.target.value))}),r&&d(`p`,{className:`mt-1 text-[11px] text-warning`,"data-testid":`nc-sensor-transition-never-fires`,children:`This rule belongs to the alarm, and an alarm rule fires only when an opening OPENS. Set to “only when it clears”, it can never fire.`})]})}case`plateMatcher`:{if(!fa(e.id))break;let t=e.id;return d(Zs,{value:i[t],onChange:e=>_(t,e)})}case`occupancy`:{if(!pa(e.id))break;let t=e.id;return d(Js,{deviceIds:u,cameras:f,classOptions:ml(r),value:i[t],onChange:e=>_(t,e)})}case`audio`:{if(!ma(e.id))break;let t=e.id;return d(Xs,{taxonomy:r,value:i[t],onChange:e=>_(t,e)})}case`schedule`:return d(Mc,{value:l,onChange:v});default:break}return d(hl,{descriptor:e,conditions:i})}function ml(e){let t=Rt(`occupancy`,e);return t===null?[]:t.groups.flatMap(e=>e.options)}function hl({descriptor:e,conditions:t}){let r=Object.entries(t).find(([t])=>t===e.id);return n(`p`,{className:Z,children:[r!==void 0&&r[1]!==void 0?`Authored elsewhere and preserved — this admin editor cannot change it yet.`:`Not editable here yet — this condition has no admin editor.`,` `,n(`span`,{className:`text-foreground-muted`,children:[`(`,e.valueType,`)`]})]})}function gl(e){if(e===`pipeline`||e===`onboard`||e===`sensor`||e===`any`)return e}function _l(e){return no.find(t=>t.value===e)?.value}function vl(e,t,n){return d(q,{value:t??`any`,options:uo(e,to).map(e=>({value:e.value,label:e.label})),onChange:e=>n(gl(e.target.value))})}function yl(e,t,n){return d(Hs,{value:t,onChange:n,...e.options?{options:e.options}:{}})}function bl({catalog:e,delivery:t,conditions:r,onConditionsChange:i}){let{t:a}=en(),o=it({delivery:t,conditions:r}),s=(e,t)=>{let n={...r};t===void 0?delete n[e]:n[e]=t,i(n)},c=n=>e.find(e=>e.id===n&&Ke(e,t,o)&&ao(n,r)),l=c(`source`),u=c(`crossing`);return l===void 0&&u===void 0?null:n(`div`,{className:`space-y-2.5`,"data-testid":`rule-advanced-conditions`,children:[l&&ca(l.id)&&n(`div`,{"data-testid":`condition-source`,children:[d(`label`,{className:`block text-[11px] font-medium text-foreground`,children:ul(l,a)}),vl(l,r.source,e=>s(`source`,e)),dl(l,a)!==void 0&&d(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:dl(l,a)})]}),u&&la(u.id)&&n(`div`,{"data-testid":`condition-crossing`,children:[d(`label`,{className:`block text-[11px] font-medium text-foreground`,children:ul(u,a)}),yl(u,r.crossing,e=>s(`crossing`,e)),dl(u,a)!==void 0&&d(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:dl(u,a)})]})]})}var xl=6e4,Sl=60*xl,Cl=24*Sl,wl=Date.UTC(2e3,0,1);function Tl(e){if(e==null||e<wl)return`—`;let t=Date.now()-e;return t<0||t<3e4?`just now`:t<Sl?`${String(Math.floor(t/xl))}m ago`:t<Cl?`${String(Math.floor(t/Sl))}h ago`:`${String(Math.floor(t/Cl))}d ago`}var El=[`notificationRules`,`getRuleLastRuns`],Dl=3e4;function Ol(){let e=h(),t=i({queryKey:El,queryFn:()=>e.trpcClient.notificationRules.getRuleLastRuns.query({}),retry:!1,staleTime:Dl});return{status:t.status,data:t.data,error:t.error}}var kl={sent:`bg-success`,pending:`bg-info`,dead:`bg-danger`};function Al({cell:e}){switch(e.kind){case`pending`:return d(`span`,{"data-testid":`rule-last-run-pending`,"aria-label":`Last run loading`,className:`inline-block h-3 w-14 animate-pulse rounded bg-surface-hover`});case`failed`:return d(`span`,{"data-testid":`rule-last-run-failed`,title:`Last run could not be read: ${e.reason}`,className:`text-[11px] text-foreground-subtle`,children:`—`});case`absent`:return d(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.phrase});case`ran`:return n(`span`,{className:`flex items-center gap-1.5`,title:new Date(e.lastAt).toLocaleString(),children:[d(`span`,{"data-testid":`rule-last-run-dot`,title:e.status,className:`inline-block h-2 w-2 rounded-full ${kl[e.status]}`}),d(`span`,{className:`text-[11px] text-foreground-subtle`,children:Tl(e.lastAt)})]})}}function jl({rule:e,onOpenHistory:t}){return d(I,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>t(e),title:`History — this rule's deliveries`,"aria-label":`history of ${e.name}`,children:d(sn,{className:`h-3.5 w-3.5`})})}t();var Ml=[`notificationRules`,`listSnoozes`],Nl=[10,30,60,120];function Pl({ruleId:e,ruleName:t,exempt:r=!1,variant:i=`icon`}){let a=h(),o=s(),[c,f]=l(30),[p,m]=l(null),g=u({mutationFn:t=>a.trpcClient.notificationRules.createSnooze.mutate({snooze:{scope:`rule`,ruleId:e,durationMinutes:t}}),onMutate:()=>m(null),onSuccess:()=>o.invalidateQueries({queryKey:Ml}),onError:e=>m(e instanceof Error?e.message:`The snooze could not be opened.`)});return r?i===`icon`?null:d(`p`,{className:`text-[10px] text-foreground-subtle`,children:`This rule concerns — or triggers — the alarm panel, so no snooze window can silence it.`}):i===`icon`?d(I,{size:`sm`,variant:`ghost`,type:`button`,disabled:g.isPending,onClick:()=>g.mutate(30),title:`Silence this rule for ${Jo(30)} — it appears under "Silenced right now"`,"aria-label":`snooze ${t}`,"data-testid":`nc-rule-snooze-now`,children:g.isPending?d(G,{className:`h-3.5 w-3.5 animate-spin`}):d(Ne,{className:`h-3.5 w-3.5`})}):n(`div`,{className:`space-y-1`,children:[n(`div`,{className:`flex items-end gap-2`,children:[d(`div`,{className:`w-32`,children:d(q,{value:String(c),onChange:e=>{let t=Number(e.target.value);Number.isFinite(t)&&t>0&&f(t)},options:Nl.map(e=>({value:String(e),label:Jo(e)}))})}),n(I,{size:`sm`,variant:`outline`,type:`button`,disabled:g.isPending,onClick:()=>g.mutate(c),"data-testid":`nc-rule-snooze-now`,children:[g.isPending?d(G,{className:`h-3.5 w-3.5 animate-spin`}):d(Ne,{className:`h-3.5 w-3.5`}),`Silence this rule now`]})]}),d(`p`,{className:`text-[10px] text-foreground-subtle`,children:`Opens a real snooze window right now — distinct from the buttons above, which only choose the durations this rule's NOTIFICATION offers. It appears under "Silenced right now" and can be ended from there.`}),p!==null&&d(`p`,{className:`text-[10px] text-danger`,children:p})]})}t();function Fl(e,t,n){return e.filter(e=>e.scope===`rule`&&e.ruleId===t&&n>=e.startedAt&&n<e.expiresAt).map(e=>e.id)}function Il(e,t,n){let r=e.filter(e=>e.scope===`rule`&&e.ruleId===t&&n<e.expiresAt).map(e=>e.expiresAt);return r.length===0?null:Math.min(...r)}function Ll(e,t){let[,n]=l(0);f(()=>{let r=Il(e,t,Date.now());if(r===null)return;let i=setTimeout(()=>n(e=>e+1),Math.max(0,r-Date.now())+50);return()=>clearTimeout(i)},[e,t])}function Rl(){let e=h();return i({queryKey:Ml,queryFn:async()=>(await e.trpcClient.notificationRules.listSnoozes.query({})).snoozes}).data??[]}function zl({rule:e,snoozes:t,exempt:r}){let{t:i}=en(),a=h(),o=s();Ll(t,e.id);let c=Fl(t,e.id,Date.now()),l=()=>o.invalidateQueries({queryKey:Ml}),f=u({mutationFn:()=>a.trpcClient.notificationRules.createSnooze.mutate({snooze:{scope:`rule`,ruleId:e.id,durationMinutes:30}}),onSuccess:l}),p=u({mutationFn:async e=>{for(let t of e)await a.trpcClient.notificationRules.cancelSnooze.mutate({snoozeId:t})},onSuccess:l});if(r)return null;let m=f.isError||p.isError;return n(`span`,{className:`inline-flex flex-col items-center gap-0.5`,children:[d(F,{checked:c.length>0,disabled:!e.enabled||f.isPending||p.isPending,onCheckedChange:e=>e?f.mutate():p.mutate(c),"aria-label":i(`notificationRules.snooze.aria`,`snooze {{name}}`).replaceAll(`{{name}}`,e.name),title:i(`notificationRules.snooze.title`,{minutes:30,defaultValue:`Silence this rule for {{minutes}} minutes`}).replaceAll(`{{minutes}}`,`30`),"data-testid":`nc-rule-snooze-switch`}),m&&d(`span`,{className:`text-[10px] text-danger`,role:`alert`,children:i(`notificationRules.snooze.failed`,`The snooze could not be changed.`)})]})}var Bl=`pipeline-analytics`,Vl=`nc.getRuleStatus`,Hl=`nc.testRule`;function Ul(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Q(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function Wl(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:void 0}function Gl(e){if(!Ul(e))return;let t=Wl(e,`id`),n=Wl(e,`downloadPath`),r=Q(e,`capturedAt`);if(!(t===void 0||n===void 0||r===void 0))return{id:t,mediaType:Wl(e,`mediaType`)??`video`,sizeBytes:Q(e,`sizeBytes`)??0,capturedAt:r,downloadPath:n}}function Kl(e){if(!Ul(e))return;let t=Q(e,`startMs`),n=Q(e,`endMs`);if(!(t===void 0||n===void 0))return{startMs:t,endMs:n}}function ql(e){if(!Ul(e))return null;let t=Q(e,`deviceId`);if(t===void 0)return null;let n=Q(e,`lastGeneratedAt`),r=Gl(e.lastArtifact),i=e.rendering,a=Ul(i)?{startedAt:Q(i,`startedAt`)??0,windowStartMs:Q(i,`windowStartMs`)??0,windowEndMs:Q(i,`windowEndMs`)??0}:void 0;return{deviceId:t,...n===void 0?{}:{lastGeneratedAt:n},...r===void 0?{}:{lastArtifact:r},...a===void 0?{}:{rendering:a}}}function Jl(e){if(!Ul(e))return null;let t=Q(e,`deviceId`),n=Wl(e,`windowKey`),r=Q(e,`openedAt`),i=Q(e,`closesAt`),a=Q(e,`members`),o=Q(e,`pending`);return t===void 0||n===void 0||r===void 0||i===void 0||a===void 0||o===void 0?null:{deviceId:t,windowKey:n,openedAt:r,closesAt:i,members:a,pending:o}}function Yl(e){if(!Ul(e))return null;let t=Wl(e,`kind`);if(t===`none`)return{kind:`none`,reason:Wl(e,`reason`)??``};if(t===`occupancy`){let t=Q(e,`deviceId`),n=Q(e,`threshold`),r=Q(e,`sustainSeconds`);if(t===void 0||n===void 0||r===void 0)return null;let i=Wl(e,`unavailable`),a=i===`no-snapshot`||i===`zone-absent`?i:void 0,o=Q(e,`count`),s=Q(e,`observedAt`),c=Q(e,`since`),l=Wl(e,`scope`),u=Wl(e,`className`),d=Wl(e,`warning`);return{kind:`occupancy`,deviceId:t,threshold:n,sustainSeconds:r,...l===void 0?{}:{scope:l},...u===void 0?{}:{className:u},...o===void 0?{}:{count:o},...typeof e.occupied==`boolean`?{occupied:e.occupied}:{},...s===void 0?{}:{observedAt:s},...c===void 0?{}:{since:c},...a===void 0?{}:{unavailable:a},...d===void 0?{}:{warning:d}}}if(t===`grouped`){let t=Q(e,`groupingSec`);if(t===void 0)return null;if(e.openWindows===null){let n=Wl(e,`reason`);return{kind:`grouped`,groupingSec:t,openWindows:null,...n===void 0?{}:{reason:n}}}if(!Array.isArray(e.openWindows))return null;let n=[];for(let t of e.openWindows){let e=Jl(t);if(e===null)return null;n.push(e)}return{kind:`grouped`,groupingSec:t,openWindows:n}}if(t===`timelapse`){let t=Array.isArray(e.devices)?e.devices:[],n=[];for(let e of t){let t=ql(e);t!==null&&n.push(t)}let r=Kl(e.lastWindow),i=e.nextWindow,a=Ul(i)?{startMs:Q(i,`startMs`)??0,endMs:Q(i,`endMs`)??null}:void 0;return{kind:`timelapse`,devices:n,...r===void 0?{}:{lastWindow:r},...a===void 0?{}:{nextWindow:a},settleMs:Q(e,`settleMs`)??0}}return null}function Xl(e){let t=Math.max(0,Math.floor(e/6e4));if(t<1)return`less than a minute`;if(t<60)return`${String(t)} min`;let n=Math.floor(t/60),r=t%60;if(n<24)return r===0?`${String(n)} h`:`${String(n)} h ${String(r)} min`;let i=Math.floor(n/24),a=n%24;return a===0?`${String(i)} d`:`${String(i)} d ${String(a)} h`}function Zl(e){if(e<1024)return`${String(e)} B`;let t=e/1024;if(t<1024)return`${t.toFixed(0)} kB`;let n=t/1024;return n<1024?`${n.toFixed(1)} MB`:`${(n/1024).toFixed(2)} GB`}function Ql(e,t){let n=e.scope??`the whole frame`,r=e.className??`objects`;if(e.unavailable!==void 0){let t=e.unavailable===`no-snapshot`?`no live count for this camera yet — the condition fails closed until one arrives`:`“${n}” is not in this camera’s current snapshot — the condition fails closed (deleted zone?)`;return e.warning===void 0?t:`${e.warning} · ${t}`}let i=[`Now: ${String(e.count??0)}/${String(e.threshold)} ${r} in ${n}`,e.occupied===!0?`condition TRUE`:`condition false`];e.since!==void 0&&i.push(`for ${Xl(Math.max(0,t-e.since))}`),i.push(`holds ${String(e.sustainSeconds)} s before firing`);let a=i.join(` · `);return e.warning===void 0?a:`${e.warning} · ${a}`}function $l(e,t,n){if(e.rendering!==void 0)return`${t}: rendering for ${Xl(Math.max(0,n-e.rendering.startedAt))} — the window ${new Date(e.rendering.windowStartMs).toLocaleString()} → ${new Date(e.rendering.windowEndMs).toLocaleString()}`;if(e.lastGeneratedAt===void 0)return`${t}: never produced a video yet`;let r=new Date(e.lastGeneratedAt).toLocaleString(),i=e.lastArtifact;return i===void 0?`${t}: last produced ${r} — the video is no longer on the shelf`:`${t}: last produced ${r} · ${Zl(i.sizeBytes)}`}function eu(e){return{windows:e.length,waiting:e.reduce((e,t)=>e+t.pending,0)}}var tu=`nc.listPrunes`;function nu(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var ru=new Set([`rule`,`timelapse`,`summary`]),iu=new Set([`removed`,`kept-disabled`,`kept`,`sequence-removed`]);function au(e){return typeof e==`string`&&ru.has(e)}function ou(e){return typeof e==`string`&&iu.has(e)}function su(e){return e===`device`||e===`target`}function cu(e){if(!nu(e))return null;let{kind:t,ruleId:n,subjectKind:r,subject:i,field:a,outcome:o,at:s}=e;return!au(t)||!su(r)||!ou(o)||typeof n!=`string`||typeof i!=`string`||typeof a!=`string`||typeof s!=`number`?null:{kind:t,ruleId:n,subjectKind:r,subject:i,field:a,outcome:o,at:s}}function lu(e){return!nu(e)||!Array.isArray(e.prunes)?null:e.prunes.map(cu).filter(e=>e!==null)}function uu(e,t,n,r,i){if(r)return null;let a=e.filter(e=>e.kind===t&&e.ruleId===n);return i>a.reduce((e,t)=>Math.max(e,t.at),-1/0)?null:a.filter(e=>e.outcome===`kept-disabled`).reduce((e,t)=>e===null||t.at>e.at?t:e,null)}function du(e,t){let n=t(e.at);return e.subjectKind===`device`?`Disabled on ${n}: its last device (#${e.subject}) was deleted.`:`Disabled on ${n}: its last delivery target (${e.subject}) was deleted.`}function fu(e){return new Date(e).toLocaleDateString()}function pu({kind:e,ruleId:t,enabled:r,updatedAt:a}){let o=h(),s=i({queryKey:[`pipelineAnalytics`,tu],enabled:!r,staleTime:3e4,retry:!1,queryFn:async()=>lu(await o.trpcClient.addons.custom.mutate({addonId:Bl,action:tu,input:{}}))}).data;if(s==null)return null;let c=uu(s,e,t,r,a);return c===null?null:n(`div`,{"data-testid":`nc-prune-banner`,className:`flex items-start gap-2 rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-xs text-foreground`,children:[d(N,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-warning`}),d(`span`,{children:du(c,fu)})]})}var mu=5e3;function hu({status:e,now:t,name:r}){let{t:i}=en();if(e.openWindows===null)return n(`p`,{className:`flex items-start gap-1.5`,children:[d(ke,{className:`mt-0.5 h-3 w-3 shrink-0 text-border`}),d(`span`,{"data-testid":`nc-grouped-status-headline`,children:i(`notificationRules.status.grouped.unknown`,{reason:e.reason??``,defaultValue:`Open windows unknown — {{reason}}`})})]});let o=e.openWindows,{windows:s,waiting:c}=eu(o);return n(a,{children:[n(`p`,{className:`flex items-start gap-1.5`,children:[d(ke,{className:`mt-0.5 h-3 w-3 shrink-0 ${s>0?`text-primary`:`text-border`}`}),d(`span`,{"data-testid":`nc-grouped-status-headline`,children:s===0?i(`notificationRules.status.grouped.none`,`No window open`):`${i(`notificationRules.status.grouped.windows`,{count:s,defaultValue_one:`{{count}} open window`,defaultValue_other:`{{count}} open windows`})} · ${i(`notificationRules.status.grouped.waiting`,{count:c,defaultValue:`{{count}} waiting`})}`})]}),o.map(e=>n(`p`,{className:`flex items-start gap-1.5`,children:[d(`span`,{className:`mt-0.5 h-3 w-3 shrink-0`}),d(`span`,{children:i(`notificationRules.status.grouped.windowLine`,{camera:r(e.deviceId),members:e.members,pending:e.pending,seconds:Math.max(0,Math.ceil((e.closesAt-t)/1e3)),defaultValue:`{{camera}} · {{members}} in the window · {{pending}} waiting · closes within {{seconds}} s`})})]},e.windowKey))]})}function gu({ruleId:e,cameraName:t}){let r=h(),o=i({queryKey:[`pipelineAnalytics`,`nc.getRuleStatus`,e],refetchInterval:mu,queryFn:async()=>Yl(await r.trpcClient.addons.custom.mutate({addonId:Bl,action:Vl,input:{ruleId:e}}))}).data;if(o==null||o.kind===`none`)return null;let s=Date.now(),c=e=>t?.(e)??`camera ${String(e)}`;return n(`div`,{"data-testid":`nc-rule-status`,className:`rounded-md border border-border bg-surface-subtle px-3 py-2 text-[11px] text-foreground-subtle space-y-1`,children:[o.kind===`occupancy`&&n(`p`,{className:`flex items-start gap-1.5`,children:[o.unavailable!==void 0||o.warning!==void 0?d(A,{className:`mt-0.5 h-3 w-3 shrink-0 text-warning`}):d(ke,{className:`mt-0.5 h-3 w-3 shrink-0 text-primary`}),n(`span`,{children:[d(`span`,{className:`text-foreground`,children:c(o.deviceId)}),` —`,` `,Ql(o,s)]})]}),o.kind===`grouped`&&d(hu,{status:o,now:s,name:c}),o.kind===`timelapse`&&n(a,{children:[o.devices.map(e=>n(`p`,{className:`flex items-start gap-1.5`,children:[d(ke,{className:`mt-0.5 h-3 w-3 shrink-0 ${e.rendering===void 0?`text-border`:`text-primary animate-pulse`}`}),n(`span`,{children:[$l(e,c(e.deviceId),s),e.lastArtifact!==void 0&&n(a,{children:[` · `,d(`a`,{className:`text-primary hover:underline`,href:`/${e.lastArtifact.downloadPath.replace(/^\//,``)}`,target:`_blank`,rel:`noreferrer`,children:`open`})]})]})]},e.deviceId)),n(`p`,{className:`flex items-start gap-1.5`,children:[d(`span`,{className:`mt-0.5 h-3 w-3 shrink-0`}),n(`span`,{children:[o.nextWindow===void 0?`No further window opens in the next nine days`:`Next window opens ${new Date(o.nextWindow.startMs).toLocaleString()}`,o.settleMs>0&&` · rendered ${String(Math.round(o.settleMs/6e4))} min after it closes, so the footage has settled`]})]})]})]})}function _u(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function vu(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:void 0}function yu(e,t){let n=e[t];return Array.isArray(n)?n.filter(e=>typeof e==`string`):[]}function bu(e){if(!_u(e))return null;let t=vu(e,`ruleId`),n=vu(e,`ruleName`);if(t===void 0||n===void 0||typeof e.matched!=`boolean`)return null;let r=vu(e,`failedCondition`);return{ruleId:t,ruleName:n,matched:e.matched,...r===void 0?{}:{failedCondition:r},cooldown:vu(e,`cooldown`)??`n/a`,enqueued:typeof e.enqueued==`number`?e.enqueued:0,targetIds:yu(e,`targetIds`)}}function xu(e){if(!_u(e))return null;let t=vu(e,`conditionId`),n=vu(e,`note`);return t===void 0||n===void 0?null:{conditionId:t,note:n}}function Su(e){if(!_u(e))return;let t=e.split;if(t!==`rule`&&t!==`section`||typeof e.nothingToReport!=`boolean`)return;let n=[];for(let t of Array.isArray(e.sections)?e.sections:[]){if(!_u(t))continue;let e=vu(t,`id`),r=t.status;e===void 0||r!==`read`&&r!==`unavailable`||n.push({id:e,status:r,items:typeof t.items==`number`?t.items:0})}let r=[];for(let t of Array.isArray(e.rows)?e.rows:[]){if(!_u(t))continue;let e=vu(t,`section`);r.push({...e===void 0?{}:{section:e},enqueued:typeof t.enqueued==`number`?t.enqueued:0})}return{split:t,nothingToReport:e.nothingToReport,sections:n,rows:r}}function Cu(e){if(!_u(e))return null;let t=vu(e,`recordId`),n=vu(e,`delivery`);if(t===void 0||n===void 0||e.origin!==`synthetic`)return null;let r=[];for(let t of Array.isArray(e.outcomes)?e.outcomes:[]){let e=bu(t);e!==null&&r.push(e)}let i=[];for(let t of Array.isArray(e.planNotes)?e.planNotes:[]){let e=xu(t);e!==null&&i.push(e)}let a=vu(e,`droppedBy`),o=Su(e.stateSummary);return{recordId:t,delivery:n,trigger:vu(e,`trigger`)??n,candidates:typeof e.candidates==`number`?e.candidates:0,outcomes:r,still:vu(e,`still`)??`none`,notes:yu(e,`notes`),...a===void 0?{}:{droppedBy:a},planNotes:i,...o===void 0?{}:{stateSummary:o}}}function wu(e){if(e.stateSummary!==void 0)return Tu(e,e.stateSummary);if(e.droppedBy!==void 0)return`Nothing was evaluated (${e.droppedBy}) — the event was dropped before any rule was consulted.`;let t=e.outcomes[0];if(t===void 0)return`This rule was not a candidate for a ${e.trigger} event — check its trigger, and that it is enabled.`;if(!t.matched)return t.failedCondition===void 0?`The rule did not match the event built from its own conditions.`:`The rule did not match — the “${t.failedCondition}” condition refused the event.`;if(t.enqueued===0)return`The rule matched, but no notification was queued: every target is opted out of it, or it addresses none.`;let n=e.still===`live`?` with a live snapshot`:e.still===`unavailable`?` (the camera returned no snapshot, so it ships text-only)`:e.still===`unattachable`?` (this kind of rule carries no picture in production either)`:``;return`Matched — ${String(t.enqueued)} notification${t.enqueued===1?``:`s`} queued to ${String(t.targetIds.length)} target${t.targetIds.length===1?``:`s`}${n}. It is marked [TEST] in the body.`}function Tu(e,t){if(t.nothingToReport)return`Nothing to report right now (${t.sections.map(e=>`${e.id}: ${e.status===`unavailable`?`unavailable`:`none open`}`).join(`, `)}) — nothing was sent, exactly as the scheduled summary would send nothing.`;let n=t.rows.reduce((e,t)=>e+t.enqueued,0),r=e.outcomes[0]?.targetIds.length??0;if(n===0)return`The summary was built, but no notification was queued: the rule reaches no target (its users are not admins, or every target is opted out).`;let i=t.rows.flatMap(e=>e.section===void 0?[]:[e.section]).map(e=>`${e} (${String(t.sections.find(t=>t.id===e)?.items??0)})`),a=t.split===`section`?` (one per category: ${i.join(`, `)})`:``;return`Summary built now — ${String(n)} notification${n===1?``:`s`} queued${a} to ${String(r)} target${r===1?``:`s`}. ${n===1?`It is`:`They are`} marked [TEST] in the body.`}t();function Eu({ruleId:e,ruleName:t,fallbackDeviceId:r,variant:i=`icon`,showResult:o=!1}){let s=h(),[c,f]=l(null),[p,m]=l(null),g=u({mutationFn:async()=>Cu(await s.trpcClient.addons.custom.mutate({addonId:Bl,action:Hl,input:{ruleId:e,...r===void 0?{}:{deviceId:r}}})),onMutate:()=>{f(null),m(null)},onSuccess:e=>f(e),onError:e=>m(e instanceof Error?e.message:`The test could not be run.`)}),_=c===null?p===null?void 0:p:wu(c);return n(a,{children:[n(I,{size:`sm`,variant:i===`icon`?`ghost`:`outline`,type:`button`,disabled:g.isPending,onClick:()=>g.mutate(),title:_??`Test now — fires this rule and really sends the notification`,"aria-label":`test ${t} now`,"data-testid":`nc-rule-test-now`,children:[g.isPending?d(G,{className:`h-3.5 w-3.5 animate-spin`}):d(Ie,{className:`h-3.5 w-3.5`}),i===`full`&&`Test now`]}),o&&p!==null&&d(`div`,{className:`mt-2 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-[11px] text-danger`,children:p}),o&&c!==null&&n(`div`,{"data-testid":`nc-rule-test-result`,className:`mt-2 space-y-1 rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:[d(`p`,{className:`text-foreground`,children:wu(c)}),c.planNotes.map(e=>n(`p`,{className:`flex gap-1.5`,children:[d(A,{className:`mt-0.5 h-3 w-3 shrink-0 text-warning`}),d(`span`,{children:e.note})]},e.conditionId)),c.notes.map(e=>n(`p`,{children:[`· `,e]},e))]})]})}t();var Du=[`notificationRules`,`listSnoozes`],Ou=3e4;function ku(e,t){return Math.max(0,Math.ceil((e.expiresAt-t)/6e4))}function Au(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 ju({rules:e}){let t=h(),a=s(),o=i({queryKey:Du,refetchInterval:Ou,queryFn:async()=>(await t.trpcClient.notificationRules.listSnoozes.query({})).snoozes}),c=u({mutationFn:e=>t.trpcClient.notificationRules.cancelSnooze.mutate({snoozeId:e}),onSuccess:()=>a.invalidateQueries({queryKey:Du})}),l=r(()=>{let t=new Map;for(let n of e)t.set(n.id,n.name);return t},[e]),f=Date.now(),p=(o.data??[]).filter(e=>f>=e.startedAt&&f<e.expiresAt);return n(H,{className:`p-4`,children:[n(`div`,{className:`flex items-center gap-2 mb-3`,children:[d(Ne,{className:`h-4 w-4 text-foreground-subtle`}),d(`h3`,{className:`text-sm font-medium text-foreground`,children:`Silenced right now`})]}),p.length===0&&d(`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.`}),d(`div`,{className:`max-h-64 space-y-2 overflow-y-auto`,children:p.map(e=>n(`div`,{className:`flex items-center justify-between gap-3 rounded-md border border-border px-3 py-2`,children:[n(`div`,{className:`min-w-0`,children:[n(`div`,{className:`flex items-center gap-2`,children:[d(`span`,{className:`text-xs text-foreground truncate`,children:e.scope===`all`?`Everything`:e.scope===`device`?`Camera ${e.deviceId??`?`}`:l.get(e.ruleId??``)??`A rule`}),e.global&&d(U,{variant:`warning`,className:`text-[10px]`,children:`everyone`}),e.classes!==void 0&&e.classes.length>0&&d(U,{variant:`info`,className:`text-[10px]`,children:e.classes.join(`, `)}),!e.summary&&d(U,{variant:`default`,className:`text-[10px]`,children:`no summary`})]}),n(`span`,{className:`text-[10px] text-foreground-subtle`,children:[`set by `,e.userId,` · `,Au(ku(e,f))]})]}),d(I,{size:`sm`,variant:`outline`,disabled:c.isPending,onClick:()=>c.mutate(e.id),children:`End now`})]},e.id))})]})}function Mu(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 Nu=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function Pu(e){let t=Math.floor(e/60),n=e%60;return`${String(t).padStart(2,`0`)}:${String(n).padStart(2,`0`)}`}function Fu(e){let t=e.windows[0];if(t===void 0)return`No window`;let n=t.days.toSorted((e,t)=>e-t).map(e=>Nu[e]??String(e)).join(` `),r=t.startMinute>t.endMinute?` (overnight)`:``,i=e.windows.length-1,a=e.invert===!0?` · outside`:``;return`${n} ${Pu(t.startMinute)}–${Pu(t.endMinute)}${r}${i>0?` +${i}`:``}${a}`}function Iu(e,t,n){if(e===void 0||e<=0)return n;let r=Math.max(0,t-e);return`${Mu(Math.round(r/1e3))} ago`}function Lu(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ru(e){return Array.isArray(e)?`[${e.map(Ru).join(`,`)}]`:Lu(e)?`{${Object.keys(e).toSorted().map(t=>`${JSON.stringify(t)}:${Ru(e[t])}`).join(`,`)}}`:JSON.stringify(e)??`null`}function zu(e,t){return Ru(e)===Ru(t)}function Bu(e){return e.map(e=>({targetId:e}))}var $=`pipeline-analytics`,Vu=`nc.getTexts`,Hu=`nc.setLanguage`,Uu=`nc.setTextOverrides`,Wu={en:`English`,it:`Italiano`};function Gu(e){return e===`en`||e===`it`}function Ku(e){return e===`override`||e===`shipped`||e===`fallback`}function qu(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ju(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 Yu(e){if(!qu(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`||!Gu(r)||!Ku(o)||i!==null&&typeof i!=`string`)return null;let s=Ju(e.placeholders),c=Ju(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 Xu(e){if(!qu(e))return null;let{language:t,activeLanguage:n}=e;if(!Gu(t)||!Gu(n))return null;let r=Ju(e.languages);if(r===null||r.length===0)return null;let i=[];for(let e of r)Gu(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=Yu(e);if(t===null)return null;o.push(t)}return{language:t,activeLanguage:n,languages:i,entries:o}}function Zu(e,t){return t.get(e.key)??e.override??e.shipped}function Qu(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 $u(e,t){return Object.keys(Qu(e,t)).length}function ed(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 td(e){return e.placeholders.map(e=>({name:e,label:e,example:`{{${e}}}`,group:`rule`,families:[`rule`]}))}function nd(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 rd=`nc.listSummaryRules`,id=`nc.upsertSummaryRule`,ad=`nc.deleteSummaryRule`,od=`nc.testSummaryRule`,sd=3600,cd=86400,ld=3600,ud=3600,dd=3*36e5,fd=[`importance`,`recency`,`dwell`],pd={importance:`Most important`,recency:`Most recent`,dwell:`Longest stay`},md=[`none`,`tiles`,`all`],hd=`none`,gd={none:`Images only — no text anywhere`,tiles:`A label under each tile`,all:`Tile labels and a caption across the top`},_d=[`en`,`it`],vd=[`deliver-without-text`,`skip`],yd=2048,bd=2e3;function xd(e){return e.window.kind!==`unsupported`&&!e.readOnly}function Sd(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Cd(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 wd(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 Td(e){if(e!==void 0)return typeof e==`string`?e:null}function Ed(e){if(e!==void 0)return typeof e==`number`&&Number.isFinite(e)?e:null}function Dd(e){return fd.some(t=>t===e)}function Od(e){return e===void 0?hd:md.find(t=>t===e)??null}function kd(e){if(!Sd(e)||!Array.isArray(e.windows)||e.windows.length===0)return null;let t=[];for(let n of e.windows){if(!Sd(n))return null;let e=Cd(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=Td(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 Ad(e){if(!Sd(e)||typeof e.kind!=`string`)return null;if(e.kind===`schedule`){let t=kd(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 jd(e){if(e==null)return;if(!Sd(e))return null;let t=e.classes===void 0?void 0:wd(e.classes),n=e.classesExclude===void 0?void 0:wd(e.classesExclude),r=e.zones===void 0?void 0:wd(e.zones);if(t===null||n===null||r===null)return null;let i=Ed(e.minImportance),a=Ed(e.minDwellSeconds);if(i===null||a===null)return null;let o=e.includeStationary;return o!==void 0&&typeof o!=`boolean`?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},...o===!0?{includeStationary:!0}:{}}}function Md(e){if(e==null)return;if(!Sd(e))return null;let t=Td(e.title),n=Td(e.body);return t===null||n===null?null:{...t===void 0?{}:{title:t},...n===void 0?{}:{body:n}}}function Nd(e){return _d.some(t=>t===e)}function Pd(e){return vd.some(t=>t===e)}function Fd(e){if(e==null)return;if(!Sd(e)||typeof e.enabled!=`boolean`)return null;let t=Td(e.profileId),n=Td(e.prompt);if(t===null||n===null)return null;let r=Ed(e.maxImagePx),i=Ed(e.timeoutMs);if(r===null||i===null)return null;let a=e.language;if(a!==void 0&&!Nd(a))return null;let o=e.onFailure;return o!==void 0&&!Pd(o)?null:{enabled:e.enabled,...t===void 0?{}:{profileId:t},...n===void 0?{}:{prompt:n},...a===void 0?{}:{language:a},...r===void 0?{}:{maxImagePx:r},...i===void 0?{}:{timeoutMs:i},...o===void 0?{}:{onFailure:o}}}function Id(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(!Sd(n)||typeof n.targetId!=`string`)return null;let e=n.params;if(e!==void 0&&!Sd(e))return null;t.push({targetId:n.targetId,...e===void 0?{}:{params:e}})}return t}function Ld(e){if(!Sd(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`||!Dd(o)||typeof s!=`number`||typeof c!=`boolean`||typeof e.priority!=`number`)return null;let l=Cd(e.deviceIds),u=Ad(e.window),d=Id(e.targets);if(l===null||u===null||d===null)return null;let f=jd(e.filters),p=Md(e.template);if(f===null||p===null)return null;let m=Td(e.captionText),h=Ed(e.generatedAt),g=Ed(e.updatedAt);if(m===null||h===null||g===null)return null;let _=Od(e.captions);if(_===null)return null;let v=Fd(e.ai);return v===null?null:{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},captions:_,...m===void 0?{}:{captionText:m},deliverEmpty:c,priority:e.priority,...h===void 0?{}:{generatedAt:h},...g===void 0?{}:{updatedAt:g},readOnly:e.readOnly===!0,...v===void 0?{}:{ai:v}}}function Rd(e){if(!Sd(e)||!Array.isArray(e.rules))return null;let t=[];for(let n of e.rules){let e=Ld(n);if(e===null)return null;t.push(e)}return t}function zd(e){if(!Sd(e)||typeof e.produced!=`number`)return null;let t=[`tiles`,`cameras`,`matched`,`droppedStationary`,`enqueued`,`mosaicBytes`,`aiImages`],n={produced:e.produced};for(let r of t){let t=Ed(e[r]);if(t===null)return null;t!==void 0&&(n[r]=t)}for(let t of[`windowStartMs`,`windowEndMs`]){let r=Ed(e[t]);if(r===null)return null;r!==void 0&&(n[t]=r)}for(let t of[`mosaicUrl`,`error`,`aiText`,`aiFailure`]){let r=Td(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.droppedStationary==`number`?{droppedStationary:n.droppedStationary}:{},...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}:{},...typeof n.aiText==`string`?{aiText:n.aiText}:{},...typeof n.aiFailure==`string`?{aiFailure:n.aiFailure}:{},...typeof n.aiImages==`number`?{aiImages:n.aiImages}:{},...e.skippedByAi===!0?{skippedByAi:!0}:{}}}function Bd(){return{name:``,enabled:!0,deviceIds:[],windowKind:`motion`,schedule:void 0,quietSeconds:60,maxWindowSeconds:300,classes:[],classesExclude:[],zones:[],minImportance:void 0,minDwellSeconds:void 0,includeStationary:!1,maxTiles:12,maxAiImages:6,rank:`importance`,barrierSeconds:120,targetIds:[],templateTitle:``,templateBody:``,mosaicCaptions:hd,captionText:``,deliverEmpty:!1,priority:3,aiEnabled:!1,aiProfileId:``,aiPrompt:``,aiLanguage:``,aiMaxImagePx:void 0,aiTimeoutSeconds:void 0,aiOnFailure:`deliver-without-text`}}function Vd(e){let t=Bd(),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,includeStationary:e.filters?.includeStationary===!0,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??``,mosaicCaptions:e.captions,captionText:e.captionText??``,deliverEmpty:e.deliverEmpty,priority:e.priority,aiEnabled:e.ai?.enabled??t.aiEnabled,aiProfileId:e.ai?.profileId??``,aiPrompt:e.ai?.prompt??``,aiLanguage:e.ai?.language??``,aiMaxImagePx:e.ai?.maxImagePx,aiTimeoutSeconds:e.ai?.timeoutMs===void 0?void 0:Math.round(e.ai.timeoutMs/1e3),aiOnFailure:e.ai?.onFailure??t.aiOnFailure}}function Hd(e){return e.windowKind===`schedule`&&e.schedule!==void 0?{kind:`schedule`,schedule:e.schedule}:{kind:`motion`,quietSeconds:e.quietSeconds,maxWindowSeconds:e.maxWindowSeconds}}function Ud(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},...e.includeStationary?{includeStationary:!0}:{}};return Object.keys(t).length===0?void 0:t}function Wd(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 Gd(e){return Bu(e.targetIds)}function Kd(e){let t=e.aiProfileId.trim(),n=e.aiPrompt.trim(),r=t.length>0||n.length>0||e.aiLanguage!==``||e.aiMaxImagePx!==void 0||e.aiTimeoutSeconds!==void 0||e.aiOnFailure!==`deliver-without-text`;if(!(!e.aiEnabled&&!r))return{enabled:e.aiEnabled,...t.length>0?{profileId:t}:{},...n.length>0?{prompt:n}:{},...e.aiLanguage===``?{}:{language:e.aiLanguage},...e.aiMaxImagePx===void 0?{}:{maxImagePx:e.aiMaxImagePx},...e.aiTimeoutSeconds===void 0?{}:{timeoutMs:Math.round(e.aiTimeoutSeconds*1e3)},...e.aiOnFailure===`deliver-without-text`?{}:{onFailure:e.aiOnFailure}}}function qd(e){let t=Ud(e),n=Wd(e),r=Kd(e),i=e.captionText.trim();return{name:e.name.trim(),enabled:e.enabled,deviceIds:[...e.deviceIds],window:Hd(e),...t===void 0?{}:{filters:t},maxTiles:e.maxTiles,maxAiImages:e.maxAiImages,rank:e.rank,barrierSeconds:e.barrierSeconds,targets:Gd(e),...n===void 0?{}:{template:n},captions:e.mosaicCaptions,...i.length>0?{captionText:i}:{},deliverEmpty:e.deliverEmpty,priority:e.priority,...r===void 0?{}:{ai:r}}}function Jd(e,t){let n=qd(e),r={};return n.name!==t.name&&(r.name=n.name),n.enabled!==t.enabled&&(r.enabled=n.enabled),zu(n.deviceIds,t.deviceIds)||(r.deviceIds=n.deviceIds),zu(n.window,t.window)||(r.window=n.window),zu(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),zu(n.targets,t.targets)||(r.targets=n.targets),zu(n.template,t.template)||(r.template=n.template??null),n.captions!==t.captions&&(r.captions=n.captions),(n.captionText??``)!==(t.captionText??``)&&(r.captionText=n.captionText??``),n.deliverEmpty!==t.deliverEmpty&&(r.deliverEmpty=n.deliverEmpty),n.priority!==t.priority&&(r.priority=n.priority),zu(n.ai,t.ai)||(r.ai=n.ai??null),r}function Yd(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 ${sd}s.`),(e.maxWindowSeconds<60||e.maxWindowSeconds>86400)&&t.push(`The longest window must be between 60s and ${cd}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 ${ld}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 ${ud}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.`),e.aiPrompt.length>2e3&&t.push(`The AI question is at most ${bd} characters.`),e.aiTimeoutSeconds!==void 0&&(e.aiTimeoutSeconds<10||e.aiTimeoutSeconds>600)&&t.push(`The AI time limit is between 10s and 600s.`),e.aiMaxImagePx!==void 0&&(e.aiMaxImagePx<64||e.aiMaxImagePx>2048)&&t.push(`The AI frame size is between 64 and ${yd} pixels.`);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 Xd(e){return Yd(e).length===0}function Zd(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.`),e.aiEnabled&&e.aiOnFailure===`skip`&&t.push(`With “hold the digest” selected, a window whose AI pass fails is NOT delivered at all — no mosaic, no counts — and the window does not come back.`),t}var Qd=[{key:`rule`,label:`Rule`,fields:[`name`,`enabled`,`deviceIds`]},{key:`window`,label:`Window`,fields:[`windowKind`,`schedule`,`quietSeconds`,`maxWindowSeconds`,`barrierSeconds`]},{key:`content`,label:`What goes in`,fields:[`classes`,`classesExclude`,`zones`,`minImportance`,`minDwellSeconds`,`includeStationary`]},{key:`mosaic`,label:`Mosaic`,fields:[`maxTiles`,`rank`,`mosaicCaptions`,`captionText`]},{key:`ai`,label:`AI`,fields:[`aiEnabled`,`aiProfileId`,`aiPrompt`,`aiLanguage`,`aiMaxImagePx`,`aiTimeoutSeconds`,`aiOnFailure`,`maxAiImages`]},{key:`delivery`,label:`Delivery`,fields:[`targetIds`,`priority`,`deliverEmpty`,`templateTitle`,`templateBody`]}],$d=`rule`;function ef(e){return Qd.find(t=>t.key===e)?.key}function tf(e){return e.kind===`motion`?`Motion · ${Mu(e.quietSeconds)} quiet · max ${Mu(e.maxWindowSeconds)}`:e.kind===`unsupported`?`Unsupported window (${e.raw}) — authored on a newer hub`:`Schedule · ${Fu(e.schedule)}`}function nf(e,t){return Iu(e,t,`Never run`)}function rf(e){if(e===void 0)return`All passages`;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 ≥ ${Mu(e.minDwellSeconds)}`),e.includeStationary===!0&&t.push(`incl. parked`),t.length===0?`All passages`:t.join(` · `)}function af(e){return{windowStartMs:e-dd,windowEndMs:e}}t();var of={"deliver-without-text":`Deliver the digest anyway, without the text`,skip:`Hold the whole digest — deliver nothing`},sf={en:`English`,it:`Italiano`};function cf(e){return fd.find(t=>t===e)}function lf(e){return md.find(t=>t===e)}function uf(e){return _d.find(t=>t===e)??``}function df(e){return vd.find(t=>t===e)}function ff({rule:e,cameras:t,fleet:a,targets:o,taxonomy:s,onSaved:c,onCancel:f}){let p=h(),[m,g]=l(()=>e===null?Bd():Vd(e)),[_,v]=l(null),[y,b]=l($d),x=e=>g(t=>({...t,...e})),S=r(()=>{let e=Rt(`occupancy`,s);return e===null?[]:e.groups.flatMap(e=>e.options)},[s]),{options:T,loading:O}=ba(m.deviceIds,t.map(e=>({id:e.id,name:e.name}))),k=i({queryKey:[`llm`,`listProfiles`,`summary-editor`],queryFn:()=>p.trpcClient.llm.listProfiles.query({}),retry:!1}),A=(k.data??[]).filter(e=>e.supportsVision),j=u({mutationFn:async()=>{let t=e===null?{rule:qd(m)}:{ruleId:e.id,patch:Jd(m,e)};await p.trpcClient.addons.custom.mutate({addonId:$,action:id,input:t})},onSuccess:c,onError:e=>v(e instanceof Error?e.message:`Save failed`)}),N=qr(),P=N.data?Ur(N.data,{family:`summary`,field:`captionText`}):void 0,F=m.mosaicCaptions===`all`,te=Yd(m),ne=Zd(m),re=Xd(m)&&!j.isPending,ie=Qd.some(e=>e.key===y)?y:$d;return d(w,{open:!0,onOpenChange:e=>!e&&f(),children:n(De,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,children:[n(`div`,{className:`mb-3 flex shrink-0 items-center justify-between`,children:[n(`h3`,{className:`flex min-w-0 items-center gap-2 text-sm font-semibold text-foreground`,children:[d(cn,{className:`h-4 w-4 shrink-0 text-foreground-subtle`}),d(`span`,{className:`truncate`,children:e===null?`New summary`:`Edit ${e.name}`})]}),d(I,{size:`sm`,variant:`ghost`,type:`button`,onClick:f,children:`Cancel`})]}),_!==null&&d(`div`,{className:`mb-3 shrink-0 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger`,children:_}),n(`div`,{className:`shrink-0 space-y-2`,children:[e!==null&&d(pu,{kind:`summary`,ruleId:e.id,enabled:e.enabled,updatedAt:e.updatedAt??1/0}),d(ni,{problems:te,testId:`summary-problems`}),d(ri,{warnings:ne,testId:`summary-warnings`})]}),n(ee,{value:ie,onValueChange:e=>b(ef(e)??y),className:`mt-3 flex min-h-0 flex-1 flex-col`,children:[d(C,{className:`mb-3 shrink-0`,children:Qd.map(e=>d(E,{value:e.key,children:e.label},e.key))}),n(D,{className:`pr-1`,children:[n(M,{value:`rule`,className:`space-y-3`,children:[d(ti,{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:n(`div`,{className:`flex items-end gap-3`,children:[n(`div`,{className:`min-w-0 flex-1`,children:[d(`label`,{className:Y,children:`Name`}),d(B,{value:m.name,onChange:e=>x({name:e.target.value}),placeholder:`e.g. Overnight sweep`,"data-testid":`summary-name`})]}),d(`div`,{className:`pb-1.5`,children:d(si,{label:`Enabled`,checked:m.enabled,onChange:e=>x({enabled:e}),testId:`summary-enabled`})})]})}),d(ti,{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:d(ii,{cameras:t,value:m.deviceIds,fleet:a,onChange:e=>x({deviceIds:e}),hint:`The first camera selected owns the delivered notification.`})})]}),d(M,{value:`window`,className:`space-y-3`,children:n(ti,{title:`When the window closes`,children:[n(`div`,{children:[d(`label`,{className:Y,children:`Window`}),d(q,{value:m.windowKind,options:[{value:`motion`,label:`Motion — opened and closed by activity`},{value:`schedule`,label:`Schedule — fixed weekly windows`}],onChange:e=>x({windowKind:e.target.value===`schedule`?`schedule`:`motion`}),"data-testid":`summary-window-kind`})]}),m.windowKind===`motion`?n(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[d(oi,{label:`Quiet period (seconds)`,value:m.quietSeconds,min:30,max:sd,onChange:e=>x({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`}),d(oi,{label:`Longest window (seconds)`,value:m.maxWindowSeconds,min:60,max:cd,onChange:e=>x({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`})]}):n(`div`,{children:[d(`label`,{className:Y,children:`Weekly windows`}),d(Mc,{value:m.schedule,onChange:e=>x({schedule:e})}),d(`p`,{className:ei,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.`})]}),d(oi,{label:`Wait for open tracks (seconds)`,value:m.barrierSeconds,min:0,max:ld,onChange:e=>x({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`})]})}),d(M,{value:`content`,className:`space-y-3`,children:n(ti,{title:`What goes in`,hint:`Evaluated on tracks: one passage is one tile.`,children:[n(`div`,{children:[d(`label`,{className:Y,children:`Classes`}),d(wa,{options:S,value:m.classes,onChange:e=>x({classes:e}),emptyHint:`No class vocabulary from this hub — leave empty to keep every class.`,placeholder:``,noFreeText:!0}),d(`p`,{className:ei,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.`})]}),n(`div`,{children:[d(`label`,{className:Y,children:`Excluded classes`}),d(wa,{options:S,value:m.classesExclude,onChange:e=>x({classesExclude:e}),emptyHint:`No class vocabulary from this hub.`,placeholder:``,noFreeText:!0})]}),n(`div`,{children:[d(`label`,{className:Y,children:`Zones`}),d(wa,{options:T,value:m.zones,onChange:e=>x({zones:e}),loading:O,emptyHint:`Pick a camera first — the zones offered are its own.`,placeholder:``,noFreeText:!0}),d(`p`,{className:ei,children:`Zones are scoped per camera: picking a zone on one camera does not mute the others, which keep matching on the whole frame.`})]}),n(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[d(oi,{label:`Minimum importance`,value:m.minImportance,min:0,max:1,step:.05,emptyPlaceholder:`any`,onChange:e=>x({minImportance:e}),hint:`The pipeline's own score, 0–1. Empty keeps everything.`,testId:`summary-min-importance`}),d(oi,{label:`Minimum stay (seconds)`,value:m.minDwellSeconds,min:0,max:ud,emptyPlaceholder:`any`,onChange:e=>x({minDwellSeconds:e}),hint:`Drops the passages too brief to be worth a tile.`,testId:`summary-min-dwell`})]}),d(si,{label:`Include parked objects`,checked:m.includeStationary,onChange:e=>x({includeStationary:e}),hint:`Off by default. A car left in the drive is tracked until it is recognised as parked, and it stays parked for as long as it is there — with this on, a digest fills up with the same stationary object instead of the passages. Parked objects remain on the Events page either way.`,testId:`summary-include-stationary`})]})}),d(M,{value:`mosaic`,className:`space-y-3`,children:n(ti,{title:`The mosaic`,children:[n(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[d(oi,{label:`Tiles`,value:m.maxTiles,min:1,max:24,onChange:e=>x({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`}),n(`div`,{children:[d(`label`,{className:Y,children:`When there are more tracks than tiles`}),d(q,{value:m.rank,options:fd.map(e=>({value:e,label:pd[e]})),onChange:e=>{let t=cf(e.target.value);t!==void 0&&x({rank:t})},"data-testid":`summary-rank`}),d(`p`,{className:ei,children:`Every contributing camera keeps its single best tile first; the remaining slots go to this ranking.`})]})]}),n(`div`,{children:[d(`label`,{className:Y,children:`Text on the mosaic`}),d(q,{value:m.mosaicCaptions,options:md.map(e=>({value:e,label:gd[e]})),onChange:e=>{let t=lf(e.target.value);t!==void 0&&x({mosaicCaptions:t})},"data-testid":`summary-captions`}),d(`p`,{className:ei,children:`Images only is the default, and it is what a rule with nothing set here does. Anything drawn is burnt into the picture for good — a label covers the bottom of the tile, which is where feet, wheels and parcels are, and a caption from a detection that was wrong cannot be un-drawn. Nothing downstream needs the words: the written summary reads the frames themselves and is told the camera, the class and the time in its prompt.`})]}),n(`div`,{children:[d(Qr,{label:`Caption burned onto the mosaic`,value:m.captionText,disabled:!F,onChange:e=>x({captionText:e}),placeholder:`Leave empty for no caption`,vars:P,testId:`summary-caption`}),d(`p`,{className:ei,children:F?`Across the top band.`:`Only drawn with “tile labels and a caption across the top”. What you type here is kept either way.`})]})]})}),d(M,{value:`ai`,className:`space-y-3`,children:n(ti,{title:`Written summary`,hint:`One vision call over the window's best frames TOGETHER, so the answer is an account of what happened rather than a list of pictures. The sentence goes in the notification body.`,children:[d(si,{label:`Have a model describe the window`,checked:m.aiEnabled,onChange:e=>x({aiEnabled:e}),hint:`Off by default. The mosaic and the counts are delivered either way.`,testId:`summary-ai-enabled`}),!m.aiEnabled&&d(`p`,{className:`rounded-md border border-border bg-surface px-2.5 py-1.5 text-[10px] text-foreground-muted`,"data-testid":`summary-ai-off-note`,children:`The switch above is off, so nothing below it can be edited. Everything you already set is kept — turning it on hands the fields back exactly as you left them.`}),n(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[n(`div`,{children:[d(`label`,{className:Y,children:`Vision profile`}),d(q,{value:m.aiProfileId,disabled:!m.aiEnabled,options:[{value:``,label:`The hub's default vision profile`},...A.map(e=>({value:e.id,label:`${e.name} · ${e.model}${e.enabled?``:` · disabled`}`}))],onChange:e=>x({aiProfileId:e.target.value}),"data-testid":`summary-ai-profile`}),d(`p`,{className:ei,children:k.isError?`This hub did not answer with a profile list — the digest will use whatever the AI addon resolves for the “ai-summary” consumer.`:A.length===0?`No vision-capable profile on this hub yet. Add one under AI → Profiles; until then the digest delivers without text.`:`Only vision-capable profiles are offered — a vision call against a text profile is refused, never degraded.`})]}),n(`div`,{children:[d(`label`,{className:Y,children:`Answer in`}),d(q,{value:m.aiLanguage,disabled:!m.aiEnabled,options:[{value:``,label:`Don’t ask for a language`},..._d.map(e=>({value:e,label:sf[e]}))],onChange:e=>x({aiLanguage:uf(e.target.value)}),"data-testid":`summary-ai-language`}),d(`p`,{className:ei,children:`Nothing is added to the prompt unless you pick one, and these models answer in English on their own.`})]})]}),n(`div`,{children:[d(`label`,{className:Y,children:`Your question (optional)`}),d(`textarea`,{value:m.aiPrompt,rows:3,maxLength:bd,disabled:!m.aiEnabled,onChange:e=>x({aiPrompt:e.target.value}),"data-testid":`summary-ai-prompt`,placeholder:`e.g. Tell me whether anybody approached the gate, and whether a parcel was left.`,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 disabled:opacity-50`}),d(`p`,{className:ei,children:`Leave blank for “what happened during this period?”. Your words are the only free text the model is given: what the cameras are called and what the pipeline classified are reduced to plain labels first, and anything written INSIDE a frame — a sign, a plate, an overlay — is treated as scenery, never as an instruction.`})]}),n(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[d(oi,{label:`Frames the model may look at`,value:m.maxAiImages,min:1,max:8,disabled:!m.aiEnabled,onChange:e=>x({maxAiImages:e??1}),hint:`The highest-ranked tiles, sent as ONE question. Bounded separately from the tile budget — one is bounded by pixels, the other by the model's time — and never larger than it.`,testId:`summary-max-ai-images`}),d(oi,{label:`Time limit (seconds)`,value:m.aiTimeoutSeconds,min:10,max:600,emptyPlaceholder:`180`,disabled:!m.aiEnabled,onChange:e=>x({aiTimeoutSeconds:e}),hint:`Nobody is waiting on a phone for a digest, so this is generous. At the bound the generation is cancelled, not merely abandoned.`,testId:`summary-ai-timeout`})]}),n(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[d(oi,{label:`Frame size sent (pixels)`,value:m.aiMaxImagePx,min:64,max:yd,emptyPlaceholder:`448`,disabled:!m.aiEnabled,onChange:e=>x({aiMaxImagePx:e}),hint:`Longest edge. 448 is the native tile size of these vision encoders — larger costs tokens and latency without adding detail the encoder can see.`,testId:`summary-ai-max-px`}),n(`div`,{children:[d(`label`,{className:Y,children:`If the model gives no answer`}),d(q,{value:m.aiOnFailure,disabled:!m.aiEnabled,options:vd.map(e=>({value:e,label:of[e]})),onChange:e=>{let t=df(e.target.value);t!==void 0&&x({aiOnFailure:t})},"data-testid":`summary-ai-on-failure`}),d(`p`,{className:ei,children:`A cold model, an unreachable endpoint or an answer the hub cannot parse are all this case. The default delivers: the mosaic and the counts are worth more than silence, and a closed window does not come back.`})]})]})]})}),d(M,{value:`delivery`,className:`space-y-3`,children:n(ti,{title:`Delivery`,children:[d(ai,{targets:o,value:m.targetIds,onChange:e=>x({targetIds:e})}),n(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[d(oi,{label:`Priority`,value:m.priority,min:1,max:5,onChange:e=>x({priority:e??3}),testId:`summary-priority`}),d(si,{label:`Deliver a window that matched nothing`,checked:m.deliverEmpty,onChange:e=>x({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`})]}),d(ci,{title:m.templateTitle,body:m.templateBody,onTitleChange:e=>x({templateTitle:e}),onBodyChange:e=>x({templateBody:e}),family:`summary`,testIdPrefix:`summary-template`}),n(`p`,{className:ei,children:[d(`code`,{children:`{{ai}}`}),` is the written summary. A body that never names it still gets the sentence, appended on its own line — a template written before the AI pass existed must not make the feature look broken.`]})]})})]})]}),n(`div`,{className:`mt-3 flex shrink-0 justify-end gap-2`,children:[d(I,{size:`sm`,variant:`secondary`,type:`button`,onClick:f,children:`Cancel`}),n(I,{size:`sm`,type:`button`,disabled:!re,onClick:()=>j.mutate(),children:[j.isPending&&d(G,{className:`h-3.5 w-3.5 animate-spin`}),e===null?`Create`:`Save`]})]})]})})}function pf({children:e,className:t}){return d(`span`,{className:t,onClick:e=>e.stopPropagation(),children:e})}function mf(){return d(`div`,{className:`flex items-center justify-center py-16`,children:d(G,{className:`h-6 w-6 animate-spin text-primary`})})}function hf({children:e,testId:t}){return d(`div`,{className:`text-xs text-foreground-subtle text-center py-16`,...t===void 0?{}:{"data-testid":t},children:e})}function gf({columns:e,rows:t,rowKey:n,minWidthPx:r,onRowClick:i}){return d(H,{children:d(Pe,{columns:e,rows:t,rowKey:n,minWidthPx:r,bordered:!1,mobileMode:`scroll`,maxBodyHeight:ie,...i===void 0?{}:{onRowClick:i}})})}function _f({name:e,enabled:t,onOpen:r,badges:i,openTestId:a}){return n(`span`,{className:`flex flex-wrap items-center gap-2`,children:[r===void 0?d(`span`,{className:`truncate text-sm font-medium text-foreground`,children:e}):d(pf,{children:d(`button`,{type:`button`,onClick:r,className:`truncate rounded text-left text-sm font-medium text-foreground hover:underline focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary`,...a===void 0?{}:{"data-testid":a},children:e})}),!t&&d(U,{variant:`warning`,children:`disabled`}),i]})}function vf({disabled:e=!1,pending:t=!1,title:n,message:r,confirmLabel:i=`Delete`,cancelLabel:a=`Cancel`,ariaLabel:o,testId:s,onConfirm:c}){let l=j(),u=async()=>{await l({title:n,message:r,confirmLabel:i,cancelLabel:a,variant:`danger`})&&c()};return d(`button`,{type:`button`,title:i,"aria-label":o,disabled:e||t,className:`inline-flex h-7 items-center rounded-md px-2 hover:bg-surface-hover disabled:opacity-50`,onClick:()=>void u(),...s===void 0?{}:{"data-testid":s},children:d(_,{className:`h-3.5 w-3.5 text-danger`})})}t();var yf=[`notificationSummaries`,`listSummaryRules`],bf=`One window, one picture: every camera’s best moments as a single mosaic.`;function xf({embedded:e=!1,openCreateKey:t}={}){let o=h(),[s,c]=l({mode:`closed`}),[p,m]=l(null),[g,_]=l(null),[v,y]=l(!1);f(()=>{t!==void 0&&t>0&&c({mode:`form`,rule:null})},[t]);let b=i({queryKey:yf,queryFn:async()=>Rd(await o.trpcClient.addons.custom.mutate({addonId:$,action:rd,input:{}}))});f(()=>{b.isSuccess&&y(b.data===null)},[b.isSuccess,b.data]);let x=se({projection:`slim`}),S=r(()=>(x.data??[]).filter(e=>e.type===Ft.Camera).map(e=>({id:e.id,name:e.name})).toSorted((e,t)=>e.name.localeCompare(t.name)),[x.data]),C=i({queryKey:Vp,queryFn:()=>o.trpcClient.notificationOutput.listTargets.query({})}),w=i({queryKey:Hp,queryFn:()=>o.trpcClient.notificationRules.getConditionCatalog.query({})}),T=u({mutationFn:e=>o.trpcClient.addons.custom.mutate({addonId:$,action:id,input:{ruleId:e.ruleId,patch:{enabled:e.enabled}}}),onSuccess:()=>void b.refetch()}),E=u({mutationFn:e=>o.trpcClient.addons.custom.mutate({addonId:$,action:ad,input:{ruleId:e}}),onSuccess:()=>void b.refetch()}),D=u({mutationFn:async e=>zd(await o.trpcClient.addons.custom.mutate({addonId:$,action:od,input:{ruleId:e,...af(Date.now())}})),onSuccess:e=>{m(null),_(e)}}),O=b.data??[],k=(C.data??[]).map(e=>({id:e.id,name:e.name,enabled:e.enabled})),A=new Map(k.map(e=>[e.id,e.name])),j=b.isError||b.data===null,ee=e=>{xd(e)&&c({mode:`form`,rule:e})},M=n(a,{children:[b.isLoading&&d(mf,{}),j&&!b.isLoading&&d(J,{title:`Summary rules are not available on this hub`,message:v?`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.`,onRetry:()=>void b.refetch()}),!b.isLoading&&!j&&n(a,{children:[E.isError&&d(J,{title:`Could not delete the rule`,message:String(E.error)}),D.isError&&d(J,{title:`The test run failed`,message:String(D.error)}),g!==null&&n(`div`,{className:`mb-3 rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,"data-testid":`summary-test-outcome`,children:[g.error===void 0?n(`span`,{children:[`Produced `,g.produced,` digest`,g.produced===1?``:`s`,` — `,g.tiles??0,` tile`,(g.tiles??0)===1?``:`s`,` from `,g.cameras??0,` camera`,(g.cameras??0)===1?``:`s`,`, `,g.matched??0,` track`,(g.matched??0)===1?``:`s`,` matched, `,g.enqueued??0,` `,`notification`,(g.enqueued??0)===1?``:`s`,` sent.`,(g.droppedStationary??0)>0&&n(`span`,{"data-testid":`summary-test-dropped-stationary`,children:[` `,g.droppedStationary,` parked object`,g.droppedStationary===1?``:`s`,` left out.`]})]}):n(`span`,{className:`text-warning`,children:[`Nothing was produced: `,g.error]}),d(I,{size:`sm`,variant:`ghost`,type:`button`,className:`ml-2`,onClick:()=>_(null),children:`Dismiss`})]}),O.length===0?d(hf,{testId:`summary-empty`,children:`No summary rules yet — create one, and every window it covers arrives as a single picture.`}):d(gf,{columns:Sf({nowMs:Date.now(),targetNameById:A,deletePending:E.isPending,onToggle:(e,t)=>T.mutate({ruleId:e.id,enabled:t}),onOpen:ee,onTest:m,onConfirmDelete:e=>E.mutate(e.id)}),rows:O,rowKey:e=>e.id,minWidthPx:860,onRowClick:ee})]}),s.mode===`form`&&d(ff,{rule:s.rule,cameras:S,fleet:ve(x),targets:k,taxonomy:w.data?.taxonomy,onCancel:()=>c({mode:`closed`}),onSaved:()=>{c({mode:`closed`}),b.refetch()}}),d(li,{open:p!==null,ruleName:p?.name??``,windowDescription:`the last 3 hours`,targetDescription:`${p?.targets.length??0} target${(p?.targets.length??0)===1?``:`s`}`,pending:D.isPending,onCancel:()=>m(null),onConfirm:()=>{p!==null&&D.mutate(p.id)}})]});return e?M:d(nn,{icon:cn,title:`Summaries`,subtitle:bf,actions:j?void 0:n(I,{size:`sm`,type:`button`,onClick:()=>c({mode:`form`,rule:null}),"data-testid":`summary-new`,children:[d(W,{className:`h-3.5 w-3.5`}),`New summary`]}),children:M})}function Sf(e){return[{key:`name`,header:`Digest`,render:t=>d(_f,{name:t.name,enabled:t.enabled,...xd(t)?{onOpen:()=>e.onOpen(t)}:{},openTestId:`summary-edit-${t.id}`,badges:n(a,{children:[!xd(t)&&d(U,{variant:`warning`,children:`read-only`}),t.ai?.enabled===!0&&d(U,{variant:`info`,children:`AI`}),t.ai!==void 0&&!t.ai.enabled&&d(U,{variant:`default`,children:`AI off`})]})})},{key:`cameras`,header:`Cameras`,align:`center`,nowrap:!0,render:e=>d(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.deviceIds.length})},{key:`window`,header:`Window`,render:e=>d(`span`,{className:`text-[11px] text-foreground-subtle`,children:tf(e.window)})},{key:`filters`,header:`Keeps`,render:e=>d(`span`,{className:`text-[11px] text-foreground-subtle`,children:rf(e.filters)})},{key:`mosaic`,header:`Mosaic`,nowrap:!0,render:e=>n(`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 d(`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=>d(`span`,{className:`text-[11px] text-foreground-subtle`,"data-testid":`summary-last-${t.id}`,children:nf(t.generatedAt,e.nowMs)})},{key:`enabled`,header:`On`,align:`center`,nowrap:!0,render:t=>d(pf,{children:d(F,{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=>n(pf,{className:`flex items-center justify-end gap-1`,children:[d(I,{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:d(ce,{className:`h-3.5 w-3.5`})}),d(vf,{disabled:t.readOnly,pending:e.deletePending,title:`Delete this summary?`,message:`This will permanently delete "${t.name}". This action cannot be undone.`,ariaLabel:`delete ${t.name}`,testId:`summary-delete-${t.id}`,onConfirm:()=>e.onConfirmDelete(t)})]})}]}var Cf=`nc.listTimelapseRules`,wf=`nc.upsertTimelapseRule`,Tf=`nc.deleteTimelapseRule`,Ef=`nc.testTimelapseRule`,Df=3600,Of=3600,kf=30,Af=1,jf=[`image`,`gif`],Mf={image:`Still frame`,gif:`Short animation (GIF)`},Nf=Yt({rules:Xt(zt.extend({readOnly:Zt().optional()}))});function Pf(e){let t=Nf.safeParse(e);return t.success?t.data.rules:null}function Ff(e){return e.readOnly!==!0}var If=Yt({produced:qt(),exportId:Jt().optional(),coveragePercent:qt().optional(),enqueued:qt().optional(),windowStartMs:qt().optional(),windowEndMs:qt().optional(),error:Jt().optional()});function Lf(e){let t=If.safeParse(e);return t.success?t.data:null}function Rf(){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 zf(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 Bf={windows:[{days:[1],startMinute:0,endMinute:60}]};function Vf(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 Hf(e){let t=Vf(e);return{name:e.name.trim(),enabled:e.enabled,deviceIds:[...e.deviceIds],schedule:e.schedule??Bf,cadenceSec:e.cadenceSec,framerate:e.framerate,...e.denseCadenceSec===void 0?{}:{denseCadenceSec:e.denseCadenceSec},...e.minDwellSec===void 0?{}:{minDwellSec:e.minDwellSec},targets:Bu(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 Uf(e,t){let n=Hf(e),r={};return n.name!==t.name&&(r.name=n.name),n.enabled!==t.enabled&&(r.enabled=n.enabled),zu(n.deviceIds,t.deviceIds)||(r.deviceIds=n.deviceIds),zu(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??Wf(n.cadenceSec)),n.minDwellSec!==t.minDwellSec&&n.minDwellSec!==void 0&&(r.minDwellSec=n.minDwellSec),zu(n.targets,t.targets)||(r.targets=n.targets),zu(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),zu(n.reportClasses,t.reportClasses)||(r.reportClasses=n.reportClasses??[]),n.priority!==t.priority&&(r.priority=n.priority),r}function Wf(e){return Math.max(Af,e/kf)}function Gf(e,t,n){return t<=0||n<=0?0:e/t/n}function Kf(e,t){return e*t*Dt}function qf(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 ${Df}.`),(!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 ${Dt}s and ${Of}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 Jf(e){return qf(e).length===0}function Yf(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=Kf(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 Xf(e){return Fu(e)}function Zf(e,t){return Iu(e,t,`Never run`)}function Qf(e){return e.denseCadenceSec===void 0?{seconds:Wf(e.cadenceSec),derived:!0}:{seconds:e.denseCadenceSec,derived:!1}}var $f=[{key:`rule`,label:`Rule`,fields:[`name`,`enabled`,`deviceIds`]},{key:`window`,label:`Window`,fields:[`schedule`]},{key:`sampling`,label:`Sampling`,fields:[`cadenceSec`,`framerate`,`denseCadenceSec`,`minDwellSec`]},{key:`delivery`,label:`Delivery`,fields:[`targetIds`,`priority`,`previewMode`,`previewText`,`previewTextSet`,`templateTitle`,`templateBody`,`reportClasses`]}],ep=`rule`;function tp(e){return $f.find(t=>t.key===e)?.key}t();var np=7;function rp(e){return jf.find(t=>t===e)}function ip({rule:e,cameras:t,fleet:r,targets:i,onSaved:o,onCancel:s}){let c=h(),[f,p]=l(()=>e===null?Rf():zf(e)),[m,g]=l(null),[_,v]=l(ep),y=e=>p(t=>({...t,...e})),b=qr(),x=b.data?Ur(b.data,{family:`timelapse`,field:`previewText`}):void 0,S=u({mutationFn:async()=>{let t=e===null?{rule:Hf(f)}:{ruleId:e.id,patch:Uf(f,e)};await c.trpcClient.addons.custom.mutate({addonId:$,action:wf,input:t})},onSuccess:o,onError:e=>g(e instanceof Error?e.message:`Save failed`)}),T=qf(f),O=Yf(f),k=Qf(f),A=Gf(np,k.seconds,f.framerate),j=Jf(f)&&!S.isPending,N=$f.some(e=>e.key===_)?_:ep;return d(w,{open:!0,onOpenChange:e=>!e&&s(),children:n(De,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,children:[n(`div`,{className:`mb-3 flex shrink-0 items-center justify-between`,children:[n(`h3`,{className:`flex min-w-0 items-center gap-2 text-sm font-semibold text-foreground`,children:[d(oe,{className:`h-4 w-4 shrink-0 text-foreground-subtle`}),d(`span`,{className:`truncate`,children:e===null?`New timelapse`:`Edit ${e.name}`})]}),d(I,{size:`sm`,variant:`ghost`,type:`button`,onClick:s,children:`Cancel`})]}),m!==null&&d(`div`,{className:`mb-3 shrink-0 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger`,children:m}),n(`div`,{className:`shrink-0 space-y-2`,children:[e!==null&&d(pu,{kind:`timelapse`,ruleId:e.id,enabled:e.enabled,updatedAt:e.updatedAt}),d(ni,{problems:T,testId:`timelapse-problems`}),d(ri,{warnings:O,testId:`timelapse-warnings`})]}),n(ee,{value:N,onValueChange:e=>v(tp(e)??_),className:`mt-3 flex min-h-0 flex-1 flex-col`,children:[d(C,{className:`mb-3 shrink-0`,children:$f.map(e=>d(E,{value:e.key,children:e.label},e.key))}),n(D,{className:`pr-1`,children:[n(M,{value:`rule`,className:`space-y-3`,children:[d(ti,{title:`What it is`,hint:`One video per camera, assembled from that camera's RECORDED footage when the window closes.`,children:n(`div`,{className:`flex items-end gap-3`,children:[n(`div`,{className:`min-w-0 flex-1`,children:[d(`label`,{className:Y,children:`Name`}),d(B,{value:f.name,onChange:e=>y({name:e.target.value}),placeholder:`e.g. Night driveway`,"data-testid":`timelapse-name`})]}),d(`div`,{className:`pb-1.5`,children:d(si,{label:`Enabled`,checked:f.enabled,onChange:e=>y({enabled:e}),testId:`timelapse-enabled`})})]})}),d(ti,{title:`Cameras`,children:d(ii,{cameras:t,value:f.deviceIds,fleet:r,onChange:e=>y({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.`})})]}),d(M,{value:`window`,className:`space-y-3`,children:d(ti,{title:`When`,children:n(`div`,{children:[d(`label`,{className:Y,children:`Weekly windows`}),d(Mc,{value:f.schedule,onChange:e=>y({schedule:e})}),d(`p`,{className:ei,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.`})]})})}),d(M,{value:`sampling`,className:`space-y-3`,children:n(ti,{title:`Sampling`,hint:`Two rates: a base rate for the whole window, and a denser one inside the ranges where something was detected.`,children:[n(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[d(oi,{label:`Base cadence (seconds)`,value:f.cadenceSec,min:2,max:Df,onChange:e=>y({cadenceSec:e??0}),hint:`One frame every N seconds across the quiet parts of the window.`,testId:`timelapse-cadence`}),d(oi,{label:`Output frame rate (fps)`,value:f.framerate,min:1,max:60,onChange:e=>y({framerate:e??0}),hint:`How fast the assembled video plays.`,testId:`timelapse-framerate`})]}),n(`div`,{children:[d(`label`,{className:Y,children:`Dense cadence, near the detections`}),n(`div`,{className:`flex items-center gap-2`,children:[d(q,{value:f.denseCadenceSec===void 0?`auto`:`explicit`,options:[{value:`auto`,label:`Automatic (${k.seconds}s)`},{value:`explicit`,label:`Set it myself`}],onChange:e=>y({denseCadenceSec:e.target.value===`auto`?void 0:Qf(f).seconds}),"data-testid":`timelapse-dense-mode`}),f.denseCadenceSec!==void 0&&d(B,{type:`number`,className:`w-28`,min:.1,step:.1,value:String(f.denseCadenceSec),onChange:e=>{let t=Number(e.target.value);Number.isFinite(t)&&y({denseCadenceSec:t})},"data-testid":`timelapse-dense-seconds`})]}),n(`p`,{className:ei,"data-testid":`timelapse-dense-hint`,children:[`Lower = slower near the detections. At `,k.seconds,`s and `,f.framerate,` fps a `,np,`-second passage lasts `,A.toFixed(2),`s on screen; halving the cadence doubles that, and the quiet parts of the night do not change length.`,k.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 (${Qf({...f,denseCadenceSec:void 0}).seconds}s) explicitly.`]})]}),d(oi,{label:`Minimum seconds of video per detection (optional)`,value:f.minDwellSec,min:0,max:60,step:.5,emptyPlaceholder:`no guarantee`,onChange:e=>y({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`})]})}),d(M,{value:`delivery`,className:`space-y-3`,children:n(ti,{title:`The notification`,children:[d(ai,{targets:i,value:f.targetIds,onChange:e=>y({targetIds:e})}),n(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[n(`div`,{children:[d(`label`,{className:Y,children:`Preview`}),d(q,{value:f.previewMode,options:jf.map(e=>({value:e,label:Mf[e]})),onChange:e=>{let t=rp(e.target.value);t!==void 0&&y({previewMode:t})},"data-testid":`timelapse-preview-mode`})]}),d(oi,{label:`Priority`,value:f.priority,min:1,max:5,onChange:e=>y({priority:e??3}),testId:`timelapse-priority`})]}),n(`div`,{children:[d(Qr,{label:`Caption on the preview frame`,value:f.previewTextSet?f.previewText:``,placeholder:`${pt} (shipped default)`,onChange:e=>y({previewText:e,previewTextSet:!0}),vars:x,testId:`timelapse-preview-text`}),n(`p`,{className:ei,children:[f.previewTextSet&&f.previewText.length===0?`Empty and set: the preview frame carries NO caption.`:`Leave untouched for the shipped caption (${pt}).`,f.previewTextSet&&n(a,{children:[` `,d(`button`,{type:`button`,className:`underline`,onClick:()=>y({previewText:``,previewTextSet:!1}),"data-testid":`timelapse-preview-text-reset`,children:`Back to the shipped caption`})]})]})]}),d(ci,{title:f.templateTitle,body:f.templateBody,onTitleChange:e=>y({templateTitle:e}),onBodyChange:e=>y({templateBody:e}),family:`timelapse`,testIdPrefix:`timelapse-template`}),n(`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`,` `,d(`code`,{children:`{{detectionSummary}}`}),`.`]})]})})]})]}),n(`div`,{className:`mt-3 flex shrink-0 justify-end gap-2`,children:[d(I,{size:`sm`,variant:`secondary`,type:`button`,onClick:s,children:`Cancel`}),n(I,{size:`sm`,type:`button`,disabled:!j,onClick:()=>S.mutate(),children:[S.isPending&&d(G,{className:`h-3.5 w-3.5 animate-spin`}),e===null?`Create`:`Save`]})]})]})})}t();var ap=[`notificationTimelapses`,`listTimelapseRules`],op=`A night of recorded footage, assembled into one short video per camera.`;function sp({embedded:e=!1,openCreateKey:t}={}){let o=h(),[s,c]=l({mode:`closed`}),[p,m]=l(null),[g,_]=l(null),[v,y]=l(!1);f(()=>{t!==void 0&&t>0&&c({mode:`form`,rule:null})},[t]);let b=i({queryKey:ap,queryFn:async()=>Pf(await o.trpcClient.addons.custom.mutate({addonId:$,action:Cf,input:{}}))});f(()=>{b.isSuccess&&y(b.data===null)},[b.isSuccess,b.data]);let x=se({projection:`slim`}),S=r(()=>(x.data??[]).filter(e=>e.type===Ft.Camera).map(e=>({id:e.id,name:e.name})).toSorted((e,t)=>e.name.localeCompare(t.name)),[x.data]),C=i({queryKey:Vp,queryFn:()=>o.trpcClient.notificationOutput.listTargets.query({})}),w=u({mutationFn:e=>o.trpcClient.addons.custom.mutate({addonId:$,action:wf,input:{ruleId:e.ruleId,patch:{enabled:e.enabled}}}),onSuccess:()=>void b.refetch()}),T=u({mutationFn:e=>o.trpcClient.addons.custom.mutate({addonId:$,action:Tf,input:{ruleId:e}}),onSuccess:()=>void b.refetch()}),E=u({mutationFn:async e=>Lf(await o.trpcClient.addons.custom.mutate({addonId:$,action:Ef,input:e})),onSuccess:e=>{m(null),_(e)}}),D=b.data??[],O=new Map(S.map(e=>[e.id,e.name])),k=(C.data??[]).map(e=>({id:e.id,name:e.name,enabled:e.enabled})),A=new Map(k.map(e=>[e.id,e.name])),j=b.isError||b.data===null,ee=e=>{Ff(e)&&c({mode:`form`,rule:e})},M=n(a,{children:[b.isLoading&&d(mf,{}),j&&!b.isLoading&&d(J,{title:`Timelapse rules are not available on this hub`,message:v?`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.`,onRetry:()=>void b.refetch()}),!b.isLoading&&!j&&n(a,{children:[T.isError&&d(J,{title:`Could not delete the rule`,message:String(T.error)}),E.isError&&d(J,{title:`The test run failed`,message:String(E.error)}),g!==null&&n(`div`,{className:`mb-3 rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,"data-testid":`timelapse-test-outcome`,children:[g.error===void 0?n(`span`,{children:[`Produced `,g.produced,` video`,g.produced===1?``:`s`,g.coveragePercent===void 0?``:` — ${Math.round(g.coveragePercent)}% of the window had footage`,`, `,g.enqueued??0,` notification`,(g.enqueued??0)===1?``:`s`,` sent.`]}):n(`span`,{className:`text-warning`,children:[`Nothing was produced: `,g.error]}),d(I,{size:`sm`,variant:`ghost`,type:`button`,className:`ml-2`,onClick:()=>_(null),children:`Dismiss`})]}),D.length===0?d(hf,{testId:`timelapse-empty`,children:`No timelapse rules yet — create one, and each night's recorded footage arrives as a short video.`}):d(gf,{columns:cp({nowMs:Date.now(),cameraNameById:O,targetNameById:A,deletePending:T.isPending,onToggle:(e,t)=>w.mutate({ruleId:e.id,enabled:t}),onOpen:ee,onTest:e=>m({rule:e,deviceId:e.deviceIds[0]??null}),onConfirmDelete:e=>T.mutate(e.id)}),rows:D,rowKey:e=>e.id,minWidthPx:900,onRowClick:ee})]}),s.mode===`form`&&d(ip,{rule:s.rule,cameras:S,fleet:ve(x),targets:k,onCancel:()=>c({mode:`closed`}),onSaved:()=>{c({mode:`closed`}),b.refetch()}}),d(li,{open:p!==null,ruleName:p?.rule.name??``,windowDescription:`its last closed window`,targetDescription:`${p?.rule.targets.length??0} target${(p?.rule.targets.length??0)===1?``:`s`}`,pending:E.isPending,confirmDisabled:p?.deviceId===null,extra:p===null?null:n(`div`,{children:[d(`label`,{className:`mb-1 block text-[11px] font-medium text-foreground`,children:`Which camera`}),d(q,{value:p.deviceId===null?``:String(p.deviceId),options:p.rule.deviceIds.map(e=>({value:String(e),label:O.get(e)??`#${e}`})),onChange:e=>{let t=Number(e.target.value);Number.isFinite(t)&&m({rule:p.rule,deviceId:t})},"data-testid":`timelapse-test-camera`})]}),onCancel:()=>m(null),onConfirm:()=>{p!==null&&p.deviceId!==null&&E.mutate({ruleId:p.rule.id,deviceId:p.deviceId})}})]});return e?M:d(nn,{icon:oe,title:`Timelapses`,subtitle:op,actions:j?void 0:n(I,{size:`sm`,type:`button`,onClick:()=>c({mode:`form`,rule:null}),"data-testid":`timelapse-new`,children:[d(W,{className:`h-3.5 w-3.5`}),`New timelapse`]}),children:M})}function cp(e){return[{key:`name`,header:`Timelapse`,render:t=>d(_f,{name:t.name,enabled:t.enabled,...Ff(t)?{onOpen:()=>e.onOpen(t),openTestId:`timelapse-edit-${t.id}`}:{},badges:Ff(t)?null:d(U,{variant:`warning`,children:`read-only`})})},{key:`cameras`,header:`Cameras`,render:t=>d(`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=>d(`span`,{className:`text-[11px] text-foreground-subtle`,children:Xf(e.schedule)})},{key:`sampling`,header:`Sampling`,nowrap:!0,render:e=>{let t=Qf(zf(e));return n(`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 d(`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=>d(`span`,{className:`text-[11px] text-foreground-subtle`,"data-testid":`timelapse-last-${t.id}`,children:Zf(t.lastGeneratedAt,e.nowMs)})},{key:`enabled`,header:`On`,align:`center`,nowrap:!0,render:t=>d(pf,{children:d(F,{checked:t.enabled,disabled:!Ff(t),onCheckedChange:n=>e.onToggle(t,n),"aria-label":`toggle ${t.name}`})})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:t=>n(pf,{className:`flex items-center justify-end gap-1`,children:[d(I,{size:`sm`,variant:`ghost`,type:`button`,disabled:!Ff(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:d(ce,{className:`h-3.5 w-3.5`})}),d(vf,{disabled:!Ff(t),pending:e.deletePending,title:`Delete this timelapse?`,message:`This will permanently delete "${t.name}". This action cannot be undone.`,ariaLabel:`delete ${t.name}`,testId:`timelapse-delete-${t.id}`,onConfirm:()=>e.onConfirmDelete(t)})]})}]}t();var lp=[`notificationCalendarEvents`,`list`],up=`nc.listCalendarEventsRules`,dp=`nc.upsertCalendarEventsRule`,fp=`nc.deleteCalendarEventsRule`;function pp({openCreateKey:e=0}={}){let t=h(),r=s(),a=ue(),[o,c]=l(!1),[p,m]=l(`Morning calendar`),[g,_]=l(7),[v,y]=l(Ro(void 0,void 0)),[b,x]=l(``),S=i({queryKey:lp,queryFn:async()=>(await t.trpcClient.addons.custom.mutate({addonId:$,action:up,input:{}})).rules}),C=i({queryKey:[`notificationOutput`,`listTargets`,`calendar-events`],queryFn:()=>t.trpcClient.notificationOutput.listTargets.query({})});f(()=>{e>0&&c(!0)},[e]);let w=u({mutationFn:async()=>{if(b.length===0)throw Error(`Pick a notification target`);let e=Wo(v);await t.trpcClient.addons.custom.mutate({addonId:$,action:dp,input:{rule:{name:p,enabled:!0,horizonDays:g,...e.include===void 0?{}:{calendars:e.include},...e.exclude===void 0?{}:{calendarsExclude:e.exclude},schedule:{timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,windows:[{days:[0,1,2,3,4,5,6],startMinute:420,endMinute:425}]},targets:[{targetId:b}],deliverEmpty:!1,priority:3}}})},onSuccess:async()=>{c(!1),await r.invalidateQueries({queryKey:lp})}}),T=u({mutationFn:async e=>{await t.trpcClient.addons.custom.mutate({addonId:$,action:fp,input:{ruleId:e}})},onSuccess:async()=>{await r.invalidateQueries({queryKey:lp})}}),E=(a.data??[]).map(e=>({id:e.id,name:e.name})),D=C.data??[];return n(`div`,{className:`space-y-4`,"data-testid":`calendar-events-rules`,children:[o?n(`div`,{className:`space-y-3 rounded-md border p-4`,children:[d(`h3`,{className:`font-medium`,children:`New calendar events rule`}),n(`label`,{className:`block text-sm`,children:[`Name`,d(`input`,{className:`mt-1 w-full rounded border px-2 py-1`,value:p,onChange:e=>m(e.target.value)})]}),n(`label`,{className:`block text-sm`,children:[`Horizon (days)`,d(`input`,{type:`number`,min:1,max:30,className:`mt-1 w-full rounded border px-2 py-1`,value:g,onChange:e=>_(Number(e.target.value))})]}),d(_c,{draft:v,onChange:y,exceptOffered:!0,plural:`calendars`,describe:e=>E.find(t=>t.id===e)?.name??e,testId:`calendar-events-scope`,renderPicker:(e,t,n)=>d(V,{devices:E,listState:a.isPending?`pending`:`answered`,value:e,onChange:t,emptyMeansAll:!0,noun:`calendar`,testId:`calendar-picker`},n)}),n(`label`,{className:`block text-sm`,children:[`Target`,n(`select`,{className:`mt-1 w-full rounded border px-2 py-1`,value:b,onChange:e=>x(e.target.value),children:[d(`option`,{value:``,children:`Select…`}),D.map(e=>d(`option`,{value:e.id,children:typeof e.name==`string`?e.name:e.id},e.id))]})]}),d(`p`,{className:`text-xs text-muted-foreground`,children:`Default schedule: every day 07:00–07:05 in your local timezone.`}),n(`div`,{className:`flex gap-2`,children:[d(`button`,{type:`button`,className:`btn btn-primary`,disabled:w.isPending,onClick:()=>void w.mutateAsync(),children:`Save`}),d(`button`,{type:`button`,className:`btn btn-secondary`,onClick:()=>c(!1),children:`Cancel`})]}),w.isError?d(`p`,{className:`text-sm text-destructive`,children:w.error instanceof Error?w.error.message:String(w.error)}):null]}):d(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>c(!0),children:`New calendar events`}),S.isPending?d(`p`,{className:`text-sm text-muted-foreground`,children:`Loading…`}):S.isError?d(`p`,{className:`text-sm text-destructive`,children:S.error instanceof Error?S.error.message:String(S.error)}):(S.data??[]).length===0?d(`p`,{className:`text-sm text-muted-foreground`,children:`No calendar-events rules yet. Create one to send upcoming events at schedule time.`}):d(`ul`,{className:`divide-y rounded-md border`,children:(S.data??[]).map(e=>n(`li`,{className:`flex items-center justify-between gap-3 px-4 py-3`,children:[n(`div`,{children:[d(`div`,{className:`font-medium`,children:e.name}),n(`div`,{className:`text-xs text-muted-foreground`,children:[`next `,e.horizonDays,` day(s) · `,e.enabled?`enabled`:`disabled`]})]}),e.readOnly?null:d(`button`,{type:`button`,className:`btn btn-secondary text-xs`,onClick:()=>void T.mutateAsync(e.id),children:`Delete`})]},e.id))})]})}var mp=[{key:`summaries`,label:`Summaries`,blurb:`One window, one picture: every camera's best moments as a single mosaic, delivered once when the window closes.`,newLabel:`New summary`,emptyHint:`No summary rules yet. Use "New summary" (or pick Summary under New rule) to author one.`},{key:`timelapses`,label:`Timelapses`,blurb:`A night of recorded footage, assembled into one short video per camera when the window closes.`,newLabel:`New timelapse`,emptyHint:`No timelapse rules yet. Use "New timelapse" (or pick Timelapse under New rule) to author one.`},{key:`calendar-events`,label:`Calendar events`,blurb:`At schedule time, send the upcoming events from selected calendars for the next N days.`,newLabel:`New calendar events`,emptyHint:`No calendar-events rules yet. Use "New calendar events" (or pick Calendar events under New rule) to author one.`}],hp=[{type:`rule`,label:`Rule`,hint:`Fire on a detection, sensor, sound, occupancy, device or system event.`},{type:`summary`,label:`Summary`,hint:`One mosaic of the best moments across cameras for a window.`},{type:`timelapse`,label:`Timelapse`,hint:`One short video per camera from recorded footage.`},{type:`calendar-events`,label:`Calendar events`,hint:`Upcoming calendar events for the next N days, at schedule time.`}];function gp(e){return e===`summaries`||e===`timelapses`||e===`calendar-events`}function _p(e){if(!(e==null||e.length===0))return gp(e)?e:ze(e)}function vp(e){let t=mp.find(t=>t.key===e);if(t===void 0)throw Error(`unknown producer area: ${e}`);return t}function yp(e){return[...Fa.filter(t=>t.key!==`mixed`||(e.get(`mixed`)??0)>0),...mp]}function bp(e){return!gp(e)}var xp={days:[0,1,2,3,4,5,6],minute:480},Sp=[{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 Cp(e){let t=Math.floor(e/60),n=e%60;return`${String(t).padStart(2,`0`)}:${String(n).padStart(2,`0`)}`}function wp(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 Tp(e){if(typeof e!=`object`||!e||!(`data`in e))return;let t=e.data;if(!(typeof t!=`object`||!t||!(`code`in t)))return typeof t.code==`string`?t.code:void 0}function Ep(e){let t=Object.entries(e).map(([e,t])=>`${e} ${String(t)}`);return t.length>0?`Left out by this rule's filters or a camera mute: ${t.join(`, `)}.`:null}function Dp(e,t,n,r=`rule`){if(e===`error`)return Tp(n)===`NOT_FOUND`?{lines:[`This hub does not serve summary rules yet — update @camstack/server first. A rule saved now would be stored without its summary, and stay instant.`]}:{lines:[`The preview could not be read: ${n instanceof Error?n.message:String(n)}`]};if(e!==`success`||t===void 0)return null;let i=[];if(r===`section`&&t.split===void 0&&i.push(`This hub does not send per-category summaries yet — update @camstack/server first. Until then it sends one message.`),t.empty)i.push(`Nothing to report right now — no notification would be sent.`);else if(t.split===`section`&&t.rows!==void 0){let e=t.rows.length;i.push(`${String(e)} notification${e===1?``:`s`} would be sent now, one per category:`);for(let e of t.rows)i.push(`${e.title}\n${e.text}`)}else i.push(`${String(t.count)} item(s) would be sent now:\n${t.text}`);let a=Ep(t.dropped);return a!==null&&i.push(a),t.excludedGroups.includes(`backups-exports`)&&i.push(`Backups and exports are completed jobs, not a state — they are not in a summary.`),{lines:i}}function Op(e,t){return{...e,schedule:t}}function kp(e,t){let{split:n,...r}=e;return t===`section`?{...r,split:t}:r}function Ap({value:e,family:t,onChange:r,draft:i}){if(t===void 0||!kt.includes(t))return null;let a=e?.mode===`summary`?e:null;return n(`div`,{className:`rounded-md border border-border px-3 py-3`,"data-testid":`rule-delivery`,children:[d(`div`,{className:`mb-2 text-[11px] font-semibold text-foreground`,children:`Delivery`}),n(`div`,{className:`flex flex-wrap gap-3 text-xs`,children:[n(`label`,{className:`flex items-center gap-1.5`,children:[d(`input`,{type:`radio`,name:`system-event-delivery`,checked:a===null,onChange:()=>r({mode:`instant`}),"data-testid":`rule-delivery-instant`}),`Instant — a notification per event`]}),n(`label`,{className:`flex items-center gap-1.5`,children:[d(`input`,{type:`radio`,name:`system-event-delivery`,checked:a!==null,onChange:()=>r({mode:`summary`,schedule:St([xp])}),"data-testid":`rule-delivery-summary`}),`Summary on schedule — the current state, at set times`]})]}),a!==null&&d(jp,{value:a,onChange:r,draft:i})]})}function jp({value:e,onChange:t,draft:r}){let i=ut(e.schedule),o=e.schedule.timezone,s=n=>{n.length!==0&&t(Op(e,St(n,o)))},c=Gt({systemEventDelivery:e});return n(`div`,{className:`mt-2 space-y-2`,children:[n(`p`,{className:Z,children:[`Nothing is sent per event. At each time below, one notification lists what is still true for the kinds and filters of this rule — low batteries, consumables, devices or streams offline, updates available — or one notification per category, if you choose so below. Nothing to report sends nothing. Time zone: `,o??`the hub’s`,`.`]}),i===null?n(a,{children:[d(`p`,{className:Z,"data-testid":`rule-delivery-custom`,children:`Custom schedule: the summary is sent when each window below ENDS.`}),d(Mc,{value:e.schedule,onChange:n=>{n!==void 0&&t(Op(e,n))}})]}):n(a,{children:[i.map((e,t)=>d(Mp,{time:e,onChange:e=>s(i.map((n,r)=>r===t?e:n)),onRemove:i.length>1?()=>s(i.filter((e,n)=>n!==t)):void 0,index:t},t)),n(`button`,{type:`button`,onClick:()=>s([...i,xp]),className:`flex items-center gap-1 rounded-md bg-surface-hover px-2 py-1 text-[11px] text-foreground-subtle hover:text-foreground`,"data-testid":`rule-delivery-add-time`,children:[d(W,{className:`h-3 w-3`}),` Add a send time`]})]}),n(`fieldset`,{className:`flex flex-wrap gap-3 text-xs`,"data-testid":`rule-delivery-split`,children:[d(`legend`,{className:`sr-only`,children:`How the summary is sent`}),n(`label`,{className:`flex items-center gap-1.5`,children:[d(`input`,{type:`radio`,name:`system-event-summary-split`,checked:c===`rule`,onChange:()=>t(kp(e,`rule`)),"data-testid":`rule-delivery-split-rule`}),`One message with every category`]}),n(`label`,{className:`flex items-center gap-1.5`,children:[d(`input`,{type:`radio`,name:`system-event-summary-split`,checked:c===`section`,onChange:()=>t(kp(e,`section`)),"data-testid":`rule-delivery-split-section`}),`One notification per category (batteries, consumables, devices…)`]})]}),d(Np,{draft:r,split:c})]})}function Mp({time:e,index:t,onChange:r,onRemove:i}){let a=t=>{let n=e.days.includes(t)?e.days.filter(e=>e!==t):[...e.days,t];n.length!==0&&r({...e,days:n})};return n(`div`,{className:`space-y-1.5 rounded-md border border-border p-2`,children:[n(`div`,{className:`flex items-center gap-2 text-xs`,children:[d(`span`,{className:`text-foreground-subtle`,children:`Send at`}),d(`input`,{type:`time`,value:Cp(e.minute),onChange:t=>r({...e,minute:wp(t.target.value)}),className:`rounded-md border border-border bg-background px-1 py-0.5`,"data-testid":`rule-delivery-time-${String(t)}`}),d(`span`,{className:`flex-1`}),i!==void 0&&d(`button`,{type:`button`,onClick:i,"aria-label":`Remove send time`,className:`text-foreground-subtle hover:text-danger`,children:d(_,{className:`h-3.5 w-3.5`})})]}),d(`div`,{className:`flex flex-wrap gap-1`,children:Sp.map(t=>d(`button`,{type:`button`,onClick:()=>a(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))})]})}function Np({draft:e,split:t}){let r=h(),i=u({mutationFn:e=>r.trpcClient.notificationRules.previewStateSummary.mutate({rule:e})}),a=Dp(i.status,i.data,i.error,t);return n(`div`,{className:`space-y-1.5`,children:[d(I,{size:`sm`,variant:`secondary`,onClick:()=>i.mutate(e()),disabled:i.isPending,"data-testid":`rule-delivery-preview`,children:i.isPending?`Reading the state…`:`Preview the summary now`}),a!==null&&d(`div`,{className:`text-[10px] text-foreground-subtle mt-0.5`,"data-testid":`rule-delivery-preview-result`,children:a.lines.map((e,t)=>d(`p`,{className:`whitespace-pre-wrap`,children:e},t))})]})}function Pp(e,t){if(e.status===`error`)return{kind:`failed`,reason:e.error instanceof Error?e.error.message:`unknown error`};if(e.status!==`success`||e.data===void 0)return{kind:`pending`};let n=e.data.runs.find(e=>e.ruleId===t);return n===void 0?{kind:`absent`,phrase:zp(e.data.horizonMs)}:{kind:`ran`,lastAt:n.lastAt,status:n.status,deviceId:n.deviceId}}var Fp=6e4,Ip=60*Fp,Lp=24*Ip;function Rp(e,t){return e===1?`the last ${t}`:`the last ${String(e)} ${t}s`}function zp(e){return e===null?`No delivery on record`:e>=Lp?`Not in ${Rp(Math.floor(e/Lp),`day`)}`:e>=Ip?`Not in ${Rp(Math.floor(e/Ip),`hour`)}`:e>=Fp?`Not in ${Rp(Math.floor(e/Fp),`minute`)}`:`Not in the window read`}t();var Bp=[`notificationRules`,`listRules`],Vp=[`notificationOutput`,`listTargets`,`forRules`],Hp=[`notificationRules`,`getConditionCatalog`],Up=[`deviceManager`,`gateableDevices`],Wp=Nt.options;function Gp({onSimulateRule:t,onOpenHistory:o}={}){let s=h(),{t:c}=en(),[p,g]=tn(),[_,v]=l({mode:`closed`}),[y,S]=l(0),[w,D]=l(0),[O,k]=l(0),[A,j]=l(()=>_p(p.get(`section`))??`all`),M=e=>{j(e);let t=new URLSearchParams(p);e===`all`?t.delete(`section`):t.set(`section`,e),g(t,{replace:!0})},N=i({queryKey:Bp,queryFn:async()=>(await s.trpcClient.notificationRules.listRules.query({})).rules}),P=e(null);f(()=>{if(_.mode!==`closed`)return;let e=p.get(`rule`);if(e===null||e===`new`||P.current===e)return;let t=N.data?.find(t=>t.id===e);t===void 0||!Ia(t)||(P.current=e,v({mode:`form`,rule:t}))},[_.mode,p,N.data]);let F=i({queryKey:yf,queryFn:async()=>Rd(await s.trpcClient.addons.custom.mutate({addonId:$,action:rd,input:{}}))}),te=i({queryKey:ap,queryFn:async()=>Pf(await s.trpcClient.addons.custom.mutate({addonId:$,action:Cf,input:{}}))}),ne=i({queryKey:lp,queryFn:async()=>(await s.trpcClient.addons.custom.mutate({addonId:`pipeline-analytics`,action:`nc.listCalendarEventsRules`,input:{}})).rules??[]}),re=i({queryKey:Vp,queryFn:()=>s.trpcClient.notificationOutput.listTargets.query({})}),ie=i({queryKey:Hp,queryFn:()=>s.trpcClient.notificationRules.getConditionCatalog.query({})}),ae=se({projection:`slim`}),oe=Ol(),R=r(()=>ae.data??[],[ae.data]),ce=ve(ae),le=r(()=>R.map(e=>e.id),[R]),ue=i({queryKey:[...Up,le],enabled:le.length>0,queryFn:async()=>{let e=[];for(let t of R){let n=Ze(await s.trpcClient.deviceManager.loadRuntimeState.query({deviceId:t.id}),Wp);n.length>0&&e.push({id:t.id,name:t.name,states:n})}return e},staleTime:6e4}),de=r(()=>{let e=Qt(R);return R.map(t=>{let n=e.get(t.id);return{id:t.id,name:t.name,type:String(t.type),location:t.location??null,...n===void 0?{}:{parentName:n}}}).sort((e,t)=>e.name.localeCompare(t.name))},[R]),fe=r(()=>R.filter(e=>e.type===Ft.Camera).map(e=>({id:e.id,name:e.name})),[R]),pe=on(r(()=>fe.map(e=>e.id),[fe])),me=r(()=>{let e=new Map(fe.map(e=>[e.id,e.name]));return pe.results.flatMap(t=>t.monitors.map(n=>({sceneId:n.id,deviceId:t.deviceId,cameraName:e.get(t.deviceId)??`#${String(t.deviceId)}`,label:n.label,verdict:n.verdict,latched:n.latched,emit:n.emit})))},[pe.results,fe]),z=r(()=>{let e=new Map;for(let t of re.data??[])e.set(t.id,t.name);return e},[re.data]),ge=u({mutationFn:e=>s.trpcClient.notificationRules.setRuleEnabled.mutate(e),onSuccess:()=>void N.refetch()}),ye=u({mutationFn:e=>s.trpcClient.notificationRules.deleteRule.mutate({ruleId:e}),onSuccess:()=>void N.refetch()}),be=Rl(),B=_e({}),V=B.data?.sequences??[],xe=he(),H=N.data??[],Se=r(()=>{let e=new Map;for(let t of Fa)e.set(t.key,H.filter(e=>We(e,t.key)).length);return e},[H]),U=r(()=>{let e=new Map;return e.set(`summaries`,F.data?.length??0),e.set(`timelapses`,te.data?.length??0),e.set(`calendar-events`,ne.data?.length??0),e},[F.data,te.data,ne.data]),G=yp(Se),K=G.find(e=>e.key===A)??G[0]??Fa[0],Ce=gp(K.key)?vp(K.key):void 0,we=bp(K.key)?K.key:null,Te=r(()=>we===null?[]:H.filter(e=>We(e,we)).toSorted((e,t)=>e.name.localeCompare(t.name)),[H,we]),Ee=we===null?!1:La(we),De=(e,t)=>{let n=new URLSearchParams(p);e===null?n.delete(`rule`):n.set(`rule`,e),t===void 0||t===`rule`?n.delete(`editTab`):n.set(`editTab`,t),g(n,{replace:!0})},Oe=()=>{let e=new URLSearchParams(p);e.delete(`rule`),e.delete(`editTab`),g(e,{replace:!0})},ke=e=>{Ia(e)&&(v({mode:`form`,rule:e}),De(e.id))},Ae=()=>{v({mode:`form`,rule:null,seed:Je(we??`all`)}),De(`new`)},je=e=>{if(e===`rule`){Ae();return}if(e===`summary`){M(`summaries`),S(e=>e+1);return}if(e===`timelapse`){M(`timelapses`),D(e=>e+1);return}M(`calendar-events`),k(e=>e+1)};return n(nn,{icon:x,title:`Rules`,subtitle:Ce?.blurb??(`blurb`in K?K.blurb:``),actions:Ce!==void 0||`creatable`in K&&K.creatable?A===`all`?n(Fe,{children:[n(T,{className:`inline-flex h-8 items-center gap-1.5 rounded-md bg-primary px-3 text-xs font-medium text-primary-foreground hover:bg-primary/90`,"data-testid":`rules-new-menu`,children:[d(W,{className:`h-3.5 w-3.5`}),`New rule`,d(m,{className:`h-3 w-3 opacity-80`})]}),d(b,{align:`end`,className:`min-w-[14rem] py-1`,children:hp.map(e=>d(L,{onClick:()=>je(e.type),"data-testid":`rules-new-${e.type}`,title:e.hint,children:n(`span`,{className:`flex flex-col gap-0.5`,children:[d(`span`,{className:`font-medium`,children:e.label}),d(`span`,{className:`text-[10px] text-foreground-subtle font-normal`,children:e.hint})]})},e.type))})]}):Ce===void 0?n(I,{size:`sm`,type:`button`,onClick:Ae,children:[d(W,{className:`h-3.5 w-3.5`}),`newRuleLabel`in K?K.newRuleLabel:`New rule`]}):n(I,{size:`sm`,type:`button`,onClick:()=>je(Ce.key===`summaries`?`summary`:Ce.key===`timelapses`?`timelapse`:`calendar-events`),"data-testid":Ce.key===`summaries`?`summary-new`:Ce.key===`timelapses`?`timelapse-new`:`calendar-events-new`,children:[d(W,{className:`h-3.5 w-3.5`}),Ce.newLabel]}):void 0,children:[d(ee,{value:K.key,onValueChange:e=>M(_p(e)??A),children:d(C,{className:`mb-3`,children:G.map(e=>n(E,{value:e.key,children:[e.label,d(`span`,{className:`ml-1.5 text-[10px] text-foreground-subtle`,children:bp(e.key)?Se.get(e.key)??0:U.get(e.key)??0})]},e.key))})}),Ce?.key===`summaries`&&d(xf,{embedded:!0,openCreateKey:y}),Ce?.key===`timelapses`&&d(sp,{embedded:!0,openCreateKey:w}),Ce?.key===`calendar-events`&&d(pp,{embedded:!0,openCreateKey:O}),we!==null&&n(a,{children:[d(ju,{rules:H}),N.isLoading&&d(mf,{}),N.isError&&!N.isLoading&&d(J,{title:`Failed to load rules`,message:N.error instanceof Error?N.error.message:`Unknown error`,onRetry:()=>void N.refetch()}),!N.isLoading&&!N.isError&&Te.length===0&&d(hf,{children:`emptyHint`in K?K.emptyHint:`No rules yet.`}),Te.length>0&&d(gf,{columns:Ee?Xp({targetNameById:z,snoozes:be,sequences:V,deletePending:ye.isPending,onToggle:(e,t)=>ge.mutate({ruleId:e.id,enabled:t}),onOpen:ke,t:c,onDuplicate:e=>ke({...e,id:``,name:`${e.name} (copy)`}),onConfirmDelete:e=>ye.mutate(e.id),lastRunOf:e=>Pp(oe,e),...o?{onOpenHistory:o}:{}}):qp({targetNameById:z,snoozes:be,sequences:V,deletePending:ye.isPending,onToggle:(e,t)=>ge.mutate({ruleId:e.id,enabled:t}),onOpen:ke,t:c,onDuplicate:e=>ke({...e,id:``,name:`${e.name} (copy)`}),onConfirmDelete:e=>ye.mutate(e.id),...t?{onTest:t}:{},lastRunOf:e=>Pp(oe,e),...o?{onOpenHistory:o}:{}}),rows:Te,rowKey:e=>e.id,onRowClick:ke,minWidthPx:760}),_.mode===`form`&&d(Zp,{rule:_.rule,..._.seed?{seed:_.seed}:{},targets:re.data??[],actuatable:de,fleet:ce,sequences:V,onCreateSequence:async e=>{let t=await xe.mutateAsync({sequence:{name:e.name,...e.minDelaySec===void 0?{}:{minDelaySec:e.minDelaySec},actions:[...e.actions]}});return await B.refetch(),t.sequence.id},catalog:Ss(ie.data?.catalog??[]),taxonomy:ie.data?.taxonomy,cameras:fe,gateable:ue.data??[],gateableScenes:me,initialEditTab:Fs(p.get(`editTab`)??``)??`rule`,onEditTabChange:e=>De(_.mode===`form`?_.rule?.id??`new`:`new`,e),onCancel:()=>{v({mode:`closed`}),Oe()},onSaved:()=>{v({mode:`closed`}),Oe(),N.refetch()}})]})]})}function Kp(e,t){return e.replaceAll(`{{name}}`,t)}function qp(e){return[{key:`name`,header:`Rule`,render:t=>d(_f,{name:t.name,enabled:t.enabled,...Ia(t)?{onOpen:()=>e.onOpen(t)}:{}})},{key:`trigger`,header:`Trigger`,nowrap:!0,render:t=>n(`span`,{className:`flex items-center gap-1.5`,children:[d(`span`,{className:`text-[11px] text-foreground-subtle`,children:ja(t,e.t(`notificationRules.grouping.choice`,Ea))}),!Pa(t.delivery)&&d(U,{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 d(`span`,{className:`text-[11px] text-foreground-subtle`,children:t.targets.length===1&&r?r:`${t.targets.length} target${t.targets.length===1?``:`s`}`})}},{key:`lastRun`,header:`Last run`,nowrap:!0,render:t=>d(Al,{cell:e.lastRunOf(t.id)})},{key:`priority`,header:`Priority`,align:`center`,nowrap:!0,render:e=>d(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.priority})},{key:`snooze`,header:e.t(`notificationRules.columns.snooze`,`Snooze`),align:`center`,nowrap:!0,render:t=>d(pf,{children:d(zl,{rule:t,snoozes:e.snoozes,exempt:Zo(t.conditions,Qo({onActivation:t.actions?.onActivation??[],onDeactivation:t.actions?.onDeactivation??[],onTrigger:t.actions?.onTrigger??[],onTriggerOff:t.actions?.onTriggerOff??[],buttons:t.actions?.buttons??[]},e.sequences))})})},{key:`enabled`,header:`On`,align:`center`,nowrap:!0,render:t=>d(pf,{children:d(F,{checked:t.enabled,onCheckedChange:n=>e.onToggle(t,n),"aria-label":`toggle ${t.name}`})})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:t=>Ia(t)?n(pf,{className:`flex items-center justify-end gap-1`,children:[d(Eu,{ruleId:t.id,ruleName:t.name,...t.conditions.devices?.[0]===void 0?{}:{fallbackDeviceId:t.conditions.devices[0]}}),e.onOpenHistory&&d(jl,{rule:t,onOpenHistory:e.onOpenHistory}),e.onTest&&d(I,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onTest?.(t),title:`Open in the simulator — describe an event and tune it before injecting`,"aria-label":`simulate ${t.name}`,children:d(ce,{className:`h-3.5 w-3.5`})}),d(I,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onDuplicate(t),title:`Duplicate`,children:d(be,{className:`h-3.5 w-3.5`})}),d(Yp,{rule:t,deps:e})]}):d(Jp,{rule:t,deps:e})}]}function Jp({rule:e,deps:t}){return n(pf,{className:`flex items-center justify-end gap-1`,children:[d(`span`,{title:ot(it(e)).blurb,children:d(U,{variant:`warning`,children:`Recreate as one rule per family`})}),t.onOpenHistory&&d(jl,{rule:e,onOpenHistory:t.onOpenHistory}),d(Yp,{rule:e,deps:t})]})}function Yp({rule:e,deps:t}){let{t:n}=en();return d(vf,{pending:t.deletePending,title:n(`notificationRules.delete.confirm`,`Delete this rule?`),message:Kp(n(`notificationRules.delete.message`,`This will permanently delete "{{name}}". This action cannot be undone.`),e.name),confirmLabel:n(`common.delete`,`Delete`),cancelLabel:n(`common.cancel`,`Cancel`),ariaLabel:Kp(n(`notificationRules.delete.aria`,`delete {{name}}`),e.name),onConfirm:()=>t.onConfirmDelete(e)})}function Xp(e){let t=qp(e),n=e=>t.filter(t=>t.key===e);return[...n(`name`),{key:`events`,header:`Events`,render:e=>d(`span`,{className:`text-[11px] text-foreground-subtle`,children:No(e.conditions.systemEvent?.kinds)})},{key:`scope`,header:`Scope`,nowrap:!0,render:e=>d(`span`,{className:`text-[11px] text-foreground-subtle`,children:Po(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 d(`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=>d(`span`,{className:`text-[11px] text-foreground-subtle`,children:Va(e.throttle.cooldownSec)})},...n(`lastRun`),...n(`snooze`),...n(`enabled`),...n(`actions`)]}function Zp({rule:e,seed:t,targets:o,catalog:s,taxonomy:c,cameras:f,gateable:p,gateableScenes:m,actuatable:g,fleet:_,sequences:v,onCreateSequence:y,initialEditTab:b=Ps,onEditTabChange:S,onSaved:T,onCancel:O}){let k=h(),{t:A}=en(),j=e!=null&&e.id.length>0,[N]=l(()=>e?is(e):rs(t?.delivery,t?.conditions)),[P,te]=l(N),[ne,re]=l(null),[ie,ae]=l(null),[oe,se]=l(b),L=e=>te(t=>({...t,...e})),R=e?Ds(e):void 0,le=u({mutationFn:async()=>{let t=Os(P,R,s);if(j&&e){let n=ks(P,s);await k.trpcClient.notificationRules.updateRule.mutate({ruleId:e.id,patch:t,...n.length>0?{clear:n}:{}})}else await k.trpcClient.notificationRules.createRule.mutate({rule:t})},onSuccess:T,onError:e=>re(e instanceof Error?e.message:`Save failed`)}),ue=u({mutationFn:async()=>{let e=Os(P,R,s);return(await k.trpcClient.notificationRules.testRule.mutate({rule:e,lookbackMinutes:60})).results},onMutate:()=>ae(null),onSuccess:e=>ae(e),onError:e=>re(e instanceof Error?e.message:`Test failed`)}),de=P.targetIds.map(e=>o.find(t=>t.id===e)?.name??e),fe=e=>L({targetIds:P.targetIds.includes(e)?P.targetIds.filter(t=>t!==e):[...P.targetIds,e]}),pe=i({queryKey:[`userManagement`,`listUsers`],queryFn:()=>k.trpcClient.userManagement.listUsers.query()}).data,me=e=>L({targetUsers:P.targetUsers.includes(e)?P.targetUsers.filter(t=>t!==e):[...P.targetUsers,e]}),z=Oa(P),he=z===`immediate-grouped`,ge=String(P.groupingSec??20),_e=ka(P).map(e=>({...e,label:e.value===`immediate-grouped`?A(`notificationRules.grouping.choice`,e.label):e.label,hint:e.value===`immediate-grouped`?A(`notificationRules.grouping.hint`,{n:ge,defaultValue:`Immediate, grouped — waits up to {{n}} s for subjects to be recognised, then sends one message with a mosaic, one picture per subject. Closes earlier when every subject is final.`}).replaceAll(`{{n}}`,ge):e.hint})),ve=_e.find(e=>e.value===z)?.hint,ye=as(P,R),be=tt(P.delivery),V=it(P),xe=ot(V),H=Pt(V),Se=at(V),W=i({queryKey:[`deviceManager`,`listDeviceIdsByCaps`,`nc-rule-devices`,Se??[]],enabled:Se!==null,queryFn:async()=>{let e=await Promise.all((Se??[]).map(e=>k.trpcClient.deviceManager.listDeviceIdsByCaps.query({capNames:[...e]})));return new Set(e.flat())},staleTime:6e4}),K=r(()=>{if(Se===null||W.data===void 0)return g;let e=W.data,t=new Set(Bo(P.deviceScope));return g.filter(n=>e.has(n.id)||t.has(n.id))},[g,Se,W.data,P.deviceScope]),Ce=Se!==null&&W.isLoading,we=Se!==null&&W.isError,Te=qr(),Ee=e=>({family:`rule`,field:e,kind:V,delivery:P.delivery,...cs(P)?{systemEventDelivery:`summary`}:{},...P.conditions.systemEvent?{systemEventKinds:[...P.conditions.systemEvent.kinds]}:{}}),Oe=e=>Te.data?Ur(Te.data,Ee(e)):void 0,ke=Ns(P),Ae=Zo(P.conditions,Qo(P.actions,v)),je=P.conditions.identities!==void 0||P.conditions.plates!==void 0,Me=js(P.delivery,P.conditions),Ne=Me.some(e=>e.key===oe)?oe:Ps;return Pa(P.delivery)?d(w,{open:!0,onOpenChange:e=>!e&&O(),children:n(De,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,children:[n(`div`,{className:`flex shrink-0 items-center justify-between mb-3`,children:[n(`h3`,{className:`text-sm font-semibold text-foreground flex min-w-0 items-center gap-2`,children:[d(x,{className:`h-4 w-4 shrink-0 text-foreground-subtle`}),d(`span`,{className:`truncate`,children:j?`Edit ${e?.name}`:`New notification rule`})]}),d(I,{size:`sm`,variant:`ghost`,type:`button`,onClick:O,children:`Cancel`})]}),ne&&d(`div`,{className:`shrink-0 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger mb-3`,children:ne}),j&&e&&n(`div`,{className:`shrink-0 mb-3 space-y-2`,children:[d(pu,{kind:`rule`,ruleId:e.id,enabled:e.enabled,updatedAt:e.updatedAt}),d(gu,{ruleId:e.id,cameraName:e=>f.find(t=>t.id===e)?.name??`camera ${String(e)}`})]}),n(ee,{value:Ne,onValueChange:e=>{let t=Fs(e);t!==void 0&&(se(t),S?.(t))},className:`flex min-h-0 flex-1 flex-col`,children:[d(C,{className:`mb-3 shrink-0`,children:Me.map(e=>d(E,{value:e.key,children:e.label},e.key))}),n(D,{className:`pr-1`,children:[n(M,{value:`rule`,className:`space-y-4`,children:[n(`div`,{className:`flex items-end gap-3`,children:[n(`div`,{className:`min-w-0 flex-1`,children:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Name`}),d(B,{value:P.name,onChange:e=>L({name:e.target.value}),placeholder:`e.g. Front door package`})]}),n(`label`,{className:`flex items-center gap-2 pb-1.5 text-[11px] font-medium text-foreground`,children:[d(F,{checked:P.enabled,onCheckedChange:e=>L({enabled:e}),"aria-label":`enabled`}),`Enabled`]})]}),n(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Trigger`}),d(q,{value:z,onChange:e=>{let t=Aa(e.target.value);t&&te(e=>ds(e,t))},options:_e.map(e=>({value:e.value,label:e.label}))}),ve&&d(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:ve}),he&&n(`div`,{className:`mt-2`,children:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:A(`notificationRules.grouping.seconds`,`Group for (seconds)`)}),d(B,{type:`number`,min:5,max:60,step:1,value:ge,"data-testid":`rule-grouping-sec`,onChange:e=>{let t=Ma(e.target.value);t!==void 0&&L({groupingSec:t})}}),d(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:A(`notificationRules.grouping.minNote`,`At least 5 s: subjects arriving together share one message.`)}),je&&d(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:A(`notificationRules.grouping.scopedHint`,{n:ge,defaultValue:`A subject not recognised within {{n}} s is not notified.`}).replaceAll(`{{n}}`,ge)})]}),z===`immediate`&&je&&d(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:A(`notificationRules.grouping.plainRecognitionHint`,`Fires only if the name is already known when an event is written — choose Immediate, grouped to wait for it.`)})]}),!j&&H!==void 0&&d(al,{family:H,onChange:e=>te(t=>gs(t,e))}),n(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Delivery targets`}),o.length===0?d(`p`,{className:`text-[11px] text-foreground-subtle`,children:`No delivery targets configured. Add one under the Targets tab first.`}):d(`div`,{className:`rounded-md border border-border divide-y divide-border`,children:o.map(e=>n(`label`,{className:`flex items-center gap-2.5 px-3 py-1.5 text-xs text-foreground cursor-pointer hover:bg-surface-hover`,children:[d(`input`,{type:`checkbox`,checked:P.targetIds.includes(e.id),onChange:()=>fe(e.id),className:`accent-primary`}),d(`span`,{className:`flex-1 truncate`,children:e.name}),!e.enabled&&d(U,{variant:`warning`,children:`disabled`})]},e.id))})]}),n(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Notify users`}),(pe??[]).length===0?d(`p`,{className:`text-[11px] text-foreground-subtle`,children:`No users to notify.`}):d(`div`,{className:`rounded-md border border-border divide-y divide-border`,children:(pe??[]).map(e=>n(`label`,{className:`flex items-center gap-2.5 px-3 py-1.5 text-xs text-foreground cursor-pointer hover:bg-surface-hover`,children:[d(`input`,{type:`checkbox`,checked:P.targetUsers.includes(e.id),onChange:()=>me(e.id),className:`accent-primary`}),d(`span`,{className:`flex-1 truncate`,children:e.username}),e.isAdmin&&d(U,{variant:`info`,children:`admin`})]},e.id))}),d(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:`Delivers to the targets each user owns, only for cameras that user can access.`})]})]}),n(M,{value:`devices`,className:`space-y-4`,children:[Ce&&d(`p`,{className:`text-[10px] text-foreground-subtle`,"data-testid":`rule-devices-compat-loading`,children:A(`notificationRules.devices.compatLoading`,`Checking which devices this rule's kind can use…`)}),we&&d(`p`,{className:`text-[10px] text-foreground-subtle`,"data-testid":`rule-devices-compat-failed`,children:A(`notificationRules.devices.compatFailed`,`Couldn't check which devices this rule's kind can use — every device is listed. The hub still refuses an incompatible one on save.`)}),d(Ic,{devices:K,scope:P.deviceScope,onChange:e=>L({deviceScope:e}),listState:_.state,savedScope:N.deviceScope,exceptOffered:ns(s,`devicesExclude`,P)})]}),d(M,{value:`actions`,className:`space-y-4`,children:d(Qi,{value:P.actions,onChange:e=>L({actions:e}),devices:g,devicesState:_.state,sequences:v,onCreateSequence:y})}),n(M,{value:`advanced`,className:`space-y-4`,children:[d(bl,{catalog:s,delivery:P.delivery,conditions:P.conditions,onConditionsChange:e=>L({conditions:e})}),n(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Cooldown (seconds)`}),d(B,{type:`number`,min:0,max:Ba,step:1,value:String(P.cooldownSec),"data-testid":`rule-cooldown`,onChange:e=>{let t=Ha(e.target.value);t!==void 0&&L({cooldownSec:t})}}),n(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:[be?`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 as chosen below.`,` `,`Any whole number from 0 (deliver every match) to `,String(Ba),` (24 hours).`]})]}),n(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[n(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Cooldown counted`}),d(q,{value:P.cooldownScope,onChange:e=>{let t=Wa(e.target.value);t!==void 0&&L({cooldownScope:t})},options:Ua.map(e=>({value:e.value,label:e.label})),"data-testid":`rule-cooldown-scope`}),d(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:`Per device: a delivery about one camera (or node) does not hold back another. Whole rule: one delivery per cooldown, whichever device matched.`})]}),n(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Across object classes`}),d(q,{value:P.cooldownGranularity??`per-class`,onChange:e=>L({cooldownGranularity:Ka(e.target.value)}),options:Ga.map(e=>({value:e.value,label:e.label})),"data-testid":`rule-cooldown-granularity`}),d(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:`Separate (default): a dog after a cat is delivered at once, a second cat still waits. Shared: a cat holds back the next dog for the cooldown. Sounds always count per class.`})]})]}),n(`div`,{children:[n(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[d(F,{checked:P.snoozeAllowGlobal,onCheckedChange:e=>L({snoozeAllowGlobal:e}),"aria-label":`allow global snooze`,disabled:Ae}),`Anyone may snooze this rule for everyone`]}),d(`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.`})]}),!Ae&&n(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Snooze buttons`}),n(a,{children:[d(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:qo.map(e=>{let t=P.snoozeOptions??Ko,n=t.includes(e);return d(I,{type:`button`,size:`sm`,variant:n?`primary`:`outline`,onClick:()=>L({snoozeOptions:n?t.filter(t=>t!==e):[...t,e].toSorted((e,t)=>e-t)}),children:Jo(e)},e)})}),d(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:P.snoozeOptions===void 0?`Not set — the notification offers the defaults (${Ko.map(Jo).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.`:P.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.`}),P.snoozeOptions!==void 0&&d(I,{type:`button`,size:`sm`,variant:`ghost`,className:`mt-1`,onClick:()=>L({snoozeOptions:void 0}),children:`Back to the defaults`})]})]}),j&&e&&!Ae&&n(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Silence it now`}),d(Pl,{ruleId:e.id,ruleName:e.name,exempt:Ae,variant:`full`})]})]}),n(M,{value:`notification`,className:`space-y-4`,children:[n(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[n(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Priority`}),d(q,{value:String(P.priority),onChange:e=>L({priority:Number(e.target.value)}),options:lo.map(e=>({value:String(e.value),label:e.label}))})]}),!xe.carriesMedia&&d(`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.`}),xe.carriesMedia&&V===`sensor`&&d(`div`,{className:`rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:A(`notificationRules.media.sensorOneSnapshot`,`A sensor rule attaches one snapshot of the camera automatically — there is no detection to choose a crop, a GIF or a clip around.`)}),xe.carriesMedia&&V!==`sensor`&&xe.mediaBlurb!==void 0&&d(`div`,{className:`rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:xe.mediaBlurb}),xe.carriesMedia&&V!==`sensor`&&n(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Media attachment`}),d(q,{value:P.mediaAttach,onChange:e=>{let t=Ja(e.target.value);t&&L({mediaAttach:t})},options:qa.map(e=>({value:e.value,label:e.label}))}),d(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:qa.find(e=>e.value===P.mediaAttach)?.description}),n(`div`,{className:`mt-2 space-y-1`,children:[xe.carriesSubjectCrop&&n(`label`,{className:`flex items-center gap-2 text-xs text-foreground cursor-pointer`,children:[d(`input`,{type:`checkbox`,checked:P.mediaZoneCrop,onChange:e=>L({mediaZoneCrop:e.target.checked}),className:`accent-primary`}),`Crop the image to the rule's zone`]}),n(`label`,{className:`flex items-center gap-2 text-xs text-foreground cursor-pointer`,children:[d(`input`,{type:`checkbox`,checked:P.mediaGif,onChange:e=>L({mediaGif:e.target.checked}),className:`accent-primary`}),`Attach a GIF around the event`]}),n(`label`,{className:`flex items-center gap-2 text-xs text-foreground cursor-pointer`,children:[d(`input`,{type:`checkbox`,checked:P.mediaClip,onChange:e=>L({mediaClip:e.target.checked}),className:`accent-primary`}),`Attach an MP4 clip around the event`]})]}),(P.mediaGif||P.mediaClip)&&n(`div`,{className:`mt-2`,children:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Video quality`}),d(q,{value:P.mediaProfile??``,onChange:e=>L({mediaProfile:eo(e.target.value)}),options:$a.map(e=>({value:e.value,label:e.label}))}),d(`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.`}),d(`label`,{className:`mt-2 block text-[11px] font-medium text-foreground mb-1`,children:`Playback speed`}),d(q,{value:P.mediaClipSpeed===void 0?``:String(P.mediaClipSpeed),onChange:e=>L({mediaClipSpeed:po(e.target.value)}),options:fo.map(e=>({value:e.value,label:e.label}))}),d(`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.`})]})]}),V===`sensor`&&xe.carriesMedia&&n(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Linked cameras`}),d(q,{value:P.mediaLinkedCameras??``,onChange:e=>L({mediaLinkedCameras:Qa(e.target.value)}),options:Za.map(e=>({value:e.value,label:e.label})),"data-testid":`rule-media-linked-cameras`}),d(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:`When the sensor is linked to several cameras, all of them are photographed the moment it fires. Cameras that are offline or asleep are left out.`})]}),xe.carriesMedia&&V!==`sensor`&&xe.carriesSubjectCrop&&n(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Image frame`}),d(q,{value:P.mediaFrame??``,onChange:e=>L({mediaFrame:Xa(e.target.value)}),options:Ya.map(e=>({value:e.value,label:e.label}))}),d(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:`What the attached still shows. "Automatic" leaves it to the attachment mode above.`})]})]}),n(`div`,{className:`space-y-2`,children:[d(Qr,{label:`Notification title`,value:P.templateTitle,onChange:e=>L({templateTitle:e}),vars:Oe(`title`),testId:`rule-template-title`}),d(Qr,{label:`Notification body`,value:P.templateBody,onChange:e=>L({templateBody:e}),vars:Oe(`body`),multiline:!0,testId:`rule-template-body`}),d(`p`,{className:`text-[10px] text-foreground-subtle`,children:`Leave both blank for the hub's own wording (editable on the Texts tab).`}),ss(P)!==null&&d(`p`,{className:`text-[10px] text-warning`,"data-testid":`rule-template-summary-warning`,children:ss(P)}),d($r,{context:Ee(`body`),title:P.templateTitle,body:P.templateBody,testId:`rule-template-preview`})]})]}),n(M,{value:`conditions`,className:`space-y-4`,children:[n(`div`,{className:`rounded-md border border-border px-3 py-3`,children:[d(`div`,{className:`mb-2 text-[11px] font-semibold text-foreground`,children:be?`Which system events`:Ms(P.conditions)??`Conditions`}),P.conditions.audio!==void 0&&d(`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).`}),P.conditions.occupancy!==void 0&&d(`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.`}),be&&d(`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.`}),s.length===0?d(`p`,{className:`text-[10px] text-foreground-subtle`,children:`Condition catalog unavailable — this rule matches on its trigger and targets alone.`}):d(ol,{catalog:cs(P)?s.filter(e=>e.id!==`schedule`):s,taxonomy:c,delivery:P.delivery,conditions:P.conditions,classScope:P.classScope,onClassScopeChange:e=>L({classScope:e}),actions:Bi(P.actions),sequenceActionsOf:e=>v.find(t=>t.id===e)?.actions,savedConditions:N.conditions,schedule:P.schedule,deviceIds:ts(P),zoneCameraIds:vc(P.deviceScope,f),cameras:f,fleet:_,allDevices:g,gateable:p,gateableScenes:m,onConditionsChange:e=>L({conditions:e}),onScheduleChange:e=>L({schedule:e})})]}),be&&d(Ap,{value:P.systemEventDelivery,family:H,onChange:e=>L({systemEventDelivery:e}),draft:()=>Os(P,R,s)}),j&&e&&n(`div`,{className:`rounded-md border border-border px-3 py-3`,children:[n(`div`,{className:`flex items-center justify-between gap-2`,children:[d(`div`,{className:`text-[11px] font-semibold text-foreground`,children:`Test this rule for real`}),d(Eu,{ruleId:e.id,ruleName:e.name,variant:`full`,showResult:!0,...ts(P)[0]===void 0?{}:{fallbackDeviceId:ts(P)[0]}})]}),d(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:`Builds the event this rule is about, runs the REAL evaluation and delivery, and sends the notification to every target — marked [TEST] in the body. The cooldown and the camera mute are bypassed (neither window is consumed); the rule's actions are never run. Saved conditions only: save first to test an edit.`})]}),!be&&n(`div`,{className:`rounded-md border border-border px-3 py-3`,children:[n(`div`,{className:`flex items-center justify-between gap-2`,children:[d(`div`,{className:`text-[11px] font-semibold text-foreground`,children:`Test rule`}),n(I,{size:`sm`,variant:`outline`,type:`button`,disabled:ue.isPending||!ls(P,R,new Set(v.map(e=>e.id))),onClick:()=>{re(null),ue.mutate()},children:[ue.isPending?d(G,{className:`h-3.5 w-3.5 animate-spin`}):d(ce,{className:`h-3.5 w-3.5`}),`Dry-run (last 60 min)`]})]}),d(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:`Evaluate the CURRENT (unsaved) rule against recently persisted records — no notification is sent.`}),ie!==null&&d($p,{delivery:P.delivery,results:ie,targetNames:de})]})]})]})]}),ke.length>0&&n(`div`,{"data-testid":`rule-form-dropped`,className:`mt-3 shrink-0 rounded-md border border-border bg-surface-subtle px-3 py-2 text-[11px] text-foreground-subtle space-y-1`,children:[n(`p`,{className:`text-foreground`,children:[`Saving drops `,ke.length,` condition`,ke.length===1?``:`s`,` this kind of rule cannot use:`]}),ke.map(e=>n(`p`,{children:[d(`span`,{className:`text-foreground`,children:e.conditionId}),` — `,e.reason]},e.conditionId))]}),ye.length>0&&d(`div`,{"data-testid":`rule-form-problems`,className:`mt-3 shrink-0 rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-[11px] text-warning space-y-1`,children:ye.map(e=>d(`p`,{children:e},e))}),n(`div`,{className:`flex shrink-0 justify-end gap-2 mt-4`,children:[d(I,{variant:`secondary`,size:`sm`,type:`button`,onClick:O,children:`Cancel`}),n(I,{size:`sm`,type:`button`,disabled:le.isPending||!ls(P,R,new Set(v.map(e=>e.id))),onClick:()=>{re(null),le.mutate()},children:[le.isPending&&d(G,{className:`h-3.5 w-3.5 animate-spin`}),j?`Save changes`:`Create rule`]})]})]})}):d(Qp,{rule:e,onCancel:O})}function Qp({rule:e,onCancel:t}){let r=Object.keys(e?.conditions??{});return d(w,{open:!0,onOpenChange:e=>!e&&t(),children:n(De,{width:`lg`,placement:`sheet-on-mobile`,children:[n(`div`,{className:`flex items-center justify-between mb-3`,children:[n(`h3`,{className:`text-sm font-semibold text-foreground flex items-center gap-2`,children:[d(x,{className:`h-4 w-4 text-foreground-subtle`}),e?.name??`Rule`]}),d(U,{variant:`warning`,children:`read-only`})]}),n(`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 `,d(`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.`]}),n(`dl`,{className:`mt-3 space-y-1.5 text-[11px]`,children:[n(`div`,{className:`flex gap-2`,children:[d(`dt`,{className:`w-24 shrink-0 text-foreground-subtle`,children:`Trigger`}),d(`dd`,{className:`text-foreground`,children:e?.delivery})]}),n(`div`,{className:`flex gap-2`,children:[d(`dt`,{className:`w-24 shrink-0 text-foreground-subtle`,children:`Enabled`}),d(`dd`,{className:`text-foreground`,children:e?.enabled?`yes`:`no`})]}),n(`div`,{className:`flex gap-2`,children:[d(`dt`,{className:`w-24 shrink-0 text-foreground-subtle`,children:`Targets`}),d(`dd`,{className:`text-foreground`,children:e?.targets.length??0})]}),n(`div`,{className:`flex gap-2`,children:[d(`dt`,{className:`w-24 shrink-0 text-foreground-subtle`,children:`Conditions`}),d(`dd`,{className:`text-foreground`,children:r.length>0?r.join(`, `):`none`})]})]}),d(`div`,{className:`flex justify-end gap-2 mt-4`,children:d(I,{variant:`secondary`,size:`sm`,type:`button`,onClick:t,children:`Close`})})]})})}function $p({delivery:e,results:t,targetNames:r}){if(e===`device-event`)return d(`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 d(`p`,{className:`mt-2 text-[11px] text-foreground-subtle`,children:`No records in the last 60 minutes matched — nothing to evaluate.`});let i=t.filter(e=>e.wouldFire).length;return n(`div`,{className:`mt-2 space-y-1.5`,children:[n(`div`,{className:`text-[11px] text-foreground-subtle`,children:[i,` of `,t.length,` evaluated record`,t.length===1?``:`s`,` would fire.`]}),d(`ul`,{className:`divide-y divide-border rounded-md border border-border`,children:t.slice(0,50).map(e=>n(`li`,{className:`flex items-center gap-2 px-2.5 py-1.5 text-[11px]`,children:[e.wouldFire?d(Oe,{className:`h-3.5 w-3.5 shrink-0 text-success`}):d(ye,{className:`h-3.5 w-3.5 shrink-0 text-foreground-subtle`}),d(`span`,{className:`w-32 shrink-0 text-foreground-subtle`,children:new Date(e.timestamp).toLocaleString()}),n(`span`,{className:`w-14 shrink-0 text-foreground-subtle`,children:[`#`,e.deviceId]}),d(`span`,{className:`min-w-0 flex-1 truncate text-foreground`,children:e.label??e.className??`object`}),e.wouldFire?n(`span`,{className:`shrink-0 truncate text-success`,children:[`→ `,r.join(`, `)||`targets`]}):e.failedCondition&&n(`span`,{className:`shrink-0 text-foreground-subtle`,children:[`failed: `,e.failedCondition]})]},e.recordId))})]})}t();var em=`mt-1 w-full rounded border border-border bg-background px-2 py-1 text-xs`,tm=`block text-[11px] font-medium text-foreground`,nm=[[`notificationRules`,`listSequences`]];function rm(){return{name:``,minDelaySec:``,actions:[Gi()]}}function im(e){return{id:e.id,name:e.name,minDelaySec:e.minDelaySec===void 0?``:String(e.minDelaySec),actions:[...e.actions]}}function am(){let e=s(),t=_e({}),i=he(),a=re(),o=Me(),[c,u]=l(null),f=se({projection:`slim`}),p=ve(f),m=r(()=>(f.data??[]).map(e=>({id:e.id,name:e.name,type:String(e.type),location:e.location??null})).toSorted((e,t)=>e.name.localeCompare(t.name)),[f.data]),h=()=>{e.invalidateQueries({queryKey:nm})},g=async()=>{if(c===null||c.name.trim()===``||c.actions.length===0)return;let e={name:c.name.trim(),...c.minDelaySec===``?{}:{minDelaySec:Number(c.minDelaySec)},actions:c.actions};c.id===void 0?await i.mutateAsync({sequence:e}):await a.mutateAsync({sequenceId:c.id,sequence:e}),u(null),h()},v=t.data?.sequences??[];return n(nn,{icon:un,title:`Sequences`,subtitle:`Named step lists shared by notification rules and buttons. A rule binds to one by id; two rules sharing a gate share its throttle.`,actions:n(I,{size:`sm`,type:`button`,onClick:()=>u(rm()),children:[d(W,{className:`h-3.5 w-3.5`}),` New sequence`]}),children:[c!==null&&n(`div`,{className:`mb-4 space-y-3 rounded-md border border-border p-4`,children:[n(`div`,{className:`flex flex-wrap items-end gap-2`,children:[n(`div`,{className:`min-w-0 flex-1`,children:[d(`label`,{className:tm,children:`Name`}),d(B,{className:`mt-1`,value:c.name,onChange:e=>u({...c,name:e.target.value})})]}),n(`div`,{className:`w-28`,children:[d(`label`,{className:tm,children:`Min delay (s)`}),d(`input`,{type:`number`,min:0,className:em,value:c.minDelaySec,onChange:e=>u({...c,minDelaySec:e.target.value})})]})]}),n(`div`,{className:`space-y-2 border-l-2 border-border-subtle pl-3`,children:[c.actions.map((e,t)=>d(om,{step:e,devices:m,listState:p.state,fleet:p,onChange:e=>u({...c,actions:c.actions.map((n,r)=>r===t?e:n)}),onRemove:()=>u({...c,actions:c.actions.filter((e,n)=>n!==t)})},`s-${String(t)}`)),n(I,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>u({...c,actions:[...c.actions,Gi()]}),children:[d(W,{className:`h-3.5 w-3.5`}),` Step`]})]}),n(`div`,{className:`flex gap-2`,children:[d(I,{size:`sm`,type:`button`,onClick:()=>void g(),children:`Save`}),d(I,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>u(null),children:`Cancel`})]})]}),t.isPending?d(`p`,{className:`text-sm text-foreground-subtle`,children:`Loading…`}):v.length===0?d(`p`,{className:`rounded border border-border px-3 py-2 text-sm text-foreground-subtle`,children:`No sequences yet. Create one, then bind it from a rule's Actions tab.`}):d(`ul`,{className:`space-y-2`,children:v.map(e=>n(`li`,{className:`flex flex-wrap items-center justify-between gap-2 rounded-md border border-border px-3 py-2`,children:[n(`div`,{className:`min-w-0`,children:[d(`div`,{className:`text-sm font-medium text-foreground`,children:e.name}),n(`div`,{className:`text-[11px] text-foreground-subtle`,children:[e.actions.length,` step`,e.actions.length===1?``:`s`,e.minDelaySec===void 0?``:` · min delay ${String(e.minDelaySec)}s`]})]}),n(`div`,{className:`flex gap-1`,children:[d(I,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>u(im(e)),children:`Edit`}),d(I,{size:`sm`,variant:`ghost`,type:`button`,title:`Delete`,onClick:()=>{o.mutateAsync({sequenceId:e.id}).then(h)},children:d(_,{className:`h-3.5 w-3.5`})})]})]},e.id))})]})}function om({step:e,devices:t,listState:r,fleet:i,onChange:a,onRemove:o}){return n(`div`,{className:`flex flex-wrap items-start gap-2`,children:[n(`div`,{className:`w-24`,children:[d(`label`,{className:tm,children:`Step`}),n(`select`,{className:em,value:e.kind,onChange:e=>a(e.target.value===`wait`?{kind:`wait`,seconds:5}:{kind:`cap`,deviceId:t[0]?.id??0,cap:``,method:``}),children:[d(`option`,{value:`cap`,children:`Do`}),d(`option`,{value:`wait`,children:`Wait`})]})]}),e.kind===`wait`?n(`div`,{className:`w-28`,children:[d(`label`,{className:tm,children:`Seconds`}),d(`input`,{type:`number`,min:0,max:300,className:em,value:e.seconds,onChange:e=>a({kind:`wait`,seconds:Number(e.target.value)})})]}):d(rn,{value:e,devices:t,listState:r,fleet:i,onChange:e=>{a({kind:`cap`,deviceId:typeof e.deviceId==`number`?e.deviceId:0,cap:e.cap,method:e.method,...e.args===void 0?{}:{args:{...e.args}}})}}),d(I,{size:`sm`,variant:`ghost`,type:`button`,onClick:o,title:`Remove`,children:d(_,{className:`h-3.5 w-3.5`})})]})}var sm=[{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 cm(e){return sm.find(t=>t.value===e)?.value}function lm(e){return e===`object-event`||e===`audio-event`?`immediate`:e===`occupancy-event`?`device-event`:e}function um(e){return``}var dm={x:.25,y:.25,w:.5,h:.5},fm={zoneId:``,zoneName:``,className:``,count:1,previousCount:0,occupied:!0,threshold:1};function pm(){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:dm,occupancy:fm,timestampLocal:``,onlyRuleId:``,bypassCooldown:!1,bypassMute:!1,runActions:!1,still:`live`}}function mm(e){return e.deviceId!==null}function hm(e){if(e.trim().length===0)return;let t=Number(e);return Number.isFinite(t)?t:void 0}function gm(e){if(e.trim().length===0)return;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}function _m(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 vm(e){if(e.deviceId===null)return null;let t=e.trigger,n=gm(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:ym(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 ym(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 bm(e){return Math.min(1,Math.round((e+.05)*100)/100)}function xm(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 Sm(e){let t=pm(),n=e.conditions,r=xm(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:bm(n.minConfidence)},...n.minLabelConfidence===void 0?{}:{labelConfidence:bm(n.minLabelConfidence)},...n.minImportance===void 0?{}:{importance:bm(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:um(r),...n.customZones!==void 0&&n.customZones.length>0?{bboxEnabled:!0}:{},...n.occupancy===void 0?{}:{occupancy:Cm(n.occupancy)},onlyRuleId:e.id}}function Cm(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 wm(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.scene!==void 0&&t.push({conditionId:`scene`,note:`This rule is gated on a scene being ${e.conditions.scene.requiredState}. The gate reads the scene's REAL state — put the scene in that state first (or reset it), 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 Tm(e){return{form:Sm(e),caveats:wm(e),ruleName:e.name}}var Em=null;function Dm(e){Em=e}function Om(){return Em}function km(){Em=null}var Am=[`n/a`,`clear`,`suppressed`,`bypassed`],jm=[`live`,`none`,`unavailable`,`unattachable`];function Mm(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Nm(e,t){let n=e[t];return typeof n==`string`?n:void 0}function Pm(e,t){let n=e[t];return Array.isArray(n)?n.filter(e=>typeof e==`string`):[]}function Fm(e){if(!Mm(e))return null;let t=Nm(e,`ruleId`),n=Nm(e,`ruleName`),r=Nm(e,`cooldown`),i=Am.find(e=>e===r);if(t===void 0||n===void 0||i===void 0||typeof e.matched!=`boolean`)return null;let a=Nm(e,`failedCondition`),o=Array.isArray(e.matchedOn)?Pm(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:Pm(e,`targetIds`)}}function Im(e){if(!Mm(e))return null;let t=Nm(e,`recordId`),n=Nm(e,`delivery`),r=Nm(e,`still`),i=jm.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=Fm(e);t!==null&&o.push(t)}let s=Nm(e,`droppedBy`);return{recordId:t,origin:`synthetic`,delivery:n,candidates:typeof e.candidates==`number`?e.candidates:0,outcomes:o,still:i,notes:Pm(e,`notes`),...s===void 0?{}:{droppedBy:s}}}function Lm(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 Rm=new Set([`sensor`,`control`,`custom`]);function zm({form:e,cameras:t,taxonomy:r,kinds:i,kindsLoading:a,onPatch:o}){let s=e.deviceId===null?[]:[e.deviceId],c=Rt(`classes`,r);if(e.trigger===`device-event`)return n(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-2`,children:[d(`div`,{className:`text-[11px] font-semibold text-foreground`,children:`What happened`}),d(Bm,{form:e,kinds:i,loading:a,onPatch:o})]});if(e.trigger===`audio-event`){let r=i.filter(e=>e.category===`audio`&&e.level===`sub`).map(e=>({value:e.kind,label:e.label}));return n(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-2`,children:[d(`div`,{className:`text-[11px] font-semibold text-foreground`,children:`What happened`}),n(`div`,{children:[d(`label`,{className:X,children:`Audio classes`}),d(wa,{options:r,value:e.classNames,onChange:e=>o({classNames:e}),loading:a,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…`})]}),n(`div`,{children:[d(`label`,{className:X,children:`Zones`}),d(Ws,{deviceIds:s,cameras:t,value:e.zones,onChange:e=>o({zones:e})})]})]})}return e.trigger===`occupancy-event`?n(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-2`,children:[d(`div`,{className:`text-[11px] font-semibold text-foreground`,children:`What happened`}),d(Vm,{form:e,cameras:t,taxonomy:r,onPatch:o})]}):n(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-2`,children:[d(`div`,{className:`text-[11px] font-semibold text-foreground`,children:`What happened`}),n(`div`,{children:[d(`label`,{className:X,children:`Detected classes`}),c===null?d(zs,{value:e.classNames,placeholder:`Class id (person, car…)`,onChange:e=>o({classNames:e})}):d(Bs,{picker:c,value:e.classNames,onChange:e=>o({classNames:e})})]}),n(`div`,{children:[d(`label`,{className:X,children:`Zones the subject is in`}),d(Ws,{deviceIds:s,cameras:t,value:e.zones,onChange:e=>o({zones:e})})]}),e.trigger===`package-event`&&n(`div`,{className:`max-w-[14rem]`,children:[d(`label`,{className:`block text-[11px] font-medium text-foreground`,children:`Package phase`}),d(q,{value:e.packagePhase,options:[{value:``,label:`— none —`},{value:`delivered`,label:`Delivered`},{value:`picked-up`,label:`Picked up`}],onChange:e=>o({packagePhase:e.target.value===`delivered`?`delivered`:e.target.value===`picked-up`?`picked-up`:``})})]})]})}function Bm({form:e,kinds:t,loading:r,onPatch:i}){let o=t.filter(e=>Rm.has(e.category)),s=o.find(t=>t.kind===e.sensorKind);return n(a,{children:[n(`div`,{children:[d(`label`,{className:X,children:`Event kind`}),d(q,{value:e.sensorKind,options:[{value:``,label:r?`Loading kinds…`:`— pick a kind —`},...o.map(e=>({value:e.kind,label:`${e.label} (${e.category})`}))],onChange:e=>{let t=o.find(t=>t.kind===e.target.value);i({sensorKind:t?.kind??``,sourceDeviceId:t?.source.deviceId??null})}}),!r&&o.length===0&&d(`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.`})]}),n(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[n(`div`,{children:[d(`label`,{className:X,children:`Source device`}),d(B,{type:`number`,value:e.sourceDeviceId===null?``:String(e.sourceDeviceId),placeholder:`the camera itself`,onChange:e=>i({sourceDeviceId:hm(e.target.value)??null})}),d(`p`,{className:Z,children:s===void 0?`The linked device whose state changed. Filled in for you when you pick a kind.`:`Filled in from "${s.label}" — contributed by device #${s.source.deviceId} via the ${s.source.capName} capability.`})]}),n(`div`,{children:[d(`label`,{className:X,children:`Event type token`}),d(B,{value:e.eventType,placeholder:`press, press_long…`,onChange:e=>i({eventType:e.target.value})}),d(`p`,{className:Z,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 Vm({form:e,cameras:t,taxonomy:r,onPatch:i}){let o=e.deviceId===null?[]:[e.deviceId],s=Rt(`occupancy`,r),c=s===null?[]:s.groups.flatMap(e=>e.options),l=e.occupancy,u=e=>i({occupancy:{...l,...e}});return n(a,{children:[n(`div`,{children:[d(`label`,{className:X,children:`Zone`}),d(Ws,{deviceIds:o,cameras:t,value:l.zoneId===``?[]:[l.zoneId],onChange:e=>u({zoneId:e[e.length-1]??``})}),d(`p`,{className:Z,children:`Leave empty for the whole frame.`})]}),n(`div`,{className:`max-w-[14rem]`,children:[d(`label`,{className:X,children:`Class`}),d(q,{value:l.className,options:[{value:``,label:`— any class —`},...c.map(e=>({value:e.value,label:e.label}))],onChange:e=>u({className:e.target.value})})]}),n(`div`,{className:`flex flex-wrap items-end gap-3`,children:[n(`label`,{className:`text-[11px] text-foreground-subtle`,children:[`Count now`,d(B,{type:`number`,min:0,className:`w-20`,value:String(l.count),onChange:e=>u({count:hm(e.target.value)??0})})]}),n(`label`,{className:`text-[11px] text-foreground-subtle`,children:[`Count before`,d(B,{type:`number`,min:0,className:`w-20`,value:String(l.previousCount),onChange:e=>u({previousCount:hm(e.target.value)??0})})]}),n(`label`,{className:`text-[11px] text-foreground-subtle`,children:[`Threshold`,d(B,{type:`number`,min:1,className:`w-20`,value:String(l.threshold),onChange:e=>u({threshold:hm(e.target.value)??1})})]}),n(`label`,{className:`flex items-center gap-2 pb-1 text-[11px] text-foreground`,children:[d(F,{checked:l.occupied,onCheckedChange:e=>u({occupied:e}),"aria-label":`occupied`}),`Occupied`]})]})]})}function Hm({form:e,cameras:t,onPatch:r}){let i=e.deviceId===null?[]:[e.deviceId];return n(`details`,{className:`rounded-md border border-border px-3 py-2`,children:[d(`summary`,{className:`cursor-pointer text-[11px] font-semibold text-foreground`,children:`Advanced`}),n(`div`,{className:`mt-2 space-y-3`,children:[e.trigger===`object-event`&&n(`div`,{children:[n(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[d(F,{checked:e.crossingEnabled,onCheckedChange:e=>r({crossingEnabled:e}),"aria-label":`zone crossing`}),`This event is a confirmed zone crossing`]}),e.crossingEnabled&&n(`div`,{className:`mt-1 space-y-1.5`,children:[d(`div`,{className:`max-w-[12rem]`,children:d(q,{value:e.crossingDirection,options:[{value:`enter`,label:`Entered the zone`},{value:`exit`,label:`Left the zone`}],onChange:e=>r({crossingDirection:e.target.value===`exit`?`exit`:`enter`})})}),d(Ws,{deviceIds:i,cameras:t,value:e.crossingZoneId===``?[]:[e.crossingZoneId],onChange:e=>r({crossingZoneId:e[e.length-1]??``})})]})]}),n(`div`,{children:[n(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[d(F,{checked:e.bboxEnabled,onCheckedChange:e=>r({bboxEnabled:e}),"aria-label":`bounding box`}),`Carry a bounding box`]}),d(`p`,{className:Z,children:"Normalized 0–1, top-left origin. Feeds the `customZones` condition and decides how the still is cropped or boxed."}),e.bboxEnabled&&d(`div`,{className:`mt-1 flex flex-wrap gap-2`,children:[`x`,`y`,`w`,`h`].map(t=>n(`label`,{className:`text-[11px] text-foreground-subtle`,children:[t,d(B,{type:`number`,min:0,max:1,step:.05,className:`w-20`,value:String(e.bbox[t]),onChange:n=>r({bbox:{...e.bbox,[t]:hm(n.target.value)??0}})})]},t))})]}),n(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[n(`div`,{children:[d(`label`,{className:X,children:`Happened at`}),n(`div`,{className:`flex items-center gap-2`,children:[d(B,{type:`datetime-local`,value:e.timestampLocal,onChange:e=>r({timestampLocal:e.target.value})}),e.timestampLocal===``?d(I,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>r({timestampLocal:_m(Date.now())}),children:`Set`}):d(I,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>r({timestampLocal:``}),children:`Now`})]}),d(`p`,{className:Z,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.`})]}),n(`div`,{children:[d(`label`,{className:X,children:`Detection source`}),d(q,{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;r({source:t===`pipeline`||t===`onboard`||t===`sensor`||t===`audio`?t:``})}})]})]})]})]})}function Um({checked:e,label:t,hint:r,danger:i=!1,onChange:a}){return n(`div`,{children:[n(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[d(F,{checked:e,onCheckedChange:a,"aria-label":t}),t,i&&d(U,{variant:`danger`,children:`actuates devices`})]}),d(`p`,{className:Z,children:r})]})}t();var Wm={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.`},Gm={"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 Km({result:e,targetName:t}){return n(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-3`,children:[d(`p`,{className:`text-xs font-medium text-foreground`,children:Lm(e)}),n(`div`,{className:`flex flex-wrap items-center gap-2 text-[11px] text-foreground-subtle`,children:[d(qm,{recordId:e.recordId}),n(`span`,{children:[`delivery `,d(`span`,{className:`text-foreground`,children:e.delivery})]}),n(`span`,{children:[`candidates `,d(`span`,{className:`text-foreground`,children:e.candidates})]}),n(`span`,{title:Wm[e.still],children:[`still `,d(`span`,{className:`text-foreground`,children:e.still})]}),e.droppedBy!==void 0&&n(U,{variant:`warning`,children:[`dropped: `,e.droppedBy]})]}),e.notes.length>0&&d(`ul`,{className:`space-y-1 rounded-md border border-border bg-surface px-2.5 py-2`,children:e.notes.map(e=>d(`li`,{className:`text-[11px] leading-snug text-foreground-subtle`,children:e},e))}),e.outcomes.length===0?n(`p`,{className:`text-[11px] text-foreground-subtle`,children:[`No rule was evaluated. Either no enabled rule declares the`,` `,d(`span`,{className:`text-foreground`,children:e.delivery}),` delivery, or the ones that do were filtered out before evaluation — the notes above say which.`]}):d(`ul`,{className:`divide-y divide-border rounded-md border border-border`,children:e.outcomes.map(e=>d(Jm,{outcome:e,targetName:t},e.ruleId))})]})}function qm({recordId:e}){let[t,r]=l(!1);return n(`span`,{className:`inline-flex items-center gap-1 rounded border border-border px-1.5 py-0.5`,children:[d(`code`,{className:`text-[10px] text-foreground`,children:e}),d(I,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>{let t=navigator.clipboard;t!==void 0&&t.writeText(e).then(()=>{r(!0),setTimeout(()=>r(!1),1500)},()=>r(!1))},title:`Copy record id`,children:d(be,{className:`h-3 w-3`})}),t&&d(`span`,{className:`text-[10px] text-success`,children:`copied`})]})}function Jm({outcome:e,targetName:t}){return n(`li`,{className:`space-y-1 px-2.5 py-2`,children:[n(`div`,{className:`flex items-center gap-2`,children:[e.matched?d(Oe,{className:`h-3.5 w-3.5 shrink-0 text-success`}):d(ye,{className:`h-3.5 w-3.5 shrink-0 text-foreground-subtle`}),d(`span`,{className:`min-w-0 flex-1 truncate text-xs text-foreground`,children:e.ruleName}),n(`span`,{className:`shrink-0 text-[10px] text-foreground-subtle`,title:Gm[e.cooldown],children:[`cooldown: `,e.cooldown]})]}),!e.matched&&d(`p`,{className:`pl-5 text-[11px] text-foreground-subtle`,children:e.failedCondition===void 0?`Did not match. The engine reported no failing condition id.`:n(a,{children:[`Did not match — first failing condition`,` `,d(`code`,{className:`text-foreground`,children:e.failedCondition}),`.`]})}),e.matched&&n(`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&&n(`p`,{className:`pl-5 text-[10px] text-foreground-muted`,children:[`matched on: `,e.matchedOn.join(`, `)]})]})}t();var Ym=`pipeline-analytics`,Xm=`nc.injectTestEvent`;function Zm(){let e=h(),[t,a]=l(()=>Om()?.form??pm()),[o]=l(()=>Om()?.caveats??[]),[s]=l(()=>Om()?.ruleName??null);f(()=>km(),[]);let[c,p]=l(null),[m,g]=l(!1),[_,v]=l(null),y=e=>a(t=>({...t,...e})),b=se({projection:`slim`}),x=i({queryKey:Hp,queryFn:()=>e.trpcClient.notificationRules.getConditionCatalog.query({})}),S=i({queryKey:Bp,queryFn:async()=>(await e.trpcClient.notificationRules.listRules.query({})).rules}),C=i({queryKey:Vp,queryFn:()=>e.trpcClient.notificationOutput.listTargets.query({})}),w=t.deviceId,T=i({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=r(()=>(b.data??[]).filter(e=>e.type===Ft.Camera).map(e=>({id:e.id,name:e.name})),[b.data]),D=x.data?.taxonomy,O=T.data??[],k=r(()=>{let e=new Map;for(let t of C.data??[])e.set(t.id,t.name);return e},[C.data]),j=u({mutationFn:async()=>{let n=vm(t);if(n===null)throw Error(`Pick a camera first.`);return e.trpcClient.addons.custom.mutate({addonId:Ym,action:Xm,input:n})},onMutate:()=>{p(null),g(!1),v(null)},onSuccess:e=>{let t=Im(e);p(t),g(t===null)},onError:e=>v(e instanceof Error?e.message:`The simulation failed.`)}),ee=lm(t.trigger),M=S.data?.find(e=>e.id===t.onlyRuleId);return n(nn,{icon:ce,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:[b.isError&&d(J,{title:`Failed to load cameras`,message:b.error instanceof Error?b.error.message:`Unknown error`,onRetry:()=>void b.refetch()}),s!==null&&n(`div`,{className:`rounded-md border border-primary/40 bg-primary/5 px-3 py-2 text-[11px] text-foreground`,children:[`Seeded from the rule `,d(`span`,{className:`font-medium`,children:s}),`. Only that rule will be evaluated — clear "Evaluate only one rule" below to run the whole rule set.`]}),o.length>0&&d(`div`,{className:`space-y-1 rounded-md border border-warning/40 bg-warning/5 px-3 py-2`,children:o.map(e=>n(`p`,{className:`flex gap-1.5 text-[11px] text-foreground`,children:[d(A,{className:`mt-0.5 h-3 w-3 shrink-0 text-warning`}),d(`span`,{children:e.note})]},e.conditionId))}),n(H,{className:`space-y-4`,children:[n(`div`,{children:[d(`label`,{className:X,children:`Camera`}),d(q,{"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=>{y({deviceId:hm(e.target.value)??null,zones:[],crossingZoneId:``,sensorKind:``,sourceDeviceId:null,occupancy:{...t.occupancy,zoneId:``}})}}),d(`p`,{className:Z,children:`The camera the event is attributed to — what a notification shows.`})]}),n(`div`,{children:[d(`label`,{className:X,children:`Trigger`}),d(q,{"data-testid":`simulate-trigger`,value:t.trigger,options:sm.map(e=>({value:e.value,label:e.label})),onChange:e=>{let n=cm(e.target.value);if(!n)return;let r=um(t.trigger);y({trigger:n,source:t.source===``||t.source===r?um(n):t.source})}}),n(`p`,{className:Z,children:[sm.find(e=>e.value===t.trigger)?.hint,` Only rules whose trigger is `,d(`span`,{className:`text-foreground`,children:ee}),` are candidates.`]})]}),d(zm,{form:t,cameras:E,taxonomy:D,kinds:O,kindsLoading:T.isLoading,onPatch:y}),n(`details`,{className:`rounded-md border border-border px-3 py-2`,open:!0,children:[d(`summary`,{className:`cursor-pointer text-[11px] font-semibold text-foreground`,children:`Quality`}),n(`div`,{className:`mt-2 space-y-3`,children:[d(`p`,{className:Z,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.`}),n(`div`,{children:[d(`label`,{className:X,children:`Label (identity name / plate / subclass)`}),d(B,{value:t.label,placeholder:`e.g. Marco, AB123CD`,onChange:e=>y({label:e.target.value})})]}),n(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[n(`div`,{children:[d(`label`,{className:X,children:`Detection confidence`}),d(Vs,{value:t.confidence,min:0,max:1,step:.05,onChange:e=>y({confidence:e})})]}),n(`div`,{children:[d(`label`,{className:X,children:`Label-match confidence`}),d(Vs,{value:t.labelConfidence,min:0,max:1,step:.05,onChange:e=>y({labelConfidence:e})})]}),n(`div`,{children:[d(`label`,{className:X,children:`Importance`}),d(Vs,{value:t.importance,min:0,max:1,step:.05,onChange:e=>y({importance:e})})]}),n(`div`,{children:[d(`label`,{className:X,children:`Dwell (seconds)`}),d(Vs,{value:t.dwellSeconds,min:0,step:1,onChange:e=>y({dwellSeconds:e})})]})]})]})]}),d(Hm,{form:t,cameras:E,onPatch:y}),n(`div`,{className:`space-y-2 rounded-md border border-border px-3 py-2`,children:[d(`div`,{className:`text-[11px] font-semibold text-foreground`,children:`How to run it`}),d(Um,{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=>y({bypassCooldown:e})}),d(Um,{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=>y({bypassMute:e})}),d(Um,{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=>y({runActions:e})}),n(`div`,{className:`max-w-[14rem]`,children:[d(`label`,{className:X,children:`Still image`}),d(q,{value:t.still,options:[{value:`live`,label:`Live snapshot of the camera`},{value:`none`,label:`No image`}],onChange:e=>y({still:e.target.value===`none`?`none`:`live`})})]}),n(`div`,{children:[d(`label`,{className:X,children:`Evaluate only one rule`}),d(q,{value:t.onlyRuleId,options:[{value:``,label:`— every enabled rule —`},...(S.data??[]).map(e=>({value:e.id,label:e.name}))],onChange:e=>y({onlyRuleId:e.target.value})}),t.onlyRuleId.length>0&&M===void 0&&n(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:[`Rule `,d(`code`,{children:t.onlyRuleId}),` is not in the current list — it may have been deleted. The run will find no candidate.`]})]})]}),_!==null&&d(`div`,{className:`rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger`,children:_}),n(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[d(`p`,{className:`min-w-0 flex-1 text-[10px] text-foreground-subtle`,children:`Nothing is persisted: no track, no event row, no stored media. Delivery is real.`}),n(I,{size:`sm`,type:`button`,disabled:j.isPending||!mm(t),onClick:()=>j.mutate(),children:[j.isPending?d(G,{className:`h-3.5 w-3.5 animate-spin`}):d(ce,{className:`h-3.5 w-3.5`}),`Inject event`]})]})]}),m&&d(`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.`}),c!==null&&d(Km,{result:c,targetName:e=>k.get(e)??e})]})}var Qm=e=>typeof e==`string`&&e.length>0;function $m(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 eh(e,t){return e.format.includes(t)?t:e.format[0]??`text`}function th(e,t){let n=[];for(let r of e.attachments.mediaTypes){if(n.length>=e.attachments.max)break;let i=t[r];Qm(i)&&n.push({mediaType:r,url:i})}return n}function nh(e,t){if(e.actions<=0)return[];let n=[];for(let r of t){if(n.length>=e.actions)break;let t=Qm(r.label),i=Qm(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 rh(e,t){let n=e.levels.some(e=>e.id===t.level)?t.level:void 0,r=th(e,t.attachmentUrls),i=nh(e,t.actions),a=e.ttl&&Qm(t.ttl)?Number(t.ttl):void 0;return{body:t.body,format:eh(e,t.format),priority:ih(t.priority),...Qm(t.title)?{title:t.title}:{},...n?{level:n}:{},...r.length>0?{attachments:r}:{},...i.length>0?{actions:i}:{},...e.clickUrl&&Qm(t.clickUrl)?{clickUrl:t.clickUrl}:{},...e.sound&&Qm(t.sound)?{sound:t.sound}:{},...a!==void 0&&Number.isFinite(a)?{ttl:a}:{},...Qm(t.tag)?{tag:t.tag}:{}}}function ih(e){return Number.isFinite(e)?Math.min(5,Math.max(1,Math.round(e))):3}function ah(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 oh(e){return{level:``,priority:3,format:e.format[0]??`text`,title:``,body:``,attachmentUrls:{},actions:[],clickUrl:``,sound:``,ttl:``,tag:``}}var sh={image:p(`/addon/notifiers/samples/image`),video:p(`/addon/notifiers/samples/video`),gif:p(`/addon/notifiers/samples/gif`),audio:p(`/addon/notifiers/samples/audio`),icon:p(`/addon/notifiers/samples/icon`)};function ch(e,t){return e.attachments.max>0&&e.attachments.mediaTypes.includes(t)}function lh(e){let t=[`text`];for(let n of[`image`,`gif`,`video`,`audio`])ch(e,n)&&t.push(n);return e.actions>0&&t.push(`actions`),e.levels.length>0&&t.push(`critical`),t.push(`overflow`),t}function uh(e,t,n){let r=oh(e);return ch(e,t)?{...r,body:n,attachmentUrls:{[t]:sh[t]}}:{...r,body:n}}function dh(e,t){let n=oh(e);switch(t){case`text`:return{...n,title:`CamStack`,body:`Test notification — text only.`};case`image`:return uh(e,`image`,`Test notification with an image.`);case`gif`:return uh(e,`gif`,`Test notification with an animation.`);case`video`:return uh(e,`video`,`Test notification with a video.`);case`audio`:return uh(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=ah(e);return{...n,title:`CamStack`,body:`Critical test notification.`,priority:5,level:t?.id??``}}case`overflow`:return{...n,body:`X`.repeat(e.bodyMaxLen+50)}}}t();var fh={text:`Text only`,image:`With image`,gif:`With GIF`,video:`With video`,audio:`With audio`,actions:`With buttons`,critical:`Critical`,overflow:`Overflow (advanced)`},ph=`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`,mh=`block text-[11px] font-medium text-foreground mb-1`;function hh({target:e,kind:t,open:i,onClose:a}){let o=h(),s=r(()=>$m(t.caps),[t.caps]),c=r(()=>lh(t.caps),[t.caps]),[f,p]=l(()=>oh(t.caps)),[m,g]=l(null),_=r(()=>rh(t.caps,f),[t.caps,f]),v=f.body.length,y=v>s.bodyMaxLen,b=e=>p(t=>({...t,...e})),x=u({mutationFn:()=>o.trpcClient.notificationOutput.testTarget.mutate({addonId:e.addonId,targetId:e.id,sample:rh(t.caps,f)}),onMutate:()=>g(null),onSuccess:e=>g(e),onError:e=>g({success:!1,error:e instanceof Error?e.message:`Test failed`})}),S=e=>{p(dh(t.caps,e)),g(null)},C=(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},b({actions:r})};return d(w,{open:i,onOpenChange:e=>!e&&a(),children:n(De,{width:`lg`,className:`!max-w-2xl`,scroll:`body`,children:[d(le,{children:n(pe,{children:[`Test "`,e.name,`" (`,t.label,`)`]})}),n(D,{className:`space-y-4 pr-1`,children:[d(`div`,{className:`flex flex-wrap gap-1.5`,children:c.map(e=>d(I,{size:`sm`,variant:`outline`,type:`button`,onClick:()=>S(e),children:fh[e]},e))}),n(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[s.levels.length>0&&n(`div`,{children:[d(`label`,{className:mh,children:`Level`}),n(`select`,{className:ph,value:f.level,onChange:e=>b({level:e.target.value}),children:[d(`option`,{value:``,children:`— derive from priority —`}),s.levels.map(e=>n(`option`,{value:e.id,children:[e.label,e.ordinal===null?` (qualitative)`:` (p${e.ordinal})`]},e.id))]}),(()=>{let e=s.levels.find(e=>e.id===f.level);return e?n(`div`,{className:`mt-1 space-y-1`,children:[e.description&&d(`p`,{className:`text-[10px] text-foreground-subtle`,children:e.description}),n(`div`,{className:`flex flex-wrap gap-1`,children:[e.flags?.critical&&d(U,{variant:`danger`,"data-testid":`flag-critical`,children:`critical`}),e.flags?.silent&&d(U,{variant:`info`,children:`silent`}),e.flags?.noPush&&d(U,{variant:`warning`,children:`no-push`})]}),e.requires&&e.requires.length>0&&n(`p`,{className:`text-[10px] text-warning`,children:[`Requires target config: `,e.requires.join(`, `)]})]}):null})()]}),n(`div`,{children:[n(`label`,{className:mh,children:[`Priority (ordinal): `,f.priority]}),d(`input`,{type:`range`,min:1,max:5,step:1,value:f.priority,onChange:e=>b({priority:Number(e.target.value)}),className:`w-full accent-primary`,"aria-label":`priority`})]})]}),s.formats.length>0&&n(`div`,{children:[d(`label`,{className:mh,children:`Format`}),d(`div`,{className:`flex flex-wrap gap-2`,children:s.formats.map(e=>n(`label`,{className:`flex items-center gap-1.5 text-xs text-foreground cursor-pointer`,children:[d(`input`,{type:`radio`,name:`format`,className:`accent-primary`,checked:f.format===e,onChange:()=>b({format:e})}),e]},e))})]}),n(`div`,{children:[d(`label`,{className:mh,children:`Title`}),d(`input`,{className:ph,value:f.title,onChange:e=>b({title:e.target.value})})]}),n(`div`,{children:[n(`label`,{className:mh,children:[`Body`,` `,n(`span`,{className:y?`text-danger`:`text-foreground-subtle`,children:[`(`,v,`/`,s.bodyMaxLen,y?` — overflow`:``,`)`]})]}),d(`textarea`,{className:`${ph} min-h-[80px] resize-y`,value:f.body,onChange:e=>b({body:e.target.value})})]}),s.attachmentSlots.length>0&&n(`div`,{children:[n(`label`,{className:mh,children:[`Attachments`,` `,n(`span`,{className:`text-foreground-subtle`,children:[`(mode: `,s.attachmentMode,`, max `,s.attachmentMax,s.attachmentMaxBytes?`, ≤${Math.round(s.attachmentMaxBytes/1024/1024)}MB`:``,`)`]})]}),d(`div`,{className:`space-y-1.5`,children:s.attachmentSlots.map(e=>n(`div`,{className:`flex items-center gap-2`,children:[d(`span`,{className:`text-[10px] w-12 shrink-0 text-foreground-subtle`,children:e}),d(`input`,{className:ph,placeholder:`${e} URL`,value:f.attachmentUrls[e]??``,onChange:t=>b({attachmentUrls:{...f.attachmentUrls,[e]:t.target.value}})})]},e))})]}),s.showActions&&n(`div`,{children:[n(`label`,{className:mh,children:[`Actions (up to `,s.maxActions,`)`]}),d(`div`,{className:`space-y-1.5`,children:Array.from({length:Math.min(s.maxActions,3)},(e,t)=>n(`div`,{className:`flex items-center gap-2`,children:[d(`input`,{className:ph,placeholder:`label`,value:f.actions[t]?.label??``,onChange:e=>C(t,`label`,e.target.value)}),d(`input`,{className:ph,placeholder:`url`,value:f.actions[t]?.url??``,onChange:e=>C(t,`url`,e.target.value)})]},t))})]}),n(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[s.showClickUrl&&n(`div`,{children:[d(`label`,{className:mh,children:`Click URL`}),d(`input`,{className:ph,value:f.clickUrl,onChange:e=>b({clickUrl:e.target.value})})]}),s.showSound&&n(`div`,{children:[d(`label`,{className:mh,children:`Sound`}),d(`input`,{className:ph,value:f.sound,onChange:e=>b({sound:e.target.value})})]}),s.showTtl&&n(`div`,{children:[d(`label`,{className:mh,children:`TTL (seconds)`}),d(`input`,{className:ph,type:`number`,value:f.ttl,onChange:e=>b({ttl:e.target.value})})]}),s.showTag&&n(`div`,{children:[d(`label`,{className:mh,children:`Tag`}),d(`input`,{className:ph,value:f.tag,onChange:e=>b({tag:e.target.value})})]})]}),m&&d(gh,{result:m}),n(`details`,{className:`text-[10px]`,children:[d(`summary`,{className:`cursor-pointer text-foreground-subtle`,children:`Payload preview`}),d(`pre`,{className:`mt-1 overflow-x-auto rounded bg-surface p-2 text-foreground-subtle`,children:JSON.stringify(_,null,2)})]})]}),n(de,{children:[d(I,{variant:`secondary`,size:`sm`,type:`button`,onClick:a,children:`Close`}),n(I,{size:`sm`,type:`button`,disabled:x.isPending||f.body.length===0,onClick:()=>x.mutate(),children:[x.isPending?d(G,{className:`h-3.5 w-3.5 animate-spin`}):d(Ie,{className:`h-3.5 w-3.5`}),`Send test`]})]})]})})}function gh({result:e}){let t=e.renderedAs;return n(`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:[n(`div`,{className:`flex items-center gap-2 font-medium`,children:[e.success?d(Oe,{className:`h-3.5 w-3.5 text-success`}):d(ye,{className:`h-3.5 w-3.5 text-danger`}),d(`span`,{children:e.success?`Delivered`:`Failed`})]}),e.error&&d(`p`,{className:`mt-1 text-danger`,children:e.error}),t&&n(`dl`,{className:`mt-2 grid grid-cols-2 gap-x-3 gap-y-0.5 text-[11px] text-foreground-subtle`,children:[d(`dt`,{children:`Resolved level`}),d(`dd`,{className:`text-foreground`,children:t.level}),d(`dt`,{children:`Format sent`}),d(`dd`,{className:`text-foreground`,children:t.format}),d(`dt`,{children:`Attachments sent`}),d(`dd`,{className:`text-foreground`,children:t.attachmentsSent}),d(`dt`,{children:`Actions sent`}),d(`dd`,{className:`text-foreground`,children:t.actionsSent}),d(`dt`,{children:`Truncated`}),d(`dd`,{className:`text-foreground`,children:t.truncated?`yes`:`no`}),d(`dt`,{children:`Dropped`}),d(`dd`,{className:`text-foreground`,children:t.dropped.length>0?t.dropped.join(`, `):`—`})]})]})}function _h(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 vh(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 yh(e){let t=new Map,n=e=>{for(let r of e)if(r.type===`group`)n(r.fields);else if(r.type===`sub-tabs`)for(let e of r.tabs)n(e.fields);else r.type!==`separator`&&t.set(r.key,r.label)};for(let t of e.sections)n(t.fields);return t}function bh(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 xh(e,t){let n=new Set(t),r={};for(let[t,i]of Object.entries(e))r[t]=n.has(t)?``:i;return r}var Sh=[`Refusing to reuse the stored secret`,`Re-enter the secret`];function Ch(e){return Sh.some(t=>e.includes(t))}function wh(e){return e==null||e===``?``:typeof e==`string`?e:JSON.stringify(e)}function Th(e,t,n){let r=new Set(n);return[...new Set([...Object.keys(e),...Object.keys(t)])].filter(n=>!r.has(n)&&wh(e[n])!==wh(t[n]))}function Eh(e,t,n,r){if(r===void 0)return Th(e,t,n);let i=new Set(n),a=bh(e,t,n);return r.filter(n=>i.has(n)?n in a:wh(e[n])!==wh(t[n]))}function Dh(e,t,n){let r=bh(e,t,n);return n.filter(e=>!(e in r))}function Oh(e,t){return e.map(e=>e.type===`password`&&t.has(e.key)?{...e,required:!0}:e.type===`group`?{...e,fields:Oh(e.fields,t)}:e.type===`sub-tabs`?{...e,tabs:e.tabs.map(e=>({...e,fields:Oh(e.fields,t)}))}:e)}function kh(e,t){if(t.length===0)return e;let n=new Set(t);return{...e,sections:e.sections.map(e=>({...e,fields:Oh(e.fields,n)}))}}function Ah({refusal:e,edited:t,reenter:r}){let i=r.length>0?`Re-type: ${r.join(`, `)}.`:null;return e===null?t.length===0||i===null?null:n(`p`,{className:`text-[11px] text-warning`,"data-testid":`target-secret-reenter`,children:[`You changed `,t.join(`, `),`. If that changes where this target sends, the hub will not reuse the stored secret. `,i]}):n(`div`,{className:`rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger`,"data-testid":`target-secret-refusal`,role:`alert`,children:[d(`p`,{className:`font-semibold`,children:`The hub needs the secret again — nothing was saved.`}),d(`p`,{className:`mt-1`,children:e}),i===null?null:d(`p`,{className:`mt-1 font-medium`,children:i})]})}t();var jh=[`notificationOutput`,`listTargets`],Mh=[`notificationOutput`,`listTargetKinds`],Nh=[`userManagement`,`listUsers`],Ph=`ownerUserId`;function Fh(e){let t=e.config[Ph];return typeof t==`string`&&t.length>0?t:null}function Ih(e){return[{key:`name`,header:`Target`,render:t=>{let r=e.kindByKey.get(t.kind);return n(`span`,{className:`flex items-center gap-2`,children:[d(`span`,{className:`flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-surface text-xs`,title:r?.label??t.kind,children:d(Lh,{kind:r,imgClassName:`h-5 w-5 object-contain`,fallbackClassName:``})}),d(`span`,{className:`truncate text-sm font-medium text-foreground`,children:t.name}),!t.enabled&&d(U,{variant:`warning`,children:`disabled`})]})}},{key:`kind`,header:`Kind`,nowrap:!0,render:t=>d(`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=Fh(t);return n===null?d(U,{variant:`default`,children:`system`}):d(`span`,{className:`text-[11px] text-foreground`,children:e.userNameById.get(n)??n})}},{key:`enabled`,header:`On`,align:`center`,nowrap:!0,render:t=>d(F,{checked:t.enabled,onCheckedChange:n=>e.onToggle(t,n),"aria-label":`toggle ${t.name}`})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:t=>{let r=e.kindByKey.get(t.kind);return n(`span`,{className:`flex items-center justify-end gap-1`,children:[d(I,{size:`sm`,variant:`ghost`,type:`button`,disabled:!r,onClick:()=>e.onTest(t),title:`Test`,children:d(Ie,{className:`h-3.5 w-3.5`})}),d(I,{size:`sm`,variant:`ghost`,type:`button`,disabled:!r,onClick:()=>r&&e.onEdit(t,r),title:`Edit`,children:d(ge,{className:`h-3.5 w-3.5`})}),d(I,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onDelete(t),title:`Delete`,children:d(_,{className:`h-3.5 w-3.5 text-danger`})})]})}}]}function Lh({kind:e,imgClassName:t,fallbackClassName:n}){return e?.iconUrl?d(`img`,{src:e.iconUrl,alt:e.label,className:t,loading:`lazy`,draggable:!1}):d(`span`,{className:n,children:e?.icon??`🔔`})}function Rh(){let e=h(),[t,a]=l({mode:`closed`}),[o,s]=l(null),c=i({queryKey:jh,queryFn:()=>e.trpcClient.notificationOutput.listTargets.query({})}),f=i({queryKey:Mh,queryFn:async()=>(await e.trpcClient.notificationOutput.listTargetKinds.query({})).map(e=>{let t=e.iconUrl;return{...e,configSchema:e.configSchema,iconUrl:t}})}),p=r(()=>f.data??[],[f.data]),m=r(()=>{let e=new Map;for(let t of p)e.set(t.kind,t);return e},[p]),g=i({queryKey:Nh,queryFn:()=>e.trpcClient.userManagement.listUsers.query()}),_=r(()=>{let e=new Map;for(let t of g.data??[])e.set(t.id,t.username);return e},[g.data]),v=u({mutationFn:t=>e.trpcClient.notificationOutput.setTargetEnabled.mutate({addonId:t.target.addonId,targetId:t.target.id,enabled:t.enabled}),onSuccess:()=>void c.refetch()}),y=u({mutationFn:t=>e.trpcClient.notificationOutput.deleteTarget.mutate({addonId:t.addonId,targetId:t.id}),onSuccess:()=>void c.refetch()}),b=o?m.get(o.kind):void 0;return n(nn,{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:n(I,{size:`sm`,type:`button`,onClick:()=>a({mode:`pick-kind`}),children:[d(W,{className:`h-3.5 w-3.5`}),`Add target`]}),children:[c.isLoading&&d(`div`,{className:`flex items-center justify-center py-16`,children:d(G,{className:`h-6 w-6 animate-spin text-primary`})}),c.isError&&!c.isLoading&&d(J,{title:`Failed to load targets`,message:c.error instanceof Error?c.error.message:`Unknown error`,onRetry:()=>void c.refetch()}),!c.isLoading&&!c.isError&&(c.data??[]).length===0&&d(`div`,{className:`text-xs text-foreground-subtle text-center py-16`,children:`No notification targets yet. Click "Add target" to configure one.`}),(c.data??[]).length>0&&d(H,{children:d(Pe,{columns:Ih({kindByKey:m,userNameById:_,onToggle:(e,t)=>v.mutate({target:e,enabled:t}),onTest:s,onEdit:(e,t)=>a({mode:`form`,kind:t,target:e}),onDelete:e=>y.mutate(e)}),rows:c.data??[],rowKey:e=>e.id,minWidthPx:720,bordered:!1,mobileMode:`scroll`,maxBodyHeight:`max-h-[60vh]`})}),t.mode===`pick-kind`&&d(zh,{kinds:p,onCancel:()=>a({mode:`closed`}),onPick:e=>a({mode:`form`,kind:e,target:null})}),t.mode===`form`&&d(Bh,{kind:t.kind,target:t.target,users:g.data??[],onCancel:()=>a({mode:`closed`}),onSaved:()=>{a({mode:`closed`}),c.refetch()}}),o&&b&&d(hh,{target:o,kind:b,open:!0,onClose:()=>s(null)})]})}function zh({kinds:e,onPick:t,onCancel:i}){let a=r(()=>_h(e),[e]);return n(H,{className:`p-4 space-y-4`,children:[n(`div`,{className:`flex items-center justify-between`,children:[d(`h3`,{className:`text-sm font-semibold text-foreground`,children:`Choose a notification kind`}),d(I,{size:`sm`,variant:`ghost`,type:`button`,onClick:i,children:`Cancel`})]}),a.length===0&&d(`p`,{className:`text-xs text-foreground-subtle`,children:`No notification providers are installed. Install the notifiers addon (or connect Home Assistant) to add targets.`}),a.map(e=>n(`div`,{children:[d(`div`,{className:`text-[10px] font-semibold uppercase tracking-wider text-foreground-subtle mb-1.5`,children:e.addonId}),d(`div`,{className:`grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-2`,children:e.kinds.map(r=>n(`button`,{type:`button`,onClick:()=>t(r),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:[d(Lh,{kind:r,imgClassName:`h-7 w-7 object-contain`,fallbackClassName:`text-lg leading-7`}),d(`span`,{className:`font-medium text-foreground`,children:r.label}),r.supportsDiscovery&&d(U,{variant:`info`,style:`outline`,children:`discover`})]},`${e.addonId}:${r.kind}`))})]},e.addonId))]})}function Bh({kind:e,target:t,users:i,onSaved:a,onCancel:o}){let s=h(),c=r(()=>vh(e.configSchema),[e.configSchema]),f=r(()=>t?.config??{},[t]),[p,m]=l(t?.name??e.label),[g,_]=l(()=>t?xh(t.config,c):{}),[v,y]=l(null),[b,x]=l(null),[S,C]=l(null),[w,T]=l(t?Fh(t)??``:``),E=u({mutationFn:()=>s.trpcClient.notificationOutput.discoverTargets.query({addonId:e.addonId,kind:e.kind,config:g}),onSuccess:e=>y(e),onError:e=>x(e instanceof Error?e.message:`Discovery failed`)}),D=u({mutationFn:()=>{let{[Ph]:n,...r}=bh(g,f,c),i=w===``?r:{...r,[Ph]:w},a={id:t?.id??`${e.kind}-${Date.now()}`,name:p,kind:e.kind,addonId:e.addonId,enabled:t?.enabled??!0,config:i};return s.trpcClient.notificationOutput.upsertTarget.mutate({addonId:e.addonId,target:a})},onSuccess:a,onError:e=>{let t=e instanceof Error?e.message:`Save failed`;Ch(t)?C(t):x(t)}}),O=r(()=>yh(e.configSchema),[e.configSchema]),k=r(()=>t===null?[]:Eh(g,f,c,e.destinationKeys),[t,g,f,c,e.destinationKeys]),A=r(()=>t!==null&&(S!==null||k.length>0)?Dh(g,f,c):[],[t,S,k,g,f,c]),j=r(()=>kh(e.configSchema,A),[e.configSchema,A]),ee=e=>O.get(e)??e,M=e=>{m(e.suggestedName),_(t=>({...t,...e.config})),y(null)};return n(H,{className:`p-4 space-y-4`,children:[n(`div`,{className:`flex items-center justify-between`,children:[n(`h3`,{className:`text-sm font-semibold text-foreground flex items-center gap-2`,children:[d(Lh,{kind:e,imgClassName:`h-5 w-5 object-contain`,fallbackClassName:`text-lg`}),t?`Edit ${t.name}`:`Add ${e.label} target`]}),d(I,{size:`sm`,variant:`ghost`,type:`button`,onClick:o,children:`Cancel`})]}),b&&d(`div`,{className:`rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger`,"data-testid":`target-form-error`,children:b}),n(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Name`}),d(`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:p,onChange:e=>m(e.target.value)})]}),n(`div`,{children:[d(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Owner`}),d(q,{value:w,options:[{value:``,label:`System (shared, admin-managed)`},...i.map(e=>({value:e.id,label:e.username}))],onChange:e=>T(e.target.value)}),d(`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&&n(`div`,{className:`space-y-2`,children:[n(I,{size:`sm`,variant:`outline`,type:`button`,disabled:E.isPending,onClick:()=>{x(null),E.mutate()},children:[E.isPending?d(G,{className:`h-3.5 w-3.5 animate-spin`}):d(Te,{className:`h-3.5 w-3.5`}),`Discover`]}),v&&v.length===0&&d(`p`,{className:`text-[11px] text-foreground-subtle`,children:`No candidates discovered.`}),v&&v.length>0&&d(`div`,{className:`rounded-md border border-border divide-y divide-border`,children:v.map((e,t)=>n(`button`,{type:`button`,onClick:()=>M(e),className:`flex w-full items-center justify-between px-3 py-1.5 text-xs hover:bg-surface-hover`,children:[d(`span`,{className:`text-foreground`,children:e.suggestedName}),d(`span`,{className:`text-[10px] text-primary`,children:`use`})]},`${e.suggestedName}-${t}`))})]}),c.length>0&&t&&d(`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.`}),d(Ah,{refusal:S,edited:k.map(ee),reenter:A.map(ee)}),d(K,{schema:j,values:g,onChange:_}),n(`div`,{className:`flex justify-end gap-2`,children:[d(I,{variant:`secondary`,size:`sm`,type:`button`,onClick:o,children:`Cancel`}),n(I,{size:`sm`,type:`button`,disabled:D.isPending||p.trim().length===0,onClick:()=>{x(null),C(null),D.mutate()},children:[D.isPending&&d(G,{className:`h-3.5 w-3.5 animate-spin`}),t?`Save changes`:`Create target`]})]})]})}t();var Vh=`notificationTexts`,Hh=`Every sentence the Notification Center can print — and your wording for it.`;function Uh({entry:e,value:t,busy:r,onChange:i,onReset:a}){let o=nd(e),s=e.override!==null;return n(`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:[n(`div`,{className:`flex items-center gap-2 flex-wrap`,children:[d(`code`,{className:`text-xs font-medium`,children:e.key}),s?d(U,{variant:`info`,children:`customised`}):null,e.source===`fallback`?d(U,{variant:`warning`,children:`English fallback`}):null]}),n(`div`,{className:`flex items-start gap-2`,children:[d(`div`,{className:`flex-1`,children:d(Qr,{label:``,value:t,onChange:i,vars:td(e),disabled:r,testId:`text-input-${e.key}`})}),d(I,{variant:`ghost`,size:`sm`,disabled:r||!s&&t===e.shipped,onClick:a,title:`Reset to the shipped wording`,"data-testid":`text-reset-${e.key}`,children:d(g,{className:`h-3.5 w-3.5`})})]}),n(`p`,{className:`text-xs text-foreground-subtle`,children:[d(`span`,{className:`font-medium`,children:`Shipped:`}),` `,d(`span`,{className:`font-mono`,children:e.shipped})]}),o===null?null:d(`p`,{className:`text-xs text-warning`,children:o})]})}function Wh(){let e=h(),t=s(),[a,o]=l(null),[c,f]=l(``),[p,m]=l(new Map),[g,_]=l(!1),v=i({queryKey:[Vh,a??`hub`],queryFn:async()=>{let t=Xu(await e.trpcClient.addons.custom.mutate({addonId:$,action:Vu,input:a===null?{}:{language:a}}));return _(t===null),t}}),y=()=>{m(new Map),t.invalidateQueries({queryKey:[Vh]})},b=u({mutationFn:t=>e.trpcClient.addons.custom.mutate({addonId:$,action:Hu,input:{language:t}}),onSuccess:y}),x=u({mutationFn:t=>e.trpcClient.addons.custom.mutate({addonId:$,action:Uu,input:t}),onSuccess:y}),S=v.data??null,C=r(()=>S===null?[]:ed(S.entries,c),[S,c]);if(v.isLoading)return d(nn,{icon:ln,title:`Texts`,subtitle:Hh,children:d(G,{className:`h-5 w-5 animate-spin`})});if(v.isError||S===null)return d(nn,{icon:ln,title:`Texts`,subtitle:Hh,children:d(J,{title:`The notification text catalog is not available on this hub`,message:g?`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=S.language,T=b.isPending||x.isPending,E=Qu(S.entries,p),D=$u(S.entries,p),O=S.entries.filter(e=>e.override!==null).length,k=S.languages.map(e=>({value:e,label:Wu[e]})),A=(e,t)=>m(n=>new Map(n).set(e,t)),j=e=>A(e.key,e.shipped);return d(nn,{icon:ln,title:`Texts`,subtitle:Hh,children:n(`div`,{className:`flex flex-col gap-4`,children:[b.isError?d(J,{title:`Could not change the language`,message:String(b.error)}):null,x.isError?d(J,{title:`Could not save`,message:String(x.error)}):null,n(H,{className:`p-4`,children:[n(`div`,{className:`flex flex-wrap items-end gap-6`,children:[n(`div`,{className:`flex flex-col gap-1`,children:[d(`label`,{className:`text-sm font-medium`,children:`Hub language`}),d(`div`,{className:`w-44`,children:d(q,{value:S.activeLanguage,disabled:T,options:k,onChange:e=>{let t=e.target.value;Gu(t)&&b.mutate(t)},"data-testid":`texts-hub-language`})}),d(`p`,{className:`text-xs text-foreground-subtle`,children:`Every notification is written in this language.`})]}),n(`div`,{className:`flex flex-col gap-1`,children:[d(`label`,{className:`text-sm font-medium`,children:`Editing`}),d(`div`,{className:`w-44`,children:d(q,{value:w,disabled:T,options:k,onChange:e=>{let t=e.target.value;Gu(t)&&(m(new Map),o(t))},"data-testid":`texts-editing-language`})}),d(`p`,{className:`text-xs text-foreground-subtle`,children:w===S.activeLanguage?`${O} of ${S.entries.length} texts customised.`:`This hub does not speak this language — these words are not in use yet.`})]})]}),d(`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.`})]}),n(`div`,{className:`flex flex-wrap items-center gap-3`,children:[n(`div`,{className:`relative min-w-[12rem] flex-1`,children:[d(Te,{className:`absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-foreground-muted`}),d(B,{value:c,placeholder:`Search a key or a sentence…`,onChange:e=>f(e.target.value),className:`pl-7`,"data-testid":`texts-search`})]}),n(`span`,{className:`text-xs text-foreground-subtle whitespace-nowrap`,children:[C.length,` of `,S.entries.length]}),n(I,{className:`ml-auto`,disabled:T||D===0,onClick:()=>x.mutate({language:w,overrides:E}),"data-testid":`texts-save`,children:[T?d(G,{className:`h-3.5 w-3.5 animate-spin`}):null,D===0?`Save`:`Save ${D}`]})]}),d(`div`,{className:`flex max-h-[60vh] flex-col gap-2 overflow-y-auto pr-1`,"data-testid":`texts-rows`,children:C.length===0?d(`p`,{className:`text-sm text-foreground-subtle`,children:`No text matches that search.`}):C.map(e=>d(Uh,{entry:e,value:Zu(e,p),busy:T,onChange:t=>A(e.key,t),onReset:()=>j(e)},e.key))})]})})}t();var Gh=`simulate`,Kh=`rules`;function qh(){let[e,t]=tn();return f(()=>{let n=e.get(`tab`);if(n===null||!gp(n))return;let r=new URLSearchParams(e);r.set(`tab`,Kh),r.set(`section`,n),t(r,{replace:!0})},[e,t]),d(`div`,{className:`flex flex-col p-4`,children:d(an,{tabs:[{id:`targets`,label:`Targets`,icon:ne,content:d(Rh,{})},{id:Kh,label:`Rules`,icon:x,content:d(Gp,{onSimulateRule:n=>{Dm(Tm(n));let r=new URLSearchParams(e);r.set(`tab`,Gh),t(r,{replace:!0})},onOpenHistory:n=>{t(Ti(e,n.id),{replace:!0})}}),ownedParams:[`section`,`rule`,`editTab`]},{id:`sequences`,label:`Sequences`,icon:un,content:d(am,{})},{id:Gh,label:`Simulate`,icon:ce,content:d(Zm,{})},{id:yi,label:`History`,icon:sn,content:d(Pi,{}),ownedParams:xi},{id:`alarm`,label:`Alarm`,icon:fe,content:d(_i,{})},{id:`texts`,label:`Texts`,icon:ln,content:d(Wh,{})}]})})}export{qh as NotificationsPage,qh as default};
|