@camstack/addon-admin-ui 1.2.320 → 1.2.325
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-CxXDirJC.js +1 -0
- package/dist/assets/Addons-yUjR3ne-.js +1 -0
- package/dist/assets/AdminTabs-BAM_VEcr.js +1 -0
- package/dist/assets/AiProfiles-DFt8Msz0.js +3 -0
- package/dist/assets/BrokerForm-DJ3qfWi2.js +1 -0
- package/dist/assets/Build-WoqeOLcT.js +40 -0
- package/dist/assets/{Calendars-B1_mLIVE.js → Calendars-xVXTf8RZ.js} +1 -1
- package/dist/assets/{Capabilities-VNPaMHq7.js → Capabilities-navCtLqG.js} +1 -1
- package/dist/assets/Cluster-BY1QM5Z2.js +11 -0
- package/dist/assets/CompositionEditor-I994CTE1.js +1 -0
- package/dist/assets/CompositionEditorPage-Cvw-au86.js +1 -0
- package/dist/assets/Data-ZLMpTx54.js +1 -0
- package/dist/assets/DetectionIntelligence-k4KVX3Uf.js +1 -0
- package/dist/assets/DeviceDetail-CqO4P4tT.js +2 -0
- package/dist/assets/DeviceDoActionFields-Dpj5IfHA.js +1 -0
- package/dist/assets/Devices-Ch7ANkBl.js +1 -0
- package/dist/assets/{EmbedPlayerPage-BGgzYptJ.js → EmbedPlayerPage-71VuS-Bb.js} +1 -1
- package/dist/assets/Events-BKJoiU2D.js +1 -0
- package/dist/assets/Identity-CiNMp8j1.js +1 -0
- package/dist/assets/IntegrationDetail-D43nbJRT.js +1 -0
- package/dist/assets/Integrations-D_DZgBSS.js +1 -0
- package/dist/assets/{Integrations-AXOsTawD.js → Integrations-G7_JMVno.js} +1 -1
- package/dist/assets/Locations-DQ9JzyGW.js +3 -0
- package/dist/assets/Logs-zT3fieFH.js +1 -0
- package/dist/assets/ModelLicenses-gTKgSLAN.js +1 -0
- package/dist/assets/{MotionZonesSettings-Ld-j-FOf.js → MotionZonesSettings-KM6kSbLo.js} +1 -1
- package/dist/assets/{MyAccess-DkAeD0Ir.js → MyAccess-Rrl2hM65.js} +1 -1
- package/dist/assets/Network-CPjvZo6T.js +1 -0
- package/dist/assets/NodeAddonsSettingsPanel-CCwfGq_E.js +1 -0
- package/dist/assets/{NodeInferenceDevices-DPflIBwk.js → NodeInferenceDevices-DzgwYV4u.js} +1 -1
- package/dist/assets/Notifications-pUbzRZix.js +1 -0
- package/dist/assets/Pipeline-BNeb9r9-.js +1 -0
- package/dist/assets/Plates-4Amk2xfY.js +1 -0
- package/dist/assets/{PrivacyMaskSettings-BZrLQhuR.js → PrivacyMaskSettings-CuPF3MaA.js} +1 -1
- package/dist/assets/Recordings-CO2jBj0N.js +1 -0
- package/dist/assets/ScanNetworkModal-kJrj8OJb.js +1 -0
- package/dist/assets/{SceneMonitorEditor-DArl0gdm.js → SceneMonitorEditor-CpUHyGR_.js} +1 -1
- package/dist/assets/{Scenes-DKjp5Iid.js → Scenes-CvLBgWoy.js} +1 -1
- package/dist/assets/{Settings-DmbFUzbw.js → Settings-QZKVIFMF.js} +1 -1
- package/dist/assets/Showroom-DcYPKtQJ.js +1 -0
- package/dist/assets/{StorageLocationsPanel-BSZbgwvo.js → StorageLocationsPanel-X-MRft-g.js} +1 -1
- package/dist/assets/{Terminal-CQwcJHRr.js → Terminal-s6Zu_1EM.js} +5 -5
- package/dist/assets/Viewer-DAQPh3zV.js +1 -0
- package/dist/assets/{_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-8eP7BPxU.js → _virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-BUHP4cOg.js} +1 -1
- package/dist/assets/{archive-bhxXcFdH.js → archive-BdrfT8Tm.js} +1 -1
- package/dist/assets/{authed-media-DoAWMi2a.js → authed-media-CRNsxF0o.js} +1 -1
- package/dist/assets/{boxes-j_W4wNc5.js → boxes-Cn405C00.js} +1 -1
- package/dist/assets/circle-slash-C8P2Biab.js +1 -0
- package/dist/assets/{debounced-invalidate-i8fFRjDI.js → debounced-invalidate-Dez2UBjF.js} +1 -1
- package/dist/assets/device-integration-icon-B5QgUAfP.js +1 -0
- package/dist/assets/device-picker-model-C2sF6CIo.js +1 -0
- package/dist/assets/dist-Bar-bGVd.js +349 -0
- package/dist/assets/{dist-CuhmUcM3.js → dist-CV-syViC.js} +1 -1
- package/dist/assets/{face-bbox-6mKTh5h_.js → face-bbox-CQK8LoSC.js} +1 -1
- package/dist/assets/{hard-drive-download-CfRqYj8Y.js → hard-drive-download-BE7uIvf-.js} +1 -1
- package/dist/assets/{hostInit-DK6L4JlB.js → hostInit-CG02F6uF.js} +1 -1
- package/dist/assets/index-BRONX8do.css +2 -0
- package/dist/assets/index-DFWOuEL5.js +4 -0
- package/dist/assets/{layers-QOUNNTM5.js → layers-6dQVJNN5.js} +1 -1
- package/dist/assets/location-owned-usage-DbA3r5FN.js +1 -0
- package/dist/assets/{mf-entry-bootstrap-0-a0da9d1e.js → mf-entry-bootstrap-0-66979c19.js} +2 -2
- package/dist/assets/mount-C2sF6CIo.js +1 -0
- package/dist/assets/notification-schedule-field-BK0G8TgA.js +1 -0
- package/dist/assets/{player-overlays-BiMOywnH.js → player-overlays-aOXZvSE_.js} +1 -1
- package/dist/assets/remoteEntry-CQ1SACyJ.js +1 -0
- package/dist/assets/{send-BJx_S3it.js → send-wsqOcYXe.js} +1 -1
- package/dist/assets/{settings-2-sRY7papp.js → settings-2-CFEBspgz.js} +1 -1
- package/dist/assets/{square-check-big-DIDWLK6q.js → square-check-big-DWTXdL5u.js} +1 -1
- package/dist/assets/src-Cq9_wgDT.js +349 -0
- package/dist/assets/src-DP92R2_g.js +67 -0
- package/dist/assets/{use-scenes-feed-Cc_D9YMA.js → use-scenes-feed-CTIPfYEG.js} +1 -1
- package/dist/assets/{use-stationary-objects-BK-lZxz5.js → use-stationary-objects-Bok446Um.js} +1 -1
- package/dist/assets/useEventInvalidation-C2sF6CIo.js +1 -0
- package/dist/assets/{useNodeUrlSelection-DEofbZPd.js → useNodeUrlSelection-D912mZ5j.js} +1 -1
- package/dist/assets/useTranslation-Bc5yH9V9.js +1 -0
- package/dist/assets/user-round-BLAmXvb7.js +1 -0
- package/dist/assets/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-Bw8wYSqx.js → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_--fCbD2Tp.js} +2 -2
- package/dist/index.html +9 -6
- package/dist/server/addon.js +88 -5
- package/package.json +1 -1
- package/dist/assets/AddonCollectionPage-5nQd-fl7.js +0 -1
- package/dist/assets/Addons-nH13f52s.js +0 -1
- package/dist/assets/AdminTabs-ya1bCNSO.js +0 -1
- package/dist/assets/AiProfiles-BMleMmAA.js +0 -3
- package/dist/assets/BrokerForm-DHZ8hUlp.js +0 -1
- package/dist/assets/Build-CD7-IGea.js +0 -375
- package/dist/assets/CapabilityBadges-D54okPp4.js +0 -1
- package/dist/assets/Cluster-C9Odf0CH.js +0 -11
- package/dist/assets/CompositionEditor-LVv358x7.js +0 -1
- package/dist/assets/CompositionEditorPage-C1WliWGd.js +0 -1
- package/dist/assets/Data-hilVqnUh.js +0 -1
- package/dist/assets/DetectionIntelligence-yqs4-_p5.js +0 -1
- package/dist/assets/DeviceAggregateSection-WJZBDahv.js +0 -1
- package/dist/assets/DeviceDetail-BChiwD-w.js +0 -2
- package/dist/assets/DeviceDoActionFields-DzNdsRac.js +0 -1
- package/dist/assets/Devices-4YZ9Sf8I.js +0 -1
- package/dist/assets/Events-tVjjBxsP.js +0 -1
- package/dist/assets/FormBuilder-Mm2KUHj_.js +0 -1
- package/dist/assets/Identity-8eGv_R6C.js +0 -1
- package/dist/assets/IntegrationDetail-3Pyar-gL.js +0 -1
- package/dist/assets/Integrations-4v0L4iRd.js +0 -1
- package/dist/assets/Locations-BbGnTY6L.js +0 -3
- package/dist/assets/Logs-Bu8iqW5z.js +0 -1
- package/dist/assets/ModelLicenses-UdDC7tYP.js +0 -1
- package/dist/assets/Network-DrjDUX_p.js +0 -1
- package/dist/assets/NodeAddonsSettingsPanel-aN5DSImk.js +0 -1
- package/dist/assets/Notifications-DnWt27Kz.js +0 -1
- package/dist/assets/Pipeline-DRDZgfL-.js +0 -1
- package/dist/assets/Plates-ZWQhgQK-.js +0 -1
- package/dist/assets/ProviderIcon-ChyLY-K8.js +0 -1
- package/dist/assets/Recordings-ECXZUa6a.js +0 -1
- package/dist/assets/ScanNetworkModal-DaVszVsh.js +0 -1
- package/dist/assets/SchemaTabBar-Bvm8GY8a.js +0 -1
- package/dist/assets/Showroom-CfI9H0xt.js +0 -1
- package/dist/assets/StableTabPanel-Dc954AQl.js +0 -1
- package/dist/assets/Viewer-Cp1t9JAa.js +0 -1
- package/dist/assets/circle-slash-B992-uTX.js +0 -1
- package/dist/assets/device-integration-icon-C0LvIHA1.js +0 -1
- package/dist/assets/device-picker-model-Bx-MZkA4.js +0 -1
- package/dist/assets/dist-CKSjSzEl.js +0 -349
- package/dist/assets/index-BBheY5o3.css +0 -2
- package/dist/assets/index-j5fkiwRk.js +0 -4
- package/dist/assets/location-owned-usage-CTvGcaad.js +0 -1
- package/dist/assets/remoteEntry-BpoD5TCl.js +0 -1
- package/dist/assets/src-BMvSPnxA.js +0 -349
- package/dist/assets/src-D5VbJHEA.js +0 -67
- package/dist/assets/useDevice-UWeOTc-3.js +0 -1
- package/dist/assets/useEventInvalidation-Bx-MZkA4.js +0 -1
- package/dist/assets/user-round-CCoCiRZv.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,o,p as s,q as c,t as l,x as u,z as d}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 f,_t as p,at as m,lt as h,st as g,yt as _}from"./player-overlays-aOXZvSE_.js";import{Co as v,Dd as y,Ed as b,Fn as x,Ft as S,Gn as C,Gt as w,Hn as T,Il as E,In as D,It as O,Kt as k,Ku as A,Ln as j,Lu as M,Mn as N,Mu as P,Nt as ee,Pt as F,Q as te,Qr as I,Qt as L,Td as ne,To as R,Tt as re,Un as ie,Vn as z,Wi as ae,Wn as oe,Wu as se,Xt as B,Yt as ce,Zt as le,_ as ue,au as de,bl as fe,bn as V,bo as pe,d as me,en as H,eu as he,f as U,fu as ge,g as _e,h as ve,hn as W,j as ye,ln as be,m as xe,md as G,p as K,pd as Se,pu as Ce,qt as we,rd as Te,v as Ee,vn as q,vu as J,wt as De,xn as Y,xo as Oe,y as ke,z as Ae}from"./src-DP92R2_g.js";import{t as je}from"./send-wsqOcYXe.js";import{$ as Me,A as Ne,C as Pe,D as Fe,E as Ie,F as Le,G as Re,H as ze,J as Be,Jn as Ve,K as He,L as Ue,M as We,N as Ge,Pt as Ke,S as qe,T as Je,V as Ye,W as Xe,X as Ze,b as Qe,c as $e,dn as et,f as tt,g as nt,j as rt,l as it,m as at,mn as ot,nt as st,p as ct,q as lt,rt as ut,u as dt,w as ft,z as pt}from"./src-Cq9_wgDT.js";import{D as mt,M as ht,O as gt,v as _t,y as vt}from"./__vite-browser-external-Cc3gW-QT.js";import{t as yt}from"./useTranslation-Bc5yH9V9.js";import"./mount-C2sF6CIo.js";import{$ as bt,$t as xt,A as St,At as Ct,B as wt,Bt as Tt,C as Et,Ct as Dt,D as Ot,Dt as kt,E as At,Et as jt,F as Mt,Ft as Nt,G as Pt,Gt as Ft,H as It,Ht as Lt,I as Rt,It as zt,J as Bt,Jt as Vt,K as Ht,Kt as Ut,L as Wt,Lt as Gt,M as Kt,Mt as qt,N as Jt,Nt as Yt,O as Xt,Ot as Zt,P as Qt,Pt as $t,Q as en,Qt as tn,R as nn,Rt as rn,S as an,St as on,T as sn,Tt as cn,U as ln,Ut as un,V as dn,Vt as fn,W as pn,Wt as mn,X as hn,Xt as gn,Y as _n,Yt as vn,Z as yn,Zt as bn,_ as xn,_n as Sn,_t as Cn,a as wn,an as Tn,at as En,b as Dn,bt as On,c as kn,cn as An,ct as jn,d as Mn,dn as Nn,dt as Pn,en as Fn,et as In,f as X,fn as Ln,ft as Rn,g as zn,gn as Bn,gt as Vn,h as Hn,hn as Un,ht as Wn,i as Gn,in as Kn,it as qn,j as Jn,jt as Yn,k as Xn,kt as Zn,l as Qn,ln as $n,lt as er,m as tr,mn as nr,mt as rr,n as ir,nn as ar,nt as or,o as sr,on as cr,ot as lr,p as ur,pn as dr,pt as fr,q as pr,qt as mr,r as hr,rn as gr,rt as _r,s as vr,sn as yr,st as br,t as xr,tn as Sr,tt as Cr,u as wr,un as Tr,ut as Er,v as Dr,vn as Or,vt as kr,w as Ar,wt as jr,x as Mr,xt as Nr,y as Pr,yn as Fr,yt as Ir,z as Lr,zt as Rr}from"./notification-schedule-field-BK0G8TgA.js";import{F as zr,M as Br,l as Vr}from"./index-DFWOuEL5.js";import{t as Hr}from"./AdminPage-CiKtOLQm.js";import{t as Ur}from"./DeviceDoActionFields-Dpj5IfHA.js";import"./device-picker-model-C2sF6CIo.js";import{t as Wr}from"./AdminTabs-BAM_VEcr.js";import{t as Gr}from"./use-scenes-feed-CTIPfYEG.js";var Kr=_(`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`}]]),qr=_(`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`}]]),Jr=_(`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`}]]),Yr=_(`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 Xr=[`contact`,`cover`,`lock-control`,`switch`];function Zr(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 Qr(e){let t=new Set(Zr(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 $r(e){return e.ids.length>0||e.unresolved?null:`no-opening`}function ei(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=>_e([e],r,t)[0];return{nameOf:e=>{let t=a(e);return i(e)??(t===void 0?`Device #${String(e)}`:xe(t))},isRemoved:e=>i(e)===null&&a(e)?.removed===!0}}function ti(e){let t=e.name.trim();return t===``?`Device #${String(e.deviceId)}`:t}function ni(e){return e===0?`Not armed — the hub refused without naming an open device.`:`Not armed — these are open:`}var ri={home:`Home`,away:`Away`,night:`Night`};function ii(e){return ri[e]??e}function ai(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 oi(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 — ${ui(e.ruleCount,`rule`)} with no device scope.`:e.deviceIds.length===0?`${ui(e.ruleCount,`rule`)}, no device restriction.`:e.deviceIds.map(t).join(`, `)}function si(e,t){if(e.length===0)return``;let n=e.map(e=>`${t(e.deviceId)} (${ci[e.reason]})`);return`${e.length} excluded: ${n.join(`, `)}`}var ci={muted:`notifications muted`,"detection-off":`detection off`,offline:`offline`};function li(e){return e.ruleCount===0}function ui(e,t){return e===1?`1 ${t}`:`${e} ${t}s`}function di(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 fi=2e3,pi=15e3,mi=new Set([`arming`,`pending`,`triggered`]);function hi(e){return e!==void 0&&mi.has(e)?fi:pi}var gi={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 _i(e){let t=gi[e.state];return e.state===`disarmed`||e.targetMode===null?t:`${t} — ${ii(e.targetMode)}`}function vi(e){return e!==`disarmed`}function yi(e){return e===`open`?`ignored until it closes`:`closed — monitored at next open`}function bi(e,t){return(e.nonBlocking??[]).find(e=>e.mode===t)?.deviceIds??[]}function xi(e,t){return(e.blocking??[]).find(e=>e.mode===t)?.deviceIds??[]}function Si(e,t){return(e.secureOnArmOff??[]).find(e=>e.mode===t)?.deviceIds??[]}function Ci(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 wi(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 Ti(e,t,n,r){let i=Ci(e,t,n);return r==="default"?i===void 0?null:wi(t,n,null):i===r?null:wi(t,n,r)}var Ei=[`unknown-refusal`,`stale`,`expired`,`used`];function Di(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Oi(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(!Di(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 ki(e){if(!Di(e))return null;let t=e.outcome;if(t===`armed`||t===`arming`){let n=Oi(e.excluded);return n===null?null:{outcome:t,excluded:n}}if(t===`refused`){let n=Oi(e.blocking),r=e.refusalId;return n===null||typeof r!=`string`||r===``?null:{outcome:t,refusalId:r,blocking:n}}if(t===`rejected`){let n=Ei.find(t=>t===e.reason);return n===void 0?null:{outcome:t,reason:n}}return null}var Ai={"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 ji(e){return Ai[e]}var Mi=`pipeline-analytics`,Ni=`The hub answered something this build cannot read — refresh after updating.`;function Pi(e){return e instanceof Error?e.message:String(e)}function Fi(e){return e.map(e=>`${ti(e)} (${e.state})`).join(`, `)}function Ii({live:e,onChanged:t}){let r=m(),[i,a]=c(null),[o,s]=c(null),[d,f]=c(null),p=(e,t)=>r.trpcClient.addons.custom.mutate({addonId:Mi,action:e,input:t}),h=e=>{if(e===null){s(Ni);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: ${ji(e.reason)}.`);return}let t=e.outcome===`armed`?`Armed`:`Arming`;f(e.excluded.length===0?`${t}.`:`${t} — excluded: ${Fi(e.excluded)}.`)},g=()=>{s(null),f(null)},_=l({mutationFn:async e=>ki(await p(`nc.armAlarm`,{mode:e})),onMutate:g,onSuccess:h,onError:e=>s(Pi(e)),onSettled:t}),v=l({mutationFn:async e=>ki(await p(`nc.armAlarmAnyway`,{refusalId:e})),onMutate:g,onSuccess:h,onError:e=>s(Pi(e)),onSettled:t}),y=l({mutationFn:async()=>p(`nc.disarmAlarm`,{}),onMutate:()=>{g(),a(null)},onSuccess:()=>f(`Disarmed.`),onError:e=>s(Pi(e)),onSettled:t});if(e===void 0)return n(W,{className:`p-4`,children:[u(`h3`,{className:`text-sm font-semibold mb-1`,children:`Panel`}),u(`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(W,{className:`p-4`,children:[n(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[n(`div`,{children:[u(`h3`,{className:`text-sm font-semibold`,children:`Panel`}),u(`p`,{className:`text-lg font-medium`,"data-testid":`alarm-state`,children:_i(e)})]}),n(`div`,{className:`flex flex-wrap items-center gap-2`,children:[b?u(P,{className:`h-4 w-4 animate-spin`}):null,e.availableModes.map(e=>n(Y,{type:`button`,size:`md`,variant:`outline`,disabled:b,onClick:()=>_.mutate(e),"data-testid":`alarm-arm-${e}`,children:[`Arm `,ii(e)]},e)),u(Y,{type:`button`,size:`md`,variant:vi(e.state)?`danger`:`secondary`,disabled:b,onClick:()=>y.mutate(),"data-testid":`alarm-disarm`,children:`Disarm`})]})]}),o===null?null:u(`div`,{className:`mt-3`,children:u(q,{title:`The panel did not do that`,message:o})}),d===null?null:u(`p`,{className:`mt-3 text-sm text-foreground-subtle`,children:d}),i===null?null:n(`div`,{className:`mt-3 rounded border border-warning p-3`,"data-testid":`alarm-refused`,children:[u(`p`,{className:`text-sm font-medium`,children:ni(i.blocking.length)}),i.blocking.length>0?u(`ul`,{className:`mt-1 list-disc pl-5 text-sm`,children:i.blocking.map(e=>n(`li`,{children:[ti(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:[u(Y,{type:`button`,size:`md`,variant:`danger`,disabled:b,onClick:()=>v.mutate(i.refusalId),children:`Arm anyway`}),u(`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:[u(`h4`,{className:`text-xs font-semibold uppercase text-foreground-subtle`,children:`Excluded sensors`}),e.exclusions.length===0?u(`p`,{className:`text-sm text-foreground-subtle`,children:`No sensor is excluded.`}):u(`ul`,{className:`mt-1 flex flex-col gap-1 text-sm`,children:e.exclusions.map(e=>n(`li`,{children:[ti(e),` —`,` `,u(`span`,{className:`text-foreground-subtle`,children:yi(e.phase)})]},e.deviceId))})]})]})}t();var Li=[{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:et,zeroMeans:`until disarmed`}];function Ri(e){return`Enter a whole number of seconds from 0 to ${e}.`}function zi(e,t){let n=e.trim();return`${n===``?`Nothing was entered, so nothing was saved`:`${n} was not saved`} — ${Ri(t)}`}function Bi({label:e,value:t,max:r,zeroMeans:i,disabled:a,testId:o,hint:s,adornment:l,onCommit:d}){let[f,p]=c(null),[m,h]=c(null),g=f??String(t),_=f!==null&&f.trim()!==``&&di(f,r)===null,v=ai(t,i),y=()=>{let e=f===null?null:di(f,r);p(null),e===null?f!==null&&h(f):(h(null),d(e))};return n(ye,{label:e,...s===void 0?{}:{description:s},..._?{error:Ri(r)}:m===null?{}:{error:zi(m,r)},children:[n(`div`,{className:`flex items-center gap-2`,children:[u(H,{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}),u(`span`,{className:`text-xs text-foreground-subtle`,children:`s`}),l]}),v===`${t} s`?null:u(`span`,{className:`text-[10px] text-foreground-subtle`,children:v})]})}function Vi(e,t){let n=e?.trim()??``;if(n===``)return``;if(t.state===`answered`){let e=ke(n),r=t.zones.find(t=>t.locationKeys.includes(e));if(r!==void 0)return`${r.label} · ${n}`}return n}function Hi(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 Ui=`Not checked by this mode — switch on to remove the entry`;function Wi(e){return e.listedUncovered?{word:`No`,note:Ui}:Gi(e.coverage)}function Gi(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 Ki(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 qi(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 Ji({name:e,variant:t,words:r}){return n(`span`,{"data-testid":`alarm-cell-${e}`,className:`flex flex-col items-start gap-0.5`,children:[u(z,{variant:t,"data-testid":`alarm-cell-${e}-badge`,children:r.word}),r.note===null?null:u(`span`,{className:`text-[10px] text-foreground-subtle`,"data-testid":`alarm-cell-${e}-note`,children:r.note})]})}var Yi=`hidden sm:table-cell`;function Xi(e){let{mode:t,inFlight:r,onSwitch:i,zones:a,disabled:o}=e;return[{key:`name`,header:`Name`,cell:e=>{let t=Vi(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:[u(`span`,{className:`truncate text-xs font-medium text-foreground`,children:e.device.name}),t===``?null:u(`span`,{className:`truncate text-[10px] text-foreground-subtle`,"data-testid":`alarm-cell-zone`,children:t})]})}},{key:`type`,header:`Type`,headerClassName:Yi,cellClassName:`${Yi} text-[11px] text-foreground-subtle`,cell:e=>Ee(e.device.type??null)},{key:`state`,header:`State`,cell:e=>u(Ji,{name:`state`,variant:Ki(e.cell),words:Hi(e.cell)})},{key:`coverage`,header:`Checked when arming`,headerClassName:Yi,cellClassName:Yi,cell:e=>u(Ji,{name:`coverage`,variant:qi(e),words:Wi(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?u(P,{className:`h-3 w-3 animate-spin`}):null,u(L,{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:u(`span`,{title:`Close, lock, or turn off when this mode arms`,children:`Secure on arm`}),headerClassName:`text-right`,cellClassName:`text-right`,cell:e=>{if(!e.controllable)return u(`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?u(P,{className:`h-3 w-3 animate-spin`}):null,u(L,{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 (close/lock/off): ${e.device.name}`,title:`Close, lock, or turn off when this mode arms`,"aria-busy":a?!0:void 0,"aria-disabled":s?!0:void 0,className:s?`opacity-50`:void 0})]})}}]}function Zi(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:[u(`span`,{children:`Could not read the sensor states.`}),u(Y,{type:`button`,size:`sm`,variant:`outline`,onClick:i,children:`Retry`})]}),u(Ae,{mode:`generic`,items:r,getKey:e=>String(e.device.id),getSearchText:e=>[e.device.name,Vi(e.device.location,a),Ee(e.device.type??null)].join(` `),getFilterType:e=>Ee(e.device.type??null),columns:Xi(e),rowClassName:e=>e.listedUncovered?`opacity-60`:``,searchPlaceholder:`Search sensors`,emptyLabel:`No sensor matches.`})]})}var Qi=[/has no (?:handler for )?custom action ["']nc\.getAlarmSensors["']/,/No "query"-procedure on path "notificationRules\.getAlarmSensors"/,/method 'getAlarmSensors' not found on provider 'notification-rules'/];function $i(e){return Qi.some(t=>t.test(e))}function ea(e,t,n){if(n)return{kind:`removed`};if(e.status===`pending`)return{kind:`checking`};if(e.status===`failed`)return $i(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 ta(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 na(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 ra(e){return e.kind===`unscoped`||e.kind===`not-covered`}function ia(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=na(e.coverage,r.id),a=ta(e.sensors,r.id,t,r.type),o=We({controllable:a,deviceId:r.id,nonBlocking:e.nonBlocking,blocking:e.blocking}),s=Ge({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&&ra(i)&&(!o||c)&&c;!t&&ra(i)&&!c||n.push({device:r,removed:t,cell:ea(e.sensors,r.id,t),coverage:i,controllable:a,blocks:o,secureOnArm:s,listedUncovered:l})}return n}function aa(e){return e.rowCount>0?`rows`:e.candidatesComplete?`none`:`pending`}function oa(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 sa(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 ca(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 la(e,t){return Ne(ca(e),t)?{kind:`landed`}:{kind:`not-landed`}}function ua({coverage:e,rows:t,names:r}){let i=t.filter(e=>e.coverage.kind.startsWith(`arm-checked`)).length,a=oi(e,r.nameOf);return n(`div`,{className:`flex flex-wrap items-center gap-1.5`,"data-testid":`alarm-badges-${e.mode}`,children:[li(e)?u(z,{variant:`warning`,title:a,"data-testid":`alarm-arms-nothing`,children:`Arms nothing — no enabled rule is gated on this mode`}):n(z,{variant:`default`,title:a,"data-testid":`alarm-covers`,children:[`Checks `,i,` `,i===1?`sensor`:`sensors`]}),e.skippedDevices.length>0?n(z,{variant:`warning`,title:si(e.skippedDevices,r.nameOf),"data-testid":`alarm-skipped`,children:[e.skippedDevices.length,` not notified`]}):null]})}function da(e){return e.status===`answered`?e.openingIds:null}function fa({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:[u(P,{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,`).`]}),u(Y,{type:`button`,size:`sm`,variant:`outline`,onClick:e.retry,children:`Retry`})]}):null:null}function pa({coverage:e,settings:t,disabled:n,onDelayEdit:r}){let i=e.mode,a=rt(t,i);return u(`div`,{className:`grid grid-cols-3 gap-3`,"data-testid":`alarm-delays-${i}`,children:Li.map(e=>{let o=a.source[e.field]==="default";return u(Bi,{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?u(z,{variant:`default`,title:`Uses the system default (${t[e.field]} s)`,children:`Default`}):u(Y,{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:u(h,{className:`h-3.5 w-3.5`})})},e.field)})})}var ma={"no-opening":`This household has no contact, cover or lock.`};function ha({coverage:e,live:t,settings:r,names:i,openingsCheck:a,rows:o,sensorsRetry:s,inFlight:c,onSwitch:l,zones:d,onDelayEdit:f,disabled:p}){let m=Qr({live:t,listed:bi(r,e.mode),openingIds:da(a)}),h=$r(m),g=aa({rowCount:o.length,candidatesComplete:!m.unresolved});return n(`div`,{className:`flex flex-col gap-3`,"data-mode":e.mode,"data-empty":li(e)?`true`:`false`,children:[u(ua,{coverage:e,rows:o,names:i}),u(pa,{coverage:e,settings:r,disabled:p,onDelayEdit:f}),u(`p`,{className:`text-[10px] text-foreground-subtle`,"data-testid":`alarm-delays-hint`,children:`Blank fields use the system defaults (exit 30 s, entry 20 s, siren until cleared).`}),n(`div`,{className:`flex flex-col gap-2`,"data-testid":`alarm-nonblocking-${e.mode}`,children:[u(fa,{check:a,view:m}),h===null?null:u(`p`,{className:`text-xs text-foreground-subtle`,children:ma[h]}),g===`none`&&h===null?u(`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`?u(Zi,{mode:e.mode,rows:o,sensorsRetry:s,inFlight:c,onSwitch:l,zones:d,disabled:p}):null]})]})}t();function ga({profiles:e,busy:t,onActivate:r,onCreate:i,onClone:o,onRename:s,onDelete:l}){let[d,f]=c(``),[p,m]=c(!1),h=e.items.find(t=>t.id===e.activeId)??e.items[0],_=h!==void 0&&!h.isDefault,v=d.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:[u(`label`,{className:`text-xs font-medium text-foreground-muted`,htmlFor:`alarm-profile-select`,children:`Profile`}),u(`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))}),_?u(Y,{type:`button`,variant:`ghost`,size:`sm`,disabled:t,"data-testid":`alarm-profile-delete`,title:`Delete this profile`,onClick:()=>{h!==void 0&&l(h.id)},children:u(g,{className:`h-3.5 w-3.5`})}):null]}),n(`div`,{className:`flex flex-wrap items-center gap-2`,children:[u(H,{className:`h-8 max-w-[14rem]`,"data-testid":`alarm-profile-name`,placeholder:p?`New name`:`New profile name`,value:d,disabled:t,onChange:e=>f(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(p?x():y())}}),p?n(a,{children:[u(Y,{type:`button`,size:`sm`,disabled:t||v.length===0,"data-testid":`alarm-profile-rename-save`,onClick:x,children:`Rename`}),u(Y,{type:`button`,variant:`ghost`,size:`sm`,disabled:t,"data-testid":`alarm-profile-rename-cancel`,onClick:()=>{m(!1),f(``)},children:`Cancel`})]}):n(a,{children:[n(Y,{type:`button`,size:`sm`,disabled:t||v.length===0,"data-testid":`alarm-profile-create`,title:`Create with system defaults`,onClick:y,children:[u(J,{className:`mr-1 h-3.5 w-3.5`}),`Create`]}),n(Y,{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:[u(Te,{className:`mr-1 h-3.5 w-3.5`}),`Clone`]}),u(Y,{type:`button`,size:`sm`,variant:`ghost`,disabled:t||h===void 0,"data-testid":`alarm-profile-rename`,onClick:()=>{m(!0),f(h?.name??``)},children:`Rename`})]})]}),u(`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.`})]})}t();var _a=[`notificationRules`,`getAlarmConfig`],va=[`notificationRules`,`getAlarmSensors`],ya=[`deviceManager`,`listDeviceIdsByCaps`,`alarm-openings`],ba=6e4;function xa(e){return e instanceof Error?e.message:String(e)}function Sa({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,` (`,ii(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,`, `,ii(e.write.mode),`).`]});case`failed`:return u(`p`,{className:`text-xs text-danger`,role:`alert`,"data-testid":`alarm-switch-failed`,children:`Could not change ${e.write.name} for ${ii(e.write.mode)}: ${e.error}`})}}function Ca(){let t=m(),a=o(),d=i({queryKey:_a,queryFn:async()=>t.trpcClient.notificationRules.getAlarmConfig.query({}),refetchInterval:e=>hi(e.state.data?.live?.state)}),f=ae({projection:`slim`}),[p,h]=c(!1),g=l({mutationFn:e=>t.trpcClient.notificationRules.setAlarmConfig.mutate({patch:e}),onSuccess:(e,t)=>{a.setQueryData(_a,e),h(!Ne(t,e.settings))}}),_=l({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(_a,e),h(!1)}}),v=()=>a.invalidateQueries({queryKey:_a}),y=r(()=>{let e=new Map;for(let t of f.data??[])e.set(t.id,t.name);return e},[f.data]),b=d.data?.live,x=i({queryKey:ya,staleTime:ba,queryFn:async()=>new Set(await t.trpcClient.deviceManager.listDeviceIdsByCaps.query({capNames:[...Xr]}))}),C=r(()=>(f.data??[]).map(e=>({id:e.id,name:e.name,type:String(e.type),location:e.location??null})),[f.data]),w=r(()=>new Map(C.map(e=>[e.id,e])),[C]),T=x.isError?{status:`failed`,error:x.error instanceof Error?x.error.message:String(x.error),retry:()=>void x.refetch()}:x.data===void 0?{status:`pending`}:{status:`answered`,openingIds:x.data},E=r(()=>{let e=new Map;for(let t of b?.openings??[])for(let n of t.devices)e.set(n.deviceId,ti(n));return ei(y,ve(f),e)},[b,y,f]),D=ue(!0),[k,A]=c(null),j=r(()=>{let e=new Map,t=d.data;if(t===void 0)return e;for(let n of t.coverage)e.set(n.mode,Qr({live:t.live,listed:bi(t.settings,n.mode),openingIds:x.data??null}).ids);return e},[d.data,x.data]),M=r(()=>{let e=new Set;for(let t of j.values())for(let n of t)E.isRemoved(n)||e.add(n);return[...e].toSorted((e,t)=>e-t)},[j,E]),N=i({queryKey:[...va,M],enabled:M.length>0,placeholderData:s,refetchOnWindowFocus:!0,refetchInterval:e=>e.state.error!==null&&$i(xa(e.state.error))?!1:b!==void 0&&vi(b.state)?5e3:15e3,retry:(e,t)=>!$i(xa(t))&&e<2,queryFn:async()=>{let e=[];for(let n of oa(M,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=N.isError?{status:`failed`,error:xa(N.error)}:N.data===void 0?{status:`pending`}:{status:`answered`,sensors:N.data.sensors},te=e(null),[I,L]=c(null),[ne,R]=c(null),re=async e=>{try{let n=await t.trpcClient.notificationRules.setAlarmConfig.mutate({patch:ca(e)});la(e,n.settings).kind===`landed`?a.setQueryData(_a,n):(R({kind:`not-landed`,write:e}),a.invalidateQueries({queryKey:_a}))}catch(t){R({kind:`failed`,write:e,error:xa(t)}),a.invalidateQueries({queryKey:_a})}finally{te.current=null,L(null),R(e=>e?.kind===`refused`?null:e)}},ie=(e,t,n,r)=>{let i=sa(te.current,e,t,n,r);if(i.kind===`refused`){R({kind:`refused`,inFlight:i.inFlight});return}te.current=i.write,L(i.write),R(null),re(i.write)};if(d.isLoading)return u(Hr,{icon:he,title:`Alarm`,subtitle:`Panel delays and mode coverage.`,children:u(P,{className:`h-5 w-5 animate-spin`})});let z=d.data;if(z===void 0||d.isError)return u(Hr,{icon:he,title:`Alarm`,subtitle:`Panel delays and mode coverage.`,children:u(q,{title:`Alarm settings are not available`,message:`This hub has not been updated to serve the alarm configuration yet.`})});if(z.deviceId===null)return u(Hr,{icon:he,title:`Alarm`,subtitle:`Panel delays and mode coverage.`,children:u(W,{className:`p-4`,children:u(`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 oe=z.settings,se=g.isPending||_.isPending,B=e=>{h(!1),g.mutate(e)},ce=(e,t,n)=>{let r=Ti(oe,e,t,n);r!==null&&B({modeDelays:[r]})},le=new Map(z.coverage.map(e=>[e.mode,ia({candidates:(j.get(e.mode)??[]).map(e=>({...w.get(e),id:e,name:E.nameOf(e)})),removedIds:new Set((j.get(e.mode)??[]).filter(E.isRemoved)),coverage:e,nonBlocking:bi(oe,e.mode),blocking:xi(oe,e.mode),secureOnArmOff:Si(oe,e.mode),sensors:F})])),de=z.coverage.find(e=>e.mode===k)??z.coverage.find(e=>(le.get(e.mode)?.length??0)>0)??z.coverage[0],fe=de?.mode??``;return n(Hr,{icon:he,title:`Alarm`,subtitle:`The panel, what each mode arms, and who hears about it.`,children:[g.isError?u(q,{title:`Could not save`,message:String(g.error)}):null,_.isError?u(q,{title:`Could not update profile`,message:String(_.error)}):null,p?u(`div`,{"data-testid":`alarm-save-not-landed`,children:u(q,{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,z.profiles===void 0?null:u(ga,{profiles:z.profiles,busy:se,onActivate:e=>_.mutate({kind:`activate`,id:e}),onCreate:e=>_.mutate({kind:`create`,name:e}),onClone:(e,t)=>_.mutate({kind:`clone`,fromId:e,name:t}),onRename:(e,t)=>_.mutate({kind:`rename`,id:e,name:t}),onDelete:e=>_.mutate({kind:`delete`,id:e})}),u(Ii,{live:z.live,onChanged:v}),n(W,{className:`p-4`,"data-testid":`alarm-coverage`,children:[u(ee,{value:fe,onValueChange:e=>{let t=z.coverage.find(t=>t.mode===e);t!==void 0&&A(t.mode)},children:u(S,{className:`mb-3`,children:z.coverage.map(e=>n(O,{value:e.mode,"data-testid":`alarm-tab-${e.mode}`,children:[ii(e.mode),u(`span`,{className:`ml-1.5 text-[10px] text-foreground-subtle`,children:le.get(e.mode)?.length??0})]},e.mode))})}),ne===null?null:u(Sa,{notice:ne}),de===void 0?null:u(ha,{coverage:de,live:z.live,settings:oe,names:E,openingsCheck:T,rows:le.get(de.mode)??[],sensorsRetry:F.status===`failed`&&!$i(F.error)?()=>void N.refetch():null,inFlight:I,onSwitch:(e,t,n)=>ie(de.mode,e,t,n),zones:D,onDelayEdit:(e,t)=>ce(de.mode,e,t),disabled:se},de.mode)]})]})}var wa=`history`,Ta=`ruleId`,Ea=[Ta],Da=24,Oa=0,ka=100;function Aa(e,t){let n=new URLSearchParams(e);return n.set(`tab`,wa),n.set(Ta,t),n}function ja(e,t){let n=new URLSearchParams(e);return t===``?n.delete(Ta):n.set(Ta,t),n}function Ma(e){let t=e.get(`ruleId`)??``;return{ruleId:t,deviceId:``,status:``,windowHours:t===``?Da:Oa,limit:ka}}function Na(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 Pa=[{value:1,label:`Last hour`},{value:24,label:`Last 24 hours`},{value:168,label:`Last 7 days`},{value:0,label:`All time`}],Fa=[{value:``,label:`Any status`},{value:`pending`,label:`Pending`},{value:`sent`,label:`Sent`},{value:`dead`,label:`Dead`}],Ia=[50,100,250,500];function La(e){return e===`pending`||e===`sent`||e===`dead`?e:void 0}function Ra(e){switch(e){case`pending`:return`info`;case`sent`:return`success`;case`dead`:return`danger`}}function za(){let e=m(),[t,a]=zr(),[o,s]=c(()=>Ma(t)),l=e=>s(t=>({...t,...e})),d=e=>{l({ruleId:e}),a(ja(t,e),{replace:!0})},f=i({queryKey:[`notificationRules`,`listRules`,`forHistory`],queryFn:async()=>(await e.trpcClient.notificationRules.listRules.query({})).rules}),p=ae({projection:`slim`}),h=Date.now(),g=i({queryKey:[`notificationRules`,`getHistory`,o],retry:!1,queryFn:async()=>{let t=o.windowHours>0?h-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)}:{},...La(o.status)?{status:La(o.status)}:{},...t===void 0?{}:{since:t}}})).entries}}),_=r(()=>{let e=new Map;for(let t of p.data??[])t.type===Ve.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(Hr,{icon:Kr,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:[u(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:`Rule`}),u(V,{"data-testid":`history-rule-filter`,value:o.ruleId,onChange:e=>d(e.target.value),options:[...Na({rules:f.data??[],answered:f.isSuccess,selected:o.ruleId})]})]}),n(`div`,{children:[u(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:`Camera`}),u(V,{value:o.deviceId,onChange:e=>l({deviceId:e.target.value}),options:[{value:``,label:`All cameras`},...(p.data??[]).map(e=>({value:String(e.id),label:e.name}))]})]}),n(`div`,{children:[u(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:`Status`}),u(V,{value:o.status,onChange:e=>l({status:e.target.value}),options:Fa.map(e=>({value:e.value,label:e.label}))})]}),n(`div`,{children:[u(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:`Window`}),u(V,{value:String(o.windowHours),onChange:e=>l({windowHours:Number(e.target.value)}),options:Pa.map(e=>({value:String(e.value),label:e.label}))})]}),n(`div`,{children:[u(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:`Limit`}),u(V,{value:String(o.limit),onChange:e=>l({limit:Number(e.target.value)}),options:Ia.map(e=>({value:String(e),label:String(e)}))})]})]}),g.isLoading&&u(`div`,{className:`flex items-center justify-center py-16`,children:u(P,{className:`h-6 w-6 animate-spin text-primary`})}),b&&!g.isLoading&&u(W,{children:n(`div`,{className:`flex flex-col items-center gap-2 px-4 py-14 text-center`,children:[u(Kr,{className:`h-6 w-6 text-foreground-subtle`}),u(`div`,{className:`text-sm font-medium text-foreground`,children:`Delivery history requires a server update`}),u(`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:[u(ge,{className:`h-3 w-3`}),` Retry`]})]})}),!b&&!g.isLoading&&y.length===0&&u(`div`,{className:`py-16 text-center text-xs text-foreground-subtle`,children:`No deliveries match these filters.`}),!b&&y.length>0&&u(W,{children:u(De,{columns:Ba(v),rows:y,rowKey:e=>e.id,minWidthPx:720,bordered:!1,mobileMode:`scroll`,maxBodyHeight:`max-h-[60vh]`})})]})}function Ba(e){return[{key:`when`,header:`When`,nowrap:!0,render:e=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:new Date(e.createdAt).toLocaleString()})},{key:`rule`,header:`Rule`,render:e=>u(`span`,{className:`text-xs font-medium text-foreground`,children:e.ruleName})},{key:`camera`,header:`Camera`,nowrap:!0,render:t=>u(`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:[u(z,{variant:Ra(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?u(`span`,{className:`text-[11px] text-danger`,children:e.error}):u(`span`,{className:`text-[11px] text-foreground-subtle`,children:`—`})}]}var Va=/\{\{\s*(\w+)\s*\}\}/g,Ha=[`subject`,`place`,`time`,`rule`,`occupancy`,`sound`,`sensor`,`system`,`digest`,`ai`];function Ua(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 Wa(e){let t=`{{${e.name}}}`;return{text:t,cursorOffset:e.dynamic?t.length-2:t.length}}function Ga(e){return[...e.matchAll(Va)].map(e=>e[1]??``).filter(e=>e.length>0)}function Ka(e,t){return t.some(t=>t.dynamic?e.startsWith(t.dynamic.prefix)&&e.length>t.dynamic.prefix.length:t.name===e)}function qa(e,t){return[...new Set(Ga(e))].filter(e=>!Ka(e,t))}var Ja={previewText:[`camera`,`rule`,`from`,`to`],captionText:[`rule`,`from`,`to`]};function Ya(e){return e.map(e=>{let t=Pe.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)||qe.includes(e)),i=n.filter(e=>!r.includes(e));return{...e,systemEventKinds:[...r,...i]}})}function Xa(e){let t=new Set(e.map(e=>e.name)),n=Pe.filter(e=>ft(e)&&!t.has(e.name));return[...e,...n]}function Za(e,t){if(t.field===`previewText`||t.field===`captionText`){let n=Ja[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)||!Ie(e.kinds,t.kind)||e.deliveries&&t.delivery!==void 0&&!e.deliveries.includes(t.delivery)?!1:Fe(e,t)&&Je(e,t))}function Qa(e){return Ha.map(t=>({group:t,vars:e.filter(e=>e.group===t)})).filter(e=>e.vars.length>0)}var $a=[`nc`,`template-catalog`],eo=400;function to(){let e=m();return i({queryKey:$a,staleTime:5*6e4,queryFn:async()=>Xa(Ya((await e.trpcClient.notificationRules.getTemplateCatalog.query({})).vars))})}function no(e,t,n){let r=m(),a=te(t.title??``,eo),o=te(t.body??``,eo);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 ro={subject:`Subject`,place:`Place`,time:`Time`,rule:`Rule`,occupancy:`Occupancy`,sound:`Sound`,sensor:`Sensor`,system:`System event`,digest:`Digest`,ai:`AI`},io=`block text-[11px] font-medium text-foreground mb-1`,ao=`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 oo({label:t,value:r,onChange:i,vars:a,multiline:o=!1,placeholder:s,disabled:c=!1,testId:l}){let d=e(null),f=e(null),p=a?qa(r,a):[],m=e=>{let t=o?f.current:d.current,n={start:t?.selectionStart??r.length,end:t?.selectionEnd??r.length},a=Wa(e),s=Ua(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:[u(`label`,{className:io,children:t}),o?u(`textarea`,{ref:f,value:r,rows:2,disabled:c,placeholder:s,onChange:h,className:ao,"data-testid":`${l}-input`}):u(H,{ref:d,value:r,disabled:c,placeholder:s,onChange:h,"data-testid":`${l}-input`}),a&&a.length===0?u(`p`,{className:`text-[10px] text-foreground-subtle`,children:`No variables for this field.`}):null,a&&a.length>0?u(`div`,{className:`flex flex-wrap gap-x-3 gap-y-1`,children:Qa(a).map(e=>n(`div`,{className:`flex flex-wrap items-center gap-1`,"data-testid":`${l}-group-${e.group}`,children:[u(`span`,{className:`text-[10px] uppercase text-foreground-subtle`,children:ro[e.group]}),e.vars.map(e=>u(`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:[u(E,{className:`h-3 w-3`}),p.map(e=>`{{${e}}}`).join(` `),` will be empty in this notification.`]}):null]})}function so({context:e,title:t,body:r,testId:i}){let a=no(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:[u(`p`,{className:`text-[10px] uppercase text-foreground-subtle`,children:`Preview (example values)`}),a.data.title===null?null:u(`p`,{className:`font-medium`,children:a.data.title}),a.data.body===null?null:u(`p`,{className:`whitespace-pre-wrap`,children:a.data.body})]}):null}var co=`mt-1 w-full rounded border border-border bg-background px-2 py-1 text-xs`,lo=`block text-[11px] font-medium text-foreground`;function uo({title:e,description:t,children:r}){return n(`div`,{className:`flex flex-col gap-2`,children:[n(`div`,{children:[u(`h4`,{className:`text-xs font-semibold text-foreground`,children:e}),u(`p`,{className:`text-[11px] text-foreground-subtle`,children:t})]}),r!==void 0&&u(`div`,{className:`flex flex-wrap items-center gap-1`,children:r})]})}function fo({value:e,onChange:t,devices:r,devicesState:i,sequences:a=[],onCreateSequence:o}){let s=bt(e,new Set(a.map(e=>e.id))),c=en(r),l=(n,r)=>t({...e,[n]:r}),d=(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&&u(`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=>u(`p`,{children:e.message},e.message))}),c.length>0&&o!==void 0&&u(`section`,{className:`space-y-2`,children:u(uo,{title:`Quick add`,description:`Creates a shared sequence and binds it to On trigger.`,children:c.map(r=>n(Y,{size:`sm`,variant:`ghost`,type:`button`,title:r.hint,className:`min-w-0 max-w-full`,onClick:()=>{(async()=>{let n=r.build();t(In(e,await o({name:n.name,...n.minDelaySec===void 0?{}:{minDelaySec:n.minDelaySec},actions:[...n.actions]})))})()},children:[u(fe,{className:`h-3.5 w-3.5 shrink-0`}),u(`span`,{className:`truncate`,children:r.label})]},r.id))})}),Pt.map(t=>u(po,{hookKey:t,bindings:e[t],sequences:a,devices:r,devicesState:i,onChange:e=>l(t,e)},t)),n(`section`,{className:`space-y-2`,children:[u(uo,{title:`Buttons on the notification`,description:`Each button runs one shared sequence when tapped.`,children:n(Y,{size:`sm`,variant:`ghost`,type:`button`,disabled:a.length===0,onClick:()=>t({...e,buttons:[...e.buttons,Bt(e.buttons.length,a[0]?.id??``)]}),children:[u(J,{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:[u(E,{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 `,u(`strong`,{children:`once`}),`, within 15 minutes.`]})]}),a.length===0?u(`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?u(`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)=>u(go,{button:n,sequences:a,onChange:e=>d(r,e),onRemove:()=>t({...e,buttons:e.buttons.filter((e,t)=>t!==r)})},`btn-${String(r)}`))]})]})}function po({hookKey:e,bindings:t,sequences:r,devices:i,devicesState:a,onChange:o}){let s=Ht[e];return n(`section`,{className:`space-y-2`,children:[n(uo,{title:s.title,description:s.hint,children:[n(Y,{size:`sm`,variant:`ghost`,type:`button`,disabled:t.length>=4||r.length===0,onClick:()=>o([...t,hn(r[0]?.id??``)]),children:[u(J,{className:`h-3.5 w-3.5`}),` Sequence`]}),n(Y,{size:`sm`,variant:`ghost`,type:`button`,disabled:t.length>=4,onClick:()=>o([...t,_n()]),children:[u(J,{className:`h-3.5 w-3.5`}),` Single action`]})]}),t.length===0?u(`p`,{className:`rounded border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:`Nothing on this edge.`}):t.map((n,s)=>u(mo,{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 mo({binding:e,sequences:t,devices:r,devicesState:i,onChange:a,onRemove:o}){return u(`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:[u(`label`,{className:lo,children:`Kind`}),n(`select`,{className:co,value:e.kind,onChange:e=>a(e.target.value===`sequence`?hn(t[0]?.id??``):_n()),children:[u(`option`,{value:`sequence`,children:`Sequence`}),u(`option`,{value:`do`,children:`Single action`})]})]}),e.kind===`sequence`?n(`div`,{className:`min-w-0 flex-1`,children:[u(`label`,{className:lo,children:`Sequence`}),u(`select`,{className:co,value:e.sequenceId,onChange:e=>a({kind:`sequence`,sequenceId:e.target.value}),children:t.map(e=>u(`option`,{value:e.id,children:e.name},e.id))})]}):u(ho,{action:e.action,devices:r,devicesState:i,onChange:e=>a({kind:`do`,action:e})}),u(Y,{size:`sm`,variant:`ghost`,type:`button`,onClick:o,title:`Remove`,children:u(g,{className:`h-3.5 w-3.5`})})]})})}function ho({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:[u(`label`,{className:lo,children:`Step`}),n(`select`,{className:co,value:e.kind,onChange:e=>i(e.target.value===`wait`?{kind:`wait`,seconds:5}:{kind:`cap`,deviceId:t[0]?.id??0,cap:``,method:``}),children:[u(`option`,{value:`cap`,children:`Do`}),u(`option`,{value:`wait`,children:`Wait`})]})]}),e.kind===`wait`?n(`div`,{className:`w-28`,children:[u(`label`,{className:lo,children:`Seconds`}),u(`input`,{type:`number`,min:0,max:300,className:co,value:e.seconds,onChange:e=>i({kind:`wait`,seconds:Number(e.target.value)})})]}):u(Ur,{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 go({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:[u(`label`,{className:lo,children:`Id`}),u(H,{className:`mt-1`,value:e.id,onChange:t=>r({...e,id:t.target.value})})]}),n(`div`,{className:`min-w-0 flex-1`,children:[u(`label`,{className:lo,children:`Label`}),u(H,{className:`mt-1`,value:e.label,onChange:t=>r({...e,label:t.target.value})})]}),n(`div`,{className:`min-w-0 flex-1`,children:[u(`label`,{className:lo,children:`Sequence`}),u(`select`,{className:co,value:e.sequenceId,onChange:t=>r({...e,sequenceId:t.target.value}),children:t.map(e=>u(`option`,{value:e.id,children:e.name},e.id))})]}),n(`div`,{className:`w-32`,children:[u(`label`,{className:lo,children:`Icon`}),n(`select`,{className:co,value:e.icon??``,onChange:t=>{let n={...e};t.target.value===``?delete n.icon:n.icon=t.target.value,r(n)},children:[u(`option`,{value:``,children:`—`}),pn.map(e=>u(`option`,{value:e.value,children:e.label},e.value))]})]}),u(Y,{size:`sm`,variant:`ghost`,type:`button`,onClick:i,title:`Remove`,children:u(g,{className:`h-3.5 w-3.5`})})]})}var _o=new Set([`devices`,`devicesExclude`,`customZones`,`source`,`crossing`]),vo=[[`classes`,`classesExclude`],[`zones`,`zonesExclude`],[`identities`,`identitiesExclude`]],yo={minConfidence:`class`},bo=[{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 xo(e){let t=new Set(e.map(e=>e.id)),n=new Set;for(let[e,r]of vo)t.has(e)&&n.add(r);return n}function So(e){return yo[e.id]??e.group}function Co(e){let t=e.replace(/[-_]/g,` `);return t.charAt(0).toUpperCase()+t.slice(1)}function wo(e){let t=xo(e),n=e.filter(e=>!_o.has(e.id)&&!t.has(e.id)),r=new Set(bo.map(e=>e.id)),i=[],a=e=>n.filter(t=>So(t)===e);for(let e of bo){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=So(e);!r.has(t)&&!o.includes(t)&&o.push(t)}for(let e of o)i.push({id:e,label:Co(e),descriptors:a(e)});return i}function To(e,t){switch(e){case`zones`:return En(t.zones?.ids,t.zonesExclude);case`labels`:return En(t.labelEquals,void 0);case`identities`:return Eo(t)}}function Eo(e){let t=e.identities,n=[...e.identitiesExclude??[]];return t===void 0?En(void 0,n):{mode:`only`,include:[...t],exclude:n,legacyBoth:n.length>0}}function Do(e,t,n){switch(e){case`zones`:return Oo(t,n);case`labels`:return ko(t,n);case`identities`:return Ao(t,n)}}function Oo(e,t){let{zones:n,zonesExclude:r,...i}=e,a=or(t);return{...i,...a.include===void 0?{}:{zones:{ids:[...a.include]}},...a.exclude===void 0?{}:{zonesExclude:[...a.exclude]}}}function ko(e,t){let{labelEquals:n,...r}=e,i=or(t);return{...r,...i.include===void 0?{}:{labelEquals:[...i.include]}}}function Ao(e,t){let{identities:n,identitiesExclude:r,...i}=e;if(t.mode===`only`){let e=lr(t);return{...i,identities:[...t.include],...e.length>0?{identitiesExclude:[...e]}:{}}}let a=or(t);return{...i,...a.exclude===void 0?{}:{identitiesExclude:[...a.exclude]}}}var jo={all:`All`,only:`Only these`,except:`All except these`},Mo={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 No({draft:e,onChange:t,exceptOffered:r,plural:i,renderPicker:a,describe:o,testId:s}){let{t:c}=yt(),l=(e,t,n)=>c(e,{items:n,defaultValue:t}).replaceAll(`{{items}}`,n),d=c(`ruleScope.items.${i}`,Mo[i].items),f=Cr.filter(t=>t!==`except`||r||e.mode===`except`),p=lr(e),m=qn(e),h=e.mode===`all`?null:e.mode;return n(`div`,{className:`mt-1 space-y-1.5`,"data-testid":s,children:[u(`div`,{role:`radiogroup`,"aria-label":l(`ruleScope.which`,`Which {{items}}`,d),className:`inline-flex flex-wrap items-center gap-1`,children:f.map(n=>{let r=n===e.mode;return u(`button`,{type:`button`,role:`radio`,"aria-checked":r,"data-testid":`scope-mode-${n}`,onClick:()=>t(er(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}`,jo[n])},n)})}),h===null?u(`p`,{className:`text-[11px] text-foreground-subtle`,children:c(`ruleScope.every.${i}`,Mo[i].every)}):a(br(e),n=>t(jn(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(`, `)),` `,u(`button`,{type:`button`,className:`underline hover:no-underline`,onClick:()=>t(_r(e)),children:c(`ruleScope.removeExclusions`,`Remove exclusions`)})]}),m.length>0&&u(`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 Po(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 Fo(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 Io(e,t,n){let[r,i]=c(()=>To(e,t));return[r,r=>{i(r),n(Do(e,t,r))}]}function Lo(e,t){return t?`failed`:e?`pending`:`answered`}function Ro({conditions:e,onConditionsChange:t,exceptOffered:n,cameraIds:i,cameras:a}){let{t:o}=yt(),[s,c]=Io(`zones`,e,t),{options:l,loading:d,failed:f}=gr(i,a),p=r(()=>Fo(l),[l]),m=Lo(d,!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 u(No,{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?u(`p`,{className:Mn,children:o(`notificationRules.zones.noCameras`,`This rule covers no camera, so it has no zones.`)}):u(U,{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 zo({conditions:e,onConditionsChange:t,exceptOffered:n}){let{t:i}=yt(),[a,o]=Io(`identities`,e,t),{options:s,loading:c,failed:l}=ar(),d=r(()=>s.map(e=>({id:e.value,name:e.label})),[s]),f=r(()=>new Map(d.map(e=>[e.id,e.name])),[d]);return u(No,{draft:a,onChange:o,exceptOffered:n,plural:`faces`,describe:e=>f.get(e)??e,testId:`rule-identity-scope`,renderPicker:(e,t,n)=>u(U,{devices:d,listState:Lo(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 Bo({conditions:e,onConditionsChange:t}){let{t:n}=yt(),[r,i]=Io(`labels`,e,t);return u(No,{draft:r,onChange:i,exceptOffered:!1,plural:`labels`,describe:e=>e,testId:`rule-label-scope`,renderPicker:(e,t)=>u(xn,{value:e,placeholder:n(`notificationRules.labels.add`,`Add a label…`),onChange:t})})}function Vo(e){let t=ut(e);return t===null?null:t.groups.flatMap(e=>e.options.map(t=>({id:t.value,name:t.label,type:e.fallbackLabel})))}function Ho(e){return e.type??`Other`}t();function Uo({taxonomy:e,scope:t,onChange:n,exceptOffered:i}){let a=r(()=>Vo(e),[e]),o=r(()=>new Map((a??[]).map(e=>[e.id,e.name])),[a]);return u(No,{draft:t,onChange:n,exceptOffered:i,plural:`classes`,describe:e=>o.get(e)??e,testId:`rule-class-scope`,renderPicker:(e,t,n)=>a===null?u(xn,{value:e,placeholder:`Add value…`,onChange:t}):u(U,{devices:a,listState:`answered`,value:e,onChange:t,emptyMeansAll:!0,noun:`class`,groupTitle:Ho,testId:`class-picker`},n)})}function Wo(e){return{id:e.id,name:e.name,type:e.type,location:e.location,...e.parentName===void 0?{}:{detail:e.parentName}}}function Go({devices:e,value:t,onChange:n,listState:r,savedHadDevices:i}){return u(U,{devices:e.map(Wo),listState:r,value:t,onChange:n,emptyMeansAll:!0,savedHadDevices:i,noun:`device`,showAll:!0})}function Ko({devices:e,scope:t,onChange:n,listState:r,savedScope:i,exceptOffered:a}){let o=new Map(e.map(e=>[e.id,e.name]));return u(No,{draft:t,onChange:n,exceptOffered:a,plural:`devices`,describe:e=>o.get(e)??`Device #${String(e)}`,testId:`rule-device-scope`,renderPicker:(t,n,a)=>u(Go,{devices:e,value:t,onChange:n,listState:r,savedHadDevices:(a===`only`?i.include:i.exclude).length>0},a)})}function qo(e){return e.data===void 0?e.isError?`failed`:`pending`:`answered`}function Jo(e,t){return t===`answered`?e?.complete===!0?`answered`:`failed`:t}function Yo(e){let t=qo(e),n=e.data===void 0?[]:tt(e.data.nodes),r=Jo(e.data,t);return{items:n,listState:t,fleet:{state:r,devices:r===`answered`?n:void 0}}}function Xo(e){let t=qo(e),n=e.data===void 0?[]:ct(e.data);return{items:n,listState:t,fleet:{state:t,devices:t===`answered`?n:void 0}}}var Zo=[`nc-pickers`,`node-directory`],Qo=[`nc-pickers`,`package-list`],$o=6e4,es={hub:`Hub`,agent:`Agents`},ts={server:`Server`,framework:`Framework`,wrapper:`Wrapper`,addon:`Addons`};function ns(e){let t=es[e.type??``]??`Nodes`;return e.location===`offline`?`${t} · offline`:t}function rs(e){return ts[e.type??``]??`Packages`}function is({value:e,onChange:t,testId:r}){let a=m().trpcClient,o=i({queryKey:Zo,staleTime:$o,queryFn:()=>a.nodes.directory.query()}),s=Yo(o);return n(`div`,{children:[u(U,{devices:s.items,listState:s.listState,fleet:s.fleet,value:e,onChange:t,emptyMeansAll:!0,noun:`node`,groupTitle:ns,...r===void 0?{}:{testId:r}}),o.data?.complete===!1&&u(`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 as({value:e,onChange:t,testId:n}){let r=m().trpcClient,a=Xo(i({queryKey:Qo,staleTime:$o,queryFn:()=>r.addons.listPackages.query()}));return u(U,{devices:a.items,listState:a.listState,fleet:a.fleet,value:e,onChange:t,emptyMeansAll:!0,noun:`package`,groupTitle:rs,...n===void 0?{}:{testId:n}})}var os={context:{family:`rule`,field:`body`,kind:`device-events`,systemEventKinds:[`device-tank-low`]},template:{body:`{{deviceName}}`}};function ss(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 cs(e,t){return e===`pending`?`pending`:e===`success`?`current`:ss(t)===`BAD_REQUEST`?`outdated`:`unknown`}function ls(e){let t=m(),n=i({queryKey:[`nc`,`hub-rule-schema-probe`],enabled:e,staleTime:5*6e4,retry:!1,queryFn:()=>t.trpcClient.notificationRules.previewTemplate.mutate(os)});return e?cs(n.status,n.error):`pending`}t();var us=`/system/settings`,ds=`/system/notifications?tab=alarm`,fs=`text-primary underline-offset-2 hover:underline`;function ps(e,t){let n=or(t);return rr(e,{deviceIds:n.include,excludeDeviceIds:n.exclude})}function ms({family:e,value:t,cameras:i,allDevices:a,fleet:o,savedHadDevices:s,onChange:l}){let d=r(()=>t?.kinds??[],[t]),f=r(()=>a===void 0?i:a.map(Wo),[a,i]),p=r(()=>i.map(e=>({id:e.id,name:e.name,type:`camera`})),[i]),m=Cn(e,d),h=ls(e===`device-events`),g=e===`alarm`,[_,v]=c(()=>En(t?.deviceIds,t?.excludeDeviceIds)),[y]=c(()=>En(t?.deviceIds,t?.excludeDeviceIds)),b=r(()=>{let e=new Map;for(let t of g?p:f)e.set(t.id,t.name);return e},[p,g,f]);return n(`div`,{className:`mt-1 space-y-3`,"data-testid":`system-event-field`,children:[kr(e).map(r=>n(`div`,{children:[u(`div`,{className:`text-[10px] font-semibold uppercase tracking-wide text-foreground-subtle`,children:r.label}),u(`div`,{className:`mt-1 flex flex-wrap gap-1.5`,children:r.kinds.map(n=>{let r=d.includes(n.value);return u(`button`,{type:`button`,role:`checkbox`,"aria-checked":r,"aria-label":n.label,onClick:()=>l(On(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)})})]},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):`,` `,u(Br,{to:us,target:`_blank`,rel:`noreferrer`,className:fs,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:[u(Br,{to:ds,target:`_blank`,rel:`noreferrer`,className:fs,children:`Alarm settings`}),d.includes(`alarm-triggered`)&&` — when a rule sets the alarm off, this notification carries that rule's pictures.`]}),h===`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.`]}),h===`unknown`&&u(`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.`}),m.consumableThreshold&&n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground`,htmlFor:`system-event-consumable-threshold`,children:`Consumable low at (%)`}),u(H,{id:`system-event-consumable-threshold`,"data-testid":`system-event-consumable-threshold`,type:`number`,min:1,max:Er,step:1,placeholder:`15`,value:t?.consumableLowPercent??``,className:`mt-1 max-w-[8rem]`,onChange:e=>{let n=fr(e.target.value);n.kind!==`invalid`&&l(rr(t,{consumableLowPercent:n.kind===`set`?n.value:void 0}))}})]}),m.deviceTypes&&n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground`,children:`Device types`}),u(Sr,{options:Pn,value:t?.deviceTypes??[],onChange:e=>l(rr(t,{deviceTypes:e})),emptyHint:`No device types listed — the rule watches every type.`,placeholder:`Device type…`})]}),Rn(t)&&u(`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.`}),m.devices&&n(`div`,{children:[u(No,{draft:_,onChange:e=>{v(e),l(ps(t,e))},exceptOffered:m.excludeDevices,plural:`devices`,describe:e=>b.get(e)??`Device #${String(e)}`,testId:`system-event-device-scope`,renderPicker:(e,t,n)=>u(U,{devices:g?p:f,listState:o.state,fleet:o,emptyMeansAll:!0,savedHadDevices:(n===`only`?y.include:y.exclude).length>0||n===`only`&&s,noun:g?`camera`:`device`,value:e,onChange:t,testId:n===`only`?`system-event-include`:`system-event-exclude`},n)}),s&&_.mode===`all`&&u(K,{noun:g?`camera`:`device`})]}),m.nodes&&n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground`,children:`Nodes`}),u(is,{value:t?.nodeIds??[],onChange:e=>l(rr(t,{nodeIds:e})),testId:`system-event-nodes`})]}),m.packages&&n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground`,children:`Packages`}),u(as,{value:t?.packageNames??[],onChange:e=>l(rr(t,{packageNames:e})),testId:`system-event-packages`})]})]})}function hs({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:[u(`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&&u(`p`,{className:`mt-1 text-foreground`,children:t.map(Ir).join(`, `)})]})}function gs({family:e,onChange:t}){return n(`div`,{"data-testid":`system-family-select`,children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Kind of system rule`}),u(V,{value:e,"aria-label":`Kind of system rule`,onChange:e=>{let n=e.target.value;Me(n)&&t(n)},options:Ze.map(e=>({value:e,label:Re(e).label}))}),u(`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 _s({catalog:e,taxonomy:t,delivery:i,conditions:a,classScope:o,onClassScopeChange:s,actions:c,sequenceActionsOf:l,savedConditions:d,schedule:f,deviceIds:p,zoneCameraIds:m,cameras:h,fleet:g,allDevices:_,gateable:v,gateableScenes:y,onConditionsChange:b,onScheduleChange:x}){let{t:S}=yt(),C=(e,t)=>{let n={...a};t===void 0?delete n[e]:n[e]=t,b(n)},w=Xe({delivery:i,conditions:a}),T=r(()=>e.filter(e=>Ue(e,i,w)&&Nt(e.id,a)),[e,i,w,a]),E=r(()=>wo(T),[T]),D=e=>T.some(t=>t.id===e),O=e=>vs.has(e.id)?u(Uo,{taxonomy:t,scope:o,onChange:s,exceptOffered:D(`classesExclude`)}):ys.has(e.id)?u(Ro,{conditions:a,onConditionsChange:b,exceptOffered:D(`zonesExclude`),cameraIds:m??p,cameras:h}):bs.has(e.id)?u(zo,{conditions:a,onConditionsChange:b,exceptOffered:D(`identitiesExclude`)}):e.id===`labelEquals`?u(Bo,{conditions:a,onConditionsChange:b}):null;return u(`div`,{className:`space-y-4`,children:E.map(e=>n(`div`,{className:`space-y-2.5`,"data-testid":`condition-group-${e.id}`,children:[u(`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:[u(`label`,{className:X,children:xs(e,S)}),r??u(ws,{descriptor:e,kind:w,taxonomy:t,conditions:a,actions:c,sequenceActionsOf:l,savedConditions:d,schedule:f,deviceIds:p,cameras:h,fleet:g,..._===void 0?{}:{allDevices:_},gateable:v,gateableScenes:y,onFieldChange:C,onScheduleChange:x}),Ss(e,S)!==void 0&&u(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:Ss(e,S)})]},e.id)})]},e.id))})}var vs=new Set([`classes`,`classesExclude`]),ys=new Set([`zones`,`zonesExclude`]),bs=new Set([`identities`,`identitiesExclude`]);function xs(e,t){return vs.has(e.id)?t(`notificationRules.labels.classes`,`Object classes`):ys.has(e.id)?t(`notificationRules.labels.zones`,`Zones`):bs.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 Ss(e,t){if(!Cs.has(e.id))return e.id===`scene`?t(`notificationRules.scene.hint`,`Only fire while a scene is matched or diverged.`):e.description}var Cs=new Set([...vs,...ys,...bs,`labelEquals`,`crossing`]);function ws({descriptor:e,kind:t,taxonomy:r,conditions:i,actions:o,sequenceActionsOf:s,savedConditions:c,schedule:l,deviceIds:d,cameras:f,fleet:p,allDevices:m,gateable:h,gateableScenes:g,onFieldChange:_,onScheduleChange:v}){switch(e.valueType){case`deviceIdList`:{if(!cr(e.id))break;let t=e.id,n=i[t]??[];return u(kn,{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(!Bn(e.id))break;let t=e.id,n=e=>_(t,e.length>0?e:void 0);if(t===`eventTypeTokens`)return u(wr,{deviceIds:d,value:Fr(i,t),onChange:n});let a=st(t,r);return a===null?u(xn,{value:Fr(i,t),placeholder:`Add value…`,onChange:n}):u(Dr,{picker:a,value:Fr(i,t),onChange:n})}case`number01`:{if(!An(e.id))break;let t=e.id;return u(ur,{value:Or(i,t),min:0,max:1,step:.05,onChange:e=>_(t,e)})}case`number`:{if(!$n(e.id))break;let t=e.id;return u(ur,{value:Or(i,t),min:0,step:1,onChange:e=>_(t,e)})}case`sourceSelect`:{if(!Un(e.id))break;let t=e.id;return ks(e,i[t],e=>_(t,e))}case`systemEvent`:{if(!Sn(e.id))break;let n=e.id,r=Be(t);return r===void 0?u(hs,{value:i[n]}):u(ms,{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(!yr(e.id))break;return u(Qn,{gateable:h,value:i.deviceState,onChange:e=>_(`deviceState`,e)});case`scene`:if(!dr(e.id))break;return u(zn,{scenes:g,value:i.scene,onChange:e=>_(`scene`,e)});case`crossingSelect`:{if(!Tn(e.id))break;let t=e.id;return As(e,i[t],e=>_(t,e))}case`packagePhase`:{if(!Nn(e.id))break;let t=e.id;return u(V,{value:i[t]??``,options:[{value:``,label:`— any phase —`},...Rr(e,Ct).map(e=>({value:e.value,label:e.label}))],onChange:e=>_(t,Os(e.target.value))})}case`sensorTransition`:{if(!nr(e.id))break;let t=e.id,r=Le({conditions:i,...o===void 0?{}:{actions:o},...s===void 0?{}:{sequenceActionsOf:s}});return n(a,{children:[u(V,{value:i[t]??``,options:Rr(e,Yt).map(e=>({value:e.value,label:e.label})),onChange:e=>_(t,xt(e.target.value))}),r&&u(`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(!Ln(e.id))break;let t=e.id;return u(Hn,{value:i[t],onChange:e=>_(t,e)})}case`occupancy`:{if(!Tr(e.id))break;let t=e.id;return u(tr,{deviceIds:d,cameras:f,classOptions:Ts(r),value:i[t],onChange:e=>_(t,e)})}case`audio`:{if(!Kn(e.id))break;let t=e.id;return u(sr,{taxonomy:r,value:i[t],onChange:e=>_(t,e)})}case`schedule`:return u(xr,{value:l,onChange:v});default:break}return u(Es,{descriptor:e,conditions:i})}function Ts(e){let t=st(`occupancy`,e);return t===null?[]:t.groups.flatMap(e=>e.options)}function Es({descriptor:e,conditions:t}){let r=Object.entries(t).find(([t])=>t===e.id);return n(`p`,{className:Mn,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 Ds(e){if(e===`pipeline`||e===`onboard`||e===`sensor`||e===`any`)return e}function Os(e){return Ct.find(t=>t.value===e)?.value}function ks(e,t,n){return u(V,{value:t??`any`,options:Rr(e,$t).map(e=>({value:e.value,label:e.label})),onChange:e=>n(Ds(e.target.value))})}function As(e,t,n){return u(vr,{value:t,onChange:n,...e.options?{options:e.options}:{}})}function js({catalog:e,delivery:t,conditions:r,onConditionsChange:i}){let{t:a}=yt(),o=Xe({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&&Ue(e,t,o)&&Nt(n,r)),l=c(`source`),d=c(`crossing`);return l===void 0&&d===void 0?null:n(`div`,{className:`space-y-2.5`,"data-testid":`rule-advanced-conditions`,children:[l&&Un(l.id)&&n(`div`,{"data-testid":`condition-source`,children:[u(`label`,{className:`block text-[11px] font-medium text-foreground`,children:xs(l,a)}),ks(l,r.source,e=>s(`source`,e)),Ss(l,a)!==void 0&&u(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:Ss(l,a)})]}),d&&Tn(d.id)&&n(`div`,{"data-testid":`condition-crossing`,children:[u(`label`,{className:`block text-[11px] font-medium text-foreground`,children:xs(d,a)}),As(d,r.crossing,e=>s(`crossing`,e)),Ss(d,a)!==void 0&&u(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:Ss(d,a)})]})]})}var Ms=6e4,Ns=60*Ms,Ps=24*Ns,Fs=Date.UTC(2e3,0,1);function Is(e){if(e==null||e<Fs)return`—`;let t=Date.now()-e;return t<0||t<3e4?`just now`:t<Ns?`${String(Math.floor(t/Ms))}m ago`:t<Ps?`${String(Math.floor(t/Ns))}h ago`:`${String(Math.floor(t/Ps))}d ago`}var Ls=[`notificationRules`,`getRuleLastRuns`],Rs=3e4;function zs(){let e=m(),t=i({queryKey:Ls,queryFn:()=>e.trpcClient.notificationRules.getRuleLastRuns.query({}),retry:!1,staleTime:Rs});return{status:t.status,data:t.data,error:t.error}}var Bs={sent:`bg-success`,pending:`bg-info`,dead:`bg-danger`};function Vs({cell:e}){switch(e.kind){case`pending`:return u(`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 u(`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 u(`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:[u(`span`,{"data-testid":`rule-last-run-dot`,title:e.status,className:`inline-block h-2 w-2 rounded-full ${Bs[e.status]}`}),u(`span`,{className:`text-[11px] text-foreground-subtle`,children:Is(e.lastAt)})]})}}function Hs({rule:e,onOpenHistory:t}){return u(Y,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>t(e),title:`History — this rule's deliveries`,"aria-label":`history of ${e.name}`,children:u(Kr,{className:`h-3.5 w-3.5`})})}t();var Us=[`notificationRules`,`listSnoozes`],Ws=[10,30,60,120];function Gs({ruleId:e,ruleName:t,exempt:r=!1,variant:i=`icon`}){let a=m(),s=o(),[d,f]=c(30),[p,h]=c(null),g=l({mutationFn:t=>a.trpcClient.notificationRules.createSnooze.mutate({snooze:{scope:`rule`,ruleId:e,durationMinutes:t}}),onMutate:()=>h(null),onSuccess:()=>s.invalidateQueries({queryKey:Us}),onError:e=>h(e instanceof Error?e.message:`The snooze could not be opened.`)});return r?i===`icon`?null:u(`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`?u(Y,{size:`sm`,variant:`ghost`,type:`button`,disabled:g.isPending,onClick:()=>g.mutate(30),title:`Silence this rule for ${It(30)} — it appears under "Silenced right now"`,"aria-label":`snooze ${t}`,"data-testid":`nc-rule-snooze-now`,children:g.isPending?u(P,{className:`h-3.5 w-3.5 animate-spin`}):u(y,{className:`h-3.5 w-3.5`})}):n(`div`,{className:`space-y-1`,children:[n(`div`,{className:`flex items-end gap-2`,children:[u(`div`,{className:`w-32`,children:u(V,{value:String(d),onChange:e=>{let t=Number(e.target.value);Number.isFinite(t)&&t>0&&f(t)},options:Ws.map(e=>({value:String(e),label:It(e)}))})}),n(Y,{size:`sm`,variant:`outline`,type:`button`,disabled:g.isPending,onClick:()=>g.mutate(d),"data-testid":`nc-rule-snooze-now`,children:[g.isPending?u(P,{className:`h-3.5 w-3.5 animate-spin`}):u(y,{className:`h-3.5 w-3.5`}),`Silence this rule now`]})]}),u(`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&&u(`p`,{className:`text-[10px] text-danger`,children:p})]})}t();function Ks(e,t,n){return e.filter(e=>e.scope===`rule`&&e.ruleId===t&&n>=e.startedAt&&n<e.expiresAt).map(e=>e.id)}function qs(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 Js(e,t){let[,n]=c(0);d(()=>{let r=qs(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 Ys(){let e=m();return i({queryKey:Us,queryFn:async()=>(await e.trpcClient.notificationRules.listSnoozes.query({})).snoozes}).data??[]}function Xs({rule:e,snoozes:t,exempt:r}){let{t:i}=yt(),a=m(),s=o();Js(t,e.id);let c=Ks(t,e.id,Date.now()),d=()=>s.invalidateQueries({queryKey:Us}),f=l({mutationFn:()=>a.trpcClient.notificationRules.createSnooze.mutate({snooze:{scope:`rule`,ruleId:e.id,durationMinutes:30}}),onSuccess:d}),p=l({mutationFn:async e=>{for(let t of e)await a.trpcClient.notificationRules.cancelSnooze.mutate({snoozeId:t})},onSuccess:d});if(r)return null;let h=f.isError||p.isError;return n(`span`,{className:`inline-flex flex-col items-center gap-0.5`,children:[u(L,{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`}),h&&u(`span`,{className:`text-[10px] text-danger`,role:`alert`,children:i(`notificationRules.snooze.failed`,`The snooze could not be changed.`)})]})}var Zs=`pipeline-analytics`,Qs=`nc.getRuleStatus`,$s=`nc.testRule`;function ec(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Z(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function tc(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:void 0}function nc(e){if(!ec(e))return;let t=tc(e,`id`),n=tc(e,`downloadPath`),r=Z(e,`capturedAt`);if(!(t===void 0||n===void 0||r===void 0))return{id:t,mediaType:tc(e,`mediaType`)??`video`,sizeBytes:Z(e,`sizeBytes`)??0,capturedAt:r,downloadPath:n}}function rc(e){if(!ec(e))return;let t=Z(e,`startMs`),n=Z(e,`endMs`);if(!(t===void 0||n===void 0))return{startMs:t,endMs:n}}function ic(e){if(!ec(e))return null;let t=Z(e,`deviceId`);if(t===void 0)return null;let n=Z(e,`lastGeneratedAt`),r=nc(e.lastArtifact),i=e.rendering,a=ec(i)?{startedAt:Z(i,`startedAt`)??0,windowStartMs:Z(i,`windowStartMs`)??0,windowEndMs:Z(i,`windowEndMs`)??0}:void 0;return{deviceId:t,...n===void 0?{}:{lastGeneratedAt:n},...r===void 0?{}:{lastArtifact:r},...a===void 0?{}:{rendering:a}}}function ac(e){if(!ec(e))return null;let t=Z(e,`deviceId`),n=tc(e,`windowKey`),r=Z(e,`openedAt`),i=Z(e,`closesAt`),a=Z(e,`members`),o=Z(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 oc(e){if(!ec(e))return null;let t=tc(e,`kind`);if(t===`none`)return{kind:`none`,reason:tc(e,`reason`)??``};if(t===`occupancy`){let t=Z(e,`deviceId`),n=Z(e,`threshold`),r=Z(e,`sustainSeconds`);if(t===void 0||n===void 0||r===void 0)return null;let i=tc(e,`unavailable`),a=i===`no-snapshot`||i===`zone-absent`?i:void 0,o=Z(e,`count`),s=Z(e,`observedAt`),c=Z(e,`since`),l=tc(e,`scope`),u=tc(e,`className`),d=tc(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=Z(e,`groupingSec`);if(t===void 0)return null;if(e.openWindows===null){let n=tc(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=ac(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=ic(e);t!==null&&n.push(t)}let r=rc(e.lastWindow),i=e.nextWindow,a=ec(i)?{startMs:Z(i,`startMs`)??0,endMs:Z(i,`endMs`)??null}:void 0;return{kind:`timelapse`,devices:n,...r===void 0?{}:{lastWindow:r},...a===void 0?{}:{nextWindow:a},settleMs:Z(e,`settleMs`)??0}}return null}function sc(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 cc(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 lc(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 ${sc(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 uc(e,t,n){if(e.rendering!==void 0)return`${t}: rendering for ${sc(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} · ${cc(i.sizeBytes)}`}function dc(e){return{windows:e.length,waiting:e.reduce((e,t)=>e+t.pending,0)}}var fc=`nc.listPrunes`;function pc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var mc=new Set([`rule`,`timelapse`,`summary`]),hc=new Set([`removed`,`kept-disabled`,`kept`,`sequence-removed`]);function gc(e){return typeof e==`string`&&mc.has(e)}function _c(e){return typeof e==`string`&&hc.has(e)}function vc(e){return e===`device`||e===`target`}function yc(e){if(!pc(e))return null;let{kind:t,ruleId:n,subjectKind:r,subject:i,field:a,outcome:o,at:s}=e;return!gc(t)||!vc(r)||!_c(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 bc(e){return!pc(e)||!Array.isArray(e.prunes)?null:e.prunes.map(yc).filter(e=>e!==null)}function xc(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 Sc(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 Cc(e){return new Date(e).toLocaleDateString()}function wc({kind:e,ruleId:t,enabled:r,updatedAt:a}){let o=m(),s=i({queryKey:[`pipelineAnalytics`,fc],enabled:!r,staleTime:3e4,retry:!1,queryFn:async()=>bc(await o.trpcClient.addons.custom.mutate({addonId:Zs,action:fc,input:{}}))}).data;if(s==null)return null;let c=xc(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:[u(M,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-warning`}),u(`span`,{children:Sc(c,Cc)})]})}var Tc=5e3;function Ec({status:e,now:t,name:r}){let{t:i}=yt();if(e.openWindows===null)return n(`p`,{className:`flex items-start gap-1.5`,children:[u(Ce,{className:`mt-0.5 h-3 w-3 shrink-0 text-border`}),u(`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}=dc(o);return n(a,{children:[n(`p`,{className:`flex items-start gap-1.5`,children:[u(Ce,{className:`mt-0.5 h-3 w-3 shrink-0 ${s>0?`text-primary`:`text-border`}`}),u(`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:[u(`span`,{className:`mt-0.5 h-3 w-3 shrink-0`}),u(`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 Dc({ruleId:e,cameraName:t}){let r=m(),o=i({queryKey:[`pipelineAnalytics`,`nc.getRuleStatus`,e],refetchInterval:Tc,queryFn:async()=>oc(await r.trpcClient.addons.custom.mutate({addonId:Zs,action:Qs,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?u(E,{className:`mt-0.5 h-3 w-3 shrink-0 text-warning`}):u(Ce,{className:`mt-0.5 h-3 w-3 shrink-0 text-primary`}),n(`span`,{children:[u(`span`,{className:`text-foreground`,children:c(o.deviceId)}),` —`,` `,lc(o,s)]})]}),o.kind===`grouped`&&u(Ec,{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:[u(Ce,{className:`mt-0.5 h-3 w-3 shrink-0 ${e.rendering===void 0?`text-border`:`text-primary animate-pulse`}`}),n(`span`,{children:[uc(e,c(e.deviceId),s),e.lastArtifact!==void 0&&n(a,{children:[` · `,u(`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:[u(`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 Oc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function kc(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:void 0}function Ac(e,t){let n=e[t];return Array.isArray(n)?n.filter(e=>typeof e==`string`):[]}function jc(e){if(!Oc(e))return null;let t=kc(e,`ruleId`),n=kc(e,`ruleName`);if(t===void 0||n===void 0||typeof e.matched!=`boolean`)return null;let r=kc(e,`failedCondition`);return{ruleId:t,ruleName:n,matched:e.matched,...r===void 0?{}:{failedCondition:r},cooldown:kc(e,`cooldown`)??`n/a`,enqueued:typeof e.enqueued==`number`?e.enqueued:0,targetIds:Ac(e,`targetIds`)}}function Mc(e){if(!Oc(e))return null;let t=kc(e,`conditionId`),n=kc(e,`note`);return t===void 0||n===void 0?null:{conditionId:t,note:n}}function Nc(e){if(!Oc(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(!Oc(t))continue;let e=kc(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(!Oc(t))continue;let e=kc(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 Pc(e){if(!Oc(e))return null;let t=kc(e,`recordId`),n=kc(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=jc(t);e!==null&&r.push(e)}let i=[];for(let t of Array.isArray(e.planNotes)?e.planNotes:[]){let e=Mc(t);e!==null&&i.push(e)}let a=kc(e,`droppedBy`),o=Nc(e.stateSummary);return{recordId:t,delivery:n,trigger:kc(e,`trigger`)??n,candidates:typeof e.candidates==`number`?e.candidates:0,outcomes:r,still:kc(e,`still`)??`none`,notes:Ac(e,`notes`),...a===void 0?{}:{droppedBy:a},planNotes:i,...o===void 0?{}:{stateSummary:o}}}function Fc(e){if(e.stateSummary!==void 0)return Ic(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 Ic(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 Lc({ruleId:e,ruleName:t,fallbackDeviceId:r,variant:i=`icon`,showResult:o=!1}){let s=m(),[d,f]=c(null),[p,h]=c(null),g=l({mutationFn:async()=>Pc(await s.trpcClient.addons.custom.mutate({addonId:Zs,action:$s,input:{ruleId:e,...r===void 0?{}:{deviceId:r}}})),onMutate:()=>{f(null),h(null)},onSuccess:e=>f(e),onError:e=>h(e instanceof Error?e.message:`The test could not be run.`)}),_=d===null?p===null?void 0:p:Fc(d);return n(a,{children:[n(Y,{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?u(P,{className:`h-3.5 w-3.5 animate-spin`}):u(je,{className:`h-3.5 w-3.5`}),i===`full`&&`Test now`]}),o&&p!==null&&u(`div`,{className:`mt-2 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-[11px] text-danger`,children:p}),o&&d!==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:[u(`p`,{className:`text-foreground`,children:Fc(d)}),d.planNotes.map(e=>n(`p`,{className:`flex gap-1.5`,children:[u(E,{className:`mt-0.5 h-3 w-3 shrink-0 text-warning`}),u(`span`,{children:e.note})]},e.conditionId)),d.notes.map(e=>n(`p`,{children:[`· `,e]},e))]})]})}t();var Rc=[`notificationRules`,`listSnoozes`],zc=3e4;function Bc(e,t){return Math.max(0,Math.ceil((e.expiresAt-t)/6e4))}function Vc(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 Hc({rules:e}){let t=m(),a=o(),s=i({queryKey:Rc,refetchInterval:zc,queryFn:async()=>(await t.trpcClient.notificationRules.listSnoozes.query({})).snoozes}),c=l({mutationFn:e=>t.trpcClient.notificationRules.cancelSnooze.mutate({snoozeId:e}),onSuccess:()=>a.invalidateQueries({queryKey:Rc})}),d=r(()=>{let t=new Map;for(let n of e)t.set(n.id,n.name);return t},[e]),f=Date.now(),p=(s.data??[]).filter(e=>f>=e.startedAt&&f<e.expiresAt);return n(W,{className:`p-4`,children:[n(`div`,{className:`flex items-center gap-2 mb-3`,children:[u(y,{className:`h-4 w-4 text-foreground-subtle`}),u(`h3`,{className:`text-sm font-medium text-foreground`,children:`Silenced right now`})]}),p.length===0&&u(`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.`}),u(`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:[u(`span`,{className:`text-xs text-foreground truncate`,children:e.scope===`all`?`Everything`:e.scope===`device`?`Camera ${e.deviceId??`?`}`:d.get(e.ruleId??``)??`A rule`}),e.global&&u(z,{variant:`warning`,className:`text-[10px]`,children:`everyone`}),e.classes!==void 0&&e.classes.length>0&&u(z,{variant:`info`,className:`text-[10px]`,children:e.classes.join(`, `)}),!e.summary&&u(z,{variant:`default`,className:`text-[10px]`,children:`no summary`})]}),n(`span`,{className:`text-[10px] text-foreground-subtle`,children:[`set by `,e.userId,` · `,Vc(Bc(e,f))]})]}),u(Y,{size:`sm`,variant:`outline`,disabled:c.isPending,onClick:()=>c.mutate(e.id),children:`End now`})]},e.id))})]})}var Q=`block text-[11px] font-medium text-foreground mb-1`,Uc=`mt-1 text-[10px] text-foreground-subtle`;function Wc({title:e,hint:t,children:r}){return n(`div`,{className:`rounded-md border border-border px-3 py-3`,children:[u(`div`,{className:`mb-2 text-[11px] font-semibold text-foreground`,children:e}),t!==void 0&&u(`p`,{className:`mb-2 text-[10px] text-foreground-subtle`,children:t}),u(`div`,{className:`space-y-3`,children:r})]})}function Gc({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:[u(E,{className:`h-3.5 w-3.5`}),`This rule could never produce anything, so it cannot be saved:`]}),u(`ul`,{className:`list-disc space-y-0.5 pl-4`,children:e.map(e=>u(`li`,{children:e},e))})]})}function Kc({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:[u(M,{className:`h-3.5 w-3.5`}),`Worth knowing:`]}),u(`ul`,{className:`list-disc space-y-0.5 pl-4`,children:e.map(e=>u(`li`,{children:e},e))})]})}function qc({cameras:e,value:t,onChange:r,fleet:i,hint:a}){return n(`div`,{className:`space-y-1`,children:[u(U,{devices:e,listState:i.state,fleet:i,value:t,onChange:r,emptyLabel:`No camera selected`,testId:`digest-camera-picker`}),a!==void 0&&u(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:a})]})}function Jc(e){return u(D,{...e,testIdPrefix:e.testIdPrefix??`digest-target`,emptyMessage:e.emptyMessage??`No delivery target is configured. Add one on the Targets tab first — without one the artefact is rendered and thrown away.`})}function Yc({label:e,value:t,onChange:r,min:i,max:a,step:o,hint:s,emptyPlaceholder:c,testId:l,disabled:d=!1}){return n(`div`,{children:[u(`label`,{className:Q,children:e}),u(H,{type:`number`,value:t===void 0?``:String(t),disabled:d,...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&&u(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:s})]})}function Xc({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:[u(L,{checked:t,onCheckedChange:r,"aria-label":e,...a===void 0?{}:{"data-testid":a}}),e]}),i!==void 0&&u(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:i})]})}function Zc({title:e,body:t,onTitleChange:r,onBodyChange:i,family:a,testIdPrefix:o}){let s=to(),c=e=>s.data?Za(s.data,{family:a,field:e}):void 0;return n(`div`,{className:`space-y-2`,children:[u(oo,{label:`Notification title`,value:e,onChange:r,vars:c(`title`),testId:`${o}-title`}),u(oo,{label:`Notification body`,value:t,onChange:i,vars:c(`body`),multiline:!0,testId:`${o}-body`}),u(`p`,{className:`text-[10px] text-foreground-subtle`,children:`Leave both blank to use the hub's own wording (editable on the Texts tab).`}),u(so,{context:{family:a,field:`body`},title:e,body:t,testId:`${o}-preview`})]})}function Qc({open:e,ruleName:t,windowDescription:r,targetDescription:i,pending:a,onConfirm:o,onCancel:s,extra:c,confirmDisabled:l=!1}){return e?u(w,{open:!0,onOpenChange:e=>!e&&s(),children:u(we,{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:[u(je,{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.`]}),u(`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:[u(Y,{size:`sm`,variant:`secondary`,type:`button`,onClick:s,children:`Cancel`}),u(Y,{size:`sm`,type:`button`,disabled:a||l,onClick:o,"data-testid":`digest-test-confirm-send`,children:a?`Sending…`:`Produce and send`})]})]})})}):null}function $c(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 el=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function tl(e){let t=Math.floor(e/60),n=e%60;return`${String(t).padStart(2,`0`)}:${String(n).padStart(2,`0`)}`}function nl(e){let t=e.windows[0];if(t===void 0)return`No window`;let n=t.days.toSorted((e,t)=>e-t).map(e=>el[e]??String(e)).join(` `),r=t.startMinute>t.endMinute?` (overnight)`:``,i=e.windows.length-1,a=e.invert===!0?` · outside`:``;return`${n} ${tl(t.startMinute)}–${tl(t.endMinute)}${r}${i>0?` +${i}`:``}${a}`}function rl(e,t,n){if(e===void 0||e<=0)return n;let r=Math.max(0,t-e);return`${$c(Math.round(r/1e3))} ago`}function il(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function al(e){return Array.isArray(e)?`[${e.map(al).join(`,`)}]`:il(e)?`{${Object.keys(e).toSorted().map(t=>`${JSON.stringify(t)}:${al(e[t])}`).join(`,`)}}`:JSON.stringify(e)??`null`}function ol(e,t){return al(e)===al(t)}function sl(e){return e.map(e=>({targetId:e}))}var $=`pipeline-analytics`,cl=`nc.getTexts`,ll=`nc.setLanguage`,ul=`nc.setTextOverrides`,dl={en:`English`,it:`Italiano`};function fl(e){return e===`en`||e===`it`}function pl(e){return e===`override`||e===`shipped`||e===`fallback`}function ml(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function hl(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 gl(e){if(!ml(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`||!fl(r)||!pl(o)||i!==null&&typeof i!=`string`)return null;let s=hl(e.placeholders),c=hl(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 _l(e){if(!ml(e))return null;let{language:t,activeLanguage:n}=e;if(!fl(t)||!fl(n))return null;let r=hl(e.languages);if(r===null||r.length===0)return null;let i=[];for(let e of r)fl(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=gl(e);if(t===null)return null;o.push(t)}return{language:t,activeLanguage:n,languages:i,entries:o}}function vl(e,t){return t.get(e.key)??e.override??e.shipped}function yl(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 bl(e,t){return Object.keys(yl(e,t)).length}function xl(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 Sl(e){return e.placeholders.map(e=>({name:e,label:e,example:`{{${e}}}`,group:`rule`,families:[`rule`]}))}function Cl(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 wl=`nc.listSummaryRules`,Tl=`nc.upsertSummaryRule`,El=`nc.deleteSummaryRule`,Dl=`nc.testSummaryRule`,Ol=3600,kl=86400,Al=3600,jl=3600,Ml=3*36e5,Nl=[`importance`,`recency`,`dwell`],Pl={importance:`Most important`,recency:`Most recent`,dwell:`Longest stay`},Fl=[`none`,`tiles`,`all`],Il=`none`,Ll={none:`Images only — no text anywhere`,tiles:`A label under each tile`,all:`Tile labels and a caption across the top`},Rl=[`en`,`it`],zl=[`deliver-without-text`,`skip`],Bl=2048,Vl=2e3;function Hl(e){return e.window.kind!==`unsupported`&&!e.readOnly}function Ul(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Wl(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 Gl(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 Kl(e){if(e!==void 0)return typeof e==`string`?e:null}function ql(e){if(e!==void 0)return typeof e==`number`&&Number.isFinite(e)?e:null}function Jl(e){return Nl.some(t=>t===e)}function Yl(e){return e===void 0?Il:Fl.find(t=>t===e)??null}function Xl(e){if(!Ul(e)||!Array.isArray(e.windows)||e.windows.length===0)return null;let t=[];for(let n of e.windows){if(!Ul(n))return null;let e=Wl(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=Kl(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 Zl(e){if(!Ul(e)||typeof e.kind!=`string`)return null;if(e.kind===`schedule`){let t=Xl(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 Ql(e){if(e==null)return;if(!Ul(e))return null;let t=e.classes===void 0?void 0:Gl(e.classes),n=e.classesExclude===void 0?void 0:Gl(e.classesExclude),r=e.zones===void 0?void 0:Gl(e.zones);if(t===null||n===null||r===null)return null;let i=ql(e.minImportance),a=ql(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 $l(e){if(e==null)return;if(!Ul(e))return null;let t=Kl(e.title),n=Kl(e.body);return t===null||n===null?null:{...t===void 0?{}:{title:t},...n===void 0?{}:{body:n}}}function eu(e){return Rl.some(t=>t===e)}function tu(e){return zl.some(t=>t===e)}function nu(e){if(e==null)return;if(!Ul(e)||typeof e.enabled!=`boolean`)return null;let t=Kl(e.profileId),n=Kl(e.prompt);if(t===null||n===null)return null;let r=ql(e.maxImagePx),i=ql(e.timeoutMs);if(r===null||i===null)return null;let a=e.language;if(a!==void 0&&!eu(a))return null;let o=e.onFailure;return o!==void 0&&!tu(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 ru(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(!Ul(n)||typeof n.targetId!=`string`)return null;let e=n.params;if(e!==void 0&&!Ul(e))return null;t.push({targetId:n.targetId,...e===void 0?{}:{params:e}})}return t}function iu(e){if(!Ul(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`||!Jl(o)||typeof s!=`number`||typeof c!=`boolean`||typeof e.priority!=`number`)return null;let l=Wl(e.deviceIds),u=Zl(e.window),d=ru(e.targets);if(l===null||u===null||d===null)return null;let f=Ql(e.filters),p=$l(e.template);if(f===null||p===null)return null;let m=Kl(e.captionText),h=ql(e.generatedAt),g=ql(e.updatedAt);if(m===null||h===null||g===null)return null;let _=Yl(e.captions);if(_===null)return null;let v=nu(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 au(e){if(!Ul(e)||!Array.isArray(e.rules))return null;let t=[];for(let n of e.rules){let e=iu(n);if(e===null)return null;t.push(e)}return t}function ou(e){if(!Ul(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=ql(e[r]);if(t===null)return null;t!==void 0&&(n[r]=t)}for(let t of[`windowStartMs`,`windowEndMs`]){let r=ql(e[t]);if(r===null)return null;r!==void 0&&(n[t]=r)}for(let t of[`mosaicUrl`,`error`,`aiText`,`aiFailure`]){let r=Kl(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 su(){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:Il,captionText:``,deliverEmpty:!1,priority:3,aiEnabled:!1,aiProfileId:``,aiPrompt:``,aiLanguage:``,aiMaxImagePx:void 0,aiTimeoutSeconds:void 0,aiOnFailure:`deliver-without-text`}}function cu(e){let t=su(),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 lu(e){return e.windowKind===`schedule`&&e.schedule!==void 0?{kind:`schedule`,schedule:e.schedule}:{kind:`motion`,quietSeconds:e.quietSeconds,maxWindowSeconds:e.maxWindowSeconds}}function uu(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 du(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 fu(e){return sl(e.targetIds)}function pu(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 mu(e){let t=uu(e),n=du(e),r=pu(e),i=e.captionText.trim();return{name:e.name.trim(),enabled:e.enabled,deviceIds:[...e.deviceIds],window:lu(e),...t===void 0?{}:{filters:t},maxTiles:e.maxTiles,maxAiImages:e.maxAiImages,rank:e.rank,barrierSeconds:e.barrierSeconds,targets:fu(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 hu(e,t){let n=mu(e),r={};return n.name!==t.name&&(r.name=n.name),n.enabled!==t.enabled&&(r.enabled=n.enabled),ol(n.deviceIds,t.deviceIds)||(r.deviceIds=n.deviceIds),ol(n.window,t.window)||(r.window=n.window),ol(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),ol(n.targets,t.targets)||(r.targets=n.targets),ol(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),ol(n.ai,t.ai)||(r.ai=n.ai??null),r}function gu(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 ${Ol}s.`),(e.maxWindowSeconds<60||e.maxWindowSeconds>86400)&&t.push(`The longest window must be between 60s and ${kl}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 ${Al}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 ${jl}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 ${Vl} 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 ${Bl} 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 _u(e){return gu(e).length===0}function vu(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 yu=[{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`]}],bu=`rule`;function xu(e){return yu.find(t=>t.key===e)?.key}function Su(e){return e.kind===`motion`?`Motion · ${$c(e.quietSeconds)} quiet · max ${$c(e.maxWindowSeconds)}`:e.kind===`unsupported`?`Unsupported window (${e.raw}) — authored on a newer hub`:`Schedule · ${nl(e.schedule)}`}function Cu(e,t){return rl(e,t,`Never run`)}function wu(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 ≥ ${$c(e.minDwellSeconds)}`),e.includeStationary===!0&&t.push(`incl. parked`),t.length===0?`All passages`:t.join(` · `)}function Tu(e){return{windowStartMs:e-Ml,windowEndMs:e}}t();var Eu={"deliver-without-text":`Deliver the digest anyway, without the text`,skip:`Hold the whole digest — deliver nothing`},Du={en:`English`,it:`Italiano`};function Ou(e){return Nl.find(t=>t===e)}function ku(e){return Fl.find(t=>t===e)}function Au(e){return Rl.find(t=>t===e)??``}function ju(e){return zl.find(t=>t===e)}function Mu({rule:e,cameras:t,fleet:a,targets:o,taxonomy:s,onSaved:d,onCancel:f}){let p=m(),[h,g]=c(()=>e===null?su():cu(e)),[_,v]=c(null),[y,b]=c(bu),x=e=>g(t=>({...t,...e})),C=r(()=>{let e=st(`occupancy`,s);return e===null?[]:e.groups.flatMap(e=>e.options)},[s]),{options:T,loading:E}=gr(h.deviceIds,t.map(e=>({id:e.id,name:e.name}))),D=i({queryKey:[`llm`,`listProfiles`,`summary-editor`],queryFn:()=>p.trpcClient.llm.listProfiles.query({}),retry:!1}),A=(D.data??[]).filter(e=>e.supportsVision),j=l({mutationFn:async()=>{let t=e===null?{rule:mu(h)}:{ruleId:e.id,patch:hu(h,e)};await p.trpcClient.addons.custom.mutate({addonId:$,action:Tl,input:t})},onSuccess:d,onError:e=>v(e instanceof Error?e.message:`Save failed`)}),M=to(),N=M.data?Za(M.data,{family:`summary`,field:`captionText`}):void 0,te=h.mosaicCaptions===`all`,I=gu(h),L=vu(h),ne=_u(h)&&!j.isPending,R=yu.some(e=>e.key===y)?y:bu;return u(w,{open:!0,onOpenChange:e=>!e&&f(),children:n(we,{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:[u(qr,{className:`h-4 w-4 shrink-0 text-foreground-subtle`}),u(`span`,{className:`truncate`,children:e===null?`New summary`:`Edit ${e.name}`})]}),u(Y,{size:`sm`,variant:`ghost`,type:`button`,onClick:f,children:`Cancel`})]}),_!==null&&u(`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&&u(wc,{kind:`summary`,ruleId:e.id,enabled:e.enabled,updatedAt:e.updatedAt??1/0}),u(Gc,{problems:I,testId:`summary-problems`}),u(Kc,{warnings:L,testId:`summary-warnings`})]}),n(ee,{value:R,onValueChange:e=>b(xu(e)??y),className:`mt-3 flex min-h-0 flex-1 flex-col`,children:[u(S,{className:`mb-3 shrink-0`,children:yu.map(e=>u(O,{value:e.key,children:e.label},e.key))}),n(k,{className:`pr-1`,children:[n(F,{value:`rule`,className:`space-y-3`,children:[u(Wc,{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:[u(`label`,{className:Q,children:`Name`}),u(H,{value:h.name,onChange:e=>x({name:e.target.value}),placeholder:`e.g. Overnight sweep`,"data-testid":`summary-name`})]}),u(`div`,{className:`pb-1.5`,children:u(Xc,{label:`Enabled`,checked:h.enabled,onChange:e=>x({enabled:e}),testId:`summary-enabled`})})]})}),u(Wc,{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:u(qc,{cameras:t,value:h.deviceIds,fleet:a,onChange:e=>x({deviceIds:e}),hint:`The first camera selected owns the delivered notification.`})})]}),u(F,{value:`window`,className:`space-y-3`,children:n(Wc,{title:`When the window closes`,children:[n(`div`,{children:[u(`label`,{className:Q,children:`Window`}),u(V,{value:h.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`})]}),h.windowKind===`motion`?n(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[u(Yc,{label:`Quiet period (seconds)`,value:h.quietSeconds,min:30,max:Ol,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`}),u(Yc,{label:`Longest window (seconds)`,value:h.maxWindowSeconds,min:60,max:kl,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:[u(`label`,{className:Q,children:`Weekly windows`}),u(xr,{value:h.schedule,onChange:e=>x({schedule:e})}),u(`p`,{className:Uc,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.`})]}),u(Yc,{label:`Wait for open tracks (seconds)`,value:h.barrierSeconds,min:0,max:Al,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`})]})}),u(F,{value:`content`,className:`space-y-3`,children:n(Wc,{title:`What goes in`,hint:`Evaluated on tracks: one passage is one tile.`,children:[n(`div`,{children:[u(`label`,{className:Q,children:`Classes`}),u(Sr,{options:C,value:h.classes,onChange:e=>x({classes:e}),emptyHint:`No class vocabulary from this hub — leave empty to keep every class.`,placeholder:``,noFreeText:!0}),u(`p`,{className:Uc,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:[u(`label`,{className:Q,children:`Excluded classes`}),u(Sr,{options:C,value:h.classesExclude,onChange:e=>x({classesExclude:e}),emptyHint:`No class vocabulary from this hub.`,placeholder:``,noFreeText:!0})]}),n(`div`,{children:[u(`label`,{className:Q,children:`Zones`}),u(Sr,{options:T,value:h.zones,onChange:e=>x({zones:e}),loading:E,emptyHint:`Pick a camera first — the zones offered are its own.`,placeholder:``,noFreeText:!0}),u(`p`,{className:Uc,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:[u(Yc,{label:`Minimum importance`,value:h.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`}),u(Yc,{label:`Minimum stay (seconds)`,value:h.minDwellSeconds,min:0,max:jl,emptyPlaceholder:`any`,onChange:e=>x({minDwellSeconds:e}),hint:`Drops the passages too brief to be worth a tile.`,testId:`summary-min-dwell`})]}),u(Xc,{label:`Include parked objects`,checked:h.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`})]})}),u(F,{value:`mosaic`,className:`space-y-3`,children:n(Wc,{title:`The mosaic`,children:[n(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[u(Yc,{label:`Tiles`,value:h.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:[u(`label`,{className:Q,children:`When there are more tracks than tiles`}),u(V,{value:h.rank,options:Nl.map(e=>({value:e,label:Pl[e]})),onChange:e=>{let t=Ou(e.target.value);t!==void 0&&x({rank:t})},"data-testid":`summary-rank`}),u(`p`,{className:Uc,children:`Every contributing camera keeps its single best tile first; the remaining slots go to this ranking.`})]})]}),n(`div`,{children:[u(`label`,{className:Q,children:`Text on the mosaic`}),u(V,{value:h.mosaicCaptions,options:Fl.map(e=>({value:e,label:Ll[e]})),onChange:e=>{let t=ku(e.target.value);t!==void 0&&x({mosaicCaptions:t})},"data-testid":`summary-captions`}),u(`p`,{className:Uc,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:[u(oo,{label:`Caption burned onto the mosaic`,value:h.captionText,disabled:!te,onChange:e=>x({captionText:e}),placeholder:`Leave empty for no caption`,vars:N,testId:`summary-caption`}),u(`p`,{className:Uc,children:te?`Across the top band.`:`Only drawn with “tile labels and a caption across the top”. What you type here is kept either way.`})]})]})}),u(F,{value:`ai`,className:`space-y-3`,children:n(Wc,{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:[u(Xc,{label:`Have a model describe the window`,checked:h.aiEnabled,onChange:e=>x({aiEnabled:e}),hint:`Off by default. The mosaic and the counts are delivered either way.`,testId:`summary-ai-enabled`}),!h.aiEnabled&&u(`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:[u(`label`,{className:Q,children:`Vision profile`}),u(V,{value:h.aiProfileId,disabled:!h.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`}),u(`p`,{className:Uc,children:D.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:[u(`label`,{className:Q,children:`Answer in`}),u(V,{value:h.aiLanguage,disabled:!h.aiEnabled,options:[{value:``,label:`Don’t ask for a language`},...Rl.map(e=>({value:e,label:Du[e]}))],onChange:e=>x({aiLanguage:Au(e.target.value)}),"data-testid":`summary-ai-language`}),u(`p`,{className:Uc,children:`Nothing is added to the prompt unless you pick one, and these models answer in English on their own.`})]})]}),n(`div`,{children:[u(`label`,{className:Q,children:`Your question (optional)`}),u(`textarea`,{value:h.aiPrompt,rows:3,maxLength:Vl,disabled:!h.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`}),u(`p`,{className:Uc,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:[u(Yc,{label:`Frames the model may look at`,value:h.maxAiImages,min:1,max:8,disabled:!h.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`}),u(Yc,{label:`Time limit (seconds)`,value:h.aiTimeoutSeconds,min:10,max:600,emptyPlaceholder:`180`,disabled:!h.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:[u(Yc,{label:`Frame size sent (pixels)`,value:h.aiMaxImagePx,min:64,max:Bl,emptyPlaceholder:`448`,disabled:!h.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:[u(`label`,{className:Q,children:`If the model gives no answer`}),u(V,{value:h.aiOnFailure,disabled:!h.aiEnabled,options:zl.map(e=>({value:e,label:Eu[e]})),onChange:e=>{let t=ju(e.target.value);t!==void 0&&x({aiOnFailure:t})},"data-testid":`summary-ai-on-failure`}),u(`p`,{className:Uc,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.`})]})]})]})}),u(F,{value:`delivery`,className:`space-y-3`,children:n(Wc,{title:`Delivery`,children:[u(Jc,{targets:o,value:h.targetIds,onChange:e=>x({targetIds:e})}),n(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[u(Yc,{label:`Priority`,value:h.priority,min:1,max:5,onChange:e=>x({priority:e??3}),testId:`summary-priority`}),u(Xc,{label:`Deliver a window that matched nothing`,checked:h.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`})]}),u(Zc,{title:h.templateTitle,body:h.templateBody,onTitleChange:e=>x({templateTitle:e}),onBodyChange:e=>x({templateBody:e}),family:`summary`,testIdPrefix:`summary-template`}),n(`p`,{className:Uc,children:[u(`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:[u(Y,{size:`sm`,variant:`secondary`,type:`button`,onClick:f,children:`Cancel`}),n(Y,{size:`sm`,type:`button`,disabled:!ne,onClick:()=>j.mutate(),children:[j.isPending&&u(P,{className:`h-3.5 w-3.5 animate-spin`}),e===null?`Create`:`Save`]})]})]})})}function Nu({children:e,className:t}){return u(`span`,{className:t,onClick:e=>e.stopPropagation(),children:e})}function Pu(){return u(`div`,{className:`flex items-center justify-center py-16`,children:u(P,{className:`h-6 w-6 animate-spin text-primary`})})}function Fu({children:e,testId:t}){return u(`div`,{className:`text-xs text-foreground-subtle text-center py-16`,...t===void 0?{}:{"data-testid":t},children:e})}function Iu({columns:e,rows:t,rowKey:n,minWidthPx:r,onRowClick:i}){return u(W,{children:u(De,{columns:e,rows:t,rowKey:n,minWidthPx:r,bordered:!1,mobileMode:`scroll`,maxBodyHeight:re,...i===void 0?{}:{onRowClick:i}})})}function Lu({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?u(`span`,{className:`truncate text-sm font-medium text-foreground`,children:e}):u(Nu,{children:u(`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&&u(z,{variant:`warning`,children:`disabled`}),i]})}function Ru({disabled:e=!1,pending:t=!1,title:n,message:r,confirmLabel:i=`Delete`,cancelLabel:a=`Cancel`,ariaLabel:o,testId:s,onConfirm:c}){let l=N(),d=async()=>{await l({title:n,message:r,confirmLabel:i,cancelLabel:a,variant:`danger`})&&c()};return u(`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 d(),...s===void 0?{}:{"data-testid":s},children:u(g,{className:`h-3.5 w-3.5 text-danger`})})}t();var zu=[`notificationSummaries`,`listSummaryRules`],Bu=`One window, one picture: every camera’s best moments as a single mosaic.`;function Vu({embedded:e=!1,openCreateKey:t}={}){let o=m(),[s,f]=c({mode:`closed`}),[p,h]=c(null),[g,_]=c(null),[v,y]=c(!1);d(()=>{t!==void 0&&t>0&&f({mode:`form`,rule:null})},[t]);let b=i({queryKey:zu,queryFn:async()=>au(await o.trpcClient.addons.custom.mutate({addonId:$,action:wl,input:{}}))});d(()=>{b.isSuccess&&y(b.data===null)},[b.isSuccess,b.data]);let x=ae({projection:`slim`}),S=r(()=>(x.data??[]).filter(e=>e.type===Ve.Camera).map(e=>({id:e.id,name:e.name})).toSorted((e,t)=>e.name.localeCompare(t.name)),[x.data]),C=i({queryKey:Zd,queryFn:()=>o.trpcClient.notificationOutput.listTargets.query({})}),w=i({queryKey:Qd,queryFn:()=>o.trpcClient.notificationRules.getConditionCatalog.query({})}),T=l({mutationFn:e=>o.trpcClient.addons.custom.mutate({addonId:$,action:Tl,input:{ruleId:e.ruleId,patch:{enabled:e.enabled}}}),onSuccess:()=>void b.refetch()}),E=l({mutationFn:e=>o.trpcClient.addons.custom.mutate({addonId:$,action:El,input:{ruleId:e}}),onSuccess:()=>void b.refetch()}),D=l({mutationFn:async e=>ou(await o.trpcClient.addons.custom.mutate({addonId:$,action:Dl,input:{ruleId:e,...Tu(Date.now())}})),onSuccess:e=>{h(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,M=e=>{Hl(e)&&f({mode:`form`,rule:e})},N=n(a,{children:[b.isLoading&&u(Pu,{}),j&&!b.isLoading&&u(q,{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&&u(q,{title:`Could not delete the rule`,message:String(E.error)}),D.isError&&u(q,{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]}),u(Y,{size:`sm`,variant:`ghost`,type:`button`,className:`ml-2`,onClick:()=>_(null),children:`Dismiss`})]}),O.length===0?u(Fu,{testId:`summary-empty`,children:`No summary rules yet — create one, and every window it covers arrives as a single picture.`}):u(Iu,{columns:Hu({nowMs:Date.now(),targetNameById:A,deletePending:E.isPending,onToggle:(e,t)=>T.mutate({ruleId:e.id,enabled:t}),onOpen:M,onTest:h,onConfirmDelete:e=>E.mutate(e.id)}),rows:O,rowKey:e=>e.id,minWidthPx:860,onRowClick:M})]}),s.mode===`form`&&u(Mu,{rule:s.rule,cameras:S,fleet:me(x),targets:k,taxonomy:w.data?.taxonomy,onCancel:()=>f({mode:`closed`}),onSaved:()=>{f({mode:`closed`}),b.refetch()}}),u(Qc,{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:()=>h(null),onConfirm:()=>{p!==null&&D.mutate(p.id)}})]});return e?N:u(Hr,{icon:qr,title:`Summaries`,subtitle:Bu,actions:j?void 0:n(Y,{size:`sm`,type:`button`,onClick:()=>f({mode:`form`,rule:null}),"data-testid":`summary-new`,children:[u(J,{className:`h-3.5 w-3.5`}),`New summary`]}),children:N})}function Hu(e){return[{key:`name`,header:`Digest`,render:t=>u(Lu,{name:t.name,enabled:t.enabled,...Hl(t)?{onOpen:()=>e.onOpen(t)}:{},openTestId:`summary-edit-${t.id}`,badges:n(a,{children:[!Hl(t)&&u(z,{variant:`warning`,children:`read-only`}),t.ai?.enabled===!0&&u(z,{variant:`info`,children:`AI`}),t.ai!==void 0&&!t.ai.enabled&&u(z,{variant:`default`,children:`AI off`})]})})},{key:`cameras`,header:`Cameras`,align:`center`,nowrap:!0,render:e=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.deviceIds.length})},{key:`window`,header:`Window`,render:e=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:Su(e.window)})},{key:`filters`,header:`Keeps`,render:e=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:wu(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 u(`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=>u(`span`,{className:`text-[11px] text-foreground-subtle`,"data-testid":`summary-last-${t.id}`,children:Cu(t.generatedAt,e.nowMs)})},{key:`enabled`,header:`On`,align:`center`,nowrap:!0,render:t=>u(Nu,{children:u(L,{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(Nu,{className:`flex items-center justify-end gap-1`,children:[u(Y,{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:u(se,{className:`h-3.5 w-3.5`})}),u(Ru,{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 Uu=`nc.listTimelapseRules`,Wu=`nc.upsertTimelapseRule`,Gu=`nc.deleteTimelapseRule`,Ku=`nc.testTimelapseRule`,qu=3600,Ju=3600,Yu=30,Xu=1,Zu=[`image`,`gif`],Qu={image:`Still frame`,gif:`Short animation (GIF)`},$u=gt({rules:_t(dt.extend({readOnly:vt().optional()}))});function ed(e){let t=$u.safeParse(e);return t.success?t.data.rules:null}function td(e){return e.readOnly!==!0}var nd=gt({produced:mt(),exportId:ht().optional(),coveragePercent:mt().optional(),enqueued:mt().optional(),windowStartMs:mt().optional(),windowEndMs:mt().optional(),error:ht().optional()});function rd(e){let t=nd.safeParse(e);return t.success?t.data:null}function id(){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 ad(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 od={windows:[{days:[1],startMinute:0,endMinute:60}]};function sd(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 cd(e){let t=sd(e);return{name:e.name.trim(),enabled:e.enabled,deviceIds:[...e.deviceIds],schedule:e.schedule??od,cadenceSec:e.cadenceSec,framerate:e.framerate,...e.denseCadenceSec===void 0?{}:{denseCadenceSec:e.denseCadenceSec},...e.minDwellSec===void 0?{}:{minDwellSec:e.minDwellSec},targets:sl(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 ld(e,t){let n=cd(e),r={};return n.name!==t.name&&(r.name=n.name),n.enabled!==t.enabled&&(r.enabled=n.enabled),ol(n.deviceIds,t.deviceIds)||(r.deviceIds=n.deviceIds),ol(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??ud(n.cadenceSec)),n.minDwellSec!==t.minDwellSec&&n.minDwellSec!==void 0&&(r.minDwellSec=n.minDwellSec),ol(n.targets,t.targets)||(r.targets=n.targets),ol(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),ol(n.reportClasses,t.reportClasses)||(r.reportClasses=n.reportClasses??[]),n.priority!==t.priority&&(r.priority=n.priority),r}function ud(e){return Math.max(Xu,e/Yu)}function dd(e,t,n){return t<=0||n<=0?0:e/t/n}function fd(e,t){return e*t*it}function pd(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 ${qu}.`),(!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 ${it}s and ${Ju}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 md(e){return pd(e).length===0}function hd(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=fd(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 gd(e){return nl(e)}function _d(e,t){return rl(e,t,`Never run`)}function vd(e){return e.denseCadenceSec===void 0?{seconds:ud(e.cadenceSec),derived:!0}:{seconds:e.denseCadenceSec,derived:!1}}var yd=[{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`]}],bd=`rule`;function xd(e){return yd.find(t=>t.key===e)?.key}t();var Sd=7;function Cd(e){return Zu.find(t=>t===e)}function wd({rule:e,cameras:t,fleet:r,targets:i,onSaved:o,onCancel:s}){let d=m(),[f,p]=c(()=>e===null?id():ad(e)),[h,g]=c(null),[_,v]=c(bd),y=e=>p(t=>({...t,...e})),b=to(),x=b.data?Za(b.data,{family:`timelapse`,field:`previewText`}):void 0,C=l({mutationFn:async()=>{let t=e===null?{rule:cd(f)}:{ruleId:e.id,patch:ld(f,e)};await d.trpcClient.addons.custom.mutate({addonId:$,action:Wu,input:t})},onSuccess:o,onError:e=>g(e instanceof Error?e.message:`Save failed`)}),T=pd(f),E=hd(f),D=vd(f),j=dd(Sd,D.seconds,f.framerate),M=md(f)&&!C.isPending,N=yd.some(e=>e.key===_)?_:bd;return u(w,{open:!0,onOpenChange:e=>!e&&s(),children:n(we,{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:[u(A,{className:`h-4 w-4 shrink-0 text-foreground-subtle`}),u(`span`,{className:`truncate`,children:e===null?`New timelapse`:`Edit ${e.name}`})]}),u(Y,{size:`sm`,variant:`ghost`,type:`button`,onClick:s,children:`Cancel`})]}),h!==null&&u(`div`,{className:`mb-3 shrink-0 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger`,children:h}),n(`div`,{className:`shrink-0 space-y-2`,children:[e!==null&&u(wc,{kind:`timelapse`,ruleId:e.id,enabled:e.enabled,updatedAt:e.updatedAt}),u(Gc,{problems:T,testId:`timelapse-problems`}),u(Kc,{warnings:E,testId:`timelapse-warnings`})]}),n(ee,{value:N,onValueChange:e=>v(xd(e)??_),className:`mt-3 flex min-h-0 flex-1 flex-col`,children:[u(S,{className:`mb-3 shrink-0`,children:yd.map(e=>u(O,{value:e.key,children:e.label},e.key))}),n(k,{className:`pr-1`,children:[n(F,{value:`rule`,className:`space-y-3`,children:[u(Wc,{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:[u(`label`,{className:Q,children:`Name`}),u(H,{value:f.name,onChange:e=>y({name:e.target.value}),placeholder:`e.g. Night driveway`,"data-testid":`timelapse-name`})]}),u(`div`,{className:`pb-1.5`,children:u(Xc,{label:`Enabled`,checked:f.enabled,onChange:e=>y({enabled:e}),testId:`timelapse-enabled`})})]})}),u(Wc,{title:`Cameras`,children:u(qc,{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.`})})]}),u(F,{value:`window`,className:`space-y-3`,children:u(Wc,{title:`When`,children:n(`div`,{children:[u(`label`,{className:Q,children:`Weekly windows`}),u(xr,{value:f.schedule,onChange:e=>y({schedule:e})}),u(`p`,{className:Uc,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.`})]})})}),u(F,{value:`sampling`,className:`space-y-3`,children:n(Wc,{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:[u(Yc,{label:`Base cadence (seconds)`,value:f.cadenceSec,min:2,max:qu,onChange:e=>y({cadenceSec:e??0}),hint:`One frame every N seconds across the quiet parts of the window.`,testId:`timelapse-cadence`}),u(Yc,{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:[u(`label`,{className:Q,children:`Dense cadence, near the detections`}),n(`div`,{className:`flex items-center gap-2`,children:[u(V,{value:f.denseCadenceSec===void 0?`auto`:`explicit`,options:[{value:`auto`,label:`Automatic (${D.seconds}s)`},{value:`explicit`,label:`Set it myself`}],onChange:e=>y({denseCadenceSec:e.target.value===`auto`?void 0:vd(f).seconds}),"data-testid":`timelapse-dense-mode`}),f.denseCadenceSec!==void 0&&u(H,{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:Uc,"data-testid":`timelapse-dense-hint`,children:[`Lower = slower near the detections. At `,D.seconds,`s and `,f.framerate,` fps a `,Sd,`-second passage lasts `,j.toFixed(2),`s on screen; halving the cadence doubles that, and the quiet parts of the night do not change length.`,D.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 (${vd({...f,denseCadenceSec:void 0}).seconds}s) explicitly.`]})]}),u(Yc,{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`})]})}),u(F,{value:`delivery`,className:`space-y-3`,children:n(Wc,{title:`The notification`,children:[u(Jc,{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:[u(`label`,{className:Q,children:`Preview`}),u(V,{value:f.previewMode,options:Zu.map(e=>({value:e,label:Qu[e]})),onChange:e=>{let t=Cd(e.target.value);t!==void 0&&y({previewMode:t})},"data-testid":`timelapse-preview-mode`})]}),u(Yc,{label:`Priority`,value:f.priority,min:1,max:5,onChange:e=>y({priority:e??3}),testId:`timelapse-priority`})]}),n(`div`,{children:[u(oo,{label:`Caption on the preview frame`,value:f.previewTextSet?f.previewText:``,placeholder:`${$e} (shipped default)`,onChange:e=>y({previewText:e,previewTextSet:!0}),vars:x,testId:`timelapse-preview-text`}),n(`p`,{className:Uc,children:[f.previewTextSet&&f.previewText.length===0?`Empty and set: the preview frame carries NO caption.`:`Leave untouched for the shipped caption (${$e}).`,f.previewTextSet&&n(a,{children:[` `,u(`button`,{type:`button`,className:`underline`,onClick:()=>y({previewText:``,previewTextSet:!1}),"data-testid":`timelapse-preview-text-reset`,children:`Back to the shipped caption`})]})]})]}),u(Zc,{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`,` `,u(`code`,{children:`{{detectionSummary}}`}),`.`]})]})})]})]}),n(`div`,{className:`mt-3 flex shrink-0 justify-end gap-2`,children:[u(Y,{size:`sm`,variant:`secondary`,type:`button`,onClick:s,children:`Cancel`}),n(Y,{size:`sm`,type:`button`,disabled:!M,onClick:()=>C.mutate(),children:[C.isPending&&u(P,{className:`h-3.5 w-3.5 animate-spin`}),e===null?`Create`:`Save`]})]})]})})}t();var Td=[`notificationTimelapses`,`listTimelapseRules`],Ed=`A night of recorded footage, assembled into one short video per camera.`;function Dd({embedded:e=!1,openCreateKey:t}={}){let o=m(),[s,f]=c({mode:`closed`}),[p,h]=c(null),[g,_]=c(null),[v,y]=c(!1);d(()=>{t!==void 0&&t>0&&f({mode:`form`,rule:null})},[t]);let b=i({queryKey:Td,queryFn:async()=>ed(await o.trpcClient.addons.custom.mutate({addonId:$,action:Uu,input:{}}))});d(()=>{b.isSuccess&&y(b.data===null)},[b.isSuccess,b.data]);let x=ae({projection:`slim`}),S=r(()=>(x.data??[]).filter(e=>e.type===Ve.Camera).map(e=>({id:e.id,name:e.name})).toSorted((e,t)=>e.name.localeCompare(t.name)),[x.data]),C=i({queryKey:Zd,queryFn:()=>o.trpcClient.notificationOutput.listTargets.query({})}),w=l({mutationFn:e=>o.trpcClient.addons.custom.mutate({addonId:$,action:Wu,input:{ruleId:e.ruleId,patch:{enabled:e.enabled}}}),onSuccess:()=>void b.refetch()}),T=l({mutationFn:e=>o.trpcClient.addons.custom.mutate({addonId:$,action:Gu,input:{ruleId:e}}),onSuccess:()=>void b.refetch()}),E=l({mutationFn:async e=>rd(await o.trpcClient.addons.custom.mutate({addonId:$,action:Ku,input:e})),onSuccess:e=>{h(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})),j=new Map(k.map(e=>[e.id,e.name])),M=b.isError||b.data===null,N=e=>{td(e)&&f({mode:`form`,rule:e})},P=n(a,{children:[b.isLoading&&u(Pu,{}),M&&!b.isLoading&&u(q,{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&&!M&&n(a,{children:[T.isError&&u(q,{title:`Could not delete the rule`,message:String(T.error)}),E.isError&&u(q,{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]}),u(Y,{size:`sm`,variant:`ghost`,type:`button`,className:`ml-2`,onClick:()=>_(null),children:`Dismiss`})]}),D.length===0?u(Fu,{testId:`timelapse-empty`,children:`No timelapse rules yet — create one, and each night's recorded footage arrives as a short video.`}):u(Iu,{columns:Od({nowMs:Date.now(),cameraNameById:O,targetNameById:j,deletePending:T.isPending,onToggle:(e,t)=>w.mutate({ruleId:e.id,enabled:t}),onOpen:N,onTest:e=>h({rule:e,deviceId:e.deviceIds[0]??null}),onConfirmDelete:e=>T.mutate(e.id)}),rows:D,rowKey:e=>e.id,minWidthPx:900,onRowClick:N})]}),s.mode===`form`&&u(wd,{rule:s.rule,cameras:S,fleet:me(x),targets:k,onCancel:()=>f({mode:`closed`}),onSaved:()=>{f({mode:`closed`}),b.refetch()}}),u(Qc,{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:[u(`label`,{className:`mb-1 block text-[11px] font-medium text-foreground`,children:`Which camera`}),u(V,{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)&&h({rule:p.rule,deviceId:t})},"data-testid":`timelapse-test-camera`})]}),onCancel:()=>h(null),onConfirm:()=>{p!==null&&p.deviceId!==null&&E.mutate({ruleId:p.rule.id,deviceId:p.deviceId})}})]});return e?P:u(Hr,{icon:A,title:`Timelapses`,subtitle:Ed,actions:M?void 0:n(Y,{size:`sm`,type:`button`,onClick:()=>f({mode:`form`,rule:null}),"data-testid":`timelapse-new`,children:[u(J,{className:`h-3.5 w-3.5`}),`New timelapse`]}),children:P})}function Od(e){return[{key:`name`,header:`Timelapse`,render:t=>u(Lu,{name:t.name,enabled:t.enabled,...td(t)?{onOpen:()=>e.onOpen(t),openTestId:`timelapse-edit-${t.id}`}:{},badges:td(t)?null:u(z,{variant:`warning`,children:`read-only`})})},{key:`cameras`,header:`Cameras`,render:t=>u(`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=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:gd(e.schedule)})},{key:`sampling`,header:`Sampling`,nowrap:!0,render:e=>{let t=vd(ad(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 u(`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=>u(`span`,{className:`text-[11px] text-foreground-subtle`,"data-testid":`timelapse-last-${t.id}`,children:_d(t.lastGeneratedAt,e.nowMs)})},{key:`enabled`,header:`On`,align:`center`,nowrap:!0,render:t=>u(Nu,{children:u(L,{checked:t.enabled,disabled:!td(t),onCheckedChange:n=>e.onToggle(t,n),"aria-label":`toggle ${t.name}`})})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:t=>n(Nu,{className:`flex items-center justify-end gap-1`,children:[u(Y,{size:`sm`,variant:`ghost`,type:`button`,disabled:!td(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:u(se,{className:`h-3.5 w-3.5`})}),u(Ru,{disabled:!td(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 kd=[`notificationCalendarEvents`,`list`],Ad=`nc.listCalendarEventsRules`,jd=`nc.upsertCalendarEventsRule`,Md=`nc.deleteCalendarEventsRule`;function Nd({openCreateKey:e=0}={}){let t=m(),r=o(),a=I(),[s,f]=c(!1),[p,h]=c(`Morning calendar`),[g,_]=c(7),[v,y]=c(En(void 0,void 0)),[b,S]=c(``),C=i({queryKey:kd,queryFn:async()=>(await t.trpcClient.addons.custom.mutate({addonId:$,action:Ad,input:{}})).rules}),w=i({queryKey:[`notificationOutput`,`listTargets`,`calendar-events`],queryFn:()=>t.trpcClient.notificationOutput.listTargets.query({})});d(()=>{e>0&&f(!0)},[e]);let T=l({mutationFn:async()=>{if(b.length===0)throw Error(`Pick a notification target`);let e=or(v);await t.trpcClient.addons.custom.mutate({addonId:$,action:jd,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()=>{f(!1),await r.invalidateQueries({queryKey:kd})}}),E=l({mutationFn:async e=>{await t.trpcClient.addons.custom.mutate({addonId:$,action:Md,input:{ruleId:e}})},onSuccess:async()=>{await r.invalidateQueries({queryKey:kd})}}),D=(a.data??[]).map(e=>({id:e.id,name:e.name})),O=w.data??[];return n(`div`,{className:`space-y-4`,"data-testid":`calendar-events-rules`,children:[s?n(`div`,{className:`space-y-3 rounded-md border p-4`,children:[u(`h3`,{className:`font-medium`,children:`New calendar events rule`}),n(`label`,{className:`block text-sm`,children:[`Name`,u(`input`,{className:`mt-1 w-full rounded border px-2 py-1`,value:p,onChange:e=>h(e.target.value)})]}),n(`label`,{className:`block text-sm`,children:[`Horizon (days)`,u(`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))})]}),u(No,{draft:v,onChange:y,exceptOffered:!0,plural:`calendars`,describe:e=>D.find(t=>t.id===e)?.name??e,testId:`calendar-events-scope`,renderPicker:(e,t,n)=>u(U,{devices:D,listState:a.isPending?`pending`:`answered`,value:e,onChange:t,emptyMeansAll:!0,noun:`calendar`,testId:`calendar-picker`},n)}),u(x,{label:`Target`,targets:O.map(e=>({id:e.id,name:typeof e.name==`string`?e.name:e.id,enabled:e.enabled===!0})),value:b,onChange:S,testId:`calendar-events-target`}),u(`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:[u(`button`,{type:`button`,className:`btn btn-primary`,disabled:T.isPending,onClick:()=>void T.mutateAsync(),children:`Save`}),u(`button`,{type:`button`,className:`btn btn-secondary`,onClick:()=>f(!1),children:`Cancel`})]}),T.isError?u(`p`,{className:`text-sm text-destructive`,children:T.error instanceof Error?T.error.message:String(T.error)}):null]}):u(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>f(!0),children:`New calendar events`}),C.isPending?u(`p`,{className:`text-sm text-muted-foreground`,children:`Loading…`}):C.isError?u(`p`,{className:`text-sm text-destructive`,children:C.error instanceof Error?C.error.message:String(C.error)}):(C.data??[]).length===0?u(`p`,{className:`text-sm text-muted-foreground`,children:`No calendar-events rules yet. Create one to send upcoming events at schedule time.`}):u(`ul`,{className:`divide-y rounded-md border`,children:(C.data??[]).map(e=>n(`li`,{className:`flex items-center justify-between gap-3 px-4 py-3`,children:[n(`div`,{children:[u(`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:u(`button`,{type:`button`,className:`btn btn-secondary text-xs`,onClick:()=>void E.mutateAsync(e.id),children:`Delete`})]},e.id))})]})}var Pd=[{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.`}],Fd=[{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 Id(e){return e===`summaries`||e===`timelapses`||e===`calendar-events`}function Ld(e){if(!(e==null||e.length===0))return Id(e)?e:Ye(e)}function Rd(e){let t=Pd.find(t=>t.key===e);if(t===void 0)throw Error(`unknown producer area: ${e}`);return t}function zd(e){return[...qt.filter(t=>t.key!==`mixed`||(e.get(`mixed`)??0)>0),...Pd]}function Bd(e){return!Id(e)}function Vd({value:e,family:t,onChange:r,draft:i}){if(t===void 0||!at.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:[u(`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:[u(`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:[u(`input`,{type:`radio`,name:`system-event-delivery`,checked:a!==null,onChange:()=>r({mode:`summary`,schedule:nt([ir])}),"data-testid":`rule-delivery-summary`}),`Summary on schedule — the current state, at set times`]})]}),a!==null&&u(Hd,{value:a,onChange:r,draft:i})]})}function Hd({value:e,onChange:t,draft:r}){let i=e.schedule.timezone,a=Qe({systemEventDelivery:e});return n(`div`,{className:`mt-2 space-y-2`,children:[n(`p`,{className:Mn,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: `,i??`the hub’s`,`.`]}),u(xr,{mode:`times`,value:e.schedule,onChange:n=>{n!==void 0&&t(Gn(e,n))}}),n(`fieldset`,{className:`flex flex-wrap gap-3 text-xs`,"data-testid":`rule-delivery-split`,children:[u(`legend`,{className:`sr-only`,children:`How the summary is sent`}),n(`label`,{className:`flex items-center gap-1.5`,children:[u(`input`,{type:`radio`,name:`system-event-summary-split`,checked:a===`rule`,onChange:()=>t(wn(e,`rule`)),"data-testid":`rule-delivery-split-rule`}),`One message with every category`]}),n(`label`,{className:`flex items-center gap-1.5`,children:[u(`input`,{type:`radio`,name:`system-event-summary-split`,checked:a===`section`,onChange:()=>t(wn(e,`section`)),"data-testid":`rule-delivery-split-section`}),`One notification per category (batteries, consumables, devices…)`]})]}),u(Ud,{draft:r,split:a})]})}function Ud({draft:e,split:t}){let r=m(),i=l({mutationFn:e=>r.trpcClient.notificationRules.previewStateSummary.mutate({rule:e})}),a=hr(i.status,i.data,i.error,t);return n(`div`,{className:`space-y-1.5`,children:[u(Y,{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&&u(`div`,{className:`text-[10px] text-foreground-subtle mt-0.5`,"data-testid":`rule-delivery-preview-result`,children:a.lines.map((e,t)=>u(`p`,{className:`whitespace-pre-wrap`,children:e},t))})]})}function Wd(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:Yd(e.data.horizonMs)}:{kind:`ran`,lastAt:n.lastAt,status:n.status,deviceId:n.deviceId}}var Gd=6e4,Kd=60*Gd,qd=24*Kd;function Jd(e,t){return e===1?`the last ${t}`:`the last ${String(e)} ${t}s`}function Yd(e){return e===null?`No delivery on record`:e>=qd?`Not in ${Jd(Math.floor(e/qd),`day`)}`:e>=Kd?`Not in ${Jd(Math.floor(e/Kd),`hour`)}`:e>=Gd?`Not in ${Jd(Math.floor(e/Gd),`minute`)}`:`Not in the window read`}t();var Xd=[`notificationRules`,`listRules`],Zd=[`notificationOutput`,`listTargets`,`forRules`],Qd=[`notificationRules`,`getConditionCatalog`],$d=[`deviceManager`,`gateableDevices`],ef=ot.options;function tf({onSimulateRule:t,onOpenHistory:o}={}){let s=m(),{t:f}=yt(),[h,g]=zr(),[_,y]=c({mode:`closed`}),[x,w]=c(0),[E,D]=c(0),[k,A]=c(0),j=Ld(h.get(`section`))??`all`,M=e=>{let t=new URLSearchParams(h);e===`all`?t.delete(`section`):t.set(`section`,e),g(t,{replace:!0})},N=i({queryKey:Xd,queryFn:async()=>(await s.trpcClient.notificationRules.listRules.query({})).rules}),P=e(null);d(()=>{if(_.mode!==`closed`)return;let e=h.get(`rule`);if(e===null||e===`new`){e===null&&(P.current=null);return}if(P.current===e)return;let t=N.data?.find(t=>t.id===e);t===void 0||!fn(t)||(P.current=e,y({mode:`form`,rule:t}))},[_.mode,h,N.data]);let F=i({queryKey:zu,queryFn:async()=>au(await s.trpcClient.addons.custom.mutate({addonId:$,action:wl,input:{}}))}),te=i({queryKey:Td,queryFn:async()=>ed(await s.trpcClient.addons.custom.mutate({addonId:$,action:Uu,input:{}}))}),I=i({queryKey:kd,queryFn:async()=>(await s.trpcClient.addons.custom.mutate({addonId:`pipeline-analytics`,action:`nc.listCalendarEventsRules`,input:{}})).rules??[]}),L=i({queryKey:Zd,queryFn:()=>s.trpcClient.notificationOutput.listTargets.query({})}),ne=i({queryKey:Qd,queryFn:()=>s.trpcClient.notificationRules.getConditionCatalog.query({})}),R=ae({projection:`slim`}),re=zs(),z=r(()=>R.data??[],[R.data]),se=me(R),B=r(()=>z.map(e=>e.id),[z]),ce=i({queryKey:[...$d,B],enabled:B.length>0,queryFn:async()=>{let e=[];for(let t of z){let n=Ke(await s.trpcClient.deviceManager.loadRuntimeState.query({deviceId:t.id}),ef);n.length>0&&e.push({id:t.id,name:t.name,states:n})}return e},staleTime:6e4}),le=r(()=>{let e=Vr(z);return z.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))},[z]),ue=r(()=>z.filter(e=>e.type===Ve.Camera).map(e=>({id:e.id,name:e.name})),[z]),de=Gr(r(()=>ue.map(e=>e.id),[ue])),fe=r(()=>{let e=new Map(ue.map(e=>[e.id,e.name]));return de.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})))},[de.results,ue]),V=r(()=>{let e=new Map;for(let t of L.data??[])e.set(t.id,t.name);return e},[L.data]),H=l({mutationFn:e=>s.trpcClient.notificationRules.setRuleEnabled.mutate(e),onSuccess:()=>void N.refetch()}),he=l({mutationFn:e=>s.trpcClient.notificationRules.deleteRule.mutate({ruleId:e}),onSuccess:()=>void N.refetch()}),U=Ys(),ge=v({}),_e=ge.data?.sequences??[],ve=pe(),W=N.data??[],ye=r(()=>{let e=new Map;for(let t of qt)e.set(t.key,W.filter(e=>He(e,t.key)).length);return e},[W]),be=r(()=>{let e=new Map;return e.set(`summaries`,F.data?.length??0),e.set(`timelapses`,te.data?.length??0),e.set(`calendar-events`,I.data?.length??0),e},[F.data,te.data,I.data]),xe=zd(ye),G=xe.find(e=>e.key===j)??xe[0]??qt[0],K=Id(G.key)?Rd(G.key):void 0,Se=Bd(G.key)?G.key:null,Ce=r(()=>Se===null?[]:W.filter(e=>He(e,Se)).toSorted((e,t)=>e.name.localeCompare(t.name)),[W,Se]),we=Se===null?!1:Lt(Se),Te=(e,t)=>{let n=new URLSearchParams(h);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})},Ee=()=>{let e=new URLSearchParams(h);e.delete(`rule`),e.delete(`editTab`),g(e,{replace:!0})},De=()=>{let e=h.get(`rule`);e!==null&&(P.current=e),y({mode:`closed`}),Ee()},Oe=e=>{fn(e)&&(P.current=e.id,y({mode:`form`,rule:e}),Te(e.id))},ke=()=>{let e=Se??`all`;P.current=`new`,y({mode:`form`,rule:null,seed:lt(e)}),Te(`new`)},Ae=e=>{if(e===`rule`){ke();return}if(e===`summary`){M(`summaries`),w(e=>e+1);return}if(e===`timelapse`){M(`timelapses`),D(e=>e+1);return}M(`calendar-events`),A(e=>e+1)};return n(Hr,{icon:b,title:`Rules`,subtitle:K?.blurb??(`blurb`in G?G.blurb:``),actions:K!==void 0||`creatable`in G&&G.creatable?j===`all`?n(T,{children:[n(C,{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:[u(J,{className:`h-3.5 w-3.5`}),`New rule`,u(p,{className:`h-3 w-3 opacity-80`})]}),u(ie,{align:`end`,className:`min-w-[14rem] py-1`,children:Fd.map(e=>u(oe,{onClick:()=>Ae(e.type),"data-testid":`rules-new-${e.type}`,title:e.hint,children:n(`span`,{className:`flex flex-col gap-0.5`,children:[u(`span`,{className:`font-medium`,children:e.label}),u(`span`,{className:`text-[10px] text-foreground-subtle font-normal`,children:e.hint})]})},e.type))})]}):K===void 0?n(Y,{size:`sm`,type:`button`,onClick:ke,children:[u(J,{className:`h-3.5 w-3.5`}),`newRuleLabel`in G?G.newRuleLabel:`New rule`]}):n(Y,{size:`sm`,type:`button`,onClick:()=>Ae(K.key===`summaries`?`summary`:K.key===`timelapses`?`timelapse`:`calendar-events`),"data-testid":K.key===`summaries`?`summary-new`:K.key===`timelapses`?`timelapse-new`:`calendar-events-new`,children:[u(J,{className:`h-3.5 w-3.5`}),K.newLabel]}):void 0,children:[u(ee,{value:G.key,onValueChange:e=>M(Ld(e)??j),children:u(S,{className:`mb-3`,children:xe.map(e=>n(O,{value:e.key,children:[e.label,u(`span`,{className:`ml-1.5 text-[10px] text-foreground-subtle`,children:Bd(e.key)?ye.get(e.key)??0:be.get(e.key)??0})]},e.key))})}),K?.key===`summaries`&&u(Vu,{embedded:!0,openCreateKey:x}),K?.key===`timelapses`&&u(Dd,{embedded:!0,openCreateKey:E}),K?.key===`calendar-events`&&u(Nd,{embedded:!0,openCreateKey:k}),Se!==null&&n(a,{children:[u(Hc,{rules:W}),N.isLoading&&u(Pu,{}),N.isError&&!N.isLoading&&u(q,{title:`Failed to load rules`,message:N.error instanceof Error?N.error.message:`Unknown error`,onRetry:()=>void N.refetch()}),!N.isLoading&&!N.isError&&Ce.length===0&&u(Fu,{children:`emptyHint`in G?G.emptyHint:`No rules yet.`}),Ce.length>0&&u(Iu,{columns:we?sf({targetNameById:V,snoozes:U,sequences:_e,deletePending:he.isPending,onToggle:(e,t)=>H.mutate({ruleId:e.id,enabled:t}),onOpen:Oe,t:f,onDuplicate:e=>Oe({...e,id:``,name:`${e.name} (copy)`}),onConfirmDelete:e=>he.mutate(e.id),lastRunOf:e=>Wd(re,e),...o?{onOpenHistory:o}:{}}):rf({targetNameById:V,snoozes:U,sequences:_e,deletePending:he.isPending,onToggle:(e,t)=>H.mutate({ruleId:e.id,enabled:t}),onOpen:Oe,t:f,onDuplicate:e=>Oe({...e,id:``,name:`${e.name} (copy)`}),onConfirmDelete:e=>he.mutate(e.id),...t?{onTest:t}:{},lastRunOf:e=>Wd(re,e),...o?{onOpenHistory:o}:{}}),rows:Ce,rowKey:e=>e.id,onRowClick:Oe,minWidthPx:760}),_.mode===`form`&&u(cf,{rule:_.rule,..._.seed?{seed:_.seed}:{},targets:L.data??[],actuatable:le,fleet:se,sequences:_e,onCreateSequence:async e=>{let t=await ve.mutateAsync({sequence:{name:e.name,...e.minDelaySec===void 0?{}:{minDelaySec:e.minDelaySec},actions:[...e.actions]}});return await ge.refetch(),t.sequence.id},catalog:Xt(ne.data?.catalog??[]),taxonomy:ne.data?.taxonomy,cameras:ue,gateable:ce.data??[],gateableScenes:fe,initialEditTab:Et(h.get(`editTab`)??``)??`rule`,onEditTabChange:e=>Te(_.mode===`form`?_.rule?.id??`new`:`new`,e),onCancel:De,onSaved:()=>{De(),N.refetch()}})]})]})}function nf(e,t){return e.replaceAll(`{{name}}`,t)}function rf(e){return[{key:`name`,header:`Rule`,render:t=>u(Lu,{name:t.name,enabled:t.enabled,...fn(t)?{onOpen:()=>e.onOpen(t)}:{}})},{key:`trigger`,header:`Trigger`,nowrap:!0,render:t=>n(`span`,{className:`flex items-center gap-1.5`,children:[u(`span`,{className:`text-[11px] text-foreground-subtle`,children:Fn(t,e.t(`notificationRules.grouping.choice`,kt))}),!Tt(t.delivery)&&u(z,{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 u(`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=>u(Vs,{cell:e.lastRunOf(t.id)})},{key:`priority`,header:`Priority`,align:`center`,nowrap:!0,render:e=>u(`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=>u(Nu,{children:u(Xs,{rule:t,snoozes:e.snoozes,exempt:Wt(t.conditions,Mt({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=>u(Nu,{children:u(L,{checked:t.enabled,onCheckedChange:n=>e.onToggle(t,n),"aria-label":`toggle ${t.name}`})})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:t=>fn(t)?n(Nu,{className:`flex items-center justify-end gap-1`,children:[u(Lc,{ruleId:t.id,ruleName:t.name,...t.conditions.devices?.[0]===void 0?{}:{fallbackDeviceId:t.conditions.devices[0]}}),e.onOpenHistory&&u(Hs,{rule:t,onOpenHistory:e.onOpenHistory}),e.onTest&&u(Y,{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:u(se,{className:`h-3.5 w-3.5`})}),u(Y,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onDuplicate(t),title:`Duplicate`,children:u(Te,{className:`h-3.5 w-3.5`})}),u(of,{rule:t,deps:e})]}):u(af,{rule:t,deps:e})}]}function af({rule:e,deps:t}){return n(Nu,{className:`flex items-center justify-end gap-1`,children:[u(`span`,{title:Re(Xe(e)).blurb,children:u(z,{variant:`warning`,children:`Recreate as one rule per family`})}),t.onOpenHistory&&u(Hs,{rule:e,onOpenHistory:t.onOpenHistory}),u(of,{rule:e,deps:t})]})}function of({rule:e,deps:t}){let{t:n}=yt();return u(Ru,{pending:t.deletePending,title:n(`notificationRules.delete.confirm`,`Delete this rule?`),message:nf(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:nf(n(`notificationRules.delete.aria`,`delete {{name}}`),e.name),onConfirm:()=>t.onConfirmDelete(e)})}function sf(e){let t=rf(e),n=e=>t.filter(t=>t.key===e);return[...n(`name`),{key:`events`,header:`Events`,render:e=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:Wn(e.conditions.systemEvent?.kinds)})},{key:`scope`,header:`Scope`,nowrap:!0,render:e=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:Vn(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 u(`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=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:zt(e.throttle.cooldownSec)})},...n(`lastRun`),...n(`snooze`),...n(`enabled`),...n(`actions`)]}function cf({rule:e,seed:t,targets:o,catalog:s,taxonomy:d,cameras:f,gateable:p,gateableScenes:h,actuatable:g,fleet:_,sequences:v,onCreateSequence:y,initialEditTab:x=Dn,onEditTabChange:C,onSaved:T,onCancel:E}){let A=m(),{t:M}=yt(),N=e!=null&&e.id.length>0,[te]=c(()=>e?dn(e):Jt(t?.delivery,t?.conditions)),[I,ne]=c(te),[R,re]=c(null),[ie,z]=c(null),[ae,oe]=c(x),B=e=>ne(t=>({...t,...e})),ce=e?Ot(e):void 0,le=l({mutationFn:async()=>{let t=At(I,ce,s);if(N&&e){let n=sn(I,s);await A.trpcClient.notificationRules.updateRule.mutate({ruleId:e.id,patch:t,...n.length>0?{clear:n}:{}})}else await A.trpcClient.notificationRules.createRule.mutate({rule:t})},onSuccess:T,onError:e=>re(e instanceof Error?e.message:`Save failed`)}),ue=l({mutationFn:async()=>{let e=At(I,ce,s);return(await A.trpcClient.notificationRules.testRule.mutate({rule:e,lookbackMinutes:60})).results},onMutate:()=>z(null),onSuccess:e=>z(e),onError:e=>re(e instanceof Error?e.message:`Test failed`)}),de=I.targetIds.map(e=>o.find(t=>t.id===e)?.name??e),fe=i({queryKey:[`userManagement`,`listUsers`],queryFn:()=>A.trpcClient.userManagement.listUsers.query()}).data,pe=r(()=>(fe??[]).map(e=>({value:e.id,label:e.username,...e.isAdmin?{badge:`admin`}:{}})),[fe]),me=Gt(I),he=me===`immediate-grouped`,U=String(I.groupingSec??20),ge=rn(I).map(e=>({...e,label:e.value===`immediate-grouped`?M(`notificationRules.grouping.choice`,e.label):e.label,hint:e.value===`immediate-grouped`?M(`notificationRules.grouping.hint`,{n:U,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}}`,U):e.hint})),_e=ge.find(e=>e.value===me)?.hint,ve=Lr(I,ce),W=pt(I.delivery),ye=Xe(I),be=Re(ye),xe=Be(ye),G=ze(ye),K=i({queryKey:[`deviceManager`,`listDeviceIdsByCaps`,`nc-rule-devices`,G??[]],enabled:G!==null,queryFn:async()=>{let e=await Promise.all((G??[]).map(e=>A.trpcClient.deviceManager.listDeviceIdsByCaps.query({capNames:[...e]})));return new Set(e.flat())},staleTime:6e4}),Se=r(()=>{if(G===null||K.data===void 0)return g;let e=K.data,t=new Set(br(I.deviceScope));return g.filter(n=>e.has(n.id)||t.has(n.id))},[g,G,K.data,I.deviceScope]),Ce=G!==null&&K.isLoading,Te=G!==null&&K.isError,Ee=to(),q=e=>({family:`rule`,field:e,kind:ye,delivery:I.delivery,...nn(I)?{systemEventDelivery:`summary`}:{},...I.conditions.systemEvent?{systemEventKinds:[...I.conditions.systemEvent.kinds]}:{}}),J=e=>Ee.data?Za(Ee.data,q(e)):void 0,De=an(I),Oe=Wt(I.conditions,Mt(I.actions,v)),ke=I.conditions.identities!==void 0||I.conditions.plates!==void 0,Ae=Ar(I.delivery,I.conditions),je=Ae.some(e=>e.key===ae)?ae:Dn;return Tt(I.delivery)?u(w,{open:!0,onOpenChange:e=>!e&&E(),children:n(we,{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:[u(b,{className:`h-4 w-4 shrink-0 text-foreground-subtle`}),u(`span`,{className:`truncate`,children:N?`Edit ${e?.name}`:`New notification rule`})]}),u(Y,{size:`sm`,variant:`ghost`,type:`button`,onClick:E,children:`Cancel`})]}),R&&u(`div`,{className:`shrink-0 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger mb-3`,children:R}),N&&e&&n(`div`,{className:`shrink-0 mb-3 space-y-2`,children:[u(wc,{kind:`rule`,ruleId:e.id,enabled:e.enabled,updatedAt:e.updatedAt}),u(Dc,{ruleId:e.id,cameraName:e=>f.find(t=>t.id===e)?.name??`camera ${String(e)}`})]}),n(ee,{value:je,onValueChange:e=>{let t=Et(e);t!==void 0&&(oe(t),C?.(t))},className:`flex min-h-0 flex-1 flex-col`,children:[u(S,{className:`mb-3 shrink-0`,children:Ae.map(e=>u(O,{value:e.key,children:e.label},e.key))}),n(k,{className:`pr-1`,children:[n(F,{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:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Name`}),u(H,{value:I.name,onChange:e=>B({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:[u(L,{checked:I.enabled,onCheckedChange:e=>B({enabled:e}),"aria-label":`enabled`}),`Enabled`]})]}),n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Trigger`}),u(V,{value:me,onChange:e=>{let t=Vt(e.target.value);t&&ne(e=>Jn(e,t))},options:ge.map(e=>({value:e.value,label:e.label}))}),_e&&u(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:_e}),he&&n(`div`,{className:`mt-2`,children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:M(`notificationRules.grouping.seconds`,`Group for (seconds)`)}),u(H,{type:`number`,min:5,max:60,step:1,value:U,"data-testid":`rule-grouping-sec`,onChange:e=>{let t=vn(e.target.value);t!==void 0&&B({groupingSec:t})}}),u(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:M(`notificationRules.grouping.minNote`,`At least 5 s: subjects arriving together share one message.`)}),ke&&u(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:M(`notificationRules.grouping.scopedHint`,{n:U,defaultValue:`A subject not recognised within {{n}} s is not notified.`}).replaceAll(`{{n}}`,U)})]}),me===`immediate`&&ke&&u(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:M(`notificationRules.grouping.plainRecognitionHint`,`Fires only if the name is already known when an event is written — choose Immediate, grouped to wait for it.`)})]}),!N&&xe!==void 0&&u(gs,{family:xe,onChange:e=>ne(t=>Kt(t,e))}),u(D,{label:`Delivery targets`,targets:o,value:I.targetIds,onChange:e=>ne(t=>({...t,targetIds:e})),emptyMessage:`No delivery targets configured. Add one under the Targets tab first.`,testIdPrefix:`rule-target`}),u(j,{mode:`multi`,options:pe,value:I.targetUsers,onChange:e=>B({targetUsers:e}),searchable:!0,creatable:!1,label:`Notify users`,description:`Delivers to the targets each user owns, only for cameras that user can access.`,emptyMessage:`No users to notify.`,placeholder:`Search users…`,testId:`rule-notify-users`,optionTestIdPrefix:`rule-user`,listboxId:`rule-notify-users-listbox`})]}),n(F,{value:`devices`,className:`space-y-4`,children:[Ce&&u(`p`,{className:`text-[10px] text-foreground-subtle`,"data-testid":`rule-devices-compat-loading`,children:M(`notificationRules.devices.compatLoading`,`Checking which devices this rule's kind can use…`)}),Te&&u(`p`,{className:`text-[10px] text-foreground-subtle`,"data-testid":`rule-devices-compat-failed`,children:M(`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.`)}),u(Ko,{devices:Se,scope:I.deviceScope,onChange:e=>B({deviceScope:e}),listState:_.state,savedScope:te.deviceScope,exceptOffered:wt(s,`devicesExclude`,I)})]}),u(F,{value:`actions`,className:`space-y-4`,children:u(fo,{value:I.actions,onChange:e=>B({actions:e}),devices:g,devicesState:_.state,sequences:v,onCreateSequence:y})}),n(F,{value:`advanced`,className:`space-y-4`,children:[u(js,{catalog:s,delivery:I.delivery,conditions:I.conditions,onConditionsChange:e=>B({conditions:e})}),n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Cooldown (seconds)`}),u(H,{type:`number`,min:0,max:jr,step:1,value:String(I.cooldownSec),"data-testid":`rule-cooldown`,onChange:e=>{let t=Ft(e.target.value);t!==void 0&&B({cooldownSec:t})}}),n(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:[W?`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(jr),` (24 hours).`]})]}),n(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Cooldown counted`}),u(V,{value:I.cooldownScope,onChange:e=>{let t=mr(e.target.value);t!==void 0&&B({cooldownScope:t})},options:cn.map(e=>({value:e.value,label:e.label})),"data-testid":`rule-cooldown-scope`}),u(`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:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Across object classes`}),u(V,{value:I.cooldownGranularity??`per-class`,onChange:e=>B({cooldownGranularity:Ut(e.target.value)}),options:Dt.map(e=>({value:e.value,label:e.label})),"data-testid":`rule-cooldown-granularity`}),u(`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:[u(L,{checked:I.snoozeAllowGlobal,onCheckedChange:e=>B({snoozeAllowGlobal:e}),"aria-label":`allow global snooze`,disabled:Oe}),`Anyone may snooze this rule for everyone`]}),u(`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.`})]}),!Oe&&n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Snooze buttons`}),n(a,{children:[u(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:St.map(e=>{let t=I.snoozeOptions??Xn,n=t.includes(e);return u(Y,{type:`button`,size:`sm`,variant:n?`primary`:`outline`,onClick:()=>B({snoozeOptions:n?t.filter(t=>t!==e):[...t,e].toSorted((e,t)=>e-t)}),children:It(e)},e)})}),u(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:I.snoozeOptions===void 0?`Not set — the notification offers the defaults (${Xn.map(It).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.`:I.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.`}),I.snoozeOptions!==void 0&&u(Y,{type:`button`,size:`sm`,variant:`ghost`,className:`mt-1`,onClick:()=>B({snoozeOptions:void 0}),children:`Back to the defaults`})]})]}),N&&e&&!Oe&&n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Silence it now`}),u(Gs,{ruleId:e.id,ruleName:e.name,exempt:Oe,variant:`full`})]})]}),n(F,{value:`notification`,className:`space-y-4`,children:[n(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Priority`}),u(V,{value:String(I.priority),onChange:e=>B({priority:Number(e.target.value)}),options:Yn.map(e=>({value:String(e.value),label:e.label}))})]}),!be.carriesMedia&&u(`div`,{className:`rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,"data-testid":`rule-media-none`,children:be.mediaBlurb??`A system event carries no image: there is no camera frame behind "a node went offline". This rule sends text only.`}),be.carriesMedia&&ye===`sensor`&&u(`div`,{className:`rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:M(`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.`)}),be.carriesMedia&&ye!==`sensor`&&be.mediaBlurb!==void 0&&u(`div`,{className:`rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:be.mediaBlurb}),be.carriesMedia&&ye!==`sensor`&&n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Media attachment`}),u(V,{value:I.mediaAttach,onChange:e=>{let t=bn(e.target.value);t&&B({mediaAttach:t})},options:Zn.map(e=>({value:e.value,label:e.label}))}),u(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:Zn.find(e=>e.value===I.mediaAttach)?.description}),n(`div`,{className:`mt-2 space-y-1`,children:[be.carriesSubjectCrop&&n(`label`,{className:`flex items-center gap-2 text-xs text-foreground cursor-pointer`,children:[u(`input`,{type:`checkbox`,checked:I.mediaZoneCrop,onChange:e=>B({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:[u(`input`,{type:`checkbox`,checked:I.mediaGif,onChange:e=>B({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:[u(`input`,{type:`checkbox`,checked:I.mediaClip,onChange:e=>B({mediaClip:e.target.checked}),className:`accent-primary`}),`Attach an MP4 clip around the event`]})]}),(I.mediaGif||I.mediaClip)&&n(`div`,{className:`mt-2`,children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Video quality`}),u(V,{value:I.mediaProfile??``,onChange:e=>B({mediaProfile:un(e.target.value)}),options:Nr.map(e=>({value:e.value,label:e.label}))}),u(`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.`}),u(`label`,{className:`mt-2 block text-[11px] font-medium text-foreground mb-1`,children:`Playback speed`}),u(V,{value:I.mediaClipSpeed===void 0?``:String(I.mediaClipSpeed),onChange:e=>B({mediaClipSpeed:mn(e.target.value)}),options:on.map(e=>({value:e.value,label:e.label}))}),u(`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.`})]})]}),ye===`sensor`&&be.carriesMedia&&n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Linked cameras`}),u(V,{value:I.mediaLinkedCameras??``,onChange:e=>B({mediaLinkedCameras:gn(e.target.value)}),options:Zt.map(e=>({value:e.value,label:e.label})),"data-testid":`rule-media-linked-cameras`}),u(`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.`})]}),be.carriesMedia&&ye!==`sensor`&&be.carriesSubjectCrop&&n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Image frame`}),u(V,{value:I.mediaFrame??``,onChange:e=>B({mediaFrame:tn(e.target.value)}),options:jt.map(e=>({value:e.value,label:e.label}))}),u(`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:[u(oo,{label:`Notification title`,value:I.templateTitle,onChange:e=>B({templateTitle:e}),vars:J(`title`),testId:`rule-template-title`}),u(oo,{label:`Notification body`,value:I.templateBody,onChange:e=>B({templateBody:e}),vars:J(`body`),multiline:!0,testId:`rule-template-body`}),u(`p`,{className:`text-[10px] text-foreground-subtle`,children:`Leave both blank for the hub's own wording (editable on the Texts tab).`}),ln(I)!==null&&u(`p`,{className:`text-[10px] text-warning`,"data-testid":`rule-template-summary-warning`,children:ln(I)}),u(so,{context:q(`body`),title:I.templateTitle,body:I.templateBody,testId:`rule-template-preview`})]})]}),n(F,{value:`conditions`,className:`space-y-4`,children:[n(`div`,{className:`rounded-md border border-border px-3 py-3`,children:[u(`div`,{className:`mb-2 text-[11px] font-semibold text-foreground`,children:W?`Which system events`:Mr(I.conditions)??`Conditions`}),I.conditions.audio!==void 0&&u(`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).`}),I.conditions.occupancy!==void 0&&u(`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.`}),W&&u(`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?u(`p`,{className:`text-[10px] text-foreground-subtle`,children:`Condition catalog unavailable — this rule matches on its trigger and targets alone.`}):u(_s,{catalog:nn(I)?s.filter(e=>e.id!==`schedule`):s,taxonomy:d,delivery:I.delivery,conditions:I.conditions,classScope:I.classScope,onClassScopeChange:e=>B({classScope:e}),actions:pr(I.actions),sequenceActionsOf:e=>v.find(t=>t.id===e)?.actions,savedConditions:te.conditions,schedule:I.schedule,deviceIds:Qt(I),zoneCameraIds:Po(I.deviceScope,f),cameras:f,fleet:_,allDevices:g,gateable:p,gateableScenes:h,onConditionsChange:e=>B({conditions:e}),onScheduleChange:e=>B({schedule:e})})]}),W&&u(Vd,{value:I.systemEventDelivery,family:xe,onChange:e=>B({systemEventDelivery:e}),draft:()=>At(I,ce,s)}),N&&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:[u(`div`,{className:`text-[11px] font-semibold text-foreground`,children:`Test this rule for real`}),u(Lc,{ruleId:e.id,ruleName:e.name,variant:`full`,showResult:!0,...Qt(I)[0]===void 0?{}:{fallbackDeviceId:Qt(I)[0]}})]}),u(`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.`})]}),!W&&n(`div`,{className:`rounded-md border border-border px-3 py-3`,children:[n(`div`,{className:`flex items-center justify-between gap-2`,children:[u(`div`,{className:`text-[11px] font-semibold text-foreground`,children:`Test rule`}),n(Y,{size:`sm`,variant:`outline`,type:`button`,disabled:ue.isPending||!Rt(I,ce,new Set(v.map(e=>e.id))),onClick:()=>{re(null),ue.mutate()},children:[ue.isPending?u(P,{className:`h-3.5 w-3.5 animate-spin`}):u(se,{className:`h-3.5 w-3.5`}),`Dry-run (last 60 min)`]})]}),u(`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&&u(uf,{delivery:I.delivery,results:ie,targetNames:de})]})]})]})]}),De.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 `,De.length,` condition`,De.length===1?``:`s`,` this kind of rule cannot use:`]}),De.map(e=>n(`p`,{children:[u(`span`,{className:`text-foreground`,children:e.conditionId}),` — `,e.reason]},e.conditionId))]}),ve.length>0&&u(`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:ve.map(e=>u(`p`,{children:e},e))}),n(`div`,{className:`flex shrink-0 justify-end gap-2 mt-4`,children:[u(Y,{variant:`secondary`,size:`sm`,type:`button`,onClick:E,children:`Cancel`}),n(Y,{size:`sm`,type:`button`,disabled:le.isPending||!Rt(I,ce,new Set(v.map(e=>e.id))),onClick:()=>{re(null),le.mutate()},children:[le.isPending&&u(P,{className:`h-3.5 w-3.5 animate-spin`}),N?`Save changes`:`Create rule`]})]})]})}):u(lf,{rule:e,onCancel:E})}function lf({rule:e,onCancel:t}){let r=Object.keys(e?.conditions??{});return u(w,{open:!0,onOpenChange:e=>!e&&t(),children:n(we,{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:[u(b,{className:`h-4 w-4 text-foreground-subtle`}),e?.name??`Rule`]}),u(z,{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 `,u(`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:[u(`dt`,{className:`w-24 shrink-0 text-foreground-subtle`,children:`Trigger`}),u(`dd`,{className:`text-foreground`,children:e?.delivery})]}),n(`div`,{className:`flex gap-2`,children:[u(`dt`,{className:`w-24 shrink-0 text-foreground-subtle`,children:`Enabled`}),u(`dd`,{className:`text-foreground`,children:e?.enabled?`yes`:`no`})]}),n(`div`,{className:`flex gap-2`,children:[u(`dt`,{className:`w-24 shrink-0 text-foreground-subtle`,children:`Targets`}),u(`dd`,{className:`text-foreground`,children:e?.targets.length??0})]}),n(`div`,{className:`flex gap-2`,children:[u(`dt`,{className:`w-24 shrink-0 text-foreground-subtle`,children:`Conditions`}),u(`dd`,{className:`text-foreground`,children:r.length>0?r.join(`, `):`none`})]})]}),u(`div`,{className:`flex justify-end gap-2 mt-4`,children:u(Y,{variant:`secondary`,size:`sm`,type:`button`,onClick:t,children:`Close`})})]})})}function uf({delivery:e,results:t,targetNames:r}){if(e===`device-event`)return u(`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 u(`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.`]}),u(`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?u(Se,{className:`h-3.5 w-3.5 shrink-0 text-success`}):u(G,{className:`h-3.5 w-3.5 shrink-0 text-foreground-subtle`}),u(`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]}),u(`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 df=`mt-1 w-full rounded border border-border bg-background px-2 py-1 text-xs`,ff=`block text-[11px] font-medium text-foreground`,pf=[[`notificationRules`,`listSequences`]];function mf(){return{name:``,minDelaySec:``,actions:[yn()]}}function hf(e){return{id:e.id,name:e.name,minDelaySec:e.minDelaySec===void 0?``:String(e.minDelaySec),actions:[...e.actions]}}function gf(){let e=o(),t=v({}),i=pe(),a=R(),s=Oe(),[l,d]=c(null),f=ae({projection:`slim`}),p=me(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:pf})},_=async()=>{if(l===null||l.name.trim()===``||l.actions.length===0)return;let e={name:l.name.trim(),...l.minDelaySec===``?{}:{minDelaySec:Number(l.minDelaySec)},actions:l.actions};l.id===void 0?await i.mutateAsync({sequence:e}):await a.mutateAsync({sequenceId:l.id,sequence:e}),d(null),h()},y=t.data?.sequences??[];return n(Hr,{icon:Yr,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(Y,{size:`sm`,type:`button`,onClick:()=>d(mf()),children:[u(J,{className:`h-3.5 w-3.5`}),` New sequence`]}),children:[l!==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:[u(`label`,{className:ff,children:`Name`}),u(H,{className:`mt-1`,value:l.name,onChange:e=>d({...l,name:e.target.value})})]}),n(`div`,{className:`w-28`,children:[u(`label`,{className:ff,children:`Min delay (s)`}),u(`input`,{type:`number`,min:0,className:df,value:l.minDelaySec,onChange:e=>d({...l,minDelaySec:e.target.value})})]})]}),n(`div`,{className:`space-y-2 border-l-2 border-border-subtle pl-3`,children:[l.actions.map((e,t)=>u(_f,{step:e,devices:m,listState:p.state,fleet:p,onChange:e=>d({...l,actions:l.actions.map((n,r)=>r===t?e:n)}),onRemove:()=>d({...l,actions:l.actions.filter((e,n)=>n!==t)})},`s-${String(t)}`)),n(Y,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>d({...l,actions:[...l.actions,yn()]}),children:[u(J,{className:`h-3.5 w-3.5`}),` Step`]})]}),n(`div`,{className:`flex gap-2`,children:[u(Y,{size:`sm`,type:`button`,onClick:()=>void _(),children:`Save`}),u(Y,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>d(null),children:`Cancel`})]})]}),t.isPending?u(`p`,{className:`text-sm text-foreground-subtle`,children:`Loading…`}):y.length===0?u(`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.`}):u(`ul`,{className:`space-y-2`,children:y.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:[u(`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:[u(Y,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>d(hf(e)),children:`Edit`}),u(Y,{size:`sm`,variant:`ghost`,type:`button`,title:`Delete`,onClick:()=>{s.mutateAsync({sequenceId:e.id}).then(h)},children:u(g,{className:`h-3.5 w-3.5`})})]})]},e.id))})]})}function _f({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:[u(`label`,{className:ff,children:`Step`}),n(`select`,{className:df,value:e.kind,onChange:e=>a(e.target.value===`wait`?{kind:`wait`,seconds:5}:{kind:`cap`,deviceId:t[0]?.id??0,cap:``,method:``}),children:[u(`option`,{value:`cap`,children:`Do`}),u(`option`,{value:`wait`,children:`Wait`})]})]}),e.kind===`wait`?n(`div`,{className:`w-28`,children:[u(`label`,{className:ff,children:`Seconds`}),u(`input`,{type:`number`,min:0,max:300,className:df,value:e.seconds,onChange:e=>a({kind:`wait`,seconds:Number(e.target.value)})})]}):u(Ur,{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}}})}}),u(Y,{size:`sm`,variant:`ghost`,type:`button`,onClick:o,title:`Remove`,children:u(g,{className:`h-3.5 w-3.5`})})]})}var vf=[{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 yf(e){return vf.find(t=>t.value===e)?.value}function bf(e){return e===`object-event`||e===`audio-event`?`immediate`:e===`occupancy-event`?`device-event`:e}function xf(e){return``}var Sf={x:.25,y:.25,w:.5,h:.5},Cf={zoneId:``,zoneName:``,className:``,count:1,previousCount:0,occupied:!0,threshold:1};function wf(){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:Sf,occupancy:Cf,timestampLocal:``,onlyRuleId:``,bypassCooldown:!1,bypassMute:!1,runActions:!1,still:`live`}}function Tf(e){return e.deviceId!==null}function Ef(e){if(e.trim().length===0)return;let t=Number(e);return Number.isFinite(t)?t:void 0}function Df(e){if(e.trim().length===0)return;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}function Of(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 kf(e){if(e.deviceId===null)return null;let t=e.trigger,n=Df(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:Af(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 Af(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 jf(e){return Math.min(1,Math.round((e+.05)*100)/100)}function Mf(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 Nf(e){let t=wf(),n=e.conditions,r=Mf(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:jf(n.minConfidence)},...n.minLabelConfidence===void 0?{}:{labelConfidence:jf(n.minLabelConfidence)},...n.minImportance===void 0?{}:{importance:jf(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:xf(r),...n.customZones!==void 0&&n.customZones.length>0?{bboxEnabled:!0}:{},...n.occupancy===void 0?{}:{occupancy:Pf(n.occupancy)},onlyRuleId:e.id}}function Pf(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 Ff(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 If(e){return{form:Nf(e),caveats:Ff(e),ruleName:e.name}}var Lf=null;function Rf(e){Lf=e}function zf(){return Lf}function Bf(){Lf=null}var Vf=[`n/a`,`clear`,`suppressed`,`bypassed`],Hf=[`live`,`none`,`unavailable`,`unattachable`];function Uf(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Wf(e,t){let n=e[t];return typeof n==`string`?n:void 0}function Gf(e,t){let n=e[t];return Array.isArray(n)?n.filter(e=>typeof e==`string`):[]}function Kf(e){if(!Uf(e))return null;let t=Wf(e,`ruleId`),n=Wf(e,`ruleName`),r=Wf(e,`cooldown`),i=Vf.find(e=>e===r);if(t===void 0||n===void 0||i===void 0||typeof e.matched!=`boolean`)return null;let a=Wf(e,`failedCondition`),o=Array.isArray(e.matchedOn)?Gf(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:Gf(e,`targetIds`)}}function qf(e){if(!Uf(e))return null;let t=Wf(e,`recordId`),n=Wf(e,`delivery`),r=Wf(e,`still`),i=Hf.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=Kf(e);t!==null&&o.push(t)}let s=Wf(e,`droppedBy`);return{recordId:t,origin:`synthetic`,delivery:n,candidates:typeof e.candidates==`number`?e.candidates:0,outcomes:o,still:i,notes:Gf(e,`notes`),...s===void 0?{}:{droppedBy:s}}}function Jf(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 Yf=new Set([`sensor`,`control`,`custom`]);function Xf({form:e,cameras:t,taxonomy:r,kinds:i,kindsLoading:a,onPatch:o}){let s=e.deviceId===null?[]:[e.deviceId],c=st(`classes`,r);if(e.trigger===`device-event`)return n(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-2`,children:[u(`div`,{className:`text-[11px] font-semibold text-foreground`,children:`What happened`}),u(Zf,{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:[u(`div`,{className:`text-[11px] font-semibold text-foreground`,children:`What happened`}),n(`div`,{children:[u(`label`,{className:X,children:`Audio classes`}),u(Sr,{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:[u(`label`,{className:X,children:`Zones`}),u(Pr,{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:[u(`div`,{className:`text-[11px] font-semibold text-foreground`,children:`What happened`}),u(Qf,{form:e,cameras:t,taxonomy:r,onPatch:o})]}):n(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-2`,children:[u(`div`,{className:`text-[11px] font-semibold text-foreground`,children:`What happened`}),n(`div`,{children:[u(`label`,{className:X,children:`Detected classes`}),c===null?u(xn,{value:e.classNames,placeholder:`Class id (person, car…)`,onChange:e=>o({classNames:e})}):u(Dr,{picker:c,value:e.classNames,onChange:e=>o({classNames:e})})]}),n(`div`,{children:[u(`label`,{className:X,children:`Zones the subject is in`}),u(Pr,{deviceIds:s,cameras:t,value:e.zones,onChange:e=>o({zones:e})})]}),e.trigger===`package-event`&&n(`div`,{className:`max-w-[14rem]`,children:[u(`label`,{className:`block text-[11px] font-medium text-foreground`,children:`Package phase`}),u(V,{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 Zf({form:e,kinds:t,loading:r,onPatch:i}){let o=t.filter(e=>Yf.has(e.category)),s=o.find(t=>t.kind===e.sensorKind);return n(a,{children:[n(`div`,{children:[u(`label`,{className:X,children:`Event kind`}),u(V,{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&&u(`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:[u(`label`,{className:X,children:`Source device`}),u(H,{type:`number`,value:e.sourceDeviceId===null?``:String(e.sourceDeviceId),placeholder:`the camera itself`,onChange:e=>i({sourceDeviceId:Ef(e.target.value)??null})}),u(`p`,{className:Mn,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:[u(`label`,{className:X,children:`Event type token`}),u(H,{value:e.eventType,placeholder:`press, press_long…`,onChange:e=>i({eventType:e.target.value})}),u(`p`,{className:Mn,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 Qf({form:e,cameras:t,taxonomy:r,onPatch:i}){let o=e.deviceId===null?[]:[e.deviceId],s=st(`occupancy`,r),c=s===null?[]:s.groups.flatMap(e=>e.options),l=e.occupancy,d=e=>i({occupancy:{...l,...e}});return n(a,{children:[n(`div`,{children:[u(`label`,{className:X,children:`Zone`}),u(Pr,{deviceIds:o,cameras:t,value:l.zoneId===``?[]:[l.zoneId],onChange:e=>d({zoneId:e[e.length-1]??``})}),u(`p`,{className:Mn,children:`Leave empty for the whole frame.`})]}),n(`div`,{className:`max-w-[14rem]`,children:[u(`label`,{className:X,children:`Class`}),u(V,{value:l.className,options:[{value:``,label:`— any class —`},...c.map(e=>({value:e.value,label:e.label}))],onChange:e=>d({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`,u(H,{type:`number`,min:0,className:`w-20`,value:String(l.count),onChange:e=>d({count:Ef(e.target.value)??0})})]}),n(`label`,{className:`text-[11px] text-foreground-subtle`,children:[`Count before`,u(H,{type:`number`,min:0,className:`w-20`,value:String(l.previousCount),onChange:e=>d({previousCount:Ef(e.target.value)??0})})]}),n(`label`,{className:`text-[11px] text-foreground-subtle`,children:[`Threshold`,u(H,{type:`number`,min:1,className:`w-20`,value:String(l.threshold),onChange:e=>d({threshold:Ef(e.target.value)??1})})]}),n(`label`,{className:`flex items-center gap-2 pb-1 text-[11px] text-foreground`,children:[u(L,{checked:l.occupied,onCheckedChange:e=>d({occupied:e}),"aria-label":`occupied`}),`Occupied`]})]})]})}function $f({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:[u(`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:[u(L,{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:[u(`div`,{className:`max-w-[12rem]`,children:u(V,{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`})})}),u(Pr,{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:[u(L,{checked:e.bboxEnabled,onCheckedChange:e=>r({bboxEnabled:e}),"aria-label":`bounding box`}),`Carry a bounding box`]}),u(`p`,{className:Mn,children:"Normalized 0–1, top-left origin. Feeds the `customZones` condition and decides how the still is cropped or boxed."}),e.bboxEnabled&&u(`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,u(H,{type:`number`,min:0,max:1,step:.05,className:`w-20`,value:String(e.bbox[t]),onChange:n=>r({bbox:{...e.bbox,[t]:Ef(n.target.value)??0}})})]},t))})]}),n(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[n(`div`,{children:[u(`label`,{className:X,children:`Happened at`}),n(`div`,{className:`flex items-center gap-2`,children:[u(H,{type:`datetime-local`,value:e.timestampLocal,onChange:e=>r({timestampLocal:e.target.value})}),e.timestampLocal===``?u(Y,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>r({timestampLocal:Of(Date.now())}),children:`Set`}):u(Y,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>r({timestampLocal:``}),children:`Now`})]}),u(`p`,{className:Mn,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:[u(`label`,{className:X,children:`Detection source`}),u(V,{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 ep({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:[u(L,{checked:e,onCheckedChange:a,"aria-label":t}),t,i&&u(z,{variant:`danger`,children:`actuates devices`})]}),u(`p`,{className:Mn,children:r})]})}t();var tp={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.`},np={"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 rp({result:e,targetName:t}){return n(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-3`,children:[u(`p`,{className:`text-xs font-medium text-foreground`,children:Jf(e)}),n(`div`,{className:`flex flex-wrap items-center gap-2 text-[11px] text-foreground-subtle`,children:[u(ip,{recordId:e.recordId}),n(`span`,{children:[`delivery `,u(`span`,{className:`text-foreground`,children:e.delivery})]}),n(`span`,{children:[`candidates `,u(`span`,{className:`text-foreground`,children:e.candidates})]}),n(`span`,{title:tp[e.still],children:[`still `,u(`span`,{className:`text-foreground`,children:e.still})]}),e.droppedBy!==void 0&&n(z,{variant:`warning`,children:[`dropped: `,e.droppedBy]})]}),e.notes.length>0&&u(`ul`,{className:`space-y-1 rounded-md border border-border bg-surface px-2.5 py-2`,children:e.notes.map(e=>u(`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`,` `,u(`span`,{className:`text-foreground`,children:e.delivery}),` delivery, or the ones that do were filtered out before evaluation — the notes above say which.`]}):u(`ul`,{className:`divide-y divide-border rounded-md border border-border`,children:e.outcomes.map(e=>u(ap,{outcome:e,targetName:t},e.ruleId))})]})}function ip({recordId:e}){let[t,r]=c(!1);return n(`span`,{className:`inline-flex items-center gap-1 rounded border border-border px-1.5 py-0.5`,children:[u(`code`,{className:`text-[10px] text-foreground`,children:e}),u(Y,{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:u(Te,{className:`h-3 w-3`})}),t&&u(`span`,{className:`text-[10px] text-success`,children:`copied`})]})}function ap({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?u(Se,{className:`h-3.5 w-3.5 shrink-0 text-success`}):u(G,{className:`h-3.5 w-3.5 shrink-0 text-foreground-subtle`}),u(`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:np[e.cooldown],children:[`cooldown: `,e.cooldown]})]}),!e.matched&&u(`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`,` `,u(`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 op=`pipeline-analytics`,sp=`nc.injectTestEvent`;function cp(){let e=m(),[t,a]=c(()=>zf()?.form??wf()),[o]=c(()=>zf()?.caveats??[]),[s]=c(()=>zf()?.ruleName??null);d(()=>Bf(),[]);let[f,p]=c(null),[h,g]=c(!1),[_,v]=c(null),y=e=>a(t=>({...t,...e})),b=ae({projection:`slim`}),x=i({queryKey:Qd,queryFn:()=>e.trpcClient.notificationRules.getConditionCatalog.query({})}),S=i({queryKey:Xd,queryFn:async()=>(await e.trpcClient.notificationRules.listRules.query({})).rules}),C=i({queryKey:Zd,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])}),D=r(()=>(b.data??[]).filter(e=>e.type===Ve.Camera).map(e=>({id:e.id,name:e.name})),[b.data]),O=x.data?.taxonomy,k=T.data??[],A=r(()=>{let e=new Map;for(let t of C.data??[])e.set(t.id,t.name);return e},[C.data]),j=l({mutationFn:async()=>{let n=kf(t);if(n===null)throw Error(`Pick a camera first.`);return e.trpcClient.addons.custom.mutate({addonId:op,action:sp,input:n})},onMutate:()=>{p(null),g(!1),v(null)},onSuccess:e=>{let t=qf(e);p(t),g(t===null)},onError:e=>v(e instanceof Error?e.message:`The simulation failed.`)}),M=bf(t.trigger),N=S.data?.find(e=>e.id===t.onlyRuleId);return n(Hr,{icon:se,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&&u(q,{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 `,u(`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&&u(`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:[u(E,{className:`mt-0.5 h-3 w-3 shrink-0 text-warning`}),u(`span`,{children:e.note})]},e.conditionId))}),n(W,{className:`space-y-4`,children:[n(`div`,{children:[u(`label`,{className:X,children:`Camera`}),u(V,{"data-testid":`simulate-camera`,value:t.deviceId===null?``:String(t.deviceId),options:[{value:``,label:D.length===0?`Loading cameras…`:`— pick a camera —`},...D.map(e=>({value:String(e.id),label:e.name}))],onChange:e=>{y({deviceId:Ef(e.target.value)??null,zones:[],crossingZoneId:``,sensorKind:``,sourceDeviceId:null,occupancy:{...t.occupancy,zoneId:``}})}}),u(`p`,{className:Mn,children:`The camera the event is attributed to — what a notification shows.`})]}),n(`div`,{children:[u(`label`,{className:X,children:`Trigger`}),u(V,{"data-testid":`simulate-trigger`,value:t.trigger,options:vf.map(e=>({value:e.value,label:e.label})),onChange:e=>{let n=yf(e.target.value);if(!n)return;let r=xf(t.trigger);y({trigger:n,source:t.source===``||t.source===r?xf(n):t.source})}}),n(`p`,{className:Mn,children:[vf.find(e=>e.value===t.trigger)?.hint,` Only rules whose trigger is `,u(`span`,{className:`text-foreground`,children:M}),` are candidates.`]})]}),u(Xf,{form:t,cameras:D,taxonomy:O,kinds:k,kindsLoading:T.isLoading,onPatch:y}),n(`details`,{className:`rounded-md border border-border px-3 py-2`,open:!0,children:[u(`summary`,{className:`cursor-pointer text-[11px] font-semibold text-foreground`,children:`Quality`}),n(`div`,{className:`mt-2 space-y-3`,children:[u(`p`,{className:Mn,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:[u(`label`,{className:X,children:`Label (identity name / plate / subclass)`}),u(H,{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:[u(`label`,{className:X,children:`Detection confidence`}),u(ur,{value:t.confidence,min:0,max:1,step:.05,onChange:e=>y({confidence:e})})]}),n(`div`,{children:[u(`label`,{className:X,children:`Label-match confidence`}),u(ur,{value:t.labelConfidence,min:0,max:1,step:.05,onChange:e=>y({labelConfidence:e})})]}),n(`div`,{children:[u(`label`,{className:X,children:`Importance`}),u(ur,{value:t.importance,min:0,max:1,step:.05,onChange:e=>y({importance:e})})]}),n(`div`,{children:[u(`label`,{className:X,children:`Dwell (seconds)`}),u(ur,{value:t.dwellSeconds,min:0,step:1,onChange:e=>y({dwellSeconds:e})})]})]})]})]}),u($f,{form:t,cameras:D,onPatch:y}),n(`div`,{className:`space-y-2 rounded-md border border-border px-3 py-2`,children:[u(`div`,{className:`text-[11px] font-semibold text-foreground`,children:`How to run it`}),u(ep,{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})}),u(ep,{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})}),u(ep,{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:[u(`label`,{className:X,children:`Still image`}),u(V,{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:[u(`label`,{className:X,children:`Evaluate only one rule`}),u(V,{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&&N===void 0&&n(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:[`Rule `,u(`code`,{children:t.onlyRuleId}),` is not in the current list — it may have been deleted. The run will find no candidate.`]})]})]}),_!==null&&u(`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:[u(`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(Y,{size:`sm`,type:`button`,disabled:j.isPending||!Tf(t),onClick:()=>j.mutate(),children:[j.isPending?u(P,{className:`h-3.5 w-3.5 animate-spin`}):u(se,{className:`h-3.5 w-3.5`}),`Inject event`]})]})]}),h&&u(`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.`}),f!==null&&u(rp,{result:f,targetName:e=>A.get(e)??e})]})}var lp=e=>typeof e==`string`&&e.length>0;function up(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 dp(e,t){return e.format.includes(t)?t:e.format[0]??`text`}function fp(e,t){let n=[];for(let r of e.attachments.mediaTypes){if(n.length>=e.attachments.max)break;let i=t[r];lp(i)&&n.push({mediaType:r,url:i})}return n}function pp(e,t){if(e.actions<=0)return[];let n=[];for(let r of t){if(n.length>=e.actions)break;let t=lp(r.label),i=lp(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 mp(e,t){let n=e.levels.some(e=>e.id===t.level)?t.level:void 0,r=fp(e,t.attachmentUrls),i=pp(e,t.actions),a=e.ttl&&lp(t.ttl)?Number(t.ttl):void 0;return{body:t.body,format:dp(e,t.format),priority:hp(t.priority),...lp(t.title)?{title:t.title}:{},...n?{level:n}:{},...r.length>0?{attachments:r}:{},...i.length>0?{actions:i}:{},...e.clickUrl&&lp(t.clickUrl)?{clickUrl:t.clickUrl}:{},...e.sound&&lp(t.sound)?{sound:t.sound}:{},...a!==void 0&&Number.isFinite(a)?{ttl:a}:{},...lp(t.tag)?{tag:t.tag}:{}}}function hp(e){return Number.isFinite(e)?Math.min(5,Math.max(1,Math.round(e))):3}function gp(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 _p(e){return{level:``,priority:3,format:e.format[0]??`text`,title:``,body:``,attachmentUrls:{},actions:[],clickUrl:``,sound:``,ttl:``,tag:``}}var vp={image:f(`/addon/notifiers/samples/image`),video:f(`/addon/notifiers/samples/video`),gif:f(`/addon/notifiers/samples/gif`),audio:f(`/addon/notifiers/samples/audio`),icon:f(`/addon/notifiers/samples/icon`)};function yp(e,t){return e.attachments.max>0&&e.attachments.mediaTypes.includes(t)}function bp(e){let t=[`text`];for(let n of[`image`,`gif`,`video`,`audio`])yp(e,n)&&t.push(n);return e.actions>0&&t.push(`actions`),e.levels.length>0&&t.push(`critical`),t.push(`overflow`),t}function xp(e,t,n){let r=_p(e);return yp(e,t)?{...r,body:n,attachmentUrls:{[t]:vp[t]}}:{...r,body:n}}function Sp(e,t){let n=_p(e);switch(t){case`text`:return{...n,title:`CamStack`,body:`Test notification — text only.`};case`image`:return xp(e,`image`,`Test notification with an image.`);case`gif`:return xp(e,`gif`,`Test notification with an animation.`);case`video`:return xp(e,`video`,`Test notification with a video.`);case`audio`:return xp(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=gp(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 Cp={text:`Text only`,image:`With image`,gif:`With GIF`,video:`With video`,audio:`With audio`,actions:`With buttons`,critical:`Critical`,overflow:`Overflow (advanced)`},wp=`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`,Tp=`block text-[11px] font-medium text-foreground mb-1`;function Ep({target:e,kind:t,open:i,onClose:a}){let o=m(),s=r(()=>up(t.caps),[t.caps]),d=r(()=>bp(t.caps),[t.caps]),[f,p]=c(()=>_p(t.caps)),[h,g]=c(null),_=r(()=>mp(t.caps,f),[t.caps,f]),v=f.body.length,y=v>s.bodyMaxLen,b=e=>p(t=>({...t,...e})),x=l({mutationFn:()=>o.trpcClient.notificationOutput.testTarget.mutate({addonId:e.addonId,targetId:e.id,sample:mp(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(Sp(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 u(w,{open:i,onOpenChange:e=>!e&&a(),children:n(we,{width:`lg`,className:`!max-w-2xl`,scroll:`body`,children:[u(B,{children:n(le,{children:[`Test "`,e.name,`" (`,t.label,`)`]})}),n(k,{className:`space-y-4 pr-1`,children:[u(`div`,{className:`flex flex-wrap gap-1.5`,children:d.map(e=>u(Y,{size:`sm`,variant:`outline`,type:`button`,onClick:()=>S(e),children:Cp[e]},e))}),n(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[s.levels.length>0&&n(`div`,{children:[u(`label`,{className:Tp,children:`Level`}),n(`select`,{className:wp,value:f.level,onChange:e=>b({level:e.target.value}),children:[u(`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&&u(`p`,{className:`text-[10px] text-foreground-subtle`,children:e.description}),n(`div`,{className:`flex flex-wrap gap-1`,children:[e.flags?.critical&&u(z,{variant:`danger`,"data-testid":`flag-critical`,children:`critical`}),e.flags?.silent&&u(z,{variant:`info`,children:`silent`}),e.flags?.noPush&&u(z,{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:Tp,children:[`Priority (ordinal): `,f.priority]}),u(`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:[u(`label`,{className:Tp,children:`Format`}),u(`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:[u(`input`,{type:`radio`,name:`format`,className:`accent-primary`,checked:f.format===e,onChange:()=>b({format:e})}),e]},e))})]}),n(`div`,{children:[u(`label`,{className:Tp,children:`Title`}),u(`input`,{className:wp,value:f.title,onChange:e=>b({title:e.target.value})})]}),n(`div`,{children:[n(`label`,{className:Tp,children:[`Body`,` `,n(`span`,{className:y?`text-danger`:`text-foreground-subtle`,children:[`(`,v,`/`,s.bodyMaxLen,y?` — overflow`:``,`)`]})]}),u(`textarea`,{className:`${wp} 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:Tp,children:[`Attachments`,` `,n(`span`,{className:`text-foreground-subtle`,children:[`(mode: `,s.attachmentMode,`, max `,s.attachmentMax,s.attachmentMaxBytes?`, ≤${Math.round(s.attachmentMaxBytes/1024/1024)}MB`:``,`)`]})]}),u(`div`,{className:`space-y-1.5`,children:s.attachmentSlots.map(e=>n(`div`,{className:`flex items-center gap-2`,children:[u(`span`,{className:`text-[10px] w-12 shrink-0 text-foreground-subtle`,children:e}),u(`input`,{className:wp,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:Tp,children:[`Actions (up to `,s.maxActions,`)`]}),u(`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:[u(`input`,{className:wp,placeholder:`label`,value:f.actions[t]?.label??``,onChange:e=>C(t,`label`,e.target.value)}),u(`input`,{className:wp,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:[u(`label`,{className:Tp,children:`Click URL`}),u(`input`,{className:wp,value:f.clickUrl,onChange:e=>b({clickUrl:e.target.value})})]}),s.showSound&&n(`div`,{children:[u(`label`,{className:Tp,children:`Sound`}),u(`input`,{className:wp,value:f.sound,onChange:e=>b({sound:e.target.value})})]}),s.showTtl&&n(`div`,{children:[u(`label`,{className:Tp,children:`TTL (seconds)`}),u(`input`,{className:wp,type:`number`,value:f.ttl,onChange:e=>b({ttl:e.target.value})})]}),s.showTag&&n(`div`,{children:[u(`label`,{className:Tp,children:`Tag`}),u(`input`,{className:wp,value:f.tag,onChange:e=>b({tag:e.target.value})})]})]}),h&&u(Dp,{result:h}),n(`details`,{className:`text-[10px]`,children:[u(`summary`,{className:`cursor-pointer text-foreground-subtle`,children:`Payload preview`}),u(`pre`,{className:`mt-1 overflow-x-auto rounded bg-surface p-2 text-foreground-subtle`,children:JSON.stringify(_,null,2)})]})]}),n(ce,{children:[u(Y,{variant:`secondary`,size:`sm`,type:`button`,onClick:a,children:`Close`}),n(Y,{size:`sm`,type:`button`,disabled:x.isPending||f.body.length===0,onClick:()=>x.mutate(),children:[x.isPending?u(P,{className:`h-3.5 w-3.5 animate-spin`}):u(je,{className:`h-3.5 w-3.5`}),`Send test`]})]})]})})}function Dp({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?u(Se,{className:`h-3.5 w-3.5 text-success`}):u(G,{className:`h-3.5 w-3.5 text-danger`}),u(`span`,{children:e.success?`Delivered`:`Failed`})]}),e.error&&u(`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:[u(`dt`,{children:`Resolved level`}),u(`dd`,{className:`text-foreground`,children:t.level}),u(`dt`,{children:`Format sent`}),u(`dd`,{className:`text-foreground`,children:t.format}),u(`dt`,{children:`Attachments sent`}),u(`dd`,{className:`text-foreground`,children:t.attachmentsSent}),u(`dt`,{children:`Actions sent`}),u(`dd`,{className:`text-foreground`,children:t.actionsSent}),u(`dt`,{children:`Truncated`}),u(`dd`,{className:`text-foreground`,children:t.truncated?`yes`:`no`}),u(`dt`,{children:`Dropped`}),u(`dd`,{className:`text-foreground`,children:t.dropped.length>0?t.dropped.join(`, `):`—`})]})]})}function Op(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 kp(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 Ap(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}var jp=`••••••••`;function Mp(e){return e===`••••••••`||e===`__redacted__`}function Np(e,t,n){let r=new Set(n),i={};for(let[t,n]of Object.entries(e)){if(!r.has(t)){i[t]=n;continue}n==null||n===``||Mp(n)||(i[t]=n)}return i}function Pp(e,t){let n=new Set(t),r={};for(let[t,i]of Object.entries(e)){if(!n.has(t)){r[t]=i;continue}r[t]=i!=null&&i!==``?jp:``}return r}function Fp(e){return{...e}}var Ip=[`Refusing to reuse the stored secret`,`Re-enter the secret`];function Lp(e){return Ip.some(t=>e.includes(t))}function Rp(e){return e==null||e===``?``:typeof e==`string`?e:JSON.stringify(e)}function zp(e,t,n){let r=new Set(n);return[...new Set([...Object.keys(e),...Object.keys(t)])].filter(n=>!r.has(n)&&Rp(e[n])!==Rp(t[n]))}function Bp(e,t,n,r){if(r===void 0)return zp(e,t,n);let i=new Set(n),a=Np(e,t,n);return r.filter(n=>i.has(n)?n in a:Rp(e[n])!==Rp(t[n]))}function Vp(e,t,n){let r=Np(e,t,n);return n.filter(e=>!(e in r))}function Hp(e,t){return e.map(e=>e.type===`password`&&t.has(e.key)?{...e,required:!0}:e.type===`group`?{...e,fields:Hp(e.fields,t)}:e.type===`sub-tabs`?{...e,tabs:e.tabs.map(e=>({...e,fields:Hp(e.fields,t)}))}:e)}function Up(e,t){if(t.length===0)return e;let n=new Set(t);return{...e,sections:e.sections.map(e=>({...e,fields:Hp(e.fields,n)}))}}function Wp(e){let t=e.trim();return t.length===0?`Copy`:`${t} Copy`}function Gp(e,t){return e.map(e=>e.type===`password`&&t.has(e.key)?{...e,placeholder:e.placeholder??`•••••••• (leave blank to keep)`}:e.type===`group`?{...e,fields:Gp(e.fields,t)}:e.type===`sub-tabs`?{...e,tabs:e.tabs.map(e=>({...e,fields:Gp(e.fields,t)}))}:e)}function Kp(e,t,n){let r=new Set(n.filter(e=>{let n=t[e];return n!=null&&n!==``}));return r.size===0?e:{...e,sections:e.sections.map(e=>({...e,fields:Gp(e.fields,r)}))}}var qp=`targets`,Jp=`target`,Yp=`kind`,Xp=[Jp,Yp];function Zp(e,t){let n=new URLSearchParams(e);return n.set(`tab`,qp),n.set(Jp,t),n.delete(Yp),n}function Qp(e,t){let n=new URLSearchParams(e);return n.set(`tab`,qp),n.set(Jp,`new`),t===null||t.length===0?n.delete(Yp):n.set(Yp,t),n}function $p(e){let t=new URLSearchParams(e);return t.delete(Jp),t.delete(Yp),t}function em({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:[u(`p`,{className:`font-semibold`,children:`The hub needs the secret again — nothing was saved.`}),u(`p`,{className:`mt-1`,children:e}),i===null?null:u(`p`,{className:`mt-1 font-medium`,children:i})]})}t();var tm=[`notificationOutput`,`listTargets`],nm=[`notificationOutput`,`listTargetKinds`],rm=[`userManagement`,`listUsers`],im=`ownerUserId`;function am(e){let t=e.config[im];return typeof t==`string`&&t.length>0?t:null}function om(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:[u(`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:u(sm,{kind:r,imgClassName:`h-5 w-5 object-contain`,fallbackClassName:``})}),u(Lu,{name:t.name,enabled:t.enabled,...r===void 0?{}:{onOpen:()=>e.onOpen(t,r)}})]})}},{key:`kind`,header:`Kind`,nowrap:!0,render:t=>u(`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=am(t);return n===null?u(z,{variant:`default`,children:`system`}):u(`span`,{className:`text-[11px] text-foreground`,children:e.userNameById.get(n)??n})}},{key:`enabled`,header:`On`,align:`center`,nowrap:!0,render:t=>u(Nu,{children:u(L,{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(Nu,{className:`flex items-center justify-end gap-1`,children:[u(Y,{size:`sm`,variant:`ghost`,type:`button`,disabled:!r,onClick:()=>e.onTest(t),title:`Test`,children:u(je,{className:`h-3.5 w-3.5`})}),u(Y,{size:`sm`,variant:`ghost`,type:`button`,disabled:!r,onClick:()=>r&&e.onDuplicate(t,r),title:`Duplicate`,children:u(Te,{className:`h-3.5 w-3.5`})}),u(Y,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onDelete(t),title:`Delete`,children:u(g,{className:`h-3.5 w-3.5 text-danger`})})]})}}]}function sm({kind:e,imgClassName:t,fallbackClassName:n}){return e?.iconUrl?u(`img`,{src:e.iconUrl,alt:e.label,className:t,loading:`lazy`,draggable:!1}):u(`span`,{className:n,children:e?.icon??`🔔`})}function cm(){let t=m(),[a,o]=zr(),[s,f]=c({mode:`closed`}),[p,h]=c(null),g=e(null),_=i({queryKey:tm,queryFn:()=>t.trpcClient.notificationOutput.listTargets.query({})}),v=i({queryKey:nm,queryFn:async()=>(await t.trpcClient.notificationOutput.listTargetKinds.query({})).map(e=>{let t=e.iconUrl;return{...e,configSchema:e.configSchema,iconUrl:t}})}),y=r(()=>v.data??[],[v.data]),b=r(()=>{let e=new Map;for(let t of y)e.set(t.kind,t);return e},[y]),x=i({queryKey:rm,queryFn:()=>t.trpcClient.userManagement.listUsers.query()}),S=r(()=>{let e=new Map;for(let t of x.data??[])e.set(t.id,t.username);return e},[x.data]),C=l({mutationFn:e=>t.trpcClient.notificationOutput.setTargetEnabled.mutate({addonId:e.target.addonId,targetId:e.target.id,enabled:e.enabled}),onSuccess:()=>void _.refetch()}),w=l({mutationFn:e=>t.trpcClient.notificationOutput.deleteTarget.mutate({addonId:e.addonId,targetId:e.id}),onSuccess:()=>void _.refetch()}),T=p?b.get(p.kind):void 0,E=()=>{let e=a.get(Jp);e!==null&&(g.current=e),f({mode:`closed`}),o($p(a),{replace:!0})},D=()=>{g.current=`new`,f({mode:`pick-kind`}),o(Qp(a,null),{replace:!0})},O=e=>{g.current=`new:${e.kind}`,f({mode:`form`,kind:e,target:null,cloneFrom:null}),o(Qp(a,e.kind),{replace:!0})},k=(e,t)=>{g.current=e.id,f({mode:`form`,kind:t,target:e,cloneFrom:null}),o(Zp(a,e.id),{replace:!0})};return d(()=>{if(s.mode!==`closed`)return;let e=a.get(Jp);if(e===null){g.current=null;return}if(g.current===e)return;if(e===`new`){let e=a.get(Yp);if(e===null||e.length===0){g.current=`new`,f({mode:`pick-kind`});return}let t=b.get(e);if(t===void 0)return;g.current=`new:${e}`,f({mode:`form`,kind:t,target:null,cloneFrom:null});return}let t=_.data?.find(t=>t.id===e);if(t===void 0)return;let n=b.get(t.kind);n!==void 0&&(g.current=e,f({mode:`form`,kind:n,target:t,cloneFrom:null}))},[s.mode,a,_.data,b]),n(Hr,{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(Y,{size:`sm`,type:`button`,onClick:D,children:[u(J,{className:`h-3.5 w-3.5`}),`Add target`]}),children:[_.isLoading&&u(Pu,{}),_.isError&&!_.isLoading&&u(q,{title:`Failed to load targets`,message:_.error instanceof Error?_.error.message:`Unknown error`,onRetry:()=>void _.refetch()}),!_.isLoading&&!_.isError&&(_.data??[]).length===0&&u(Fu,{children:`No notification targets yet. Click "Add target" to configure one.`}),(_.data??[]).length>0&&u(Iu,{columns:om({kindByKey:b,userNameById:S,onToggle:(e,t)=>C.mutate({target:e,enabled:t}),onTest:h,onOpen:k,onDuplicate:(e,t)=>{g.current=`new:${t.kind}`,f({mode:`form`,kind:t,target:null,cloneFrom:e}),o(Qp(a,t.kind),{replace:!0})},onDelete:e=>w.mutate(e)}),rows:_.data??[],rowKey:e=>e.id,minWidthPx:720,onRowClick:e=>{let t=b.get(e.kind);t!==void 0&&k(e,t)}}),s.mode===`pick-kind`&&u(lm,{kinds:y,onCancel:E,onPick:O}),s.mode===`form`&&u(um,{kind:s.kind,target:s.target,cloneFrom:s.cloneFrom,users:x.data??[],onCancel:E,onSaved:()=>{E(),_.refetch()}}),p&&T&&u(Ep,{target:p,kind:T,open:!0,onClose:()=>h(null)})]})}function lm({kinds:e,onPick:t,onCancel:i}){let a=r(()=>Op(e),[e]);return u(w,{open:!0,onOpenChange:e=>!e&&i(),children:n(we,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,children:[n(`div`,{className:`flex shrink-0 items-center justify-between mb-3`,children:[u(`h3`,{className:`text-sm font-semibold text-foreground`,children:`Choose a notification kind`}),u(Y,{size:`sm`,variant:`ghost`,type:`button`,onClick:i,children:`Cancel`})]}),n(k,{className:`space-y-4`,children:[a.length===0&&u(`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:[u(`div`,{className:`text-[10px] font-semibold uppercase tracking-wider text-foreground-subtle mb-1.5`,children:e.addonId}),u(`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:[u(sm,{kind:r,imgClassName:`h-7 w-7 object-contain`,fallbackClassName:`text-lg leading-7`}),u(`span`,{className:`font-medium text-foreground`,children:r.label})]},`${e.addonId}:${r.kind}`))})]},e.addonId))]})]})})}function um({kind:e,target:t,cloneFrom:i,users:a,onSaved:o,onCancel:s}){let f=m(),p=r(()=>kp(e.configSchema),[e.configSchema]),h=t??i,g=t?.id??i?.id,[_,v]=c(()=>i===null?t?.name??e.label:Wp(i.name)),[y,b]=c(()=>h?.config??{}),[x,S]=c(()=>h?Pp(h.config,p):{}),[C,T]=c(g===void 0),[E,D]=c(null),[O,A]=c(null),[j,M]=c(h?am(h)??``:``);d(()=>{if(g===void 0)return;let t=!1;return f.trpcClient.notificationOutput.getTarget.query({addonId:e.addonId,targetId:g}).then(e=>{if(t)return;let n=Fp(e.config);b(n),S(n),M(am(e)??``),T(!0)}).catch(e=>{t||(D(e instanceof Error?e.message:`Failed to load target secrets`),T(!0))}),()=>{t=!0}},[g,e.addonId,f.trpcClient]);let N=()=>Np(x,y,p),[ee,F]=c(null),te=e.kind===`whatsapp`,I=l({mutationFn:()=>f.trpcClient.notificationOutput.probeTargetConfig.mutate({addonId:e.addonId,kind:e.kind,config:N(),...g===void 0?{}:{targetId:g}}),onSuccess:e=>F(e),onError:e=>{F(null),D(e instanceof Error?e.message:`Connection test failed`)}}),L=l({mutationFn:()=>{let{[im]:n,...r}=Np(x,y,p),a=j===``?r:{...r,[im]:j},o={id:t?.id??`${e.kind}-${Date.now()}`,name:_,kind:e.kind,addonId:e.addonId,enabled:t?.enabled??!0,config:a};return f.trpcClient.notificationOutput.upsertTarget.mutate({addonId:e.addonId,target:o,...i===null?{}:{cloneSecretsFrom:i.id}})},onSuccess:o,onError:e=>{let t=e instanceof Error?e.message:`Save failed`;Lp(t)?A(t):D(t)}}),ne=r(()=>Ap(e.configSchema),[e.configSchema]),R=r(()=>g===void 0?[]:Bp(x,y,p,e.destinationKeys),[g,x,y,p,e.destinationKeys]),re=r(()=>g!==void 0&&(O!==null||R.length>0)?Vp(x,y,p):[],[g,O,R,x,y,p]),ie=r(()=>Kp(Up(e.configSchema,re),y,p),[e.configSchema,re,y,p]),z=e=>ne.get(e)??e;return u(w,{open:!0,onOpenChange:e=>!e&&s(),children:n(we,{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:[u(sm,{kind:e,imgClassName:`h-5 w-5 object-contain shrink-0`,fallbackClassName:`text-lg`}),u(`span`,{className:`truncate`,children:t?`Edit ${t.name}`:i?`Duplicate ${i.name}`:`Add ${e.label} target`})]}),u(Y,{size:`sm`,variant:`ghost`,type:`button`,onClick:s,children:`Cancel`})]}),E&&u(`div`,{className:`shrink-0 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger mb-3`,"data-testid":`target-form-error`,children:E}),n(k,{className:`space-y-4 pr-1`,children:[n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Name`}),u(`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:_,onChange:e=>v(e.target.value)})]}),n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Owner`}),u(V,{value:j,options:[{value:``,label:`System (shared, admin-managed)`},...a.map(e=>({value:e.id,label:e.username}))],onChange:e=>M(e.target.value)}),u(`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.`})]}),p.length>0&&g!==void 0&&u(`p`,{className:`text-[10px] text-foreground-subtle`,children:`Stored secrets load into the masked fields (eye to reveal). Clear a field to leave the stored value unchanged on save; type a new value to replace it.`}),u(em,{refusal:O,edited:R.map(z),reenter:re.map(z)}),u(be,{schema:ie,values:x,onChange:S}),te&&n(`div`,{className:`space-y-2`,children:[n(Y,{size:`sm`,variant:`outline`,type:`button`,disabled:I.isPending,onClick:()=>{D(null),F(null),I.mutate()},children:[I.isPending?u(P,{className:`h-3.5 w-3.5 animate-spin`}):u(je,{className:`h-3.5 w-3.5`}),`Test connection`]}),ee!==null&&n(`p`,{className:ee.ok?`text-[11px] text-success`:`text-[11px] text-danger`,"data-testid":`target-probe-result`,children:[ee.ok?`Connected — ${ee.stateInstance??`authorized`}`:ee.error??`Connection failed`,ee.resolvedUrl.length>0?` · ${ee.resolvedUrl}`:``]})]})]}),n(ce,{children:[u(Y,{variant:`secondary`,size:`sm`,type:`button`,onClick:s,children:`Cancel`}),n(Y,{size:`sm`,type:`button`,disabled:L.isPending||!C||_.trim().length===0,onClick:()=>{D(null),A(null),L.mutate()},children:[L.isPending||!C?u(P,{className:`h-3.5 w-3.5 animate-spin`}):null,t?`Save changes`:`Create target`]})]})]})})}t();var dm=`notificationTexts`,fm=`Every sentence the Notification Center can print — and your wording for it.`;function pm({entry:e,value:t,busy:r,onChange:i,onReset:a}){let o=Cl(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:[u(`code`,{className:`text-xs font-medium`,children:e.key}),s?u(z,{variant:`info`,children:`customised`}):null,e.source===`fallback`?u(z,{variant:`warning`,children:`English fallback`}):null]}),n(`div`,{className:`flex items-start gap-2`,children:[u(`div`,{className:`flex-1`,children:u(oo,{label:``,value:t,onChange:i,vars:Sl(e),disabled:r,testId:`text-input-${e.key}`})}),u(Y,{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:u(h,{className:`h-3.5 w-3.5`})})]}),n(`p`,{className:`text-xs text-foreground-subtle`,children:[u(`span`,{className:`font-medium`,children:`Shipped:`}),` `,u(`span`,{className:`font-mono`,children:e.shipped})]}),o===null?null:u(`p`,{className:`text-xs text-warning`,children:o})]})}function mm(){let e=m(),t=o(),[a,s]=c(null),[d,f]=c(``),[p,h]=c(new Map),[g,_]=c(!1),v=i({queryKey:[dm,a??`hub`],queryFn:async()=>{let t=_l(await e.trpcClient.addons.custom.mutate({addonId:$,action:cl,input:a===null?{}:{language:a}}));return _(t===null),t}}),y=()=>{h(new Map),t.invalidateQueries({queryKey:[dm]})},b=l({mutationFn:t=>e.trpcClient.addons.custom.mutate({addonId:$,action:ll,input:{language:t}}),onSuccess:y}),x=l({mutationFn:t=>e.trpcClient.addons.custom.mutate({addonId:$,action:ul,input:t}),onSuccess:y}),S=v.data??null,C=r(()=>S===null?[]:xl(S.entries,d),[S,d]);if(v.isLoading)return u(Hr,{icon:Jr,title:`Texts`,subtitle:fm,children:u(P,{className:`h-5 w-5 animate-spin`})});if(v.isError||S===null)return u(Hr,{icon:Jr,title:`Texts`,subtitle:fm,children:u(q,{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=yl(S.entries,p),D=bl(S.entries,p),O=S.entries.filter(e=>e.override!==null).length,k=S.languages.map(e=>({value:e,label:dl[e]})),A=(e,t)=>h(n=>new Map(n).set(e,t)),j=e=>A(e.key,e.shipped);return u(Hr,{icon:Jr,title:`Texts`,subtitle:fm,children:n(`div`,{className:`flex flex-col gap-4`,children:[b.isError?u(q,{title:`Could not change the language`,message:String(b.error)}):null,x.isError?u(q,{title:`Could not save`,message:String(x.error)}):null,n(W,{className:`p-4`,children:[n(`div`,{className:`flex flex-wrap items-end gap-6`,children:[n(`div`,{className:`flex flex-col gap-1`,children:[u(`label`,{className:`text-sm font-medium`,children:`Hub language`}),u(`div`,{className:`w-44`,children:u(V,{value:S.activeLanguage,disabled:T,options:k,onChange:e=>{let t=e.target.value;fl(t)&&b.mutate(t)},"data-testid":`texts-hub-language`})}),u(`p`,{className:`text-xs text-foreground-subtle`,children:`Every notification is written in this language.`})]}),n(`div`,{className:`flex flex-col gap-1`,children:[u(`label`,{className:`text-sm font-medium`,children:`Editing`}),u(`div`,{className:`w-44`,children:u(V,{value:w,disabled:T,options:k,onChange:e=>{let t=e.target.value;fl(t)&&(h(new Map),s(t))},"data-testid":`texts-editing-language`})}),u(`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.`})]})]}),u(`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:[u(de,{className:`absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-foreground-muted`}),u(H,{value:d,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(Y,{className:`ml-auto`,disabled:T||D===0,onClick:()=>x.mutate({language:w,overrides:E}),"data-testid":`texts-save`,children:[T?u(P,{className:`h-3.5 w-3.5 animate-spin`}):null,D===0?`Save`:`Save ${D}`]})]}),u(`div`,{className:`flex max-h-[60vh] flex-col gap-2 overflow-y-auto pr-1`,"data-testid":`texts-rows`,children:C.length===0?u(`p`,{className:`text-sm text-foreground-subtle`,children:`No text matches that search.`}):C.map(e=>u(pm,{entry:e,value:vl(e,p),busy:T,onChange:t=>A(e.key,t),onReset:()=>j(e)},e.key))})]})})}t();var hm=`simulate`,gm=`rules`;function _m(){let[e,t]=zr();return d(()=>{let n=e.get(`tab`);if(n===null||!Id(n))return;let r=new URLSearchParams(e);r.set(`tab`,gm),r.set(`section`,n),t(r,{replace:!0})},[e,t]),u(`div`,{className:`flex flex-col p-4`,children:u(Wr,{tabs:[{id:`targets`,label:`Targets`,icon:ne,content:u(cm,{}),ownedParams:Xp},{id:gm,label:`Rules`,icon:b,content:u(tf,{onSimulateRule:n=>{Rf(If(n));let r=new URLSearchParams(e);r.set(`tab`,hm),t(r,{replace:!0})},onOpenHistory:n=>{t(Aa(e,n.id),{replace:!0})}}),ownedParams:[`section`,`rule`,`editTab`]},{id:`sequences`,label:`Sequences`,icon:Yr,content:u(gf,{})},{id:hm,label:`Simulate`,icon:se,content:u(cp,{})},{id:wa,label:`History`,icon:Kr,content:u(za,{}),ownedParams:Ea},{id:`alarm`,label:`Alarm`,icon:he,content:u(Ca,{})},{id:`texts`,label:`Texts`,icon:Jr,content:u(mm,{})}]})})}export{_m as NotificationsPage,_m as default};
|