@camstack/addon-admin-ui 1.2.427 → 1.2.428
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/{AddonAssetIcon-BgXfFdy2.js → AddonAssetIcon-Cs_blBpK.js} +1 -1
- package/dist/assets/Addons-2xWF73cR.js +4 -0
- package/dist/assets/{AdminPage-C0Zxs_ot.js → AdminPage-DuuyDIsY.js} +1 -1
- package/dist/assets/{AdminSectionedPage-D2kYQhvu.js → AdminSectionedPage-C3VHg80L.js} +1 -1
- package/dist/assets/AiProfiles-DmHcVlS2.js +3 -0
- package/dist/assets/BrokerForm-Dqhjsi3Y.js +1 -0
- package/dist/assets/Build-CBYP1fT5.js +40 -0
- package/dist/assets/Calendars-C926x7b_.js +1 -0
- package/dist/assets/Cluster-OZlA14uV.js +1 -0
- package/dist/assets/ClusterStepModel-DHbwIGAW.js +1 -0
- package/dist/assets/CompositionEditor-vP3JcV2R.js +1 -0
- package/dist/assets/{CompositionEditorPage-CDyW_Buu.js → CompositionEditorPage-Acq7iapA.js} +1 -1
- package/dist/assets/Data-7BoejvKA.js +1 -0
- package/dist/assets/DeviceDetail-ByM0856T.js +2 -0
- package/dist/assets/DeviceDoActionFields-BDJsvRNX.js +1 -0
- package/dist/assets/{Devices-CHeb_BTk.js → Devices-PIrWjfhq.js} +1 -1
- package/dist/assets/EmbedPlayerPage-RXOmf2F3.js +1 -0
- package/dist/assets/Identity-C-tztwfa.js +1 -0
- package/dist/assets/IntegrationDetail-DugB7cv6.js +1 -0
- package/dist/assets/IntegrationHub-BePMbmC5.js +1 -0
- package/dist/assets/Integrations-Dj3nT9ZT.js +1 -0
- package/dist/assets/Integrations-OH5z-t03.js +1 -0
- package/dist/assets/Library-DDNti2te.js +1 -0
- package/dist/assets/Locations-OL9_NoSi.js +3 -0
- package/dist/assets/Logs-DIeXeCqI.js +1 -0
- package/dist/assets/{MotionZonesSettings-DjvGw8j4.js → MotionZonesSettings-CfTOerul.js} +1 -1
- package/dist/assets/MyAccess-iJP3JQIS.js +2 -0
- package/dist/assets/Network-DYssxNiN.js +1 -0
- package/dist/assets/NodeAddonsSettingsPanel-mmtEgDbu.js +1 -0
- package/dist/assets/Notifications-DEcxFWp3.js +1 -0
- package/dist/assets/{PrivacyMaskSettings-IK6ytyM8.js → PrivacyMaskSettings-CJUKFEIs.js} +1 -1
- package/dist/assets/Recordings-lygSYEJj.js +1 -0
- package/dist/assets/ScanNetworkModal-C2oJlLfj.js +1 -0
- package/dist/assets/{SceneMonitorEditor-V_pHxg3U.js → SceneMonitorEditor-D1S-D2V9.js} +1 -1
- package/dist/assets/SessionsList-CIN4GdSm.js +2 -0
- package/dist/assets/{Showroom-Cw-6ZdvC.js → Showroom-W2yJvb8s.js} +1 -1
- package/dist/assets/System-ChWpOOqN.js +1 -0
- package/dist/assets/{Terminal-D-YHBrHK.js → Terminal-CrFum1tE.js} +5 -5
- package/dist/assets/{Viewer-BmXiweP2.js → Viewer-YBzeS3RA.js} +1 -1
- package/dist/assets/{_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-wt87pCBz.js → _virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-CE2IIKhe.js} +1 -1
- package/dist/assets/{addon-icons-context-CvwUgMRr.js → addon-icons-context-D6glxUQF.js} +1 -1
- package/dist/assets/{archive-Bwv0mNo-.js → archive-kvflMCgL.js} +1 -1
- package/dist/assets/{authed-media-0TPg9TTZ.js → authed-media-CSlndmzS.js} +1 -1
- package/dist/assets/{bell-off-D2KzCQW2.js → bell-off-BYnwGeiH.js} +1 -1
- package/dist/assets/{boxes-BXQUMgws.js → boxes-Dx4USyB3.js} +1 -1
- package/dist/assets/circle-slash-D5mo-8G0.js +1 -0
- package/dist/assets/client-CMlUvfoK.js +358 -0
- package/dist/assets/{cloud-upload-BsULjxPu.js → cloud-upload-82x5w5u8.js} +1 -1
- package/dist/assets/crop-Dev61hIh.js +1 -0
- package/dist/assets/{device-integration-icon-CCoHGEQZ.js → device-integration-icon-bTnWrYe0.js} +1 -1
- package/dist/assets/device-picker-model-DlnG_8P7.js +1 -0
- package/dist/assets/{dist-DQtBl_2T.js → dist--5X8Gy0U.js} +1 -1
- package/dist/assets/{dist-DWoekMi0.js → dist-Dod19ois.js} +13 -13
- package/dist/assets/{eraser-DB7_WMyf.js → eraser-B8Awx5Sj.js} +1 -1
- package/dist/assets/{file-up-DuqaeMYR.js → file-up-LqDVgVVa.js} +1 -1
- package/dist/assets/{hard-drive-download-CKj8xKOz.js → hard-drive-download-C24D80x2.js} +1 -1
- package/dist/assets/{history-V8RQKQAb.js → history-DZsORyBG.js} +1 -1
- package/dist/assets/{hostInit-CdxLRG1l.js → hostInit-D2EmEDvv.js} +1 -1
- package/dist/assets/i18n-vggiB6gm.js +1 -0
- package/dist/assets/{icons-CEMmjIEL.js → icons-D5RaCH1q.js} +1 -1
- package/dist/assets/index-BgQGn3LX.js +4 -0
- package/dist/assets/index-BndCgmxf.css +2 -0
- package/dist/assets/{key-Bj5-ZBrb.js → key-DLwSBrPM.js} +1 -1
- package/dist/assets/{key-round-B2I1YisX.js → key-round-CYflkUyd.js} +1 -1
- package/dist/assets/{layers-BARFkXZ5.js → layers-C1wzFfr1.js} +1 -1
- package/dist/assets/linked-devices-model-CCTQ_gka.js +1 -0
- package/dist/assets/{list-ordered-9lF0Gp3K.js → list-ordered-CFeS9o_w.js} +1 -1
- package/dist/assets/location-owned-usage-DSLiI6RY.js +1 -0
- package/dist/assets/{log-in-CjtrIfG3.js → log-in-Be_RcxDr.js} +1 -1
- package/dist/assets/{memory-stick-B26_SbtH.js → memory-stick-4BwYEagi.js} +1 -1
- package/dist/assets/{message-square-plus-COMrVZEZ.js → message-square-plus-D7BNG3h7.js} +1 -1
- package/dist/assets/{mf-entry-bootstrap-0-ec37d41a.js → mf-entry-bootstrap-0-9df0d08c.js} +2 -2
- package/dist/assets/{mic-off-DBIqFVjg.js → mic-off-e162Bcfu.js} +1 -1
- package/dist/assets/{monitor-off-CTQMySOs.js → monitor-off-CARYfHC4.js} +1 -1
- package/dist/assets/{monitor-smartphone-iBd_3nPv.js → monitor-smartphone-lsNgnRRZ.js} +1 -1
- package/dist/assets/mount-DlnG_8P7.js +1 -0
- package/dist/assets/notification-schedule-field-DWpT_5Vh.js +1 -0
- package/dist/assets/{octagon-alert-DMjnTemh.js → octagon-alert-h80nyWRM.js} +1 -1
- package/dist/assets/{player-overlays-DWMIy1MJ.js → player-overlays-Cda8wso6.js} +1 -1
- package/dist/assets/{recycle-BCVF0r6Y.js → recycle-0MLWppmT.js} +1 -1
- package/dist/assets/remoteEntry-V_83-NrI.js +1 -0
- package/dist/assets/{scan-eye-DRXP3PgB.js → scan-eye-DVK8MF3K.js} +1 -1
- package/dist/assets/{scissors-DUFtPb9T.js → scissors-Cz3GoeOd.js} +1 -1
- package/dist/assets/{search-x-B3nve3vV.js → search-x-i_A-Upbe.js} +1 -1
- package/dist/assets/{send-P2KlabIu.js → send-B5VKcNUH.js} +1 -1
- package/dist/assets/{settings-2-reEhyiKz.js → settings-2-ZQsYJ0Zb.js} +1 -1
- package/dist/assets/{speaker-DSNMuvS8.js → speaker-Cl8DZGk_.js} +1 -1
- package/dist/assets/{src-BLkInT8U.js → src-eoSUZcV-.js} +8 -8
- package/dist/assets/{timer-reset-CsRTbSzh.js → timer-reset-A5ofAkBW.js} +1 -1
- package/dist/assets/{ungroup-BLeVa8__.js → ungroup-t0yDnzVf.js} +1 -1
- package/dist/assets/{unlink-DeNvF8r-.js → unlink-C1ZpCxl3.js} +1 -1
- package/dist/assets/{usb-CFseVsQJ.js → usb-DmUPajSy.js} +1 -1
- package/dist/assets/{use-scenes-feed-C8frh3hQ.js → use-scenes-feed-BQlYhRMq.js} +1 -1
- package/dist/assets/{use-stationary-objects-DNayAuMq.js → use-stationary-objects-BWM4vE0E.js} +1 -1
- package/dist/assets/useEventInvalidation-DlnG_8P7.js +1 -0
- package/dist/assets/{useNodeUrlSelection-BsLRiUy8.js → useNodeUrlSelection-CTxv9Em7.js} +1 -1
- package/dist/assets/user-round-BTaID248.js +1 -0
- package/dist/assets/{user-x-CpaZ5HO0.js → user-x-DRcPeM9C.js} +1 -1
- package/dist/assets/{video--MLJeLNU.js → video-tLHyNE3q.js} +1 -1
- package/dist/assets/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-1Do_dc2z.js → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-DOOXjnRq.js} +2 -2
- package/dist/index.html +11 -10
- package/dist/server/addon.js +27 -3
- package/package.json +1 -1
- package/dist/assets/Addons-BTWw53aT.js +0 -4
- package/dist/assets/AiProfiles-Ca7zuVMp.js +0 -3
- package/dist/assets/BrokerForm-6-BwPs-g.js +0 -1
- package/dist/assets/Build-BsduavcU.js +0 -40
- package/dist/assets/Calendars-DVTk_2iT.js +0 -1
- package/dist/assets/Cluster-BPJ4maiI.js +0 -1
- package/dist/assets/ClusterStepModel-CjuZ-oml.js +0 -1
- package/dist/assets/CompositionEditor-DJcmWU2U.js +0 -1
- package/dist/assets/Data-CLLvqZwG.js +0 -1
- package/dist/assets/DeviceDetail-BKw1gufS.js +0 -2
- package/dist/assets/DeviceDoActionFields-R-ZYIdMv.js +0 -1
- package/dist/assets/EmbedPlayerPage-B4y0Q0wO.js +0 -1
- package/dist/assets/Identity-NOlTR-3q.js +0 -1
- package/dist/assets/IntegrationDetail-CcZkPlbN.js +0 -1
- package/dist/assets/IntegrationHub-CuW7-WRy.js +0 -1
- package/dist/assets/Integrations-ACdx4iPR.js +0 -1
- package/dist/assets/Integrations-DjnhmLye.js +0 -1
- package/dist/assets/Library-B3iyoKdK.js +0 -1
- package/dist/assets/Locations-Cs1VwmXB.js +0 -3
- package/dist/assets/Logs-BMc6WXCH.js +0 -1
- package/dist/assets/MyAccess-BfUfTXrv.js +0 -2
- package/dist/assets/Network-F2lAIcbT.js +0 -1
- package/dist/assets/NodeAddonsSettingsPanel-D3ux_JIo.js +0 -1
- package/dist/assets/Notifications-Cp3qo_EC.js +0 -1
- package/dist/assets/Recordings-D91q74Ga.js +0 -1
- package/dist/assets/ScanNetworkModal-DjU-xM4X.js +0 -1
- package/dist/assets/SessionsList-DQ7kj8fX.js +0 -2
- package/dist/assets/System-DLLa4weE.js +0 -1
- package/dist/assets/circle-slash-DpUtlEnB.js +0 -1
- package/dist/assets/client-CjyKfSu1.js +0 -358
- package/dist/assets/crop-BtQBZ9jm.js +0 -1
- package/dist/assets/device-picker-model-1Z6p3UkP.js +0 -1
- package/dist/assets/index-D66JvELZ.js +0 -4
- package/dist/assets/index-dmZ34NAY.css +0 -2
- package/dist/assets/location-owned-usage-CNXQ-Obv.js +0 -1
- package/dist/assets/mount-1Z6p3UkP.js +0 -1
- package/dist/assets/notification-schedule-field-D8dd67dT.js +0 -1
- package/dist/assets/remoteEntry-RwWzzVu_.js +0 -1
- package/dist/assets/useEventInvalidation-1Z6p3UkP.js +0 -1
- package/dist/assets/user-round-BB0VDRnJ.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{Fi as f,It as p,Nr as m,Nt as h,On as g,Pi as _,Q as v,Yr as y,ar as b,bn as x,dn as S,fi as C,kr as w,on as T,ot as E,pi as D,pr as O,vn as k,yn as A}from"./player-overlays-Cda8wso6.js";import{t as j}from"./bell-off-BYnwGeiH.js";import{m as M}from"./video-tLHyNE3q.js";import{t as N}from"./history-DZsORyBG.js";import{n as P,r as F,t as I}from"./list-ordered-CFeS9o_w.js";import{t as L}from"./send-B5VKcNUH.js";import{$ as ee,$t as te,A as R,B as z,Bn as ne,D as B,E as V,F as re,H as ie,In as ae,J as oe,L as se,Mr as ce,N as le,T as ue,U as de,V as fe,W as pe,Wt as me,X as he,Y as H,Z as ge,_t as _e,at as U,bt as ve,ct as ye,dt as be,ft as xe,j as Se,k as Ce,lt as we,mt as Te,ot as Ee,q as De,rt as Oe,tt as ke,ut as Ae,xt as je,z as Me,zn as Ne}from"./client-CMlUvfoK.js";import{D as Pe,F as Fe,M as Ie,O as Le,j as Re,v as ze,y as Be}from"./__vite-browser-external-DF8Eb0aa.js";import{An as Ve,Bn as W,Dn as He,En as Ue,G as We,Ht as Ge,Kl as G,L as Ke,Ln as K,Pn as qe,R as Je,Si as Ye,Tn as Xe,Ut as Ze,Zl as q,Zn as Qe,_ as $e,ar as J,bn as et,d as tt,en as nt,er as rt,et as it,f as at,g as ot,h as st,in as ct,is as lt,jn as ut,kn as dt,m as ft,ma as pt,nn as mt,ns as ht,os as gt,p as _t,pt as vt,rn as yt,tn as Y,tr as bt,ts as xt,u as St,v as Ct,z as wt}from"./src-eoSUZcV-.js";import{t as X}from"./i18n-vggiB6gm.js";import{t as Z}from"./useTranslation-Bc5yH9V9.js";import"./mount-DlnG_8P7.js";import{$ as Tt,$t as Et,A as Dt,At as Ot,B as kt,Bt as At,C as jt,Ct as Mt,D as Nt,Dt as Pt,E as Ft,Et as It,F as Lt,Ft as Rt,G as zt,Gt as Bt,H as Vt,Ht,I as Ut,It as Wt,J as Gt,Jt as Kt,K as qt,Kt as Jt,L as Yt,Lt as Xt,M as Zt,Mt as Qt,N as $t,Nt as en,O as tn,Ot as nn,P as rn,Pt as an,Q as on,Qt as sn,R as cn,Rt as ln,S as un,St as dn,T as fn,Tt as pn,U as mn,Ut as hn,V as gn,Vt as _n,W as vn,Wt as yn,X as bn,Xt as xn,Y as Sn,Yt as Cn,Z as wn,Zt as Tn,_ as En,_n as Dn,_t as On,a as kn,an as An,at as jn,b as Mn,bt as Nn,c as Pn,cn as Fn,ct as In,d as Ln,dn as Rn,dt as zn,en as Bn,et as Vn,f as Q,fn as Hn,ft as Un,g as Wn,gn as Gn,gt as Kn,h as qn,hn as Jn,ht as Yn,i as Xn,in as Zn,it as Qn,j as $n,jt as er,k as tr,kt as nr,l as rr,ln as ir,lt as ar,m as or,mn as sr,mt as cr,n as lr,nn as ur,nt as dr,o as fr,on as pr,ot as mr,p as hr,pn as gr,pt as _r,q as vr,qt as yr,r as br,rn as xr,rt as Sr,s as Cr,sn as wr,st as Tr,t as Er,tn as Dr,tt as Or,u as kr,un as Ar,ut as jr,v as Mr,vt as Nr,w as Pr,wt as Fr,x as Ir,xt as Lr,y as Rr,yt as zr,z as Br,zt as Vr}from"./notification-schedule-field-DWpT_5Vh.js";import{C as Hr,J as Ur,Q as Wr,w as Gr}from"./index-BgQGn3LX.js";import{t as Kr}from"./AdminSectionedPage-C3VHg80L.js";import{t as qr}from"./DeviceDoActionFields-BDJsvRNX.js";import{t as Jr}from"./AdminPage-DuuyDIsY.js";import"./device-picker-model-DlnG_8P7.js";import{t as Yr}from"./use-scenes-feed-BQlYhRMq.js";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=>st([e],r,t)[0];return{nameOf:e=>{let t=a(e);return i(e)??(t===void 0?`Device #${String(e)}`:_t(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)}function Ei(e,t,n){let r=(e.modeDelays??[]).find(e=>e.mode===t)?.postTriggeredAction;if(n==="default")return r===void 0?null:{mode:t,postTriggeredAction:null};let i=oe(e,t),a=r!==n,o=n!==`doNothing`&&i.triggeredDurationSec===0;return!a&&!o?null:{mode:t,...a?{postTriggeredAction:n}:{},...o?{triggeredDurationSec:30}:{}}}function Di(e,t,n){let r=(e.modeDelays??[]).find(e=>e.mode===t)?.schedule;return n===void 0?r===void 0?null:{mode:t,schedule:null}:r!==void 0&&r.invert===n.invert&&r.timezone===n.timezone&&r.windows.length===n.windows.length&&r.windows.every((e,t)=>{let r=n.windows[t];return r!==void 0&&e.startMinute===r.startMinute&&e.endMinute===r.endMinute&&e.days.length===r.days.length&&e.days.every((e,t)=>e===r.days[t])})?null:{mode:t,schedule:n}}var Oi=[`unknown-refusal`,`stale`,`expired`,`used`];function ki(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ai(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(!ki(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 ji(e){if(!ki(e))return null;let t=e.outcome;if(t===`armed`||t===`arming`){let n=Ai(e.excluded);return n===null?null:{outcome:t,excluded:n}}if(t===`refused`){let n=Ai(e.blocking),r=e.refusalId;return n===null||typeof r!=`string`||r===``?null:{outcome:t,refusalId:r,blocking:n}}if(t===`rejected`){let n=Oi.find(t=>t===e.reason);return n===void 0?null:{outcome:t,reason:n}}return t===`outside-schedule`?{outcome:t}:null}var Mi={"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 Ni(e){return Mi[e]}function Pi(e,t,n,r){let i=(e.modeDelays??[]).find(e=>e.mode===t)?.[n];if(r&&i===!0||!r&&i===void 0)return null;let a=r?!0:null;switch(n){case`notifyDuringEntryDelay`:return{mode:t,notifyDuringEntryDelay:a};case`notifySensorRewatched`:return{mode:t,notifySensorRewatched:a};case`notifySensorIgnored`:return{mode:t,notifySensorIgnored:a}}}var Fi=`pipeline-analytics`,Ii=`The hub answered something this build cannot read — refresh after updating.`;function Li(e){return e instanceof Error?e.message:String(e)}function Ri(e){return e.map(e=>`${ti(e)} (${e.state})`).join(`, `)}function zi({live:e,onChanged:t}){let{t:r}=Z(),i=E(),[a,o]=c(null),[s,d]=c(null),[f,p]=c(null),m=(e,t)=>i.trpcClient.addons.custom.mutate({addonId:Fi,action:e,input:t}),h=e=>{if(e===null){d(Ii);return}if(e.outcome===`refused`){o({refusalId:e.refusalId,blocking:e.blocking});return}if(o(null),e.outcome===`rejected`){d(`Arm anyway was not accepted: ${Ni(e.reason)}.`);return}if(e.outcome===`outside-schedule`){d(`Outside this mode's activation schedule — arm during an allowed window.`);return}let t=e.outcome===`armed`?`Armed`:`Arming`;p(e.excluded.length===0?`${t}.`:`${t} — excluded: ${Ri(e.excluded)}.`)},g=()=>{d(null),p(null)},_=l({mutationFn:async e=>ji(await m(`nc.armAlarm`,{mode:e})),onMutate:g,onSuccess:h,onError:e=>d(Li(e)),onSettled:t}),v=l({mutationFn:async e=>ji(await m(`nc.armAlarmAnyway`,{refusalId:e})),onMutate:g,onSuccess:h,onError:e=>d(Li(e)),onSettled:t}),y=l({mutationFn:async()=>m(`nc.disarmAlarm`,{}),onMutate:()=>{g(),o(null)},onSuccess:()=>p(`Disarmed.`),onError:e=>d(Li(e)),onSettled:t});if(e===void 0)return n(qe,{className:`p-4`,children:[u(`h3`,{className:`text-sm font-semibold mb-1`,children:r(`system.alarmLiveCard.panel`,`Panel`)}),u(`p`,{className:`text-sm text-foreground-subtle`,children:r(`system.alarmLiveCard.thisHubDoesNotReport`,`This hub does not report the panel's live state yet — update it to arm from here.`)})]});let x=_.isPending||v.isPending||y.isPending;return n(qe,{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:r(`system.alarmLiveCard.panel`,`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:[x?u(b,{className:`h-4 w-4 animate-spin`}):null,e.availableModes.map(e=>n(W,{type:`button`,size:`md`,variant:`outline`,disabled:x,onClick:()=>_.mutate(e),"data-testid":`alarm-arm-${e}`,children:[`Arm `,ii(e)]},e)),u(W,{type:`button`,size:`md`,variant:vi(e.state)?`danger`:`secondary`,disabled:x,onClick:()=>y.mutate(),"data-testid":`alarm-disarm`,children:r(`system.alarmLiveCard.disarm`,`Disarm`)})]})]}),s===null?null:u(`div`,{className:`mt-3`,children:u(K,{title:r(`system.alarmLiveCard.thePanelDidNotDo`,`The panel did not do that`),message:s})}),f===null?null:u(`p`,{className:`mt-3 text-sm text-foreground-subtle`,children:f}),a===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(a.blocking.length)}),a.blocking.length>0?u(`ul`,{className:`mt-1 list-disc pl-5 text-sm`,children:a.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(W,{type:`button`,size:`md`,variant:`danger`,disabled:x,onClick:()=>v.mutate(a.refusalId),children:r(`system.alarmLiveCard.armAnyway`,`Arm anyway`)}),u(`span`,{className:`text-xs text-foreground-subtle`,children:r(`system.alarmLiveCard.eachOpenDeviceIsIgnored`,`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:r(`system.alarmLiveCard.excludedSensors`,`Excluded sensors`)}),e.exclusions.length===0?u(`p`,{className:`text-sm text-foreground-subtle`,children:r(`system.alarmLiveCard.noSensorIsExcluded`,`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 Bi=[{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:`After (seconds)`,hint:`How long the alarm stays triggered before the after-trigger action runs. Ignored when the action is “do nothing”.`,max:ae,zeroMeans:`runs the action immediately`}];function Vi(e){return`Enter a whole number of seconds from 0 to ${e}.`}function Hi(e,t){let n=e.trim();return`${n===``?`Nothing was entered, so nothing was saved`:`${n} was not saved`} — ${Vi(t)}`}function Ui({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(We,{label:e,...s===void 0?{}:{description:s},..._?{error:Vi(r)}:m===null?{}:{error:Hi(m,r)},children:[n(`div`,{className:`flex items-center gap-2`,children:[u(q,{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 Wi(e,t){let n=e?.trim()??``;if(n===``)return``;if(t.state===`answered`){let e=Ct(n),r=t.zones.find(t=>t.locationKeys.includes(e));if(r!==void 0)return`${r.label} · ${n}`}return n}function Gi(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 Ki=`Not checked by this mode — switch on to remove the entry`;function qi(e){return e.listedUncovered?{word:`No`,note:Ki}:Ji(e.coverage)}function Ji(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 Yi(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 Xi(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 Zi({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(J,{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 Qi=`hidden sm:table-cell`;function $i(e){let{mode:t,inFlight:r,onSwitch:i,zones:a,disabled:o}=e;return[{key:`name`,header:X.t(`system.alarmSensorTable.name`,`Name`),cell:e=>{let t=Wi(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:X.t(`system.alarmSensorTable.type`,`Type`),headerClassName:Qi,cellClassName:`${Qi} text-[11px] text-foreground-subtle`,cell:e=>$e(e.device.type??null)},{key:`state`,header:X.t(`system.alarmSensorTable.state`,`State`),cell:e=>u(Zi,{name:`state`,variant:Yi(e.cell),words:Gi(e.cell)})},{key:`coverage`,header:X.t(`system.alarmSensorTable.checkedWhenArming`,`Checked when arming`),headerClassName:Qi,cellClassName:Qi,cell:e=>u(Zi,{name:`coverage`,variant:Xi(e),words:qi(e)})},{key:`blocks`,header:X.t(`system.alarmSensorTable.blocksArming`,`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(b,{className:`h-3 w-3 animate-spin`}):null,u(ct,{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":X.t(`system.alarmSensorTable.blocksArming2`,`Blocks arming: {{name}}`,{name: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:X.t(`system.alarmSensorTable.closeLockOrTurnOff`,`Close, lock, or turn off when this mode arms`),children:X.t(`system.alarmSensorTable.secureOnArm`,`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(b,{className:`h-3 w-3 animate-spin`}):null,u(ct,{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":X.t(`system.alarmSensorTable.secureOnArmCloseLock`,`Secure on arm (close/lock/off): {{name}}`,{name:e.device.name}),title:X.t(`system.alarmSensorTable.closeLockOrTurnOff`,`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 ea(e){let{t}=Z(),{mode:r,rows:i,sensorsRetry:a,zones:o}=e;return n(`div`,{className:`space-y-2`,"data-testid":`alarm-sensors-${r}`,children:[a===null?null:n(`div`,{className:`flex items-center gap-2 text-xs text-warning`,"data-testid":`alarm-sensors-failed`,children:[u(`span`,{children:t(`system.alarmSensorTable.couldNotReadTheSensor`,`Could not read the sensor states.`)}),u(W,{type:`button`,size:`sm`,variant:`outline`,onClick:a,children:t(`common.retry`,`Retry`)})]}),u(it,{mode:`generic`,items:i,getKey:e=>String(e.device.id),getSearchText:e=>[e.device.name,Wi(e.device.location,o),$e(e.device.type??null)].join(` `),getFilterType:e=>$e(e.device.type??null),columns:$i(e),rowClassName:e=>e.listedUncovered?`opacity-60`:``,searchPlaceholder:t(`system.alarmSensorTable.searchSensors`,`Search sensors`),emptyLabel:`No sensor matches.`})]})}var ta=[/has no (?:handler for )?custom action ["']nc\.getAlarmSensors["']/,/No "query"-procedure on path "notificationRules\.getAlarmSensors"/,/method 'getAlarmSensors' not found on provider 'notification-rules'/];function na(e){return ta.some(t=>t.test(e))}function ra(e,t,n){if(n)return{kind:`removed`};if(e.status===`pending`)return{kind:`checking`};if(e.status===`failed`)return na(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 ia(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 aa(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 oa(e){return e.kind===`unscoped`||e.kind===`not-covered`}function sa(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=aa(e.coverage,r.id),a=ia(e.sensors,r.id,t,r.type),o=he({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&&oa(i)&&(!o||c)&&c;!t&&oa(i)&&!c||n.push({device:r,removed:t,cell:ra(e.sensors,r.id,t),coverage:i,controllable:a,blocks:o,secureOnArm:s,listedUncovered:l})}return n}function ca(e){return e.rowCount>0?`rows`:e.candidatesComplete?`none`:`pending`}function la(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 ua(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 da(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 fa(e,t){return De(da(e),t)?{kind:`landed`}:{kind:`not-landed`}}var pa=[{field:`notifyDuringEntryDelay`,key:`duringEntryDelay`},{field:`notifySensorRewatched`,key:`rewatched`},{field:`notifySensorIgnored`,key:`ignored`}];function ma({coverage:e,settings:t,disabled:r,onNotifyEdit:i}){let{t:a}=Z(),o=H(t,e.mode);return n(`div`,{className:`space-y-2`,"data-testid":`alarm-notify-${e.mode}`,children:[u(`label`,{className:`block text-[11px] font-medium text-foreground`,children:a(`notificationRules.alarmNotify.title`)}),pa.map(({field:t,key:s})=>n(`div`,{className:`flex items-start justify-between gap-3`,children:[n(`div`,{className:`min-w-0`,children:[u(`p`,{className:`text-xs text-foreground`,children:a(`notificationRules.alarmNotify.${s}`)}),u(`p`,{className:`text-[10px] text-foreground-subtle`,children:a(`notificationRules.alarmNotify.${s}Hint`)})]}),u(ct,{checked:o[t],onCheckedChange:e=>i(t,e),disabled:r,"data-testid":`alarm-notify-${e.mode}-${t}`,"aria-label":a(`notificationRules.alarmNotify.${s}`)})]},t))]})}function ha({coverage:e,rows:t,names:r}){let{t:i}=Z(),a=t.filter(e=>e.coverage.kind.startsWith(`arm-checked`)).length,o=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(J,{variant:`warning`,title:o,"data-testid":`alarm-arms-nothing`,children:i(`system.alarmModeCard.armsNothingNoEnabledRule`,`Arms nothing — no enabled rule is gated on this mode`)}):n(J,{variant:`default`,title:o,"data-testid":`alarm-covers`,children:[`Checks `,a,` `,a===1?`sensor`:`sensors`]}),e.skippedDevices.length>0?n(J,{variant:`warning`,title:si(e.skippedDevices,r.nameOf),"data-testid":`alarm-skipped`,children:[e.skippedDevices.length,` not notified`]}):null]})}function ga(e){return e.status===`answered`?e.openingIds:null}function _a({check:e,view:t}){let{t:r}=Z();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(b,{className:`h-3 w-3 animate-spin`}),r(`system.alarmModeCard.checkingWhichDevicesAreOpenings`,`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(W,{type:`button`,size:`sm`,variant:`outline`,onClick:e.retry,children:r(`common.retry`,`Retry`)})]}):null:null}var va=[{value:`rearmAfter`,label:`Re-arm after`},{value:`disableAfter`,label:`Disarm after`},{value:`doNothing`,label:`Do nothing (stay triggered)`}];function ya({coverage:e,settings:t,disabled:r,onDelayEdit:i,onPostTriggeredEdit:a,onScheduleEdit:o}){let{t:s}=Z(),c=e.mode,l=oe(t,c),d=l.source.postTriggeredAction==="default",f=l.postTriggeredAction!==`doNothing`,p=(t.modeDelays??[]).find(e=>e.mode===c)?.schedule;return n(`div`,{className:`space-y-3`,"data-testid":`alarm-delays-${c}`,children:[n(`div`,{className:`grid grid-cols-2 gap-3 sm:grid-cols-4`,children:[Bi.filter(e=>e.field!==`triggeredDurationSec`).map(e=>{let n=l.source[e.field]==="default";return u(Ui,{label:e.label,value:l[e.field],max:e.max,zeroMeans:e.zeroMeans,disabled:r,testId:`alarm-delay-${c}-${e.key}`,onCommit:t=>i(e.field,t),adornment:n?u(J,{variant:`default`,title:s(`system.alarmModeCard.usesTheSystemDefaultS`,`Uses the system default ({{value1}} s)`,{value1:t[e.field]}),children:s(`system.alarmModeCard.default`,`Default`)}):u(W,{type:`button`,size:`sm`,variant:`ghost`,disabled:r,title:s(`system.alarmModeCard.useTheDefault`,`Use the default`),"aria-label":s(`system.alarmModeCard.useTheDefault2`,`{{label}}: use the default`,{label:e.label}),onClick:()=>i(e.field,`default`),"data-testid":`alarm-delay-${c}-${e.key}-default`,children:u(k,{className:`h-3.5 w-3.5`})})},e.field)}),n(`div`,{children:[n(`label`,{className:`mb-1 block text-[11px] font-medium text-foreground`,children:[s(`system.alarmModeCard.afterTrigger`,`After trigger`),d?u(J,{variant:`default`,className:`ml-1.5 align-middle`,title:s(`system.alarmModeCard.usesTheSystemDefault`,`Uses the system default`),children:s(`system.alarmModeCard.default`,`Default`)}):u(W,{type:`button`,size:`sm`,variant:`ghost`,className:`ml-1 align-middle`,disabled:r,title:s(`system.alarmModeCard.useTheDefault`,`Use the default`),"aria-label":s(`system.alarmModeCard.afterTriggerUseTheDefault`,`After trigger: use the default`),onClick:()=>a(`default`),"data-testid":`alarm-delay-${c}-post-default`,children:u(k,{className:`h-3.5 w-3.5`})})]}),u(`select`,{className:`mt-1 w-full rounded border border-border bg-background px-2 py-1 text-xs`,value:l.postTriggeredAction,disabled:r,"data-testid":`alarm-delay-${c}-post`,onChange:e=>{let t=Ne.safeParse(e.target.value);t.success&&a(t.data)},children:va.map(e=>u(`option`,{value:e.value,children:e.label},e.value))})]}),f?Bi.filter(e=>e.field===`triggeredDurationSec`).map(e=>{let n=l.source[e.field]==="default";return u(Ui,{label:e.label,value:l[e.field],max:e.max,zeroMeans:e.zeroMeans,disabled:r,testId:`alarm-delay-${c}-${e.key}`,onCommit:t=>i(e.field,t),adornment:n?u(J,{variant:`default`,title:s(`system.alarmModeCard.usesTheSystemDefaultS`,`Uses the system default ({{value1}} s)`,{value1:t[e.field]}),children:s(`system.alarmModeCard.default`,`Default`)}):u(W,{type:`button`,size:`sm`,variant:`ghost`,disabled:r,title:s(`system.alarmModeCard.useTheDefault`,`Use the default`),"aria-label":s(`system.alarmModeCard.useTheDefault2`,`{{label}}: use the default`,{label:e.label}),onClick:()=>i(e.field,`default`),"data-testid":`alarm-delay-${c}-${e.key}-default`,children:u(k,{className:`h-3.5 w-3.5`})})},e.field)}):null]}),n(`div`,{"data-testid":`alarm-schedule-${c}`,children:[u(`label`,{className:`mb-1 block text-[11px] font-medium text-foreground`,children:s(`system.alarmModeCard.activationSchedule`,`Activation schedule`)}),u(`p`,{className:`mb-1 text-[10px] text-foreground-subtle`,children:s(`system.alarmModeCard.whenThisModeMayBe`,`When this mode may be armed. Empty means any day and time.`)}),u(`fieldset`,{disabled:r,className:`min-w-0 border-0 p-0`,children:u(Er,{value:p,onChange:o,emptyHint:`Always allowed — add a window to restrict when this mode can be armed.`})})]})]})}var ba={"no-opening":`This household has no contact, cover or lock.`};function xa({coverage:e,live:t,settings:r,names:i,openingsCheck:a,rows:o,sensorsRetry:s,inFlight:c,onSwitch:l,zones:d,onDelayEdit:f,onPostTriggeredEdit:p,onScheduleEdit:m,onNotifyEdit:h,disabled:g}){let{t:_}=Z(),v=Qr({live:t,listed:bi(r,e.mode),openingIds:ga(a)}),y=$r(v),b=ca({rowCount:o.length,candidatesComplete:!v.unresolved});return n(`div`,{className:`flex flex-col gap-3`,"data-mode":e.mode,"data-empty":li(e)?`true`:`false`,children:[u(ha,{coverage:e,rows:o,names:i}),u(ya,{coverage:e,settings:r,disabled:g,onDelayEdit:f,onPostTriggeredEdit:p,onScheduleEdit:m}),n(`p`,{className:`text-[10px] text-foreground-subtle`,"data-testid":`alarm-delays-hint`,children:[`Blank delay fields use the system defaults (exit 30 s, entry 20 s, re-arm after`,` `,30,` s).`]}),u(ma,{coverage:e,settings:r,disabled:g,onNotifyEdit:h}),n(`div`,{className:`flex flex-col gap-2`,"data-testid":`alarm-nonblocking-${e.mode}`,children:[u(_a,{check:a,view:v}),y===null?null:u(`p`,{className:`text-xs text-foreground-subtle`,children:ba[y]}),b===`none`&&y===null?u(`p`,{className:`text-xs text-foreground-subtle`,"data-testid":`alarm-sensors-none`,children:_(`system.alarmModeCard.noSensorIsCoveredBy`,`No sensor is covered by a rule of this mode.`)}):null,b===`rows`?u(ea,{mode:e.mode,rows:o,sensorsRetry:s,inFlight:c,onSwitch:l,zones:d,disabled:g}):null]})]})}t();function Sa({profiles:e,busy:t,onActivate:r,onCreate:i,onClone:o,onRename:s,onDelete:l}){let{t:d}=Z(),[f,m]=c(``),[h,_]=c(!1),v=e.items.find(t=>t.id===e.activeId)??e.items[0],b=v!==void 0&&!v.isDefault,x=f.trim(),S=()=>{x.length!==0&&(i(x),m(``))},C=()=>{x.length===0||v===void 0||(o(v.id,x),m(``))},w=()=>{x.length===0||v===void 0||(s(v.id,x),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:d(`system.alarmProfileBar.profile`,`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))}),b?u(W,{type:`button`,variant:`ghost`,size:`sm`,disabled:t,"data-testid":`alarm-profile-delete`,title:d(`system.alarmProfileBar.deleteThisProfile`,`Delete this profile`),onClick:()=>{v!==void 0&&l(v.id)},children:u(p,{className:`h-3.5 w-3.5`})}):null]}),n(`div`,{className:`flex flex-wrap items-center gap-2`,children:[u(q,{className:`h-8 max-w-[14rem]`,"data-testid":`alarm-profile-name`,placeholder:h?d(`system.alarmProfileBar.newName`,`New name`):d(`system.alarmProfileBar.newProfileName`,`New profile name`),value:f,disabled:t,onChange:e=>m(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(h?w():S())}}),h?n(a,{children:[u(W,{type:`button`,size:`sm`,disabled:t||x.length===0,"data-testid":`alarm-profile-rename-save`,onClick:w,children:d(`system.alarmProfileBar.rename`,`Rename`)}),u(W,{type:`button`,variant:`ghost`,size:`sm`,disabled:t,"data-testid":`alarm-profile-rename-cancel`,onClick:()=>{_(!1),m(``)},children:d(`common.cancel`,`Cancel`)})]}):n(a,{children:[n(W,{type:`button`,size:`sm`,disabled:t||x.length===0,"data-testid":`alarm-profile-create`,title:d(`system.alarmProfileBar.createWithSystemDefaults`,`Create with system defaults`),onClick:S,children:[u(g,{className:`mr-1 h-3.5 w-3.5`}),d(`system.alarmProfileBar.create`,`Create`)]}),n(W,{type:`button`,size:`sm`,variant:`secondary`,disabled:t||x.length===0||v===void 0,"data-testid":`alarm-profile-clone`,title:d(`system.alarmProfileBar.cloneTheSelectedProfile`,`Clone the selected profile`),onClick:C,children:[u(y,{className:`mr-1 h-3.5 w-3.5`}),d(`system.alarmProfileBar.clone`,`Clone`)]}),u(W,{type:`button`,size:`sm`,variant:`ghost`,disabled:t||v===void 0,"data-testid":`alarm-profile-rename`,onClick:()=>{_(!0),m(v?.name??``)},children:d(`system.alarmProfileBar.rename`,`Rename`)})]})]}),u(`p`,{className:`text-[11px] text-foreground-subtle`,children:d(`system.alarmProfileBar.createStartsFromSystemDefaults`,`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 Ca=[`notificationRules`,`getAlarmConfig`],wa=[`notificationRules`,`getAlarmSensors`],Ta=[`deviceManager`,`listDeviceIdsByCaps`,`alarm-openings`],Ea=6e4;function Da(e){return e instanceof Error?e.message:String(e)}function Oa({notice:e}){let{t}=Z();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:t(`system.notificationAlarm.couldNotChangeFor`,`Could not change {{name}} for {{value2}}: {{error}}`,{name:e.write.name,value2:ii(e.write.mode),error:e.error})})}}function ka(){let{t}=Z(),a=E(),d=o(),f=i({queryKey:Ca,queryFn:async()=>a.trpcClient.notificationRules.getAlarmConfig.query({}),refetchInterval:e=>hi(e.state.data?.live?.state)}),p=pt({projection:`slim`}),[m,h]=c(!1),g=l({mutationFn:e=>a.trpcClient.notificationRules.setAlarmConfig.mutate({patch:e}),onSuccess:(e,t)=>{d.setQueryData(Ca,e),h(!De(t,e.settings))}}),_=l({mutationFn:async e=>{switch(e.kind){case`activate`:return a.trpcClient.notificationRules.activateAlarmProfile.mutate({id:e.id});case`create`:return a.trpcClient.notificationRules.createAlarmProfile.mutate({name:e.name});case`clone`:return a.trpcClient.notificationRules.createAlarmProfile.mutate({name:e.name,cloneFromId:e.fromId});case`rename`:return a.trpcClient.notificationRules.renameAlarmProfile.mutate({id:e.id,name:e.name});case`delete`:return a.trpcClient.notificationRules.deleteAlarmProfile.mutate({id:e.id})}},onSuccess:e=>{d.setQueryData(Ca,e),h(!1)}}),v=()=>d.invalidateQueries({queryKey:Ca}),y=r(()=>{let e=new Map;for(let t of p.data??[])e.set(t.id,t.name);return e},[p.data]),x=f.data?.live,S=i({queryKey:Ta,staleTime:Ea,queryFn:async()=>new Set(await a.trpcClient.deviceManager.listDeviceIdsByCaps.query({capNames:[...Xr]}))}),C=r(()=>(p.data??[]).map(e=>({id:e.id,name:e.name,type:String(e.type),location:e.location??null})),[p.data]),w=r(()=>new Map(C.map(e=>[e.id,e])),[C]),D=S.isError?{status:`failed`,error:S.error instanceof Error?S.error.message:String(S.error),retry:()=>void S.refetch()}:S.data===void 0?{status:`pending`}:{status:`answered`,openingIds:S.data},O=r(()=>{let e=new Map;for(let t of x?.openings??[])for(let n of t.devices)e.set(n.deviceId,ti(n));return ei(y,ft(p),e)},[x,y,p]),k=ot(!0),[A,j]=c(null),M=r(()=>{let e=new Map,t=f.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:S.data??null}).ids);return e},[f.data,S.data]),N=r(()=>{let e=new Set;for(let t of M.values())for(let n of t)O.isRemoved(n)||e.add(n);return[...e].toSorted((e,t)=>e-t)},[M,O]),P=i({queryKey:[...wa,N],enabled:N.length>0,placeholderData:s,refetchOnWindowFocus:!0,refetchInterval:e=>e.state.error!==null&&na(Da(e.state.error))?!1:x!==void 0&&vi(x.state)?5e3:15e3,retry:(e,t)=>!na(Da(t))&&e<2,queryFn:async()=>{let e=[];for(let t of la(N,500))e.push(await a.trpcClient.notificationRules.getAlarmSensors.query({deviceIds:[...t]}));return{sensors:e.flatMap(e=>e.sensors),readAt:Math.min(...e.map(e=>e.readAt))}}}),F=P.isError?{status:`failed`,error:Da(P.error)}:P.data===void 0?{status:`pending`}:{status:`answered`,sensors:P.data.sensors},I=e(null),[L,ee]=c(null),[te,R]=c(null),z=async e=>{try{let t=await a.trpcClient.notificationRules.setAlarmConfig.mutate({patch:da(e)});fa(e,t.settings).kind===`landed`?d.setQueryData(Ca,t):(R({kind:`not-landed`,write:e}),d.invalidateQueries({queryKey:Ca}))}catch(t){R({kind:`failed`,write:e,error:Da(t)}),d.invalidateQueries({queryKey:Ca})}finally{I.current=null,ee(null),R(e=>e?.kind===`refused`?null:e)}},ne=(e,t,n,r)=>{let i=ua(I.current,e,t,n,r);if(i.kind===`refused`){R({kind:`refused`,inFlight:i.inFlight});return}I.current=i.write,ee(i.write),R(null),z(i.write)};if(f.isLoading)return u(Jr,{embedded:!0,icon:T,title:t(`system.notificationAlarm.alarm`,`Alarm`),subtitle:t(`system.notificationAlarm.panelDelaysAndModeCoverage`,`Panel delays and mode coverage.`),children:u(b,{className:`h-5 w-5 animate-spin`})});let B=f.data;if(B===void 0||f.isError)return u(Jr,{embedded:!0,icon:T,title:t(`system.notificationAlarm.alarm`,`Alarm`),subtitle:t(`system.notificationAlarm.panelDelaysAndModeCoverage`,`Panel delays and mode coverage.`),children:u(K,{title:t(`system.notificationAlarm.alarmSettingsAreNotAvailable`,`Alarm settings are not available`),message:t(`system.notificationAlarm.thisHubHasNotBeen`,`This hub has not been updated to serve the alarm configuration yet.`)})});if(B.deviceId===null)return u(Jr,{embedded:!0,icon:T,title:t(`system.notificationAlarm.alarm`,`Alarm`),subtitle:t(`system.notificationAlarm.panelDelaysAndModeCoverage`,`Panel delays and mode coverage.`),children:u(qe,{className:`p-4`,children:u(`p`,{className:`text-sm text-foreground-subtle`,children:t(`system.notificationAlarm.thisInstallationHasNoAlarm`,`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 V=B.settings,re=g.isPending||_.isPending,ie=e=>{h(!1),g.mutate(e)},ae=(e,t,n)=>{let r=Ti(V,e,t,n);r!==null&&ie({modeDelays:[r]})},oe=(e,t)=>{let n=Ei(V,e,t);n!==null&&ie({modeDelays:[n]})},se=(e,t)=>{let n=Di(V,e,t);n!==null&&ie({modeDelays:[n]})},ce=(e,t,n)=>{let r=Pi(V,e,t,n);r!==null&&ie({modeDelays:[r]})},le=new Map(B.coverage.map(e=>[e.mode,sa({candidates:(M.get(e.mode)??[]).map(e=>({...w.get(e),id:e,name:O.nameOf(e)})),removedIds:new Set((M.get(e.mode)??[]).filter(O.isRemoved)),coverage:e,nonBlocking:bi(V,e.mode),blocking:xi(V,e.mode),secureOnArmOff:Si(V,e.mode),sensors:F})])),ue=B.coverage.find(e=>e.mode===A)??B.coverage.find(e=>(le.get(e.mode)?.length??0)>0)??B.coverage[0],de=ue?.mode??``;return n(Jr,{embedded:!0,icon:T,title:t(`system.notificationAlarm.alarm`,`Alarm`),subtitle:t(`system.notificationAlarm.thePanelWhatEachMode`,`The panel, what each mode arms, and who hears about it.`),children:[g.isError?u(K,{title:t(`system.notificationAlarm.couldNotSave`,`Could not save`),message:String(g.error)}):null,_.isError?u(K,{title:t(`system.notificationAlarm.couldNotUpdateProfile`,`Could not update profile`),message:String(_.error)}):null,m?u(`div`,{"data-testid":`alarm-save-not-landed`,children:u(K,{variant:`warning`,title:t(`system.notificationAlarm.notApplied`,`Not applied`),message:t(`system.notificationAlarm.theHubDidNotApply`,`The hub did not apply this change — another editor may have changed it, or the hub needs an update`)})}):null,B.profiles===void 0?null:u(Sa,{profiles:B.profiles,busy:re,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(zi,{live:B.live,onChanged:v}),n(qe,{className:`p-4`,"data-testid":`alarm-coverage`,children:[u(nt,{value:de,onValueChange:e=>{let t=B.coverage.find(t=>t.mode===e);t!==void 0&&j(t.mode)},children:u(mt,{className:`mb-3`,children:B.coverage.map(e=>n(yt,{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))})}),te===null?null:u(Oa,{notice:te}),ue===void 0?null:u(xa,{coverage:ue,live:B.live,settings:V,names:O,openingsCheck:D,rows:le.get(ue.mode)??[],sensorsRetry:F.status===`failed`&&!na(F.error)?()=>void P.refetch():null,inFlight:L,onSwitch:(e,t,n)=>ne(ue.mode,e,t,n),zones:k,onDelayEdit:(e,t)=>ae(ue.mode,e,t),onPostTriggeredEdit:e=>oe(ue.mode,e),onScheduleEdit:e=>se(ue.mode,e),onNotifyEdit:(e,t)=>ce(ue.mode,e,t),disabled:re},ue.mode)]})]})}var Aa=`history`,ja=`ruleId`,Ma=[ja],Na=24,Pa=0,Fa=100;function Ia(e,t){let n=new URLSearchParams(e);return n.set(`tab`,Aa),n.set(ja,t),n}function La(e,t){let n=new URLSearchParams(e);return t===``?n.delete(ja):n.set(ja,t),n}function Ra(e){let t=e.get(`ruleId`)??``;return{ruleId:t,deviceId:``,status:``,windowHours:t===``?Na:Pa,limit:Fa}}function za(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 Ba=[{value:1,label:`Last hour`},{value:24,label:`Last 24 hours`},{value:168,label:`Last 7 days`},{value:0,label:`All time`}],Va=[{value:``,label:`Any status`},{value:`pending`,label:`Pending`},{value:`sent`,label:`Sent`},{value:`dead`,label:`Dead`}],Ha=[50,100,250,500];function Ua(e){return e===`pending`||e===`sent`||e===`dead`?e:void 0}function Wa(e){switch(e){case`pending`:return`info`;case`sent`:return`success`;case`dead`:return`danger`}}function Ga(e){let t=e.subject.systemEvent;if(t!==void 0)return{title:t.title,body:t.body};let n=e.subject.label??e.subject.className,r=e.subject.zones.length>0?` in ${e.subject.zones.join(`, `)}`:``;return{title:e.ruleName,body:`${n}${r}`}}function Ka({entry:e,cameraName:t,onClose:r}){let{t:i}=Z(),a=Ga(e),o=e.subject.systemEvent;return u(Xe,{open:!0,onOpenChange:e=>!e&&r(),children:n(He,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,"data-testid":`history-delivery-detail`,children:[u(Ve,{children:u(ut,{className:`min-w-0 break-words`,children:a.title||e.ruleName})}),u(Ue,{children:n(`dl`,{className:`space-y-3`,children:[n(`div`,{children:[u(`dt`,{className:`text-[10px] font-medium uppercase tracking-wide text-foreground-subtle`,children:i(`system.notificationHistory.body`,`Body`)}),u(`dd`,{className:`mt-1 whitespace-pre-wrap text-sm text-foreground`,children:a.body.length>0?a.body:`—`})]}),n(`div`,{className:`grid grid-cols-2 gap-3 text-[11px]`,children:[n(`div`,{children:[u(`dt`,{className:`font-medium text-foreground-subtle`,children:i(`system.notificationHistory.when`,`When`)}),u(`dd`,{className:`text-foreground`,children:new Date(e.createdAt).toLocaleString()})]}),n(`div`,{children:[u(`dt`,{className:`font-medium text-foreground-subtle`,children:i(`system.notificationHistory.status`,`Status`)}),u(`dd`,{className:`text-foreground`,children:e.status})]}),n(`div`,{children:[u(`dt`,{className:`font-medium text-foreground-subtle`,children:i(`system.notificationHistory.rule`,`Rule`)}),u(`dd`,{className:`text-foreground`,children:e.ruleName})]}),n(`div`,{children:[u(`dt`,{className:`font-medium text-foreground-subtle`,children:i(`system.notificationHistory.device`,`Device`)}),u(`dd`,{className:`text-foreground`,children:t})]}),o===void 0?null:n(`div`,{className:`col-span-2`,children:[u(`dt`,{className:`font-medium text-foreground-subtle`,children:i(`system.notificationHistory.kind`,`Kind`)}),u(`dd`,{className:`text-foreground`,children:o.kind})]}),e.error===void 0?null:n(`div`,{className:`col-span-2`,children:[u(`dt`,{className:`font-medium text-foreground-subtle`,children:i(`common.error`,`Error`)}),u(`dd`,{className:`text-danger`,children:e.error})]})]})]})}),u(dt,{children:u(W,{type:`button`,size:`sm`,variant:`secondary`,onClick:r,children:i(`common.close`,`Close`)})})]})})}function qa(){let{t:e}=Z(),t=E(),[a,o]=Wr(),[s,l]=c(()=>Ra(a)),[d,f]=c(null),p=e=>l(t=>({...t,...e})),m=e=>{p({ruleId:e}),o(La(a,e),{replace:!0})},h=i({queryKey:[`notificationRules`,`listRules`,`forHistory`],queryFn:async()=>(await t.trpcClient.notificationRules.listRules.query({})).rules}),g=pt({projection:`slim`}),_=Date.now(),v=i({queryKey:[`notificationRules`,`getHistory`,s],retry:!1,queryFn:async()=>{let e=s.windowHours>0?_-s.windowHours*36e5:void 0;return(await t.trpcClient.notificationRules.getHistory.query({filter:{limit:s.limit,...s.ruleId?{ruleId:s.ruleId}:{},...s.deviceId?{deviceId:Number(s.deviceId)}:{},...Ua(s.status)?{status:Ua(s.status)}:{},...e===void 0?{}:{since:e}}})).entries}}),y=r(()=>{let e=new Map;for(let t of g.data??[])t.type===ce.Camera&&e.set(t.id,t.name);return e},[g.data]),x=e=>y.get(e)??`Camera #${String(e)}`,S=v.data??[],C=v.isError;return n(Jr,{embedded:!0,icon:N,title:e(`system.notificationHistory.deliveryHistory`,`Delivery history`),subtitle:e(`system.notificationHistory.aSearchableLogOfEvery`,`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:e(`system.notificationHistory.rule`,`Rule`)}),u(G,{"data-testid":`history-rule-filter`,value:s.ruleId,onChange:e=>m(e.target.value),options:[...za({rules:h.data??[],answered:h.isSuccess,selected:s.ruleId})]})]}),n(`div`,{children:[u(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:e(`system.notificationHistory.camera`,`Camera`)}),u(G,{value:s.deviceId,onChange:e=>p({deviceId:e.target.value}),options:[{value:``,label:e(`system.notificationHistory.allCameras`,`All cameras`)},...(g.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:e(`system.notificationHistory.status`,`Status`)}),u(G,{value:s.status,onChange:e=>p({status:e.target.value}),options:Va.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:e(`system.notificationHistory.window`,`Window`)}),u(G,{value:String(s.windowHours),onChange:e=>p({windowHours:Number(e.target.value)}),options:Ba.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:e(`system.notificationHistory.limit`,`Limit`)}),u(G,{value:String(s.limit),onChange:e=>p({limit:Number(e.target.value)}),options:Ha.map(e=>({value:String(e),label:String(e)}))})]})]}),v.isLoading&&u(`div`,{className:`flex items-center justify-center py-16`,children:u(b,{className:`h-6 w-6 animate-spin text-primary`})}),C&&!v.isLoading&&u(qe,{children:n(`div`,{className:`flex flex-col items-center gap-2 px-4 py-14 text-center`,children:[u(N,{className:`h-6 w-6 text-foreground-subtle`}),u(`div`,{className:`text-sm font-medium text-foreground`,children:e(`system.notificationHistory.deliveryHistoryRequiresAServer`,`Delivery history requires a server update`)}),u(`p`,{className:`max-w-md text-xs text-foreground-subtle`,children:e(`system.notificationHistory.theHistoryQueryIsNot`,`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 v.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(A,{className:`h-3 w-3`}),` Retry`]})]})}),!C&&!v.isLoading&&S.length===0&&u(`div`,{className:`py-16 text-center text-xs text-foreground-subtle`,children:e(`system.notificationHistory.noDeliveriesMatchTheseFilters`,`No deliveries match these filters.`)}),!C&&S.length>0&&u(qe,{children:u(Ge,{columns:Ja(x),rows:S,rowKey:e=>e.id,minWidthPx:720,bordered:!1,mobileMode:`scroll`,maxBodyHeight:`max-h-[60vh]`,onRowClick:e=>f(e)})}),d!==null&&u(Ka,{entry:d,cameraName:x(d.deviceId),onClose:()=>f(null)})]})}function Ja(e){return[{key:`when`,header:X.t(`system.notificationHistory.when`,`When`),nowrap:!0,render:e=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:new Date(e.createdAt).toLocaleString()})},{key:`rule`,header:X.t(`system.notificationHistory.rule`,`Rule`),render:e=>u(`span`,{className:`text-xs font-medium text-foreground`,children:e.ruleName})},{key:`camera`,header:X.t(`system.notificationHistory.camera`,`Camera`),nowrap:!0,render:t=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:e(t.deviceId)})},{key:`subject`,header:X.t(`system.notificationHistory.notification`,`Notification`),render:e=>{let t=Ga(e);return n(`span`,{className:`block max-w-[18rem]`,children:[u(`span`,{className:`block truncate text-[11px] font-medium text-foreground`,children:t.title.length>0?t.title:e.subject.label??e.subject.className}),t.body.length>0?u(`span`,{className:`block truncate text-[10px] text-foreground-subtle`,children:t.body}):null]})}},{key:`status`,header:X.t(`system.notificationHistory.status`,`Status`),nowrap:!0,render:e=>n(`span`,{className:`flex items-center gap-1.5`,children:[u(J,{variant:Wa(e.status),children:e.status}),e.attempts>1?n(`span`,{className:`text-[10px] text-foreground-subtle`,children:[`×`,e.attempts]}):null]})},{key:`error`,header:X.t(`system.notificationHistory.detail`,`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 Ya=/\{\{\s*(\w+)\s*\}\}/g,Xa=[`subject`,`place`,`time`,`rule`,`occupancy`,`sound`,`sensor`,`system`,`digest`,`ai`];function Za(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 Qa(e){let t=`{{${e.name}}}`;return{text:t,cursorOffset:e.dynamic?t.length-2:t.length}}function $a(e){return[...e.matchAll(Ya)].map(e=>e[1]??``).filter(e=>e.length>0)}function eo(e,t){return t.some(t=>t.dynamic?e.startsWith(t.dynamic.prefix)&&e.length>t.dynamic.prefix.length:t.name===e)}function to(e,t){return[...new Set($a(e))].filter(e=>!eo(e,t))}var no={previewText:[`camera`,`rule`,`from`,`to`],captionText:[`rule`,`from`,`to`]};function ro(e){return e.map(e=>{let t=z.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)||Me.includes(e)),i=n.filter(e=>!r.includes(e));return{...e,systemEventKinds:[...r,...i]}})}function io(e){let t=new Set(e.map(e=>e.name)),n=z.filter(e=>fe(e)&&!t.has(e.name));return[...e,...n]}function ao(e,t){if(t.field===`previewText`||t.field===`captionText`){let n=no[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)||!de(e.kinds,t.kind)||e.deliveries&&t.delivery!==void 0&&!e.deliveries.includes(t.delivery)?!1:pe(e,t)&&ie(e,t))}function oo(e){return Xa.map(t=>({group:t,vars:e.filter(e=>e.group===t)})).filter(e=>e.vars.length>0)}var so=[`nc`,`template-catalog`],co=400;function lo(){let e=E();return i({queryKey:so,staleTime:5*6e4,queryFn:async()=>io(ro((await e.trpcClient.notificationRules.getTemplateCatalog.query({})).vars))})}function uo(e,t,n){let r=E(),a=vt(t.title??``,co),o=vt(t.body??``,co);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 fo={subject:`Subject`,place:`Place`,time:`Time`,rule:`Rule`,occupancy:`Occupancy`,sound:`Sound`,sensor:`Sensor`,system:`System event`,digest:`Digest`,ai:`AI`},po=`block text-[11px] font-medium text-foreground mb-1`,mo=`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 ho({label:t,value:r,onChange:i,vars:a,multiline:o=!1,placeholder:s,disabled:c=!1,testId:l}){let{t:d}=Z(),f=e(null),p=e(null),m=a?to(r,a):[],g=e=>{let t=o?p.current:f.current,n={start:t?.selectionStart??r.length,end:t?.selectionEnd??r.length},a=Qa(e),s=Za(r,n,a.text);i(s.value);let c=s.cursor-a.text.length+a.cursorOffset;requestAnimationFrame(()=>{t?.focus(),t?.setSelectionRange(c,c)})},_=e=>i(e.target.value);return n(`div`,{className:`space-y-1`,children:[u(`label`,{className:po,children:t}),o?u(`textarea`,{ref:p,value:r,rows:2,disabled:c,placeholder:s,onChange:_,className:mo,"data-testid":`${l}-input`}):u(q,{ref:f,value:r,disabled:c,placeholder:s,onChange:_,"data-testid":`${l}-input`}),a&&a.length===0?u(`p`,{className:`text-[10px] text-foreground-subtle`,children:d(`notifications.templateField.noVariablesForThisField`,`No variables for this field.`)}):null,a&&a.length>0?u(`div`,{className:`flex flex-wrap gap-x-3 gap-y-1`,children:oo(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:fo[e.group]}),e.vars.map(e=>u(`button`,{type:`button`,disabled:c,onMouseDown:e=>e.preventDefault(),onClick:()=>g(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?d(`notifications.templateField.class`,`{{name}}<class>`,{name:e.name}):e.name},e.name))]},e.group))}):null,m.length>0?n(`p`,{className:`flex items-center gap-1 text-[10px] text-warning`,"data-testid":`${l}-unknown`,children:[u(h,{className:`h-3 w-3`}),m.map(e=>`{{${e}}}`).join(` `),` will be empty in this notification.`]}):null]})}function go({context:e,title:t,body:r,testId:i}){let{t:a}=Z(),o=uo(e,{title:t,body:r},!0);return o.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:a(`notifications.templateField.previewExampleValues`,`Preview (example values)`)}),o.data.title===null?null:u(`p`,{className:`font-medium`,children:o.data.title}),o.data.body===null?null:u(`p`,{className:`whitespace-pre-wrap`,children:o.data.body})]}):null}var _o=`mt-1 w-full rounded border border-border bg-background px-2 py-1 text-xs`,vo=`block text-[11px] font-medium text-foreground`;function yo({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 bo(e){return typeof e==`number`?e>0?[e]:[]:Array.isArray(e)?e.filter(e=>e>0):[]}function xo(e,t){return{kind:`cap`,deviceId:t,cap:e.cap,method:e.method,...e.args===void 0?{}:{args:{...e.args}}}}function So(e){let t=bo(e.deviceId);return t.length===0?[xo(e,0)]:t.map(t=>xo(e,t))}function Co(e){return So(e).map(e=>({kind:`do`,action:e}))}function wo(e,t){let n=e[t];if(n===void 0||n.kind!==`cap`)return{wire:{deviceId:0,cap:``,method:``},length:1};let r=n.deviceId>0?[n.deviceId]:[],i=1;for(let a=t+1;a<e.length;a+=1){let t=e[a];if(t===void 0||t.kind!==`cap`||t.cap!==n.cap||t.method!==n.method||JSON.stringify(t.args??{})!==JSON.stringify(n.args??{}))break;t.deviceId>0&&r.push(t.deviceId),i+=1}return{wire:{deviceId:r.length===0?0:r.length===1?r[0]:[...r],cap:n.cap,method:n.method,...n.args===void 0?{}:{args:{...n.args}}},length:i}}function To(e,t){let n=e[t];return n===void 0||n.kind!==`do`?{wire:{deviceId:0,cap:``,method:``},length:1}:wo(e.slice(t).map(e=>e.kind===`do`?e.action:{kind:`wait`,seconds:0}),0)}function Eo({value:e,onChange:t,devices:r,devicesState:i,sequences:a=[],showProblems:o=!0}){let{t:s}=Z(),c=on(e,new Set(a.map(e=>e.id))),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:[o&&c.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:c.map(e=>u(`p`,{children:e.message},e.message))}):null,zt.map(t=>u(Do,{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(yo,{title:s(`system.notificationRuleActions.buttonsOnTheNotification`,`Buttons on the notification`),description:s(`system.notificationRuleActions.eachButtonRunsOneShared`,`Each button runs one shared sequence when tapped.`),children:n(W,{size:`sm`,variant:`ghost`,type:`button`,disabled:a.length===0,onClick:()=>t({...e,buttons:[...e.buttons,Gt(e.buttons.length,a[0]?.id??``)]}),children:[u(g,{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(h,{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:s(`system.notificationRuleActions.createASequenceOnThe`,`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:s(`system.notificationRuleActions.noButtonsTheNotificationArrives`,`No buttons. The notification arrives with nothing to tap.`)}):e.buttons.map((n,r)=>u(Oo,{button:n,sequences:a,onChange:e=>d(r,e),onRemove:()=>t({...e,buttons:e.buttons.filter((e,t)=>t!==r)})},`btn-${String(r)}`))]})]})}function Do({hookKey:e,bindings:t,sequences:r,devices:i,devicesState:a,onChange:o}){let{t:s}=Z(),c=qt[e],l=[],d=0;for(;d<t.length;){if(t[d].kind===`sequence`){l.push({start:d,kind:`sequence`,length:1}),d+=1;continue}let e=To(t,d);l.push({start:d,kind:`do`,length:e.length}),d+=e.length}return n(`section`,{className:`space-y-2`,children:[n(yo,{title:c.title,description:c.hint,children:[n(W,{size:`sm`,variant:`ghost`,type:`button`,disabled:t.length>=4||r.length===0,onClick:()=>o([...t,bn(r[0]?.id??``)]),children:[u(g,{className:`h-3.5 w-3.5`}),` Sequence`]}),n(W,{size:`sm`,variant:`ghost`,type:`button`,disabled:t.length>=4,onClick:()=>o([...t,Sn()]),children:[u(g,{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:s(`system.notificationRuleActions.nothingOnThisEdge`,`Nothing on this edge.`)}):l.map(e=>{if(e.kind===`sequence`){let i=t[e.start];return i.kind===`sequence`?n(`div`,{className:`flex flex-wrap items-end gap-2 rounded-md border border-border p-3`,children:[n(`div`,{className:`min-w-0 flex-1`,children:[u(`label`,{className:vo,children:s(`system.notificationRuleActions.sequence`,`Sequence`)}),u(`select`,{className:_o,value:i.sequenceId,onChange:n=>{let r=[...t];r[e.start]={kind:`sequence`,sequenceId:n.target.value},o(r)},children:r.map(e=>u(`option`,{value:e.id,children:e.name},e.id))})]}),u(W,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>o(t.filter((t,n)=>n!==e.start)),title:s(`common.remove`,`Remove`),children:u(p,{className:`h-3.5 w-3.5`})})]},`seq-${String(e.start)}`):null}return u(`div`,{className:`space-y-2 rounded-md border border-border p-3`,children:n(`div`,{className:`flex items-start justify-between gap-2`,children:[u(`div`,{className:`min-w-0 flex-1`,children:u(qr,{value:To(t,e.start).wire,devices:i,listState:a,allowMultiSameFamily:!0,onChange:n=>{let r=Co(n);o([...t.slice(0,e.start),...r,...t.slice(e.start+e.length)])}})}),u(W,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>o([...t.slice(0,e.start),...t.slice(e.start+e.length)]),title:s(`common.remove`,`Remove`),children:u(p,{className:`h-3.5 w-3.5`})})]})},`do-${String(e.start)}`)})]})}function Oo({button:e,sequences:t,onChange:r,onRemove:i}){let{t:a}=Z();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:vo,children:a(`system.notificationRuleActions.id`,`Id`)}),u(q,{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:vo,children:a(`system.notificationRuleActions.label`,`Label`)}),u(q,{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:vo,children:a(`system.notificationRuleActions.sequence`,`Sequence`)}),u(`select`,{className:_o,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:vo,children:a(`system.notificationRuleActions.icon`,`Icon`)}),n(`select`,{className:_o,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:`—`}),vn.map(e=>u(`option`,{value:e.value,children:e.label},e.value))]})]}),u(W,{size:`sm`,variant:`ghost`,type:`button`,onClick:i,title:a(`common.remove`,`Remove`),children:u(p,{className:`h-3.5 w-3.5`})})]})}var ko=new Set([`devices`,`devicesExclude`,`customZones`,`source`,`crossing`]),Ao=[[`classes`,`classesExclude`],[`zones`,`zonesExclude`],[`identities`,`identitiesExclude`]],jo={minConfidence:`class`},Mo=[{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 No(e){let t=new Set(e.map(e=>e.id)),n=new Set;for(let[e,r]of Ao)t.has(e)&&n.add(r);return n}function Po(e){return jo[e.id]??e.group}function Fo(e){let t=e.replace(/[-_]/g,` `);return t.charAt(0).toUpperCase()+t.slice(1)}function Io(e){let t=No(e),n=e.filter(e=>!ko.has(e.id)&&!t.has(e.id)),r=new Set(Mo.map(e=>e.id)),i=[],a=e=>n.filter(t=>Po(t)===e);for(let e of Mo){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=Po(e);!r.has(t)&&!o.includes(t)&&o.push(t)}for(let e of o)i.push({id:e,label:Fo(e),descriptors:a(e)});return i}function Lo(e,t){switch(e){case`zones`:return Sr(t.zones?.ids,t.zonesExclude);case`labels`:return Sr(t.labelEquals,void 0);case`identities`:return Ro(t)}}function Ro(e){let t=e.identities,n=[...e.identitiesExclude??[]];return t===void 0?Sr(void 0,n):{mode:`only`,include:[...t],exclude:n,legacyBoth:n.length>0}}function zo(e,t,n){switch(e){case`zones`:return Bo(t,n);case`labels`:return Vo(t,n);case`identities`:return Ho(t,n)}}function Bo(e,t){let{zones:n,zonesExclude:r,...i}=e,a=Vn(t);return{...i,...a.include===void 0?{}:{zones:{ids:[...a.include]}},...a.exclude===void 0?{}:{zonesExclude:[...a.exclude]}}}function Vo(e,t){let{labelEquals:n,...r}=e,i=Vn(t);return{...r,...i.include===void 0?{}:{labelEquals:[...i.include]}}}function Ho(e,t){let{identities:n,identitiesExclude:r,...i}=e;if(t.mode===`only`){let e=Qn(t);return{...i,identities:[...t.include],...e.length>0?{identitiesExclude:[...e]}:{}}}let a=Vn(t);return{...i,...a.exclude===void 0?{}:{identitiesExclude:[...a.exclude]}}}var Uo={all:`All`,only:`Only these`,except:`All except these`},Wo={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 Go({draft:e,onChange:t,exceptOffered:r,plural:i,renderPicker:a,describe:o,testId:s}){let{t:c}=Z(),l=(e,t,n)=>c(e,{items:n,defaultValue:t}).replaceAll(`{{items}}`,n),d=c(`ruleScope.items.${i}`,Wo[i].items),f=Tt.filter(t=>t!==`except`||r||e.mode===`except`),p=Qn(e),m=dr(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(Tr(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}`,Uo[n])},n)})}),h===null?u(`p`,{className:`text-[11px] text-foreground-subtle`,children:c(`ruleScope.every.${i}`,Wo[i].every)}):a(jn(e),n=>t(mr(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(Or(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 Ko(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 qo(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 Jo(e,t,n){let[r,i]=c(()=>Lo(e,t));return[r,r=>{i(r),n(zo(e,t,r))}]}function Yo(e,t){return t?`failed`:e?`pending`:`answered`}function Xo({conditions:e,onConditionsChange:t,exceptOffered:n,cameraIds:i,cameras:a}){let{t:o}=Z(),[s,c]=Jo(`zones`,e,t),{options:l,loading:d,failed:f}=Dr(i,a),p=r(()=>qo(l),[l]),m=Yo(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(Go,{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:Ln,children:o(`notificationRules.zones.noCameras`,`This rule covers no camera, so it has no zones.`)}):u(tt,{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}=Z(),[a,o]=Jo(`identities`,e,t),{options:s,loading:c,failed:l}=Bn(),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(Go,{draft:a,onChange:o,exceptOffered:n,plural:`faces`,describe:e=>f.get(e)??e,testId:`rule-identity-scope`,renderPicker:(e,t,n)=>u(tt,{devices:d,listState:Yo(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 Qo({conditions:e,onConditionsChange:t}){let{t:n}=Z(),[r,i]=Jo(`labels`,e,t);return u(Go,{draft:r,onChange:i,exceptOffered:!1,plural:`labels`,describe:e=>e,testId:`rule-label-scope`,renderPicker:(e,t)=>u(En,{value:e,placeholder:n(`notificationRules.labels.add`,`Add a label…`),onChange:t})})}function $o(e){let t=je(e);return t===null?null:t.groups.flatMap(e=>e.options.map(t=>({id:t.value,name:t.label,type:e.fallbackLabel})))}function es(e){return e.type??`Other`}t();function ts({taxonomy:e,scope:t,onChange:n,exceptOffered:i}){let{t:a}=Z(),o=r(()=>$o(e),[e]),s=r(()=>new Map((o??[]).map(e=>[e.id,e.name])),[o]);return u(Go,{draft:t,onChange:n,exceptOffered:i,plural:`classes`,describe:e=>s.get(e)??e,testId:`rule-class-scope`,renderPicker:(e,t,n)=>o===null?u(En,{value:e,placeholder:a(`system.notificationClassScopeField.addValue`,`Add value…`),onChange:t}):u(tt,{devices:o,listState:`answered`,value:e,onChange:t,emptyMeansAll:!0,noun:`class`,groupTitle:es,testId:`class-picker`},n)})}function ns(e){return{id:e.id,name:e.name,type:e.type,location:e.location,...e.parentName===void 0?{}:{detail:e.parentName}}}function rs({devices:e,value:t,onChange:n,listState:r,savedHadDevices:i}){return u(tt,{devices:e.map(ns),listState:r,value:t,onChange:n,emptyMeansAll:!0,savedHadDevices:i,noun:`device`,showAll:!0})}function is({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(Go,{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(rs,{devices:e,value:t,onChange:n,listState:r,savedHadDevices:(a===`only`?i.include:i.exclude).length>0},a)})}function as(e){return e.data===void 0?e.isError?`failed`:`pending`:`answered`}function os(e,t){return t===`answered`?e?.complete===!0?`answered`:`failed`:t}function ss(e){let t=as(e),n=e.data===void 0?[]:Ce(e.data.nodes),r=os(e.data,t);return{items:n,listState:t,fleet:{state:r,devices:r===`answered`?n:void 0}}}function cs(e){let t=as(e),n=e.data===void 0?[]:R(e.data);return{items:n,listState:t,fleet:{state:t,devices:t===`answered`?n:void 0}}}var ls=[`nc-pickers`,`node-directory`],us=[`nc-pickers`,`package-list`],ds=6e4,fs={hub:`Hub`,agent:`Agents`},ps={server:`Server`,framework:`Framework`,wrapper:`Wrapper`,addon:`Addons`};function ms(e){let t=fs[e.type??``]??`Nodes`;return e.location===`offline`?`${t} · offline`:t}function hs(e){return ps[e.type??``]??`Packages`}function gs({value:e,onChange:t,testId:r}){let{t:a}=Z(),o=E().trpcClient,s=i({queryKey:ls,staleTime:ds,queryFn:()=>o.nodes.directory.query()}),c=ss(s);return n(`div`,{children:[u(tt,{devices:c.items,listState:c.listState,fleet:c.fleet,value:e,onChange:t,emptyMeansAll:!0,noun:`node`,groupTitle:ms,...r===void 0?{}:{testId:r}}),s.data?.complete===!1&&u(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,"data-testid":`node-directory-incomplete`,children:a(`system.scopePickers.theNodeHistoryCouldNot`,`The node history could not be read — offline nodes may be missing from this list.`)})]})}function _s({value:e,onChange:t,testId:n}){let r=E().trpcClient,a=cs(i({queryKey:us,staleTime:ds,queryFn:()=>r.addons.listPackages.query()}));return u(tt,{devices:a.items,listState:a.listState,fleet:a.fleet,value:e,onChange:t,emptyMeansAll:!0,noun:`package`,groupTitle:hs,...n===void 0?{}:{testId:n}})}var vs={context:{family:`rule`,field:`body`,kind:`device-events`,systemEventKinds:[`device-tank-low`]},template:{body:`{{deviceName}}`}};function ys(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 bs(e,t){return e===`pending`?`pending`:e===`success`?`current`:ys(t)===`BAD_REQUEST`?`outdated`:`unknown`}function xs(e){let t=E(),n=i({queryKey:[`nc`,`hub-rule-schema-probe`],enabled:e,staleTime:5*6e4,retry:!1,queryFn:()=>t.trpcClient.notificationRules.previewTemplate.mutate(vs)});return e?bs(n.status,n.error):`pending`}t();var Ss=`/system/settings`,Cs=`/system/notifications?tab=alarm`,ws=`text-primary underline-offset-2 hover:underline`;function Ts(e,t){let n=Vn(t);return Un(e,{deviceIds:n.include,excludeDeviceIds:n.exclude})}function Es({family:e,value:t,cameras:i,allDevices:a,fleet:o,savedHadDevices:s,onChange:l}){let{t:d}=Z(),f=r(()=>t?.kinds??[],[t]),p=r(()=>a===void 0?i:a.map(ns),[a,i]),m=r(()=>i.map(e=>({id:e.id,name:e.name,type:`camera`})),[i]),h=Yn(e,f),g=xs(e===`device-events`),_=e===`alarm`,[v,y]=c(()=>Sr(t?.deviceIds,t?.excludeDeviceIds)),[b]=c(()=>Sr(t?.deviceIds,t?.excludeDeviceIds)),x=r(()=>{let e=new Map;for(let t of _?m:p)e.set(t.id,t.name);return e},[m,_,p]);return n(`div`,{className:`mt-1 space-y-3`,"data-testid":`system-event-field`,children:[Kn(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=f.includes(n.value);return u(`button`,{type:`button`,role:`checkbox`,"aria-checked":r,"aria-label":n.label,onClick:()=>l(Nr(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:[d(`system.notificationSystemEventField.theBatteryThresholdAndThe`,`The battery threshold and the reminder interval are cluster settings (the consumable threshold is this rule’s own, below):`),` `,u(Ur,{to:Ss,target:`_blank`,rel:`noreferrer`,className:ws,children:d(`system.notificationSystemEventField.settingsBatteryOfflineAlerts`,`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(Ur,{to:Cs,target:`_blank`,rel:`noreferrer`,className:ws,children:d(`system.notificationSystemEventField.alarmSettings`,`Alarm settings`)}),f.includes(`alarm-triggered`)&&` — when a rule sets the alarm off, this notification carries that rule's pictures.`]}),g===`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.`]}),g===`unknown`&&u(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,"data-testid":`system-event-hub-unchecked`,children:d(`system.notificationSystemEventField.couldNotCheckWhetherThis`,`Could not check whether this hub’s server knows per-rule consumable thresholds and tank alerts.`)}),h.consumableThreshold&&n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground`,htmlFor:`system-event-consumable-threshold`,children:d(`system.notificationSystemEventField.consumableLowAt`,`Consumable low at (%)`)}),u(q,{id:`system-event-consumable-threshold`,"data-testid":`system-event-consumable-threshold`,type:`number`,min:1,max:In,step:1,placeholder:`15`,value:t?.consumableLowPercent??``,className:`mt-1 max-w-[8rem]`,onChange:e=>{let n=zn(e.target.value);n.kind!==`invalid`&&l(Un(t,{consumableLowPercent:n.kind===`set`?n.value:void 0}))}})]}),h.deviceTypes&&n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground`,children:d(`system.notificationSystemEventField.deviceTypes`,`Device types`)}),u(Et,{options:ar,value:t?.deviceTypes??[],onChange:e=>l(Un(t,{deviceTypes:e})),emptyHint:`No device types listed — the rule watches every type.`,placeholder:d(`system.notificationSystemEventField.deviceType`,`Device type…`)})]}),jr(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:d(`system.notificationSystemEventField.batteryAndConsumableAlertsAre`,`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.`)}),h.devices&&n(`div`,{children:[u(Go,{draft:v,onChange:e=>{y(e),l(Ts(t,e))},exceptOffered:h.excludeDevices,plural:`devices`,describe:e=>x.get(e)??`Device #${String(e)}`,testId:`system-event-device-scope`,renderPicker:(e,t,n)=>u(tt,{devices:_?m:p,listState:o.state,fleet:o,emptyMeansAll:!0,savedHadDevices:(n===`only`?b.include:b.exclude).length>0||n===`only`&&s,noun:_?`camera`:`device`,value:e,onChange:t,testId:n===`only`?`system-event-include`:`system-event-exclude`},n)}),s&&v.mode===`all`&&u(at,{noun:_?`camera`:`device`})]}),h.nodes&&n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground`,children:d(`system.notificationSystemEventField.nodes`,`Nodes`)}),u(gs,{value:t?.nodeIds??[],onChange:e=>l(Un(t,{nodeIds:e})),testId:`system-event-nodes`})]}),h.packages&&n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground`,children:d(`system.notificationSystemEventField.packages`,`Packages`)}),u(_s,{value:t?.packageNames??[],onChange:e=>l(Un(t,{packageNames:e})),testId:`system-event-packages`})]})]})}function Ds({value:e}){let{t}=Z(),r=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:t(`system.notificationSystemEventField.thisRuleIsNotOne`,`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.`)}),r.length>0&&u(`p`,{className:`mt-1 text-foreground`,children:r.map(On).join(`, `)})]})}function Os({family:e,onChange:t}){let{t:r}=Z();return n(`div`,{"data-testid":`system-family-select`,children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:r(`system.notificationSystemEventField.kindOfSystemRule`,`Kind of system rule`)}),u(G,{value:e,"aria-label":r(`system.notificationSystemEventField.kindOfSystemRule`,`Kind of system rule`),onChange:e=>{let n=e.target.value;_e(n)&&t(n)},options:Te.map(e=>({value:e,label:we(e).label}))}),u(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:r(`system.notificationSystemEventField.oneRuleAnswersOneQuestion`,`One rule answers one question: about devices, about the installation, or about the alarm. Changing it starts the event list over.`)})]})}t();function ks({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}=Z(),C=(e,t)=>{let n={...a};t===void 0?delete n[e]:n[e]=t,b(n)},w=ye({delivery:i,conditions:a}),T=r(()=>e.filter(e=>ke(e,i,w)&&en(e.id,a)),[e,i,w,a]),E=r(()=>Io(T),[T]),D=e=>T.some(t=>t.id===e),O=e=>As.has(e.id)?u(ts,{taxonomy:t,scope:o,onChange:s,exceptOffered:D(`classesExclude`)}):js.has(e.id)?u(Xo,{conditions:a,onConditionsChange:b,exceptOffered:D(`zonesExclude`),cameraIds:m??p,cameras:h}):Ms.has(e.id)?u(Zo,{conditions:a,onConditionsChange:b,exceptOffered:D(`identitiesExclude`)}):e.id===`labelEquals`?u(Qo,{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:Q,children:Ns(e,S)}),r??u(Is,{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}),Ps(e,S)!==void 0&&u(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:Ps(e,S)})]},e.id)})]},e.id))})}var As=new Set([`classes`,`classesExclude`]),js=new Set([`zones`,`zonesExclude`]),Ms=new Set([`identities`,`identitiesExclude`]);function Ns(e,t){return As.has(e.id)?t(`notificationRules.labels.classes`,`Object classes`):js.has(e.id)?t(`notificationRules.labels.zones`,`Zones`):Ms.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 Ps(e,t){if(!Fs.has(e.id))return e.id===`scene`?t(`notificationRules.scene.hint`,`Only fire while a scene is matched or diverged.`):e.description}var Fs=new Set([...As,...js,...Ms,`labelEquals`,`crossing`]);function Is({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}){let{t:y}=Z();switch(e.valueType){case`deviceIdList`:{if(!Zn(e.id))break;let t=e.id,n=i[t]??[];return u(Pn,{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(!sr(e.id))break;let t=e.id,n=e=>_(t,e.length>0?e:void 0);if(t===`eventTypeTokens`)return u(kr,{deviceIds:d,value:Dn(i,t),onChange:n});let a=ve(t,r);return a===null?u(En,{value:Dn(i,t),placeholder:y(`system.notificationRuleConditions.addValue`,`Add value…`),onChange:n}):u(Mr,{picker:a,value:Dn(i,t),onChange:n})}case`number01`:{if(!pr(e.id))break;let t=e.id;return u(hr,{value:Gn(i,t),min:0,max:1,step:.05,onChange:e=>_(t,e)})}case`number`:{if(!wr(e.id))break;let t=e.id;return u(hr,{value:Gn(i,t),min:0,step:1,onChange:e=>_(t,e)})}case`sourceSelect`:{if(!gr(e.id))break;let t=e.id;return Vs(e,i[t],e=>_(t,e))}case`systemEvent`:{if(!Jn(e.id))break;let n=e.id,r=xe(t);return r===void 0?u(Ds,{value:i[n]}):u(Es,{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(!An(e.id))break;return u(rr,{gateable:h,value:i.deviceState,onChange:e=>_(`deviceState`,e)});case`scene`:if(!Rn(e.id))break;return u(Wn,{scenes:g,value:i.scene,onChange:e=>_(`scene`,e)});case`crossingSelect`:{if(!xr(e.id))break;let t=e.id;return Hs(e,i[t],e=>_(t,e))}case`packagePhase`:{if(!ir(e.id))break;let t=e.id;return u(G,{value:i[t]??``,options:[{value:``,label:y(`system.notificationRuleConditions.anyPhase`,`— any phase —`)},...Xt(e,nn).map(e=>({value:e.value,label:e.label}))],onChange:e=>_(t,Bs(e.target.value))})}case`sensorTransition`:{if(!Hn(e.id))break;let t=e.id,r=ee({conditions:i,...o===void 0?{}:{actions:o},...s===void 0?{}:{sequenceActionsOf:s}});return n(a,{children:[u(G,{value:i[t]??``,options:Xt(e,er).map(e=>({value:e.value,label:e.label})),onChange:e=>_(t,Tn(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(!Ar(e.id))break;let t=e.id;return u(qn,{value:i[t],onChange:e=>_(t,e)})}case`occupancy`:{if(!Fn(e.id))break;let t=e.id;return u(or,{deviceIds:d,cameras:f,classOptions:Ls(r),value:i[t],onChange:e=>_(t,e)})}case`audio`:{if(!ur(e.id))break;let t=e.id;return u(fr,{taxonomy:r,value:i[t],onChange:e=>_(t,e)})}case`schedule`:return u(Er,{value:l,onChange:v});default:break}return u(Rs,{descriptor:e,conditions:i})}function Ls(e){let t=ve(`occupancy`,e);return t===null?[]:t.groups.flatMap(e=>e.options)}function Rs({descriptor:e,conditions:t}){let{t:r}=Z(),i=Object.entries(t).find(([t])=>t===e.id);return n(`p`,{className:Ln,children:[i!==void 0&&i[1]!==void 0?r(`system.notificationRuleConditions.authoredElsewhereAndPreservedThis`,`Authored elsewhere and preserved — this admin editor cannot change it yet.`):r(`system.notificationRuleConditions.notEditableHereYetThis`,`Not editable here yet — this condition has no admin editor.`),` `,n(`span`,{className:`text-foreground-muted`,children:[`(`,e.valueType,`)`]})]})}function zs(e){if(e===`pipeline`||e===`onboard`||e===`sensor`||e===`any`)return e}function Bs(e){return nn.find(t=>t.value===e)?.value}function Vs(e,t,n){return u(G,{value:t??`any`,options:Xt(e,Qt).map(e=>({value:e.value,label:e.label})),onChange:e=>n(zs(e.target.value))})}function Hs(e,t,n){return u(Cr,{value:t,onChange:n,...e.options?{options:e.options}:{}})}function Us({catalog:e,delivery:t,conditions:r,onConditionsChange:i}){let{t:a}=Z(),o=ye({delivery:t,conditions:r}),s=(e,t)=>{let n={...r};t===void 0?delete n[e]:n[e]=t,i(n)},c=n=>e.find(e=>e.id===n&&ke(e,t,o)&&en(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&&gr(l.id)&&n(`div`,{"data-testid":`condition-source`,children:[u(`label`,{className:`block text-[11px] font-medium text-foreground`,children:Ns(l,a)}),Vs(l,r.source,e=>s(`source`,e)),Ps(l,a)!==void 0&&u(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:Ps(l,a)})]}),d&&xr(d.id)&&n(`div`,{"data-testid":`condition-crossing`,children:[u(`label`,{className:`block text-[11px] font-medium text-foreground`,children:Ns(d,a)}),Hs(d,r.crossing,e=>s(`crossing`,e)),Ps(d,a)!==void 0&&u(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:Ps(d,a)})]})]})}var Ws=6e4,Gs=60*Ws,Ks=24*Gs,qs=Date.UTC(2e3,0,1);function Js(e){if(e==null||e<qs)return`—`;let t=Date.now()-e;return t<0||t<3e4?`just now`:t<Gs?`${String(Math.floor(t/Ws))}m ago`:t<Ks?`${String(Math.floor(t/Gs))}h ago`:`${String(Math.floor(t/Ks))}d ago`}var Ys=[`notificationRules`,`getRuleLastRuns`],Xs=3e4;function Zs(){let e=E(),t=i({queryKey:Ys,queryFn:()=>e.trpcClient.notificationRules.getRuleLastRuns.query({}),retry:!1,staleTime:Xs});return{status:t.status,data:t.data,error:t.error}}var Qs={sent:`bg-success`,pending:`bg-info`,dead:`bg-danger`};function $s({cell:e}){let{t}=Z();switch(e.kind){case`pending`:return u(`span`,{"data-testid":`rule-last-run-pending`,"aria-label":t(`system.notificationRuleLastRun.lastRunLoading`,`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:t(`system.notificationRuleLastRun.lastRunCouldNotBe`,`Last run could not be read: {{reason}}`,{reason: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 ${Qs[e.status]}`}),u(`span`,{className:`text-[11px] text-foreground-subtle`,children:Js(e.lastAt)})]})}}function ec({rule:e,onOpenHistory:t}){let{t:n}=Z();return u(W,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>t(e),title:n(`system.notificationRuleLastRun.historyThisRuleSDeliveries`,`History — this rule's deliveries`),"aria-label":n(`system.notificationRuleLastRun.historyOf`,`history of {{name}}`,{name:e.name}),children:u(N,{className:`h-3.5 w-3.5`})})}t();var tc=[`notificationRules`,`listSnoozes`],nc=[10,30,60,120];function rc({ruleId:e,ruleName:t,exempt:r=!1,variant:i=`icon`}){let{t:a}=Z(),s=E(),d=o(),[f,p]=c(30),[m,h]=c(null),g=l({mutationFn:t=>s.trpcClient.notificationRules.createSnooze.mutate({snooze:{scope:`rule`,ruleId:e,durationMinutes:t}}),onMutate:()=>h(null),onSuccess:()=>d.invalidateQueries({queryKey:tc}),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:a(`system.notificationRuleSnoozeControl.thisRuleConcernsOrTriggers`,`This rule concerns — or triggers — the alarm panel, so no snooze window can silence it.`)}):i===`icon`?u(W,{size:`sm`,variant:`ghost`,type:`button`,disabled:g.isPending,onClick:()=>g.mutate(30),title:a(`system.notificationRuleSnoozeControl.silenceThisRuleForIt`,`Silence this rule for {{value1}} — it appears under "Silenced right now"`,{value1:Vt(30)}),"aria-label":a(`system.notificationRuleSnoozeControl.snooze`,`snooze {{ruleName}}`,{ruleName:t}),"data-testid":`nc-rule-snooze-now`,children:g.isPending?u(b,{className:`h-3.5 w-3.5 animate-spin`}):u(j,{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(G,{value:String(f),onChange:e=>{let t=Number(e.target.value);Number.isFinite(t)&&t>0&&p(t)},options:nc.map(e=>({value:String(e),label:Vt(e)}))})}),n(W,{size:`sm`,variant:`outline`,type:`button`,disabled:g.isPending,onClick:()=>g.mutate(f),"data-testid":`nc-rule-snooze-now`,children:[g.isPending?u(b,{className:`h-3.5 w-3.5 animate-spin`}):u(j,{className:`h-3.5 w-3.5`}),a(`system.notificationRuleSnoozeControl.silenceThisRuleNow`,`Silence this rule now`)]})]}),u(`p`,{className:`text-[10px] text-foreground-subtle`,children:a(`system.notificationRuleSnoozeControl.opensARealSnoozeWindow`,`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.`)}),m!==null&&u(`p`,{className:`text-[10px] text-danger`,children:m})]})}t();function ic(e,t,n){return e.filter(e=>e.scope===`rule`&&e.ruleId===t&&n>=e.startedAt&&n<e.expiresAt).map(e=>e.id)}function ac(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 oc(e,t){let[,n]=c(0);d(()=>{let r=ac(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 sc(){let e=E();return i({queryKey:tc,queryFn:async()=>(await e.trpcClient.notificationRules.listSnoozes.query({})).snoozes}).data??[]}function cc({rule:e,snoozes:t,exempt:r}){let{t:i}=Z(),a=E(),s=o();oc(t,e.id);let c=ic(t,e.id,Date.now()),d=()=>s.invalidateQueries({queryKey:tc}),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 m=f.isError||p.isError;return n(`span`,{className:`inline-flex flex-col items-center gap-0.5`,children:[u(ct,{checked:c.length>0,disabled:!e.enabled||f.isPending||p.isPending,onCheckedChange:e=>e?f.mutate():p.mutate(c),"aria-label":i(`notificationRules.snooze.aria`,`snooze {{name}}`).replaceAll(`{{name}}`,e.name),title:i(`notificationRules.snooze.title`,{minutes:30,defaultValue:`Silence this rule for {{minutes}} minutes`}).replaceAll(`{{minutes}}`,`30`),"data-testid":`nc-rule-snooze-switch`}),m&&u(`span`,{className:`text-[10px] text-danger`,role:`alert`,children:i(`notificationRules.snooze.failed`,`The snooze could not be changed.`)})]})}var lc=`pipeline-analytics`,uc=`nc.getRuleStatus`,dc=`nc.testRule`;function fc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function $(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function pc(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:void 0}function mc(e){if(!fc(e))return;let t=pc(e,`id`),n=pc(e,`downloadPath`),r=$(e,`capturedAt`);if(!(t===void 0||n===void 0||r===void 0))return{id:t,mediaType:pc(e,`mediaType`)??`video`,sizeBytes:$(e,`sizeBytes`)??0,capturedAt:r,downloadPath:n}}function hc(e){if(!fc(e))return;let t=$(e,`startMs`),n=$(e,`endMs`);if(!(t===void 0||n===void 0))return{startMs:t,endMs:n}}function gc(e){if(!fc(e))return null;let t=$(e,`deviceId`);if(t===void 0)return null;let n=$(e,`lastGeneratedAt`),r=mc(e.lastArtifact),i=e.rendering,a=fc(i)?{startedAt:$(i,`startedAt`)??0,windowStartMs:$(i,`windowStartMs`)??0,windowEndMs:$(i,`windowEndMs`)??0}:void 0;return{deviceId:t,...n===void 0?{}:{lastGeneratedAt:n},...r===void 0?{}:{lastArtifact:r},...a===void 0?{}:{rendering:a}}}function _c(e){if(!fc(e))return null;let t=$(e,`deviceId`),n=pc(e,`windowKey`),r=$(e,`openedAt`),i=$(e,`closesAt`),a=$(e,`members`),o=$(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 vc(e){if(!fc(e))return null;let t=pc(e,`kind`);if(t===`none`)return{kind:`none`,reason:pc(e,`reason`)??``};if(t===`occupancy`){let t=$(e,`deviceId`),n=$(e,`threshold`),r=$(e,`sustainSeconds`);if(t===void 0||n===void 0||r===void 0)return null;let i=pc(e,`unavailable`),a=i===`no-snapshot`||i===`zone-absent`?i:void 0,o=$(e,`count`),s=$(e,`observedAt`),c=$(e,`since`),l=pc(e,`scope`),u=pc(e,`className`),d=pc(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=$(e,`groupingSec`);if(t===void 0)return null;if(e.openWindows===null){let n=pc(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=_c(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=gc(e);t!==null&&n.push(t)}let r=hc(e.lastWindow),i=e.nextWindow,a=fc(i)?{startMs:$(i,`startMs`)??0,endMs:$(i,`endMs`)??null}:void 0;return{kind:`timelapse`,devices:n,...r===void 0?{}:{lastWindow:r},...a===void 0?{}:{nextWindow:a},settleMs:$(e,`settleMs`)??0}}return null}function yc(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 bc(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 xc(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 ${yc(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 Sc(e,t,n){if(e.rendering!==void 0)return`${t}: rendering for ${yc(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} · ${bc(i.sizeBytes)}`}function Cc(e){return{windows:e.length,waiting:e.reduce((e,t)=>e+t.pending,0)}}var wc=`nc.listPrunes`;function Tc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Ec=new Set([`rule`,`timelapse`,`summary`]),Dc=new Set([`removed`,`kept-disabled`,`kept`,`sequence-removed`,`binding-removed`]);function Oc(e){return typeof e==`string`&&Ec.has(e)}function kc(e){return typeof e==`string`&&Dc.has(e)}function Ac(e){return e===`device`||e===`target`}function jc(e){if(!Tc(e))return null;let{kind:t,ruleId:n,subjectKind:r,subject:i,field:a,outcome:o,at:s}=e;return!Oc(t)||!Ac(r)||!kc(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 Mc(e){return!Tc(e)||!Array.isArray(e.prunes)?null:e.prunes.map(jc).filter(e=>e!==null)}function Nc(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 Pc(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 Fc(e){return new Date(e).toLocaleDateString()}function Ic({kind:e,ruleId:t,enabled:r,updatedAt:a}){let o=E(),s=i({queryKey:[`pipelineAnalytics`,wc],enabled:!r,staleTime:3e4,retry:!1,queryFn:async()=>Mc(await o.trpcClient.addons.custom.mutate({addonId:lc,action:wc,input:{}}))}).data;if(s==null)return null;let c=Nc(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(O,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-warning`}),u(`span`,{children:Pc(c,Fc)})]})}var Lc=5e3;function Rc({status:e,now:t,name:r}){let{t:i}=Z();if(e.openWindows===null)return n(`p`,{className:`flex items-start gap-1.5`,children:[u(x,{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}=Cc(o);return n(a,{children:[n(`p`,{className:`flex items-start gap-1.5`,children:[u(x,{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 zc({ruleId:e,cameraName:t}){let{t:r}=Z(),o=E(),s=i({queryKey:[`pipelineAnalytics`,`nc.getRuleStatus`,e],refetchInterval:Lc,queryFn:async()=>vc(await o.trpcClient.addons.custom.mutate({addonId:lc,action:uc,input:{ruleId:e}}))}).data;if(s==null||s.kind===`none`)return null;let c=Date.now(),l=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:[s.kind===`occupancy`&&n(`p`,{className:`flex items-start gap-1.5`,children:[s.unavailable!==void 0||s.warning!==void 0?u(h,{className:`mt-0.5 h-3 w-3 shrink-0 text-warning`}):u(x,{className:`mt-0.5 h-3 w-3 shrink-0 text-primary`}),n(`span`,{children:[u(`span`,{className:`text-foreground`,children:l(s.deviceId)}),` —`,` `,xc(s,c)]})]}),s.kind===`grouped`&&u(Rc,{status:s,now:c,name:l}),s.kind===`timelapse`&&n(a,{children:[s.devices.map(e=>n(`p`,{className:`flex items-start gap-1.5`,children:[u(x,{className:`mt-0.5 h-3 w-3 shrink-0 ${e.rendering===void 0?`text-border`:`text-primary animate-pulse`}`}),n(`span`,{children:[Sc(e,l(e.deviceId),c),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:[s.nextWindow===void 0?r(`system.notificationRuleStatus.noFurtherWindowOpensIn`,`No further window opens in the next nine days`):r(`system.notificationRuleStatus.nextWindowOpens`,`Next window opens {{value1}}`,{value1:new Date(s.nextWindow.startMs).toLocaleString()}),s.settleMs>0&&` · rendered ${String(Math.round(s.settleMs/6e4))} min after it closes, so the footage has settled`]})]})]})]})}function Bc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Vc(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:void 0}function Hc(e,t){let n=e[t];return Array.isArray(n)?n.filter(e=>typeof e==`string`):[]}function Uc(e){if(!Bc(e))return null;let t=Vc(e,`ruleId`),n=Vc(e,`ruleName`);if(t===void 0||n===void 0||typeof e.matched!=`boolean`)return null;let r=Vc(e,`failedCondition`);return{ruleId:t,ruleName:n,matched:e.matched,...r===void 0?{}:{failedCondition:r},cooldown:Vc(e,`cooldown`)??`n/a`,enqueued:typeof e.enqueued==`number`?e.enqueued:0,targetIds:Hc(e,`targetIds`)}}function Wc(e){if(!Bc(e))return null;let t=Vc(e,`conditionId`),n=Vc(e,`note`);return t===void 0||n===void 0?null:{conditionId:t,note:n}}function Gc(e){if(!Bc(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(!Bc(t))continue;let e=Vc(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(!Bc(t))continue;let e=Vc(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 Kc(e){if(!Bc(e))return null;let t=Vc(e,`recordId`),n=Vc(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=Uc(t);e!==null&&r.push(e)}let i=[];for(let t of Array.isArray(e.planNotes)?e.planNotes:[]){let e=Wc(t);e!==null&&i.push(e)}let a=Vc(e,`droppedBy`),o=Gc(e.stateSummary);return{recordId:t,delivery:n,trigger:Vc(e,`trigger`)??n,candidates:typeof e.candidates==`number`?e.candidates:0,outcomes:r,still:Vc(e,`still`)??`none`,notes:Hc(e,`notes`),...a===void 0?{}:{droppedBy:a},planNotes:i,...o===void 0?{}:{stateSummary:o}}}function qc(e){if(e.stateSummary!==void 0)return Jc(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 Jc(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 Yc({ruleId:e,ruleName:t,fallbackDeviceId:r,variant:i=`icon`,showResult:o=!1}){let{t:s}=Z(),d=E(),[f,p]=c(null),[m,g]=c(null),_=l({mutationFn:async()=>Kc(await d.trpcClient.addons.custom.mutate({addonId:lc,action:dc,input:{ruleId:e,...r===void 0?{}:{deviceId:r}}})),onMutate:()=>{p(null),g(null)},onSuccess:e=>p(e),onError:e=>g(e instanceof Error?e.message:`The test could not be run.`)}),v=f===null?m===null?void 0:m:qc(f);return n(a,{children:[n(W,{size:`sm`,variant:i===`icon`?`ghost`:`outline`,type:`button`,disabled:_.isPending,onClick:()=>_.mutate(),title:v??s(`system.notificationRuleTestButton.testNowFiresThisRule`,`Test now — fires this rule and really sends the notification`),"aria-label":s(`system.notificationRuleTestButton.testNow`,`test {{ruleName}} now`,{ruleName:t}),"data-testid":`nc-rule-test-now`,children:[_.isPending?u(b,{className:`h-3.5 w-3.5 animate-spin`}):u(L,{className:`h-3.5 w-3.5`}),i===`full`&&s(`system.notificationRuleTestButton.testNow2`,`Test now`)]}),o&&m!==null&&u(`div`,{className:`mt-2 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-[11px] text-danger`,children:m}),o&&f!==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:qc(f)}),f.planNotes.map(e=>n(`p`,{className:`flex gap-1.5`,children:[u(h,{className:`mt-0.5 h-3 w-3 shrink-0 text-warning`}),u(`span`,{children:e.note})]},e.conditionId)),f.notes.map(e=>n(`p`,{children:[`· `,e]},e))]})]})}t();var Xc=[`notificationRules`,`listSnoozes`],Zc=3e4;function Qc(e,t){return Math.max(0,Math.ceil((e.expiresAt-t)/6e4))}function $c(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 el({rules:e}){let{t}=Z(),a=E(),s=o(),c=i({queryKey:Xc,refetchInterval:Zc,queryFn:async()=>(await a.trpcClient.notificationRules.listSnoozes.query({})).snoozes}),d=l({mutationFn:e=>a.trpcClient.notificationRules.cancelSnooze.mutate({snoozeId:e}),onSuccess:()=>s.invalidateQueries({queryKey:Xc})}),f=r(()=>{let t=new Map;for(let n of e)t.set(n.id,n.name);return t},[e]),p=Date.now(),m=(c.data??[]).filter(e=>p>=e.startedAt&&p<e.expiresAt);return n(qe,{className:`p-4`,children:[n(`div`,{className:`flex items-center gap-2 mb-3`,children:[u(j,{className:`h-4 w-4 text-foreground-subtle`}),u(`h3`,{className:`text-sm font-medium text-foreground`,children:t(`system.notificationSnoozes.silencedRightNow`,`Silenced right now`)})]}),m.length===0&&u(`p`,{className:`text-[11px] text-foreground-subtle`,children:t(`system.notificationSnoozes.nothingIsSilencedASnooze`,`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:m.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??`?`}`:f.get(e.ruleId??``)??`A rule`}),e.global&&u(J,{variant:`warning`,className:`text-[10px]`,children:`everyone`}),e.classes!==void 0&&e.classes.length>0&&u(J,{variant:`info`,className:`text-[10px]`,children:e.classes.join(`, `)}),!e.summary&&u(J,{variant:`default`,className:`text-[10px]`,children:t(`system.notificationSnoozes.noSummary`,`no summary`)})]}),n(`span`,{className:`text-[10px] text-foreground-subtle`,children:[`set by `,e.userId,` · `,$c(Qc(e,p))]})]}),u(W,{size:`sm`,variant:`outline`,disabled:d.isPending,onClick:()=>d.mutate(e.id),children:t(`system.notificationSnoozes.endNow`,`End now`)})]},e.id))})]})}var tl=`block text-[11px] font-medium text-foreground mb-1`,nl=`mt-1 text-[10px] text-foreground-subtle`;function rl({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 il({problems:e,testId:t=`digest-problems`}){let{t:r}=Z();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(h,{className:`h-3.5 w-3.5`}),r(`system.notificationDigestFields.thisRuleCouldNeverProduce`,`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 al({warnings:e,testId:t=`digest-warnings`}){let{t:r}=Z();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(O,{className:`h-3.5 w-3.5`}),r(`system.notificationDigestFields.worthKnowing`,`Worth knowing:`)]}),u(`ul`,{className:`list-disc space-y-0.5 pl-4`,children:e.map(e=>u(`li`,{children:e},e))})]})}function ol({cameras:e,value:t,onChange:r,fleet:i,hint:a}){return n(`div`,{className:`space-y-1`,children:[u(tt,{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 sl(e){let{t}=Z();return u(rt,{...e,testIdPrefix:e.testIdPrefix??`digest-target`,emptyMessage:e.emptyMessage??t(`system.notificationDigestFields.noDeliveryTargetIsConfigured`,`No delivery target is configured. Add one on the Targets tab first — without one the artefact is rendered and thrown away.`)})}function cl({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:tl,children:e}),u(q,{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 ll({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(ct,{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 ul({title:e,body:t,onTitleChange:r,onBodyChange:i,family:a,testIdPrefix:o}){let{t:s}=Z(),c=lo(),l=e=>c.data?ao(c.data,{family:a,field:e}):void 0;return n(`div`,{className:`space-y-2`,children:[u(ho,{label:s(`system.notificationDigestFields.notificationTitle`,`Notification title`),value:e,onChange:r,vars:l(`title`),testId:`${o}-title`}),u(ho,{label:s(`system.notificationDigestFields.notificationBody`,`Notification body`),value:t,onChange:i,vars:l(`body`),multiline:!0,testId:`${o}-body`}),u(`p`,{className:`text-[10px] text-foreground-subtle`,children:s(`system.notificationDigestFields.leaveBothBlankToUse`,`Leave both blank to use the hub's own wording (editable on the Texts tab).`)}),u(go,{context:{family:a,field:`body`},title:e,body:t,testId:`${o}-preview`})]})}function dl({open:e,ruleName:t,windowDescription:r,targetDescription:i,pending:a,onConfirm:o,onCancel:s,extra:c,confirmDisabled:l=!1}){let{t:d}=Z();return e?u(Xe,{open:!0,onOpenChange:e=>!e&&s(),children:u(He,{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(L,{className:`h-4 w-4 text-warning`}),d(`system.notificationDigestFields.sendARealNotificationNow`,`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:d(`system.notificationDigestFields.itDoesNotConsumeThe`,`It does not consume the schedule: the next scheduled run still happens.`)}),c,n(`div`,{className:`flex justify-end gap-2`,children:[u(W,{size:`sm`,variant:`secondary`,type:`button`,onClick:s,children:d(`common.cancel`,`Cancel`)}),u(W,{size:`sm`,type:`button`,disabled:a||l,onClick:o,"data-testid":`digest-test-confirm-send`,children:a?d(`system.notificationDigestFields.sending`,`Sending…`):d(`system.notificationDigestFields.produceAndSend`,`Produce and send`)})]})]})})}):null}function fl(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 pl=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function ml(e){let t=Math.floor(e/60),n=e%60;return`${String(t).padStart(2,`0`)}:${String(n).padStart(2,`0`)}`}function hl(e){let t=e.windows[0];if(t===void 0)return`No window`;let n=t.days.toSorted((e,t)=>e-t).map(e=>pl[e]??String(e)).join(` `),r=t.startMinute>t.endMinute?` (overnight)`:``,i=e.windows.length-1,a=e.invert===!0?` · outside`:``;return`${n} ${ml(t.startMinute)}–${ml(t.endMinute)}${r}${i>0?` +${i}`:``}${a}`}function gl(e,t,n){if(e===void 0||e<=0)return n;let r=Math.max(0,t-e);return`${fl(Math.round(r/1e3))} ago`}function _l(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function vl(e){return Array.isArray(e)?`[${e.map(vl).join(`,`)}]`:_l(e)?`{${Object.keys(e).toSorted().map(t=>`${JSON.stringify(t)}:${vl(e[t])}`).join(`,`)}}`:JSON.stringify(e)??`null`}function yl(e,t){return vl(e)===vl(t)}function bl(e){return e.map(e=>({targetId:e}))}var xl=`pipeline-analytics`,Sl=`nc.getTexts`,Cl=`nc.setLanguage`,wl=`nc.setTextOverrides`,Tl={en:`English`,it:`Italiano`};function El(e){return e===`en`||e===`it`}function Dl(e){return e===`override`||e===`shipped`||e===`fallback`}function Ol(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function kl(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 Al(e){if(!Ol(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`||!El(r)||!Dl(o)||i!==null&&typeof i!=`string`)return null;let s=kl(e.placeholders),c=kl(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 jl(e){if(!Ol(e))return null;let{language:t,activeLanguage:n}=e;if(!El(t)||!El(n))return null;let r=kl(e.languages);if(r===null||r.length===0)return null;let i=[];for(let e of r)El(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=Al(e);if(t===null)return null;o.push(t)}return{language:t,activeLanguage:n,languages:i,entries:o}}function Ml(e,t){return t.get(e.key)??e.override??e.shipped}function Nl(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 Pl(e,t){return Object.keys(Nl(e,t)).length}function Fl(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 Il(e){return e.placeholders.map(e=>({name:e,label:e,example:`{{${e}}}`,group:`rule`,families:[`rule`]}))}function Ll(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 Rl=[`notificationCalendarEvents`,`list`],zl=`nc.listCalendarEventsRules`,Bl=`nc.upsertCalendarEventsRule`,Vl=`nc.deleteCalendarEventsRule`,Hl=Le({timezone:Ie().min(1),windows:ze(Le({days:ze(Pe().int().min(0).max(6)).min(1),startMinute:Pe().int().min(0).max(1439),endMinute:Pe().int().min(0).max(1439)})).min(1),invert:Be().optional()}),Ul=Le({targetId:Ie().min(1),params:Re(Ie(),Fe()).optional()}),Wl=Le({rules:ze(Le({id:Ie().min(1),name:Ie().min(1),enabled:Be(),schedule:Hl,calendars:ze(Ie().min(1)).max(64).optional(),calendarsExclude:ze(Ie().min(1)).max(64).optional(),horizonDays:Pe().int(),deliverEmpty:Be(),targets:ze(Ul).min(1),template:Le({title:Ie().optional(),body:Ie().optional()}).optional(),priority:Pe().int(),generatedAt:Pe().optional(),readOnly:Be().optional()}))});function Gl(e){let t=Wl.safeParse(e);return t.success?t.data.rules:null}function Kl(e){return e.readOnly!==!0}var ql=[{key:`basics`,label:`Basics`},{key:`schedule`,label:`Schedule`},{key:`calendars`,label:`Calendars`},{key:`targets`,label:`Targets`},{key:`template`,label:`Template`}],Jl=`basics`;function Yl(){return le([{days:[0,1,2,3,4,5,6],minute:420}],Intl.DateTimeFormat().resolvedOptions().timeZone||`UTC`)}function Xl(e){let t=re(e);if(t===null||t.length===0)return hl(e);let n=t[0];return n===void 0?hl(e):`At ${String(Math.floor(n.minute/60)).padStart(2,`0`)}:${String(n.minute%60).padStart(2,`0`)}${t.length>1?` +${t.length-1}`:``}`}function Zl(){return{name:`Morning calendar`,enabled:!0,horizonDays:7,deliverEmpty:!1,priority:3,schedule:Yl(),calendars:[],calendarsExclude:[],targetIds:[],templateTitle:``,templateBody:``}}function Ql(e){return{name:e.name,enabled:e.enabled,horizonDays:e.horizonDays,deliverEmpty:e.deliverEmpty,priority:e.priority,schedule:e.schedule,calendars:e.calendars??[],calendarsExclude:e.calendarsExclude??[],targetIds:e.targets.map(e=>e.targetId),templateTitle:e.template?.title??``,templateBody:e.template?.body??``}}function $l(e){return e.name.trim().length>0&&e.targetIds.length>0&&e.horizonDays>=1&&e.horizonDays<=30&&e.schedule.windows.length>0}function eu(e){let t=e.targetIds.map(e=>({targetId:e}));return{name:e.name.trim(),enabled:e.enabled,horizonDays:e.horizonDays,deliverEmpty:e.deliverEmpty,priority:e.priority,schedule:e.schedule,...e.calendars.length>0?{calendars:[...e.calendars]}:{},...e.calendarsExclude.length>0&&e.calendars.length===0?{calendarsExclude:[...e.calendarsExclude]}:{},targets:t,...e.templateTitle.trim().length>0||e.templateBody.trim().length>0?{template:{...e.templateTitle.trim().length>0?{title:e.templateTitle.trim()}:{},...e.templateBody.trim().length>0?{body:e.templateBody.trim()}:{}}}:{}}}function tu(e,t){let n=eu(e);return{...n,calendars:e.calendars.length===0&&(t.calendars?.length??0)>0?null:n.calendars,calendarsExclude:e.calendarsExclude.length===0&&(t.calendarsExclude?.length??0)>0?null:n.calendarsExclude,template:e.templateTitle.trim().length===0&&e.templateBody.trim().length===0&&t.template!==void 0?null:n.template}}function nu(e){return`next ${String(e)} day(s)`}function ru(e){return e.calendars!==void 0&&e.calendars.length>0?`${String(e.calendars.length)} calendar${e.calendars.length===1?``:`s`}`:e.calendarsExclude!==void 0&&e.calendarsExclude.length>0?`all except ${String(e.calendarsExclude.length)}`:`all calendars`}t();function iu({rule:e,targets:t,onSaved:r,onCancel:i}){let{t:a}=Z(),o=E(),s=Ye(),[d,f]=c(()=>e===null?Zl():Ql(e)),[p,m]=c(()=>Sr(e===null?void 0:e.calendars,e===null?void 0:e.calendarsExclude)),[h,g]=c(Jl),[_,v]=c(null),y=e=>f(t=>({...t,...e})),x=l({mutationFn:async()=>{let t=Vn(p),n={...d,calendars:t.include??[],calendarsExclude:t.exclude??[]};if(!$l(n))throw Error(`Name, at least one target, and a schedule are required`);let r=e===null?{rule:eu(n)}:{ruleId:e.id,patch:tu(n,e)};await o.trpcClient.addons.custom.mutate({addonId:xl,action:Bl,input:r})},onSuccess:()=>r(),onError:e=>{v(e instanceof Error?e.message:String(e))}}),S=(s.data??[]).map(e=>({id:e.id,name:e.name}));return u(Xe,{open:!0,onOpenChange:e=>!e&&i(),children:n(He,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,"data-testid":`calendar-events-editor`,children:[n(`div`,{className:`mb-3 flex shrink-0 items-center justify-between gap-2 pr-10`,children:[n(`div`,{className:`flex min-w-0 items-center gap-2`,children:[u(M,{className:`h-4 w-4 shrink-0 text-foreground-subtle`}),u(`h3`,{className:`truncate text-sm font-semibold text-foreground`,children:e===null?a(`system.notificationCalendarEventsEditor.newCalendarEvents`,`New calendar events`):d.name})]}),u(W,{size:`sm`,type:`button`,disabled:x.isPending,onClick:()=>{v(null),x.mutateAsync()},"data-testid":`calendar-events-save`,children:x.isPending?u(b,{className:`h-3.5 w-3.5 animate-spin`}):a(`common.save`,`Save`)})]}),n(nt,{value:h,onValueChange:e=>{let t=ql.find(t=>t.key===e);t!==void 0&&g(t.key)},children:[u(mt,{className:`mb-3`,children:ql.map(e=>u(yt,{value:e.key,children:e.label},e.key))}),n(Ue,{className:`space-y-4 pr-1`,children:[_===null?null:u(`p`,{className:`text-sm text-destructive`,children:_}),u(Y,{value:`basics`,className:`space-y-3`,children:n(rl,{title:a(`system.notificationCalendarEventsEditor.basics`,`Basics`),children:[n(`label`,{className:`block text-sm`,children:[a(`system.notificationCalendarEventsEditor.name`,`Name`),u(q,{className:`mt-1`,value:d.name,onChange:e=>y({name:e.target.value}),"data-testid":`calendar-events-name`})]}),u(cl,{label:a(`system.notificationCalendarEventsEditor.horizonDays`,`Horizon (days)`),value:d.horizonDays,min:1,max:30,onChange:e=>{e!==void 0&&y({horizonDays:e})}}),u(cl,{label:a(`system.notificationCalendarEventsEditor.priority`,`Priority`),value:d.priority,min:1,max:5,onChange:e=>{e!==void 0&&y({priority:e})}}),u(ll,{label:a(`system.notificationCalendarEventsEditor.enabled`,`Enabled`),checked:d.enabled,onChange:e=>y({enabled:e})}),u(ll,{label:a(`system.notificationCalendarEventsEditor.deliverWhenEmpty`,`Deliver when empty`),checked:d.deliverEmpty,onChange:e=>y({deliverEmpty:e})})]})}),u(Y,{value:`schedule`,className:`space-y-3`,children:n(rl,{title:a(`system.notificationCalendarEventsEditor.schedule`,`Schedule`),children:[u(Er,{mode:`times`,value:d.schedule,onChange:e=>y({schedule:e})}),u(`p`,{className:`text-[11px] text-foreground-subtle`,children:a(`system.notificationCalendarEventsEditor.oneSendTimePerRow`,`One send time per row. The digest fires at that minute.`)})]})}),u(Y,{value:`calendars`,className:`space-y-3`,children:u(rl,{title:a(`system.notificationCalendarEventsEditor.calendars`,`Calendars`),children:u(Go,{draft:p,onChange:m,exceptOffered:!0,plural:`calendars`,describe:e=>S.find(t=>t.id===e)?.name??e,testId:`calendar-events-scope`,renderPicker:(e,t,n)=>u(tt,{devices:S,listState:s.isPending?`pending`:`answered`,value:e,onChange:t,emptyMeansAll:!0,noun:`calendar`,testId:`calendar-picker`},n)})})}),u(Y,{value:`targets`,className:`space-y-3`,children:u(rl,{title:a(`system.notificationCalendarEventsEditor.targets`,`Targets`),children:u(sl,{targets:t,value:d.targetIds,onChange:e=>y({targetIds:e})})})}),u(Y,{value:`template`,className:`space-y-3`,children:n(rl,{title:a(`system.notificationCalendarEventsEditor.template`,`Template`),children:[n(`p`,{className:`text-[11px] text-foreground-subtle`,children:[a(`system.notificationCalendarEventsEditor.optionalLeaveBlankForThe`,`Optional. Leave blank for the default digest body (tomorrow highlighted, then later days). Variables:`),` `,`{{rule}}`,`, `,`{{count}}`,`, `,`{{horizonDays}}`,`, `,`{{events}}`,`.`]}),n(`label`,{className:`block text-sm`,children:[a(`system.notificationCalendarEventsEditor.title`,`Title`),u(q,{className:`mt-1`,value:d.templateTitle,onChange:e=>y({templateTitle:e.target.value})})]}),n(`label`,{className:`block text-sm`,children:[a(`system.notificationCalendarEventsEditor.body`,`Body`),u(`textarea`,{className:`mt-1 min-h-[8rem] w-full rounded border border-border bg-background px-2 py-1 text-xs`,value:d.templateBody,onChange:e=>y({templateBody:e.target.value})})]})]})})]})]})]})})}var au=`nc.listSummaryRules`,ou=`nc.upsertSummaryRule`,su=`nc.deleteSummaryRule`,cu=`nc.testSummaryRule`,lu=3600,uu=86400,du=3600,fu=3600,pu=3*36e5,mu=[`importance`,`recency`,`dwell`],hu={importance:`Most important`,recency:`Most recent`,dwell:`Longest stay`},gu=[`none`,`tiles`,`all`],_u=`none`,vu={none:`Images only — no text anywhere`,tiles:`A label under each tile`,all:`Tile labels and a caption across the top`},yu=[`en`,`it`],bu=[`deliver-without-text`,`skip`],xu=2048,Su=2e3;function Cu(e){return e.window.kind!==`unsupported`&&!e.readOnly}function wu(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Tu(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 Eu(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 Du(e){if(e!==void 0)return typeof e==`string`?e:null}function Ou(e){if(e!==void 0)return typeof e==`number`&&Number.isFinite(e)?e:null}function ku(e){return mu.some(t=>t===e)}function Au(e){return e===void 0?_u:gu.find(t=>t===e)??null}function ju(e){if(!wu(e)||!Array.isArray(e.windows)||e.windows.length===0)return null;let t=[];for(let n of e.windows){if(!wu(n))return null;let e=Tu(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=Du(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 Mu(e){if(!wu(e)||typeof e.kind!=`string`)return null;if(e.kind===`schedule`){let t=ju(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 Nu(e){if(e==null)return;if(!wu(e))return null;let t=e.classes===void 0?void 0:Eu(e.classes),n=e.classesExclude===void 0?void 0:Eu(e.classesExclude),r=e.zones===void 0?void 0:Eu(e.zones);if(t===null||n===null||r===null)return null;let i=Ou(e.minImportance),a=Ou(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 Pu(e){if(e==null)return;if(!wu(e))return null;let t=Du(e.title),n=Du(e.body);return t===null||n===null?null:{...t===void 0?{}:{title:t},...n===void 0?{}:{body:n}}}function Fu(e){return yu.some(t=>t===e)}function Iu(e){return bu.some(t=>t===e)}function Lu(e){if(e==null)return;if(!wu(e)||typeof e.enabled!=`boolean`)return null;let t=Du(e.profileId),n=Du(e.prompt);if(t===null||n===null)return null;let r=Ou(e.maxImagePx),i=Ou(e.timeoutMs);if(r===null||i===null)return null;let a=e.language;if(a!==void 0&&!Fu(a))return null;let o=e.onFailure;return o!==void 0&&!Iu(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(!wu(n)||typeof n.targetId!=`string`)return null;let e=n.params;if(e!==void 0&&!wu(e))return null;t.push({targetId:n.targetId,...e===void 0?{}:{params:e}})}return t}function zu(e){if(!wu(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`||!ku(o)||typeof s!=`number`||typeof c!=`boolean`||typeof e.priority!=`number`)return null;let l=Tu(e.deviceIds),u=Mu(e.window),d=Ru(e.targets);if(l===null||u===null||d===null)return null;let f=Nu(e.filters),p=Pu(e.template);if(f===null||p===null)return null;let m=Du(e.captionText),h=Ou(e.generatedAt),g=Ou(e.updatedAt);if(m===null||h===null||g===null)return null;let _=Au(e.captions);if(_===null)return null;let v=Lu(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 Bu(e){if(!wu(e)||!Array.isArray(e.rules))return null;let t=[];for(let n of e.rules){let e=zu(n);if(e===null)return null;t.push(e)}return t}function Vu(e){if(!wu(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=Ou(e[r]);if(t===null)return null;t!==void 0&&(n[r]=t)}for(let t of[`windowStartMs`,`windowEndMs`]){let r=Ou(e[t]);if(r===null)return null;r!==void 0&&(n[t]=r)}for(let t of[`mosaicUrl`,`error`,`aiText`,`aiFailure`]){let r=Du(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 Hu(){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:_u,captionText:``,deliverEmpty:!1,priority:3,aiEnabled:!1,aiProfileId:``,aiPrompt:``,aiLanguage:``,aiMaxImagePx:void 0,aiTimeoutSeconds:void 0,aiOnFailure:`deliver-without-text`}}function Uu(e){let t=Hu(),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 Wu(e){return e.windowKind===`schedule`&&e.schedule!==void 0?{kind:`schedule`,schedule:e.schedule}:{kind:`motion`,quietSeconds:e.quietSeconds,maxWindowSeconds:e.maxWindowSeconds}}function Gu(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 Ku(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 qu(e){return bl(e.targetIds)}function Ju(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 Yu(e){let t=Gu(e),n=Ku(e),r=Ju(e),i=e.captionText.trim();return{name:e.name.trim(),enabled:e.enabled,deviceIds:[...e.deviceIds],window:Wu(e),...t===void 0?{}:{filters:t},maxTiles:e.maxTiles,maxAiImages:e.maxAiImages,rank:e.rank,barrierSeconds:e.barrierSeconds,targets:qu(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 Xu(e,t){let n=Yu(e),r={};return n.name!==t.name&&(r.name=n.name),n.enabled!==t.enabled&&(r.enabled=n.enabled),yl(n.deviceIds,t.deviceIds)||(r.deviceIds=n.deviceIds),yl(n.window,t.window)||(r.window=n.window),yl(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),yl(n.targets,t.targets)||(r.targets=n.targets),yl(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),yl(n.ai,t.ai)||(r.ai=n.ai??null),r}function Zu(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 ${lu}s.`),(e.maxWindowSeconds<60||e.maxWindowSeconds>86400)&&t.push(`The longest window must be between 60s and ${uu}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 ${du}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 ${fu}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 ${Su} 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 ${xu} 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 Qu(e){return Zu(e).length===0}function $u(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 ed=[{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`]}],td=`rule`;function nd(e){return ed.find(t=>t.key===e)?.key}function rd(e){return e.kind===`motion`?`Motion · ${fl(e.quietSeconds)} quiet · max ${fl(e.maxWindowSeconds)}`:e.kind===`unsupported`?`Unsupported window (${e.raw}) — authored on a newer hub`:`Schedule · ${hl(e.schedule)}`}function id(e,t){return gl(e,t,`Never run`)}function ad(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 ≥ ${fl(e.minDwellSeconds)}`),e.includeStationary===!0&&t.push(`incl. parked`),t.length===0?`All passages`:t.join(` · `)}function od(e){return{windowStartMs:e-pu,windowEndMs:e}}t();var sd={"deliver-without-text":`Deliver the digest anyway, without the text`,skip:`Hold the whole digest — deliver nothing`},cd={en:`English`,it:`Italiano`};function ld(e){return mu.find(t=>t===e)}function ud(e){return gu.find(t=>t===e)}function dd(e){return yu.find(t=>t===e)??``}function fd(e){return bu.find(t=>t===e)}function pd({rule:e,cameras:t,fleet:a,targets:o,taxonomy:s,onSaved:d,onCancel:f}){let{t:p}=Z(),m=E(),[h,g]=c(()=>e===null?Hu():Uu(e)),[_,v]=c(null),[y,x]=c(e!==null),[S,C]=c(td),w=e=>g(t=>({...t,...e})),T=r(()=>{let e=ve(`occupancy`,s);return e===null?[]:e.groups.flatMap(e=>e.options)},[s]),{options:D,loading:O}=Dr(h.deviceIds,t.map(e=>({id:e.id,name:e.name}))),k=i({queryKey:[`llm`,`listProfiles`,`summary-editor`],queryFn:()=>m.trpcClient.llm.listProfiles.query({}),retry:!1}),A=(k.data??[]).filter(e=>e.supportsVision),j=l({mutationFn:async()=>{let t=e===null?{rule:Yu(h)}:{ruleId:e.id,patch:Xu(h,e)};await m.trpcClient.addons.custom.mutate({addonId:xl,action:ou,input:t})},onSuccess:d,onError:e=>v(e instanceof Error?e.message:`Save failed`)}),M=lo(),N=M.data?ao(M.data,{family:`summary`,field:`captionText`}):void 0,P=h.mosaicCaptions===`all`,I=Zu(h),L=$u(h),ee=ed.some(e=>e.key===S)?S:td;return u(Xe,{open:!0,onOpenChange:e=>!e&&f(),children:n(He,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,children:[u(`div`,{className:`mb-3 flex shrink-0 items-center gap-2 pr-10`,children:n(`h3`,{className:`flex min-w-0 items-center gap-2 text-sm font-semibold text-foreground`,children:[u(F,{className:`h-4 w-4 shrink-0 text-foreground-subtle`}),u(`span`,{className:`truncate`,children:e===null?p(`system.notificationSummaryEditor.newSummary`,`New summary`):p(`system.notificationSummaryEditor.edit`,`Edit {{name}}`,{name:e.name})})]})}),_!==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(Ic,{kind:`summary`,ruleId:e.id,enabled:e.enabled,updatedAt:e.updatedAt??1/0}),y?u(il,{problems:I,testId:`summary-problems`}):null,u(al,{warnings:L,testId:`summary-warnings`})]}),n(nt,{value:ee,onValueChange:e=>C(nd(e)??S),className:`mt-3 flex min-h-0 flex-1 flex-col`,children:[u(mt,{className:`mb-3 shrink-0`,children:ed.map(e=>u(yt,{value:e.key,children:e.label},e.key))}),n(Ue,{className:`pr-1`,children:[n(Y,{value:`rule`,className:`space-y-3`,children:[u(rl,{title:p(`system.notificationSummaryEditor.whatItIs`,`What it is`),hint:p(`system.notificationSummaryEditor.oneWindowOnePictureThe`,`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:tl,children:p(`system.notificationSummaryEditor.name`,`Name`)}),u(q,{value:h.name,onChange:e=>w({name:e.target.value}),placeholder:p(`system.notificationSummaryEditor.eGOvernightSweep`,`e.g. Overnight sweep`),"data-testid":`summary-name`})]}),u(`div`,{className:`pb-1.5`,children:u(ll,{label:p(`system.notificationSummaryEditor.enabled`,`Enabled`),checked:h.enabled,onChange:e=>w({enabled:e}),testId:`summary-enabled`})})]})}),u(rl,{title:p(`system.notificationSummaryEditor.cameras`,`Cameras`),hint:p(`system.notificationSummaryEditor.everyCameraInTheDigest`,`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(ol,{cameras:t,value:h.deviceIds,fleet:a,onChange:e=>w({deviceIds:e}),hint:p(`system.notificationSummaryEditor.theFirstCameraSelectedOwns`,`The first camera selected owns the delivered notification.`)})})]}),u(Y,{value:`window`,className:`space-y-3`,children:n(rl,{title:p(`system.notificationSummaryEditor.whenTheWindowCloses`,`When the window closes`),children:[n(`div`,{children:[u(`label`,{className:tl,children:p(`system.notificationSummaryEditor.window`,`Window`)}),u(G,{value:h.windowKind,options:[{value:`motion`,label:p(`system.notificationSummaryEditor.motionOpenedAndClosedBy`,`Motion — opened and closed by activity`)},{value:`schedule`,label:p(`system.notificationSummaryEditor.scheduleFixedWeeklyWindows`,`Schedule — fixed weekly windows`)}],onChange:e=>w({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(cl,{label:p(`system.notificationSummaryEditor.quietPeriodSeconds`,`Quiet period (seconds)`),value:h.quietSeconds,min:30,max:lu,onChange:e=>w({quietSeconds:e??0}),hint:p(`system.notificationSummaryEditor.theWindowOpensOnThe`,`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(cl,{label:p(`system.notificationSummaryEditor.longestWindowSeconds`,`Longest window (seconds)`),value:h.maxWindowSeconds,min:60,max:uu,onChange:e=>w({maxWindowSeconds:e??0}),hint:p(`system.notificationSummaryEditor.aPermanentlyBusyDrivewayWould`,`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:tl,children:p(`system.notificationSummaryEditor.weeklyWindows`,`Weekly windows`)}),u(Er,{value:h.schedule,onChange:e=>w({schedule:e})}),u(`p`,{className:nl,children:p(`system.notificationSummaryEditor.theDigestIsProducedWhen`,`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(cl,{label:p(`system.notificationSummaryEditor.waitForOpenTracksSeconds`,`Wait for open tracks (seconds)`),value:h.barrierSeconds,min:0,max:du,onChange:e=>w({barrierSeconds:e??0}),hint:p(`system.notificationSummaryEditor.aTrackSBestShot`,`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(Y,{value:`content`,className:`space-y-3`,children:n(rl,{title:p(`system.notificationSummaryEditor.whatGoesIn`,`What goes in`),hint:p(`system.notificationSummaryEditor.evaluatedOnTracksOnePassage`,`Evaluated on tracks: one passage is one tile.`),children:[n(`div`,{children:[u(`label`,{className:tl,children:p(`system.notificationSummaryEditor.classes`,`Classes`)}),u(Et,{options:T,value:h.classes,onChange:e=>w({classes:e}),emptyHint:`No class vocabulary from this hub — leave empty to keep every class.`,placeholder:``,noFreeText:!0}),u(`p`,{className:nl,children:p(`system.notificationSummaryEditor.emptyEveryClassOnlyThe`,`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:tl,children:p(`system.notificationSummaryEditor.excludedClasses`,`Excluded classes`)}),u(Et,{options:T,value:h.classesExclude,onChange:e=>w({classesExclude:e}),emptyHint:`No class vocabulary from this hub.`,placeholder:``,noFreeText:!0})]}),n(`div`,{children:[u(`label`,{className:tl,children:p(`system.notificationSummaryEditor.zones`,`Zones`)}),u(Et,{options:D,value:h.zones,onChange:e=>w({zones:e}),loading:O,emptyHint:`Pick a camera first — the zones offered are its own.`,placeholder:``,noFreeText:!0}),u(`p`,{className:nl,children:p(`system.notificationSummaryEditor.zonesAreScopedPerCamera`,`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(cl,{label:p(`system.notificationSummaryEditor.minimumImportance`,`Minimum importance`),value:h.minImportance,min:0,max:1,step:.05,emptyPlaceholder:`any`,onChange:e=>w({minImportance:e}),hint:p(`system.notificationSummaryEditor.thePipelineSOwnScore`,`The pipeline's own score, 0–1. Empty keeps everything.`),testId:`summary-min-importance`}),u(cl,{label:p(`system.notificationSummaryEditor.minimumStaySeconds`,`Minimum stay (seconds)`),value:h.minDwellSeconds,min:0,max:fu,emptyPlaceholder:`any`,onChange:e=>w({minDwellSeconds:e}),hint:p(`system.notificationSummaryEditor.dropsThePassagesTooBrief`,`Drops the passages too brief to be worth a tile.`),testId:`summary-min-dwell`})]}),u(ll,{label:p(`system.notificationSummaryEditor.includeParkedObjects`,`Include parked objects`),checked:h.includeStationary,onChange:e=>w({includeStationary:e}),hint:p(`system.notificationSummaryEditor.offByDefaultACar`,`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(Y,{value:`mosaic`,className:`space-y-3`,children:n(rl,{title:p(`system.notificationSummaryEditor.theMosaic`,`The mosaic`),children:[n(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[u(cl,{label:p(`system.notificationSummaryEditor.tiles`,`Tiles`),value:h.maxTiles,min:1,max:24,onChange:e=>w({maxTiles:e??1}),hint:p(`system.notificationSummaryEditor.9A33Grid`,`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:tl,children:p(`system.notificationSummaryEditor.whenThereAreMoreTracks`,`When there are more tracks than tiles`)}),u(G,{value:h.rank,options:mu.map(e=>({value:e,label:hu[e]})),onChange:e=>{let t=ld(e.target.value);t!==void 0&&w({rank:t})},"data-testid":`summary-rank`}),u(`p`,{className:nl,children:p(`system.notificationSummaryEditor.everyContributingCameraKeepsIts`,`Every contributing camera keeps its single best tile first; the remaining slots go to this ranking.`)})]})]}),n(`div`,{children:[u(`label`,{className:tl,children:p(`system.notificationSummaryEditor.textOnTheMosaic`,`Text on the mosaic`)}),u(G,{value:h.mosaicCaptions,options:gu.map(e=>({value:e,label:vu[e]})),onChange:e=>{let t=ud(e.target.value);t!==void 0&&w({mosaicCaptions:t})},"data-testid":`summary-captions`}),u(`p`,{className:nl,children:p(`system.notificationSummaryEditor.imagesOnlyIsTheDefault`,`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(ho,{label:p(`system.notificationSummaryEditor.captionBurnedOntoTheMosaic`,`Caption burned onto the mosaic`),value:h.captionText,disabled:!P,onChange:e=>w({captionText:e}),placeholder:p(`system.notificationSummaryEditor.leaveEmptyForNoCaption`,`Leave empty for no caption`),vars:N,testId:`summary-caption`}),u(`p`,{className:nl,children:P?p(`system.notificationSummaryEditor.acrossTheTopBand`,`Across the top band.`):p(`system.notificationSummaryEditor.onlyDrawnWithTileLabels`,`Only drawn with “tile labels and a caption across the top”. What you type here is kept either way.`)})]})]})}),u(Y,{value:`ai`,className:`space-y-3`,children:n(rl,{title:p(`system.notificationSummaryEditor.writtenSummary`,`Written summary`),hint:p(`system.notificationSummaryEditor.oneVisionCallOverThe`,`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(ll,{label:p(`system.notificationSummaryEditor.haveAModelDescribeThe`,`Have a model describe the window`),checked:h.aiEnabled,onChange:e=>w({aiEnabled:e}),hint:p(`system.notificationSummaryEditor.offByDefaultTheMosaic`,`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:p(`system.notificationSummaryEditor.theSwitchAboveIsOff`,`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:tl,children:p(`system.notificationSummaryEditor.visionProfile`,`Vision profile`)}),u(G,{value:h.aiProfileId,disabled:!h.aiEnabled,options:[{value:``,label:p(`system.notificationSummaryEditor.theHubSDefaultVision`,`The hub's default vision profile`)},...A.map(e=>({value:e.id,label:`${e.name} · ${e.model}${e.enabled?``:` · disabled`}`}))],onChange:e=>w({aiProfileId:e.target.value}),"data-testid":`summary-ai-profile`}),u(`p`,{className:nl,children:k.isError?p(`system.notificationSummaryEditor.thisHubDidNotAnswer`,`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?p(`system.notificationSummaryEditor.noVisionCapableProfileOn`,`No vision-capable profile on this hub yet. Add one under AI → Profiles; until then the digest delivers without text.`):p(`system.notificationSummaryEditor.onlyVisionCapableProfilesAre`,`Only vision-capable profiles are offered — a vision call against a text profile is refused, never degraded.`)})]}),n(`div`,{children:[u(`label`,{className:tl,children:p(`system.notificationSummaryEditor.answerIn`,`Answer in`)}),u(G,{value:h.aiLanguage,disabled:!h.aiEnabled,options:[{value:``,label:p(`system.notificationSummaryEditor.donTAskForA`,`Don’t ask for a language`)},...yu.map(e=>({value:e,label:cd[e]}))],onChange:e=>w({aiLanguage:dd(e.target.value)}),"data-testid":`summary-ai-language`}),u(`p`,{className:nl,children:p(`system.notificationSummaryEditor.nothingIsAddedToThe`,`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:tl,children:p(`system.notificationSummaryEditor.yourQuestionOptional`,`Your question (optional)`)}),u(`textarea`,{value:h.aiPrompt,rows:3,maxLength:Su,disabled:!h.aiEnabled,onChange:e=>w({aiPrompt:e.target.value}),"data-testid":`summary-ai-prompt`,placeholder:p(`system.notificationSummaryEditor.eGTellMeWhether`,`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:nl,children:p(`system.notificationSummaryEditor.leaveBlankForWhatHappened`,`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(cl,{label:p(`system.notificationSummaryEditor.framesTheModelMayLook`,`Frames the model may look at`),value:h.maxAiImages,min:1,max:8,disabled:!h.aiEnabled,onChange:e=>w({maxAiImages:e??1}),hint:p(`system.notificationSummaryEditor.theHighestRankedTilesSent`,`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(cl,{label:p(`system.notificationSummaryEditor.timeLimitSeconds`,`Time limit (seconds)`),value:h.aiTimeoutSeconds,min:10,max:600,emptyPlaceholder:`180`,disabled:!h.aiEnabled,onChange:e=>w({aiTimeoutSeconds:e}),hint:p(`system.notificationSummaryEditor.nobodyIsWaitingOnA`,`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(cl,{label:p(`system.notificationSummaryEditor.frameSizeSentPixels`,`Frame size sent (pixels)`),value:h.aiMaxImagePx,min:64,max:xu,emptyPlaceholder:`448`,disabled:!h.aiEnabled,onChange:e=>w({aiMaxImagePx:e}),hint:p(`system.notificationSummaryEditor.longestEdge448IsThe`,`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:tl,children:p(`system.notificationSummaryEditor.ifTheModelGivesNo`,`If the model gives no answer`)}),u(G,{value:h.aiOnFailure,disabled:!h.aiEnabled,options:bu.map(e=>({value:e,label:sd[e]})),onChange:e=>{let t=fd(e.target.value);t!==void 0&&w({aiOnFailure:t})},"data-testid":`summary-ai-on-failure`}),u(`p`,{className:nl,children:p(`system.notificationSummaryEditor.aColdModelAnUnreachable`,`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(Y,{value:`delivery`,className:`space-y-3`,children:n(rl,{title:p(`system.notificationSummaryEditor.delivery`,`Delivery`),children:[u(sl,{targets:o,value:h.targetIds,onChange:e=>w({targetIds:e})}),n(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[u(cl,{label:p(`system.notificationSummaryEditor.priority`,`Priority`),value:h.priority,min:1,max:5,onChange:e=>w({priority:e??3}),testId:`summary-priority`}),u(ll,{label:p(`system.notificationSummaryEditor.deliverAWindowThatMatched`,`Deliver a window that matched nothing`),checked:h.deliverEmpty,onChange:e=>w({deliverEmpty:e}),hint:p(`system.notificationSummaryEditor.offByDefaultANightly`,`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(ul,{title:h.templateTitle,body:h.templateBody,onTitleChange:e=>w({templateTitle:e}),onBodyChange:e=>w({templateBody:e}),family:`summary`,testIdPrefix:`summary-template`}),n(`p`,{className:nl,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(W,{size:`sm`,variant:`secondary`,type:`button`,onClick:f,children:p(`common.cancel`,`Cancel`)}),n(W,{size:`sm`,type:`button`,disabled:j.isPending,onClick:()=>{x(!0),!(!Qu(h)||j.isPending)&&j.mutate()},children:[j.isPending&&u(b,{className:`h-3.5 w-3.5 animate-spin`}),e===null?p(`system.notificationSummaryEditor.create`,`Create`):p(`common.save`,`Save`)]})]})]})})}var md=`nc.listTimelapseRules`,hd=`nc.upsertTimelapseRule`,gd=`nc.deleteTimelapseRule`,_d=`nc.testTimelapseRule`,vd=3600,yd=3600,bd=30,xd=1,Sd=[`image`,`gif`],Cd={image:`Still frame`,gif:`Short animation (GIF)`},wd=Le({rules:ze(B.extend({readOnly:Be().optional()}))});function Td(e){let t=wd.safeParse(e);return t.success?t.data.rules:null}function Ed(e){return e.readOnly!==!0}var Dd=Le({produced:Pe(),exportId:Ie().optional(),coveragePercent:Pe().optional(),enqueued:Pe().optional(),windowStartMs:Pe().optional(),windowEndMs:Pe().optional(),error:Ie().optional()});function Od(e){let t=Dd.safeParse(e);return t.success?t.data:null}function kd(){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 jd={windows:[{days:[1],startMinute:0,endMinute:60}]};function Md(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 Nd(e){let t=Md(e);return{name:e.name.trim(),enabled:e.enabled,deviceIds:[...e.deviceIds],schedule:e.schedule??jd,cadenceSec:e.cadenceSec,framerate:e.framerate,...e.denseCadenceSec===void 0?{}:{denseCadenceSec:e.denseCadenceSec},...e.minDwellSec===void 0?{}:{minDwellSec:e.minDwellSec},targets:bl(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 Pd(e,t){let n=Nd(e),r={};return n.name!==t.name&&(r.name=n.name),n.enabled!==t.enabled&&(r.enabled=n.enabled),yl(n.deviceIds,t.deviceIds)||(r.deviceIds=n.deviceIds),yl(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??Fd(n.cadenceSec)),n.minDwellSec!==t.minDwellSec&&n.minDwellSec!==void 0&&(r.minDwellSec=n.minDwellSec),yl(n.targets,t.targets)||(r.targets=n.targets),yl(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),yl(n.reportClasses,t.reportClasses)||(r.reportClasses=n.reportClasses??[]),n.priority!==t.priority&&(r.priority=n.priority),r}function Fd(e){return Math.max(xd,e/bd)}function Id(e,t,n){return t<=0||n<=0?0:e/t/n}function Ld(e,t){return e*t*V}function Rd(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 ${vd}.`),(!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 ${V}s and ${yd}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 zd(e){return Rd(e).length===0}function Bd(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=Ld(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 Vd(e){return hl(e)}function Hd(e,t){return gl(e,t,`Never run`)}function Ud(e){return e.denseCadenceSec===void 0?{seconds:Fd(e.cadenceSec),derived:!0}:{seconds:e.denseCadenceSec,derived:!1}}var Wd=[{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`]}],Gd=`rule`;function Kd(e){return Wd.find(t=>t.key===e)?.key}t();var qd=7;function Jd(e){return Sd.find(t=>t===e)}function Yd({rule:e,cameras:t,fleet:r,targets:i,onSaved:o,onCancel:s}){let{t:d}=Z(),f=E(),[p,h]=c(()=>e===null?kd():Ad(e)),[g,_]=c(null),[v,y]=c(e!==null),[x,S]=c(Gd),C=e=>h(t=>({...t,...e})),w=lo(),T=w.data?ao(w.data,{family:`timelapse`,field:`previewText`}):void 0,D=l({mutationFn:async()=>{let t=e===null?{rule:Nd(p)}:{ruleId:e.id,patch:Pd(p,e)};await f.trpcClient.addons.custom.mutate({addonId:xl,action:hd,input:t})},onSuccess:o,onError:e=>_(e instanceof Error?e.message:`Save failed`)}),O=Rd(p),k=Bd(p),A=Ud(p),j=Id(qd,A.seconds,p.framerate),M=Wd.some(e=>e.key===x)?x:Gd;return u(Xe,{open:!0,onOpenChange:e=>!e&&s(),children:n(He,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,children:[u(`div`,{className:`mb-3 flex shrink-0 items-center gap-2 pr-10`,children:n(`h3`,{className:`flex min-w-0 items-center gap-2 text-sm font-semibold text-foreground`,children:[u(m,{className:`h-4 w-4 shrink-0 text-foreground-subtle`}),u(`span`,{className:`truncate`,children:e===null?d(`system.notificationTimelapseEditor.newTimelapse`,`New timelapse`):d(`system.notificationTimelapseEditor.edit`,`Edit {{name}}`,{name:e.name})})]})}),g!==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:g}),n(`div`,{className:`shrink-0 space-y-2`,children:[e!==null&&u(Ic,{kind:`timelapse`,ruleId:e.id,enabled:e.enabled,updatedAt:e.updatedAt}),v?u(il,{problems:O,testId:`timelapse-problems`}):null,u(al,{warnings:k,testId:`timelapse-warnings`})]}),n(nt,{value:M,onValueChange:e=>S(Kd(e)??x),className:`mt-3 flex min-h-0 flex-1 flex-col`,children:[u(mt,{className:`mb-3 shrink-0`,children:Wd.map(e=>u(yt,{value:e.key,children:e.label},e.key))}),n(Ue,{className:`pr-1`,children:[n(Y,{value:`rule`,className:`space-y-3`,children:[u(rl,{title:d(`system.notificationTimelapseEditor.whatItIs`,`What it is`),hint:d(`system.notificationTimelapseEditor.oneVideoPerCameraAssembled`,`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:tl,children:d(`system.notificationTimelapseEditor.name`,`Name`)}),u(q,{value:p.name,onChange:e=>C({name:e.target.value}),placeholder:d(`system.notificationTimelapseEditor.eGNightDriveway`,`e.g. Night driveway`),"data-testid":`timelapse-name`})]}),u(`div`,{className:`pb-1.5`,children:u(ll,{label:d(`system.notificationTimelapseEditor.enabled`,`Enabled`),checked:p.enabled,onChange:e=>C({enabled:e}),testId:`timelapse-enabled`})})]})}),u(rl,{title:d(`system.notificationTimelapseEditor.cameras`,`Cameras`),children:u(ol,{cameras:t,value:p.deviceIds,fleet:r,onChange:e=>C({deviceIds:e}),hint:d(`system.notificationTimelapseEditor.eachCameraRendersAndDelivers`,`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(Y,{value:`window`,className:`space-y-3`,children:u(rl,{title:d(`system.notificationTimelapseEditor.when`,`When`),children:n(`div`,{children:[u(`label`,{className:tl,children:d(`system.notificationTimelapseEditor.weeklyWindows`,`Weekly windows`)}),u(Er,{value:p.schedule,onChange:e=>C({schedule:e})}),u(`p`,{className:nl,children:d(`system.notificationTimelapseEditor.theVideoCoversExactlyOne`,`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(Y,{value:`sampling`,className:`space-y-3`,children:n(rl,{title:d(`system.notificationTimelapseEditor.sampling`,`Sampling`),hint:d(`system.notificationTimelapseEditor.twoRatesABaseRate`,`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(cl,{label:d(`system.notificationTimelapseEditor.baseCadenceSeconds`,`Base cadence (seconds)`),value:p.cadenceSec,min:2,max:vd,onChange:e=>C({cadenceSec:e??0}),hint:d(`system.notificationTimelapseEditor.oneFrameEveryNSeconds`,`One frame every N seconds across the quiet parts of the window.`),testId:`timelapse-cadence`}),u(cl,{label:d(`system.notificationTimelapseEditor.outputFrameRateFps`,`Output frame rate (fps)`),value:p.framerate,min:1,max:60,onChange:e=>C({framerate:e??0}),hint:d(`system.notificationTimelapseEditor.howFastTheAssembledVideo`,`How fast the assembled video plays.`),testId:`timelapse-framerate`})]}),n(`div`,{children:[u(`label`,{className:tl,children:d(`system.notificationTimelapseEditor.denseCadenceNearTheDetections`,`Dense cadence, near the detections`)}),n(`div`,{className:`flex items-center gap-2`,children:[u(G,{value:p.denseCadenceSec===void 0?`auto`:`explicit`,options:[{value:`auto`,label:d(`system.notificationTimelapseEditor.automaticS`,`Automatic ({{seconds}}s)`,{seconds:A.seconds})},{value:`explicit`,label:d(`system.notificationTimelapseEditor.setItMyself`,`Set it myself`)}],onChange:e=>C({denseCadenceSec:e.target.value===`auto`?void 0:Ud(p).seconds}),"data-testid":`timelapse-dense-mode`}),p.denseCadenceSec!==void 0&&u(q,{type:`number`,className:`w-28`,min:.1,step:.1,value:String(p.denseCadenceSec),onChange:e=>{let t=Number(e.target.value);Number.isFinite(t)&&C({denseCadenceSec:t})},"data-testid":`timelapse-dense-seconds`})]}),n(`p`,{className:nl,"data-testid":`timelapse-dense-hint`,children:[`Lower = slower near the detections. At `,A.seconds,`s and `,p.framerate,` fps a `,qd,`-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.`,A.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 (${Ud({...p,denseCadenceSec:void 0}).seconds}s) explicitly.`]})]}),u(cl,{label:d(`system.notificationTimelapseEditor.minimumSecondsOfVideoPer`,`Minimum seconds of video per detection (optional)`),value:p.minDwellSec,min:0,max:60,step:.5,emptyPlaceholder:`no guarantee`,onChange:e=>C({minDwellSec:e}),hint:d(`system.notificationTimelapseEditor.stateTheStayAndLet`,`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(Y,{value:`delivery`,className:`space-y-3`,children:n(rl,{title:d(`system.notificationTimelapseEditor.theNotification`,`The notification`),children:[u(sl,{targets:i,value:p.targetIds,onChange:e=>C({targetIds:e})}),n(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[n(`div`,{children:[u(`label`,{className:tl,children:d(`system.notificationTimelapseEditor.preview`,`Preview`)}),u(G,{value:p.previewMode,options:Sd.map(e=>({value:e,label:Cd[e]})),onChange:e=>{let t=Jd(e.target.value);t!==void 0&&C({previewMode:t})},"data-testid":`timelapse-preview-mode`})]}),u(cl,{label:d(`system.notificationTimelapseEditor.priority`,`Priority`),value:p.priority,min:1,max:5,onChange:e=>C({priority:e??3}),testId:`timelapse-priority`})]}),n(`div`,{children:[u(ho,{label:d(`system.notificationTimelapseEditor.captionOnThePreviewFrame`,`Caption on the preview frame`),value:p.previewTextSet?p.previewText:``,placeholder:d(`system.notificationTimelapseEditor.shippedDefault`,`{{DEFAULT_TIMELAPSE_PREVIEW_TEXT}} (shipped default)`,{DEFAULT_TIMELAPSE_PREVIEW_TEXT:ue}),onChange:e=>C({previewText:e,previewTextSet:!0}),vars:T,testId:`timelapse-preview-text`}),n(`p`,{className:nl,children:[p.previewTextSet&&p.previewText.length===0?d(`system.notificationTimelapseEditor.emptyAndSetThePreview`,`Empty and set: the preview frame carries NO caption.`):d(`system.notificationTimelapseEditor.leaveUntouchedForTheShipped`,`Leave untouched for the shipped caption ({{DEFAULT_TIMELAPSE_PREVIEW_TEXT}}).`,{DEFAULT_TIMELAPSE_PREVIEW_TEXT:ue}),p.previewTextSet&&n(a,{children:[` `,u(`button`,{type:`button`,className:`underline`,onClick:()=>C({previewText:``,previewTextSet:!1}),"data-testid":`timelapse-preview-text-reset`,children:d(`system.notificationTimelapseEditor.backToTheShippedCaption`,`Back to the shipped caption`)})]})]})]}),u(ul,{title:p.templateTitle,body:p.templateBody,onTitleChange:e=>C({templateTitle:e}),onBodyChange:e=>C({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(W,{size:`sm`,variant:`secondary`,type:`button`,onClick:s,children:d(`common.cancel`,`Cancel`)}),n(W,{size:`sm`,type:`button`,disabled:D.isPending,onClick:()=>{y(!0),!(!zd(p)||D.isPending)&&D.mutate()},children:[D.isPending&&u(b,{className:`h-3.5 w-3.5 animate-spin`}),e===null?d(`system.notificationTimelapseEditor.create`,`Create`):d(`common.save`,`Save`)]})]})]})})}function Xd({children:e,className:t}){return u(`span`,{className:t,onClick:e=>e.stopPropagation(),children:e})}function Zd(){return u(`div`,{className:`flex items-center justify-center py-16`,children:u(b,{className:`h-6 w-6 animate-spin text-primary`})})}function Qd({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 $d({columns:e,rows:t,rowKey:n,minWidthPx:r,onRowClick:i}){return u(qe,{children:u(Ge,{columns:e,rows:t,rowKey:n,minWidthPx:r,bordered:!1,mobileMode:`scroll`,maxBodyHeight:Ze,...i===void 0?{}:{onRowClick:i}})})}function ef({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(Xd,{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(J,{variant:`warning`,children:`disabled`}),i]})}function tf({disabled:e=!1,pending:t=!1,title:n,message:r,confirmLabel:i=`Delete`,cancelLabel:a=`Cancel`,ariaLabel:o,testId:s,onConfirm:c}){let l=Qe(),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(p,{className:`h-3.5 w-3.5 text-danger`})})}t();var nf=[`notificationSummaries`,`listSummaryRules`];function rf(e){return[{key:`name`,header:X.t(`system.notificationSummaries.digest`,`Digest`),render:t=>u(ef,{name:t.name,enabled:t.enabled,...Cu(t)?{onOpen:()=>e.onOpen(t)}:{},openTestId:`summary-edit-${t.id}`,badges:n(a,{children:[!Cu(t)&&u(J,{variant:`warning`,children:`read-only`}),t.ai?.enabled===!0&&u(J,{variant:`info`,children:`AI`}),t.ai!==void 0&&!t.ai.enabled&&u(J,{variant:`default`,children:X.t(`system.notificationSummaries.aiOff`,`AI off`)})]})})},{key:`cameras`,header:X.t(`system.notificationSummaries.cameras`,`Cameras`),align:`center`,nowrap:!0,render:e=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.deviceIds.length})},{key:`window`,header:X.t(`system.notificationSummaries.window`,`Window`),render:e=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:rd(e.window)})},{key:`filters`,header:X.t(`system.notificationSummaries.keeps`,`Keeps`),render:e=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:ad(e.filters)})},{key:`mosaic`,header:X.t(`system.notificationSummaries.mosaic`,`Mosaic`),nowrap:!0,render:e=>n(`span`,{className:`text-[11px] text-foreground-subtle`,children:[e.maxTiles,` tiles · `,e.rank]})},{key:`targets`,header:X.t(`system.notificationSummaries.targets`,`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:X.t(`system.notificationSummaries.lastRun`,`Last run`),nowrap:!0,render:t=>u(`span`,{className:`text-[11px] text-foreground-subtle`,"data-testid":`summary-last-${t.id}`,children:id(t.generatedAt,e.nowMs)})},{key:`enabled`,header:X.t(`system.notificationSummaries.on`,`On`),align:`center`,nowrap:!0,render:t=>u(Xd,{children:u(ct,{checked:t.enabled,disabled:t.readOnly,onCheckedChange:n=>e.onToggle(t,n),"aria-label":X.t(`system.notificationSummaries.toggle`,`toggle {{name}}`,{name:t.name})})})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:t=>n(Xd,{className:`flex items-center justify-end gap-1`,children:[u(W,{size:`sm`,variant:`ghost`,type:`button`,disabled:t.readOnly,onClick:()=>e.onTest(t),title:X.t(`system.notificationSummaries.produceThisDigestNowAnd`,`Produce this digest now and DELIVER it`),"aria-label":X.t(`system.notificationSummaries.test`,`test {{name}}`,{name:t.name}),"data-testid":`summary-test-${t.id}`,children:u(w,{className:`h-3.5 w-3.5`})}),u(tf,{disabled:t.readOnly,pending:e.deletePending,title:X.t(`system.notificationSummaries.deleteThisSummary`,`Delete this summary?`),message:X.t(`system.notificationSummaries.thisWillPermanentlyDeleteThis`,`This will permanently delete "{{name}}". This action cannot be undone.`,{name:t.name}),ariaLabel:X.t(`system.notificationSummaries.delete`,`delete {{name}}`,{name:t.name}),testId:`summary-delete-${t.id}`,onConfirm:()=>e.onConfirmDelete(t)})]})}]}t();var af=[`notificationTimelapses`,`listTimelapseRules`];function of(e){return[{key:`name`,header:X.t(`system.notificationTimelapses.timelapse`,`Timelapse`),render:t=>u(ef,{name:t.name,enabled:t.enabled,...Ed(t)?{onOpen:()=>e.onOpen(t),openTestId:`timelapse-edit-${t.id}`}:{},badges:Ed(t)?null:u(J,{variant:`warning`,children:`read-only`})})},{key:`cameras`,header:X.t(`system.notificationTimelapses.cameras`,`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]}`:X.t(`system.notificationTimelapses.cameras2`,`{{length}} cameras`,{length:t.deviceIds.length})})},{key:`schedule`,header:X.t(`system.notificationTimelapses.window`,`Window`),render:e=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:Vd(e.schedule)})},{key:`sampling`,header:X.t(`system.notificationTimelapses.sampling`,`Sampling`),nowrap:!0,render:e=>{let t=Ud(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:X.t(`system.notificationTimelapses.targets`,`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:X.t(`system.notificationTimelapses.lastRun`,`Last run`),nowrap:!0,render:t=>u(`span`,{className:`text-[11px] text-foreground-subtle`,"data-testid":`timelapse-last-${t.id}`,children:Hd(t.lastGeneratedAt,e.nowMs)})},{key:`enabled`,header:X.t(`system.notificationTimelapses.on`,`On`),align:`center`,nowrap:!0,render:t=>u(Xd,{children:u(ct,{checked:t.enabled,disabled:!Ed(t),onCheckedChange:n=>e.onToggle(t,n),"aria-label":X.t(`system.notificationTimelapses.toggle`,`toggle {{name}}`,{name:t.name})})})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:t=>n(Xd,{className:`flex items-center justify-end gap-1`,children:[u(W,{size:`sm`,variant:`ghost`,type:`button`,disabled:!Ed(t),onClick:()=>e.onTest(t),title:X.t(`system.notificationTimelapses.renderThisRuleSLast`,`Render this rule's last closed window now and DELIVER it`),"aria-label":X.t(`system.notificationTimelapses.test`,`test {{name}}`,{name:t.name}),"data-testid":`timelapse-test-${t.id}`,children:u(w,{className:`h-3.5 w-3.5`})}),u(tf,{disabled:!Ed(t),pending:e.deletePending,title:X.t(`system.notificationTimelapses.deleteThisTimelapse`,`Delete this timelapse?`),message:X.t(`system.notificationTimelapses.thisWillPermanentlyDeleteThis`,`This will permanently delete "{{name}}". This action cannot be undone.`,{name:t.name}),ariaLabel:X.t(`system.notificationTimelapses.delete`,`delete {{name}}`,{name:t.name}),testId:`timelapse-delete-${t.id}`,onConfirm:()=>e.onConfirmDelete(t)})]})}]}t();var sf={summary:{title:`Summary rules are not available on this hub`,message:`This hub has not been updated to serve summary rules yet. Deploy addon-post-analysis and reload — nothing is lost in the meantime.`},timelapse:{title:`Timelapse rules are not available on this hub`,message:`This hub has not been updated to serve timelapse rules yet. Deploy addon-post-analysis and reload — the rules themselves are untouched.`},"calendar-events":{title:`Calendar-events rules are not available on this hub`,message:`This hub has not been updated to serve calendar-events rules yet. Deploy addon-post-analysis and reload — the rules themselves are untouched.`}},cf=`The hub answered something this admin build does not understand. Update both and reload.`;function lf(e){return e===`summaries`?`summary`:e===`timelapses`?`timelapse`:e===`calendar-events`?`calendar-events`:null}function uf({cameras:e,fleet:t,targets:r,taxonomy:o}){let{t:s}=Z(),d=E(),[f,p]=c({mode:`closed`}),[m,h]=c(null),[g,_]=c(null),[v,y]=c(null),[b,x]=c(null),S=i({queryKey:nf,queryFn:async()=>Bu(await d.trpcClient.addons.custom.mutate({addonId:xl,action:au,input:{}}))}),C=i({queryKey:af,queryFn:async()=>Td(await d.trpcClient.addons.custom.mutate({addonId:xl,action:md,input:{}}))}),w=i({queryKey:Rl,queryFn:async()=>Gl(await d.trpcClient.addons.custom.mutate({addonId:xl,action:zl,input:{}}))}),T=S.data??[],D=C.data??[],O=w.data??[],k=l({mutationFn:e=>d.trpcClient.addons.custom.mutate({addonId:xl,action:ou,input:{ruleId:e.ruleId,patch:{enabled:e.enabled}}}),onSuccess:()=>void S.refetch()}),A=l({mutationFn:e=>d.trpcClient.addons.custom.mutate({addonId:xl,action:su,input:{ruleId:e}}),onSuccess:()=>void S.refetch()}),j=l({mutationFn:async e=>Vu(await d.trpcClient.addons.custom.mutate({addonId:xl,action:cu,input:{ruleId:e,...od(Date.now())}})),onSuccess:e=>{h(null),_(e)}}),M=l({mutationFn:e=>d.trpcClient.addons.custom.mutate({addonId:xl,action:hd,input:{ruleId:e.ruleId,patch:{enabled:e.enabled}}}),onSuccess:()=>void C.refetch()}),N=l({mutationFn:e=>d.trpcClient.addons.custom.mutate({addonId:xl,action:gd,input:{ruleId:e}}),onSuccess:()=>void C.refetch()}),P=l({mutationFn:async e=>Od(await d.trpcClient.addons.custom.mutate({addonId:xl,action:_d,input:e})),onSuccess:e=>{y(null),x(e)}}),F=l({mutationFn:e=>d.trpcClient.addons.custom.mutate({addonId:xl,action:Bl,input:{ruleId:e.ruleId,patch:{enabled:e.enabled}}}),onSuccess:()=>void w.refetch()}),I=l({mutationFn:e=>d.trpcClient.addons.custom.mutate({addonId:xl,action:Vl,input:{ruleId:e}}),onSuccess:()=>void w.refetch()}),L=e.toSorted((e,t)=>e.name.localeCompare(t.name)),ee=r.map(e=>({id:e.id,name:e.name,enabled:e.enabled})),te=new Map(ee.map(e=>[e.id,e.name])),R=new Map(L.map(e=>[e.id,e.name])),z=Date.now(),ne={summary:{nowMs:z,targetNameById:te,deletePending:A.isPending,onToggle:(e,t)=>k.mutate({ruleId:e.id,enabled:t}),onOpen:e=>{Cu(e)&&p({mode:`summary`,rule:e})},onTest:h,onConfirmDelete:e=>A.mutate(e.id)},timelapse:{nowMs:z,cameraNameById:R,targetNameById:te,deletePending:N.isPending,onToggle:(e,t)=>M.mutate({ruleId:e.id,enabled:t}),onOpen:e=>{Ed(e)&&p({mode:`timelapse`,rule:e})},onTest:e=>y({rule:e,deviceId:e.deviceIds[0]??null}),onConfirmDelete:e=>N.mutate(e.id)},calendar:{nowMs:z,targetNameById:te,deletePending:I.isPending,onToggle:(e,t)=>F.mutate({ruleId:e.id,enabled:t}),onOpen:e=>{Kl(e)&&p({mode:`calendar-events`,rule:e})},onConfirmDelete:e=>I.mutate(e.id)}},B=e=>{switch(e.family){case`summary`:ne.summary.onOpen(e.rule);return;case`timelapse`:ne.timelapse.onOpen(e.rule);return;case`calendar-events`:ne.calendar.onOpen(e.rule);return}},V=e=>{p(e===`summary`?{mode:`summary`,rule:null}:e===`timelapse`?{mode:`timelapse`,rule:null}:{mode:`calendar-events`,rule:null})},re=e=>{let t=e===`summary`?S:e===`timelapse`?C:w;return t.isLoading?null:t.isError?{unreadable:!1}:t.data===null?{unreadable:!0}:null},ie=e=>{e===`summary`?S.refetch():e===`timelapse`?C.refetch():w.refetch()},ae=e=>{let t=lf(e);return t!==null&&re(t)!==null},oe=e=>{let t=lf(e),r=t===null?null:re(t);return n(a,{children:[t!==null&&r!==null&&u(K,{title:sf[t].title,message:r.unreadable?cf:sf[t].message,onRetry:()=>ie(t)}),A.isError&&u(K,{title:s(`system.notificationProducerRules.couldNotDeleteTheRule`,`Could not delete the rule`),message:String(A.error)}),N.isError&&u(K,{title:s(`system.notificationProducerRules.couldNotDeleteTheRule`,`Could not delete the rule`),message:String(N.error)}),I.isError&&u(K,{title:s(`system.notificationProducerRules.couldNotDeleteTheRule`,`Could not delete the rule`),message:String(I.error)}),j.isError&&u(K,{title:s(`system.notificationProducerRules.theTestRunFailed`,`The test run failed`),message:String(j.error)}),P.isError&&u(K,{title:s(`system.notificationProducerRules.theTestRunFailed`,`The test run failed`),message:String(P.error)}),g!==null&&u(df,{outcome:g,onDismiss:()=>_(null)}),b!==null&&u(ff,{outcome:b,onDismiss:()=>x(null)})]})},se=()=>p({mode:`closed`}),ce=n(a,{children:[f.mode===`summary`&&u(pd,{rule:f.rule,cameras:L,fleet:t,targets:ee,taxonomy:o,onCancel:se,onSaved:()=>{se(),S.refetch()}}),f.mode===`timelapse`&&u(Yd,{rule:f.rule,cameras:L,fleet:t,targets:ee,onCancel:se,onSaved:()=>{se(),C.refetch()}}),f.mode===`calendar-events`&&u(iu,{rule:f.rule,targets:ee,onCancel:se,onSaved:()=>{se(),w.refetch()}}),u(dl,{open:m!==null,ruleName:m?.name??``,windowDescription:`the last 3 hours`,targetDescription:`${m?.targets.length??0} target${(m?.targets.length??0)===1?``:`s`}`,pending:j.isPending,onCancel:()=>h(null),onConfirm:()=>{m!==null&&j.mutate(m.id)}}),u(dl,{open:v!==null,ruleName:v?.rule.name??``,windowDescription:`its last closed window`,targetDescription:`${v?.rule.targets.length??0} target${(v?.rule.targets.length??0)===1?``:`s`}`,pending:P.isPending,confirmDisabled:v?.deviceId===null,extra:v===null?null:n(`div`,{children:[u(`label`,{className:`mb-1 block text-[11px] font-medium text-foreground`,children:s(`system.notificationProducerRules.whichCamera`,`Which camera`)}),u(G,{value:v.deviceId===null?``:String(v.deviceId),options:v.rule.deviceIds.map(e=>({value:String(e),label:R.get(e)??`#${e}`})),onChange:e=>{let t=Number(e.target.value);Number.isFinite(t)&&y({rule:v.rule,deviceId:t})},"data-testid":`timelapse-test-camera`})]}),onCancel:()=>y(null),onConfirm:()=>{v!==null&&v.deviceId!==null&&P.mutate({ruleId:v.rule.id,deviceId:v.deviceId})}})]});return{summaries:T,timelapses:D,calendarEvents:O,loading:S.isLoading||C.isLoading||w.isLoading,columnDeps:ne,open:B,create:V,notices:oe,listFailed:ae,overlays:ce}}function df({outcome:e,onDismiss:t}){let{t:r}=Z();return 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:[e.error===void 0?n(`span`,{children:[`Produced `,e.produced,` digest`,e.produced===1?``:`s`,` —`,` `,e.tiles??0,` tile`,(e.tiles??0)===1?``:`s`,` from`,` `,e.cameras??0,` camera`,(e.cameras??0)===1?``:`s`,`,`,` `,e.matched??0,` track`,(e.matched??0)===1?``:`s`,` matched,`,` `,e.enqueued??0,` notification`,(e.enqueued??0)===1?``:`s`,` sent.`,(e.droppedStationary??0)>0&&n(`span`,{"data-testid":`summary-test-dropped-stationary`,children:[` `,e.droppedStationary,` parked object`,e.droppedStationary===1?``:`s`,` left out.`]})]}):n(`span`,{className:`text-warning`,children:[r(`system.notificationProducerRules.nothingWasProduced`,`Nothing was produced:`),` `,e.error]}),u(W,{size:`sm`,variant:`ghost`,type:`button`,className:`ml-2`,onClick:t,children:r(`system.notificationProducerRules.dismiss`,`Dismiss`)})]})}function ff({outcome:e,onDismiss:t}){let{t:r}=Z();return 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:[e.error===void 0?n(`span`,{children:[`Produced `,e.produced,` video`,e.produced===1?``:`s`,e.coveragePercent===void 0?``:` — ${Math.round(e.coveragePercent)}% of the window had footage`,`, `,e.enqueued??0,` notification`,(e.enqueued??0)===1?``:`s`,` sent.`]}):n(`span`,{className:`text-warning`,children:[r(`system.notificationProducerRules.nothingWasProduced`,`Nothing was produced:`),` `,e.error]}),u(W,{size:`sm`,variant:`ghost`,type:`button`,className:`ml-2`,onClick:t,children:r(`system.notificationProducerRules.dismiss`,`Dismiss`)})]})}var pf=[{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.`}],mf=[{type:`detection`,label:`Detection`,hint:`Fire on what the cameras see — detections, tracks and package events.`},{type:`sensor`,label:`Sensor`,hint:`A doorbell press or linked sensor changing state.`},{type:`audio`,label:`Sound`,hint:`Sustained sound level or a named sound class.`},{type:`occupancy`,label:`Occupancy`,hint:`How many objects are in a frame or zone, and for how long.`},{type:`device-events`,label:`Device events`,hint:`Offline, battery low, stream drop, camera blind.`},{type:`system`,label:`System events`,hint:`Node, addon, update, backup or export events.`},{type:`alarm`,label:`Alarm`,hint:`Arming, armed, triggered, disarmed.`},{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 hf(e){return e===`summaries`||e===`timelapses`||e===`calendar-events`}function gf(e){if(!(e==null||e.length===0))return hf(e)?e:U(e)}function _f(e){let t=pf.find(t=>t.key===e);if(t===void 0)throw Error(`unknown producer area: ${e}`);return t}function vf(e){return[...Ot.filter(t=>t.key!==`mixed`||(e.get(`mixed`)??0)>0),...pf]}function yf(e){return!hf(e)}function bf(e){return e!==`summary`&&e!==`timelapse`&&e!==`calendar-events`}t();function xf(e){return[{key:`name`,header:X.t(`system.notificationCalendarEventsPage.rule`,`Rule`),render:t=>u(ef,{name:t.name,enabled:t.enabled,...Kl(t)?{onOpen:()=>e.onOpen(t)}:{},openTestId:`calendar-events-edit-${t.id}`,badges:Kl(t)?null:u(J,{variant:`warning`,children:`read-only`})})},{key:`schedule`,header:X.t(`system.notificationCalendarEventsPage.when`,`When`),render:e=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:Xl(e.schedule)})},{key:`horizon`,header:X.t(`system.notificationCalendarEventsPage.horizon`,`Horizon`),nowrap:!0,render:e=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:nu(e.horizonDays)})},{key:`calendars`,header:X.t(`system.notificationCalendarEventsPage.calendars`,`Calendars`),render:e=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:ru(e)})},{key:`targets`,header:X.t(`system.notificationCalendarEventsPage.targets`,`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:X.t(`system.notificationCalendarEventsPage.lastRun`,`Last run`),nowrap:!0,render:t=>u(`span`,{className:`text-[11px] text-foreground-subtle`,"data-testid":`calendar-events-last-${t.id}`,children:id(t.generatedAt,e.nowMs)})},{key:`enabled`,header:X.t(`system.notificationCalendarEventsPage.on`,`On`),align:`center`,nowrap:!0,render:t=>u(Xd,{children:u(ct,{checked:t.enabled,disabled:t.readOnly,onCheckedChange:n=>e.onToggle(t,n),"aria-label":X.t(`system.notificationCalendarEventsPage.toggle`,`toggle {{name}}`,{name:t.name})})})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:t=>u(Xd,{className:`flex items-center justify-end gap-1`,children:u(tf,{disabled:t.readOnly,pending:e.deletePending,title:X.t(`system.notificationCalendarEventsPage.deleteThisCalendarEventsRule`,`Delete this calendar-events rule?`),message:X.t(`system.notificationCalendarEventsPage.thisWillPermanentlyDeleteThis`,`This will permanently delete "{{name}}". This action cannot be undone.`,{name:t.name}),ariaLabel:X.t(`system.notificationCalendarEventsPage.delete`,`delete {{name}}`,{name:t.name}),testId:`calendar-events-delete-${t.id}`,onConfirm:()=>e.onConfirmDelete(t)})})}]}function Sf(e,t){return e.replaceAll(`{{name}}`,t)}function Cf(e){return[{key:`name`,header:X.t(`system.notificationRuleColumns.rule`,`Rule`),render:t=>u(ef,{name:t.name,enabled:t.enabled,...Vr(t)?{onOpen:()=>e.onOpen(t)}:{}})},{key:`trigger`,header:X.t(`system.notificationRuleColumns.trigger`,`Trigger`),nowrap:!0,render:t=>n(`span`,{className:`flex items-center gap-1.5`,children:[u(`span`,{className:`text-[11px] text-foreground-subtle`,children:sn(t,e.t(`notificationRules.grouping.choice`,pn))}),!ln(t.delivery)&&u(J,{variant:`warning`,children:`read-only`})]})},{key:`targets`,header:X.t(`system.notificationRuleColumns.targets`,`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:X.t(`system.notificationRuleColumns.lastRun`,`Last run`),nowrap:!0,render:t=>u($s,{cell:e.lastRunOf(t.id)})},{key:`priority`,header:X.t(`system.notificationRuleColumns.priority`,`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(Xd,{children:u(cc,{rule:t,snoozes:e.snoozes,exempt:Yt(t.conditions,Lt({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:X.t(`system.notificationRuleColumns.on`,`On`),align:`center`,nowrap:!0,render:t=>u(Xd,{children:u(ct,{checked:t.enabled,onCheckedChange:n=>e.onToggle(t,n),"aria-label":X.t(`system.notificationRuleColumns.toggle`,`toggle {{name}}`,{name:t.name})})})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:t=>Vr(t)?n(Xd,{className:`flex items-center justify-end gap-1`,children:[u(Yc,{ruleId:t.id,ruleName:t.name,...t.conditions.devices?.[0]===void 0?{}:{fallbackDeviceId:t.conditions.devices[0]}}),e.onOpenHistory&&u(ec,{rule:t,onOpenHistory:e.onOpenHistory}),e.onTest&&u(W,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onTest?.(t),title:X.t(`system.notificationRuleColumns.openInTheSimulatorDescribe`,`Open in the simulator — describe an event and tune it before injecting`),"aria-label":X.t(`system.notificationRuleColumns.simulate`,`simulate {{name}}`,{name:t.name}),children:u(w,{className:`h-3.5 w-3.5`})}),u(W,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onDuplicate(t),title:X.t(`system.notificationRuleColumns.duplicate`,`Duplicate`),children:u(y,{className:`h-3.5 w-3.5`})}),u(Tf,{rule:t,deps:e})]}):u(wf,{rule:t,deps:e})}]}function wf({rule:e,deps:t}){let{t:r}=Z();return n(Xd,{className:`flex items-center justify-end gap-1`,children:[u(`span`,{title:we(ye(e)).blurb,children:u(J,{variant:`warning`,children:r(`system.notificationRuleColumns.recreateAsOneRulePer`,`Recreate as one rule per family`)})}),t.onOpenHistory&&u(ec,{rule:e,onOpenHistory:t.onOpenHistory}),u(Tf,{rule:e,deps:t})]})}function Tf({rule:e,deps:t}){let{t:n}=Z();return u(tf,{pending:t.deletePending,title:n(`notificationRules.delete.confirm`,`Delete this rule?`),message:Sf(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:Sf(n(`notificationRules.delete.aria`,`delete {{name}}`),e.name),onConfirm:()=>t.onConfirmDelete(e)})}function Ef(e){let t=Cf(e),n=e=>t.filter(t=>t.key===e);return[...n(`name`),{key:`events`,header:X.t(`system.notificationRuleColumns.events`,`Events`),render:e=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:_r(e.conditions.systemEvent?.kinds)})},{key:`scope`,header:X.t(`system.notificationRuleColumns.scope`,`Scope`),nowrap:!0,render:e=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:cr(e.conditions.systemEvent)})},{key:`targets`,header:X.t(`system.notificationRuleColumns.targets`,`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:X.t(`system.notificationRuleColumns.cooldown`,`Cooldown`),nowrap:!0,render:e=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:an(e.throttle.cooldownSec)})},...n(`lastRun`),...n(`snooze`),...n(`enabled`),...n(`actions`)]}function Df(e){switch(e){case`detection`:return`Detection`;case`sensor`:return`Sensor`;case`sound`:return`Sound`;case`occupancy`:return`Occupancy`;case`device-events`:return`Device events`;case`system`:return`System`;case`alarm`:return`Alarm`;case`mixed`:return`To recreate`;case`summary`:return`Summary`;case`timelapse`:return`Timelapse`;case`calendar-events`:return`Calendar events`}}function Of(e){return{family:`event`,kind:ye(e),id:e.id,name:e.name,enabled:e.enabled,rule:e}}function kf(e){return{family:`summary`,kind:`summary`,id:e.id,name:e.name,enabled:e.enabled,rule:e}}function Af(e){return{family:`timelapse`,kind:`timelapse`,id:e.id,name:e.name,enabled:e.enabled,rule:e}}function jf(e){return{family:`calendar-events`,kind:`calendar-events`,id:e.id,name:e.name,enabled:e.enabled,rule:e}}function Mf(e){return[...e.events.map(Of),...e.summaries.map(kf),...e.timelapses.map(Af),...e.calendarEvents.map(jf)]}function Nf(e,t){return t===`all`?!0:hf(t)?t===`summaries`?e.family===`summary`:t===`timelapses`?e.family===`timelapse`:e.family===`calendar-events`:yf(t)&&e.family===`event`?Ae(e.rule,t):!1}function Pf(e,t){return Mf(t).filter(t=>Nf(t,e)).toSorted((e,t)=>e.name.localeCompare(t.name))}function Ff(e,t){return Pf(e,t).length}function If(e){return e===`all`?900:860}function Lf(e){return e.family===`event`?e.rule:null}function Rf(e){return e.family===`summary`?e.rule:null}function zf(e){return e.family===`timelapse`?e.rule:null}function Bf(e){return e.family===`calendar-events`?e.rule:null}function Vf(e,t){return{key:e.key,...e.header===void 0?{}:{header:e.header},...e.headerRender===void 0?{}:{headerRender:e.headerRender},...e.align===void 0?{}:{align:e.align},...e.nowrap===void 0?{}:{nowrap:e.nowrap},...e.width===void 0?{}:{width:e.width},render:(n,r)=>{let i=t(n);return i===null?null:e.render(i,r)}}}function Hf(e,t){return e.map(e=>Vf(e,t))}function Uf(e,t){return e.find(e=>e.key===t)}function Wf(e,t,n){let r=Uf(Cf(n.event),e),i=Uf(rf(n.summary),e),a=Uf(of(n.timelapse),e),o=Uf(xf(n.calendar),e);return{key:e,header:t,...r?.align===void 0?{}:{align:r.align},...r?.nowrap===void 0?{}:{nowrap:r.nowrap},render:(e,t)=>{switch(e.family){case`event`:return r?.render(e.rule,t)??null;case`summary`:return i?.render(e.rule,t)??null;case`timelapse`:return a?.render(e.rule,t)??null;case`calendar-events`:return o?.render(e.rule,t)??null}}}}function Gf(e){switch(e.family){case`event`:return null;case`summary`:return rd(e.rule.window);case`timelapse`:return Vd(e.rule.schedule);case`calendar-events`:return Xl(e.rule.schedule)}}function Kf(e){let t=Uf(Cf(e.event),`trigger`);return{key:`when`,header:X.t(`system.unifiedRulesColumns.when`,`When`),render:(e,n)=>{let r=Gf(e);return r===null?e.family===`event`?t?.render(e.rule,n)??null:null:u(`span`,{className:`text-[11px] text-foreground-subtle`,children:r})}}}function qf(e){return[Wf(`name`,`Name`,e),{key:`type`,header:X.t(`system.unifiedRulesColumns.type`,`Type`),nowrap:!0,render:e=>u(`span`,{className:`text-[11px] text-foreground-subtle`,"data-testid":`rule-type-${e.id}`,children:Df(e.kind)})},Kf(e),Wf(`targets`,`Targets`,e),Wf(`lastRun`,`Last run`,e),Wf(`snooze`,e.event.t(`notificationRules.columns.snooze`,`Snooze`),e),Wf(`enabled`,`On`,e),Wf(`actions`,``,e)]}function Jf(e,t){return e===`all`?qf(t):e===`summaries`?Hf(rf(t.summary),Rf):e===`timelapses`?Hf(of(t.timelapse),zf):e===`calendar-events`?Hf(xf(t.calendar),Bf):yf(e)&&At(e)?Hf(Ef(t.event),Lf):Hf(Cf(t.event),Lf)}function Yf({value:e,family:t,onChange:r,draft:i}){let{t:a}=Z();if(t===void 0||!Se.includes(t))return null;let o=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:a(`system.notificationSystemEventDelivery.delivery`,`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:o===null,onChange:()=>r({mode:`instant`}),"data-testid":`rule-delivery-instant`}),a(`system.notificationSystemEventDelivery.instantANotificationPerEvent`,`Instant — a notification per event`)]}),n(`label`,{className:`flex items-center gap-1.5`,children:[u(`input`,{type:`radio`,name:`system-event-delivery`,checked:o!==null,onChange:()=>r({mode:`summary`,schedule:le([lr])}),"data-testid":`rule-delivery-summary`}),a(`system.notificationSystemEventDelivery.summaryOnScheduleTheCurrent`,`Summary on schedule — the current state, at set times`)]})]}),o!==null&&u(Xf,{value:o,onChange:r,draft:i})]})}function Xf({value:e,onChange:t,draft:r}){let{t:i}=Z(),a=e.schedule.timezone,o=se({systemEventDelivery:e});return n(`div`,{className:`mt-2 space-y-2`,children:[n(`p`,{className:Ln,children:[i(`system.notificationSystemEventDelivery.nothingIsSentPerEvent`,`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:`),` `,a??i(`system.notificationSystemEventDelivery.theHubS`,`the hub’s`),`.`]}),u(Er,{mode:`times`,value:e.schedule,onChange:n=>{n!==void 0&&t(Xn(e,n))}}),n(`fieldset`,{className:`flex flex-wrap gap-3 text-xs`,"data-testid":`rule-delivery-split`,children:[u(`legend`,{className:`sr-only`,children:i(`system.notificationSystemEventDelivery.howTheSummaryIsSent`,`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:o===`rule`,onChange:()=>t(kn(e,`rule`)),"data-testid":`rule-delivery-split-rule`}),i(`system.notificationSystemEventDelivery.oneMessageWithEveryCategory`,`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:o===`section`,onChange:()=>t(kn(e,`section`)),"data-testid":`rule-delivery-split-section`}),i(`system.notificationSystemEventDelivery.oneNotificationPerCategoryBatteries`,`One notification per category (batteries, consumables, devices…)`)]})]}),u(Zf,{draft:r,split:o})]})}function Zf({draft:e,split:t}){let{t:r}=Z(),i=E(),a=l({mutationFn:e=>i.trpcClient.notificationRules.previewStateSummary.mutate({rule:e})}),o=br(a.status,a.data,a.error,t);return n(`div`,{className:`space-y-1.5`,children:[u(W,{size:`sm`,variant:`secondary`,onClick:()=>a.mutate(e()),disabled:a.isPending,"data-testid":`rule-delivery-preview`,children:a.isPending?r(`system.notificationSystemEventDelivery.readingTheState`,`Reading the state…`):r(`system.notificationSystemEventDelivery.previewTheSummaryNow`,`Preview the summary now`)}),o!==null&&u(`div`,{className:`text-[10px] text-foreground-subtle mt-0.5`,"data-testid":`rule-delivery-preview-result`,children:o.lines.map((e,t)=>u(`p`,{className:`whitespace-pre-wrap`,children:e},t))})]})}function Qf(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:rp(e.data.horizonMs)}:{kind:`ran`,lastAt:n.lastAt,status:n.status,deviceId:n.deviceId}}var $f=6e4,ep=60*$f,tp=24*ep;function np(e,t){return e===1?`the last ${t}`:`the last ${String(e)} ${t}s`}function rp(e){return e===null?`No delivery on record`:e>=tp?`Not in ${np(Math.floor(e/tp),`day`)}`:e>=ep?`Not in ${np(Math.floor(e/ep),`hour`)}`:e>=$f?`Not in ${np(Math.floor(e/$f),`minute`)}`:`Not in the window read`}t();var ip=[`notificationRules`,`listRules`],ap=[`notificationOutput`,`listTargets`,`forRules`],op=[`notificationRules`,`getConditionCatalog`],sp=[`deviceManager`,`gateableDevices`],cp=ne.options;function lp({onSimulateRule:t,onOpenHistory:a,createRequested:o=!1,onCreateConsumed:s,createTypeRequested:p=null,onCreateTypeConsumed:m,headerOwnsCreate:h=!1}={}){let _=E(),{t:v}=Z(),{state:y,openEdit:b,close:x}=Ke({editKey:`rule`}),[S,C]=Je(`section`),[w,T]=Je(`editTab`),[D,O]=c({mode:`closed`}),[k,A]=c(!1),j=gf(S)??`all`,M=e=>{C(e===`all`?null:e)},N=i({queryKey:ip,queryFn:async()=>(await _.trpcClient.notificationRules.listRules.query({})).rules}),P=e(null);d(()=>{if(D.mode!==`closed`)return;if(y.mode!==`edit`){y.mode===`closed`&&(P.current=null);return}let e=y.id;if(e===`new`||P.current===e)return;let t=N.data?.find(t=>t.id===e);t===void 0||!Vr(t)||(P.current=e,O({mode:`form`,rule:t}))},[D.mode,y,N.data]);let F=i({queryKey:ap,queryFn:()=>_.trpcClient.notificationOutput.listTargets.query({})}),I=i({queryKey:op,queryFn:()=>_.trpcClient.notificationRules.getConditionCatalog.query({})}),L=pt({projection:`slim`}),ee=Zs(),R=r(()=>L.data??[],[L.data]),z=St(L),ne=r(()=>R.map(e=>e.id),[R]),B=i({queryKey:[...sp,ne],enabled:ne.length>0,queryFn:async()=>{let e=[];for(let t of R){let n=te(await _.trpcClient.deviceManager.loadRuntimeState.query({deviceId:t.id}),cp);n.length>0&&e.push({id:t.id,name:t.name,states:n})}return e},staleTime:6e4}),V=r(()=>{let e=Gr(R);return R.filter(e=>me(String(e.type))).map(t=>{let n=e.get(t.id);return{id:t.id,name:t.name,type:String(t.type),location:t.location??null,...n===void 0?{}:{parentName:n}}}).sort((e,t)=>e.name.localeCompare(t.name))},[R]),re=r(()=>R.filter(e=>e.type===ce.Camera).map(e=>({id:e.id,name:e.name})),[R]),ie=Yr(r(()=>re.map(e=>e.id),[re])),ae=r(()=>{let e=new Map(re.map(e=>[e.id,e.name]));return ie.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})))},[ie.results,re]),oe=r(()=>{let e=new Map;for(let t of F.data??[])e.set(t.id,t.name);return e},[F.data]),se=l({mutationFn:e=>_.trpcClient.notificationRules.setRuleEnabled.mutate(e),onSuccess:()=>void N.refetch()}),le=l({mutationFn:e=>_.trpcClient.notificationRules.deleteRule.mutate({ruleId:e}),onSuccess:()=>void N.refetch()}),ue=sc(),de=lt({}),fe=de.data?.sequences??[],pe=xt(),he=N.data??[],H=uf({cameras:re,fleet:z,targets:F.data??[],taxonomy:I.data?.taxonomy}),ge={events:he,summaries:H.summaries,timelapses:H.timelapses,calendarEvents:H.calendarEvents},_e=vf(new Map(Ot.map(e=>[e.key,Ff(e.key,ge)]))),U=_e.find(e=>e.key===j)??_e[0]??Ot[0],ve=hf(U.key)?_f(U.key):void 0;yf(U.key)&&U.key;let ye=Pf(U.key,ge),xe=()=>{y.mode===`edit`&&(P.current=y.id),O({mode:`closed`}),x(),T(null)},Se=e=>{if(!Vr(e))return;let t=e.id.length>0?e.id:`new`;P.current=t,O({mode:`form`,rule:e}),b(t),T(null)},Ce=e=>{if(bf(e)){P.current=`new`,O({mode:`form`,rule:null,seed:be(e)}),b(`new`),T(null);return}H.create(e)};d(()=>{p!==null&&(Ce(p),m?.())},[p]),d(()=>{o&&(A(!0),s?.())},[o]);let we=e=>{if(e.family===`event`){Se(e.rule);return}H.open(e)},Te={targetNameById:oe,snoozes:ue,sequences:fe,deletePending:le.isPending,onToggle:(e,t)=>se.mutate({ruleId:e.id,enabled:t}),onOpen:Se,t:v,onDuplicate:e=>Se({...e,id:``,name:`${e.name} (copy)`}),onConfirmDelete:e=>le.mutate(e.id),...t?{onTest:t}:{},lastRunOf:e=>Qf(ee,e),...a?{onOpenHistory:a}:{}},Ee=Jf(U.key,{event:Te,summary:H.columnDeps.summary,timelapse:H.columnDeps.timelapse,calendar:H.columnDeps.calendar}),De=ve?.blurb??(`blurb`in U?U.blurb:``),Oe=ve===void 0?`creatable`in U?U.creatable:!1:!0,ke=h||!Oe?null:j===`all`?n(W,{size:`sm`,type:`button`,"data-testid":`rules-new-menu`,onClick:()=>A(!0),children:[u(g,{className:`h-3.5 w-3.5`}),v(`system.notificationRules.newRule`,`New rule`)]}):ve===void 0?n(W,{size:`sm`,type:`button`,onClick:()=>Ce(U.key),"data-testid":`rules-new-${U.key}`,children:[u(g,{className:`h-3.5 w-3.5`}),`newRuleLabel`in U?U.newRuleLabel:v(`system.notificationRules.newRule`,`New rule`)]}):n(W,{size:`sm`,type:`button`,onClick:()=>Ce(ve.key===`summaries`?`summary`:ve.key===`timelapses`?`timelapse`:`calendar-events`),"data-testid":ve.key===`summaries`?`summary-new`:ve.key===`timelapses`?`timelapse-new`:`calendar-events-new`,children:[u(g,{className:`h-3.5 w-3.5`}),ve.newLabel]});return u(Jr,{embedded:!0,icon:f,title:v(`system.notificationRules.rules`,`Rules`),subtitle:De,children:n(`div`,{className:`flex flex-col gap-3`,children:[ke===null?null:u(`div`,{className:`flex justify-end`,children:ke}),u(nt,{appearance:`pills`,value:U.key,onValueChange:e=>M(gf(e)??j),children:u(mt,{children:_e.map(e=>n(yt,{value:e.key,children:[e.label,u(`span`,{className:`ml-1.5 text-[10px] text-foreground-subtle`,children:Ff(e.key,ge)})]},e.key))})}),u(el,{rules:he}),H.notices(U.key),(N.isLoading||H.loading)&&u(Zd,{}),N.isError&&!N.isLoading&&u(K,{title:v(`system.notificationRules.failedToLoadRules`,`Failed to load rules`),message:N.error instanceof Error?N.error.message:v(`system.notificationRules.unknownError`,`Unknown error`),onRetry:()=>void N.refetch()}),!N.isLoading&&!H.loading&&!N.isError&&!H.listFailed(U.key)&&ye.length===0&&u(Qd,{children:ve?.emptyHint??(`emptyHint`in U?U.emptyHint:v(`system.notificationRules.noRulesYet`,`No rules yet.`))}),ye.length>0&&u($d,{columns:Ee,rows:ye,rowKey:e=>`${e.family}:${e.id}`,onRowClick:we,minWidthPx:If(U.key)}),D.mode===`form`&&u(dp,{rule:D.rule,...D.seed?{seed:D.seed}:{},targets:F.data??[],actuatable:V,fleet:z,sequences:fe,onCreateSequence:async e=>{let t=await pe.mutateAsync({sequence:{name:e.name,...e.minDelaySec===void 0?{}:{minDelaySec:e.minDelaySec},actions:[...e.actions]}});return await de.refetch(),t.sequence.id},catalog:tn(I.data?.catalog??[]),taxonomy:I.data?.taxonomy,cameras:re,gateable:B.data??[],gateableScenes:ae,initialEditTab:jt(w??``)??`rule`,onEditTabChange:e=>T(e===`rule`?null:e),onCancel:xe,onSaved:()=>{xe(),N.refetch()}}),H.overlays,k?u(up,{onCancel:()=>A(!1),onPick:e=>{A(!1),Ce(e)}}):null]})})}function up({onPick:e,onCancel:t}){let{t:r}=Z();return u(wt,{open:!0,onClose:t,title:r(`system.notificationRules.chooseARuleType`,`Choose a rule type`),width:`lg`,children:u(`div`,{className:`grid grid-cols-1 gap-2 sm:grid-cols-2`,children:mf.map(t=>n(`button`,{type:`button`,"data-testid":`rules-new-${t.type}`,title:t.hint,onClick:()=>e(t.type),className:`flex flex-col items-start gap-1 rounded-lg border border-border bg-surface px-3 py-3 text-left text-xs hover:border-primary/50 hover:bg-surface-hover transition-colors`,children:[u(`span`,{className:`font-medium text-foreground`,children:t.label}),u(`span`,{className:`text-[10px] font-normal text-foreground-subtle`,children:t.hint})]},t.type))})})}function dp({rule:e,seed:t,targets:o,catalog:s,taxonomy:d,cameras:p,gateable:m,gateableScenes:h,actuatable:g,fleet:_,sequences:v,onCreateSequence:y,initialEditTab:x=Mn,onEditTabChange:S,onSaved:C,onCancel:T}){let D=E(),{t:O}=Z(),k=e!=null&&e.id.length>0,[A]=c(()=>e?gn(e):$t(t?.delivery,t?.conditions)),[j,M]=c(A),[N,P]=c(null),[F,I]=c(k),[L,ee]=c(null),[te,R]=c(x),z=e=>M(t=>({...t,...e})),ne=e?Nt(e):void 0,B=l({mutationFn:async()=>{let t=Ft(j,ne,s);if(k&&e){let n=fn(j,s);await D.trpcClient.notificationRules.updateRule.mutate({ruleId:e.id,patch:t,...n.length>0?{clear:n}:{}})}else await D.trpcClient.notificationRules.createRule.mutate({rule:t})},onSuccess:C,onError:e=>P(e instanceof Error?e.message:`Save failed`)}),V=l({mutationFn:async()=>{let e=Ft(j,ne,s);return(await D.trpcClient.notificationRules.testRule.mutate({rule:e,lookbackMinutes:60})).results},onMutate:()=>ee(null),onSuccess:e=>ee(e),onError:e=>P(e instanceof Error?e.message:`Test failed`)}),re=j.targetIds.map(e=>o.find(t=>t.id===e)?.name??e),ie=i({queryKey:[`userManagement`,`listUsers`],queryFn:()=>D.trpcClient.userManagement.listUsers.query()}).data,ae=r(()=>(ie??[]).map(e=>({value:e.id,label:e.username,...e.isAdmin?{badge:`admin`}:{}})),[ie]),oe=Rt(j),se=oe===`immediate-grouped`,ce=String(j.groupingSec??20),le=Wt(j).map(e=>({...e,label:e.value===`immediate-grouped`?O(`notificationRules.grouping.choice`,e.label):e.label,hint:e.value===`immediate-grouped`?O(`notificationRules.grouping.hint`,{n:ce,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}}`,ce):e.hint})),ue=le.find(e=>e.value===oe)?.hint,de=Br(j,ne),fe=Oe(j.delivery),pe=ye(j),me=we(pe),he=xe(pe),H=Ee(pe),ge=i({queryKey:[`deviceManager`,`listDeviceIdsByCaps`,`nc-rule-devices`,H??[]],enabled:H!==null,queryFn:async()=>{let e=await Promise.all((H??[]).map(e=>D.trpcClient.deviceManager.listDeviceIdsByCaps.query({capNames:[...e]})));return new Set(e.flat())},staleTime:6e4}),_e=r(()=>{if(H===null||ge.data===void 0)return g;let e=ge.data,t=new Set(jn(j.deviceScope));return g.filter(n=>e.has(n.id)||t.has(n.id))},[g,H,ge.data,j.deviceScope]),U=H!==null&&ge.isLoading,ve=H!==null&&ge.isError,be=lo(),Se=e=>({family:`rule`,field:e,kind:pe,delivery:j.delivery,...cn(j)?{systemEventDelivery:`summary`}:{},...j.conditions.systemEvent?{systemEventKinds:[...j.conditions.systemEvent.kinds]}:{}}),Ce=e=>be.data?ao(be.data,Se(e)):void 0,Te=un(j),De=Yt(j.conditions,Lt(j.actions,v)),ke=j.conditions.identities!==void 0||j.conditions.plates!==void 0,Ae=Pr(j.delivery,j.conditions),je=Ae.some(e=>e.key===te)?te:Mn;return ln(j.delivery)?u(nt,{value:je,onValueChange:e=>{let t=jt(e);t!==void 0&&(R(t),S?.(t))},children:n(wt,{open:!0,onClose:T,title:k?O(`system.notificationRules.edit`,`Edit {{name}}`,{name:e?.name}):O(`system.notificationRules.newNotificationRule`,`New notification rule`),icon:f,error:N,width:`lg`,testId:`rule-form-dialog`,beforeBody:n(a,{children:[k&&e&&n(`div`,{className:`mb-3 space-y-2`,children:[u(Ic,{kind:`rule`,ruleId:e.id,enabled:e.enabled,updatedAt:e.updatedAt}),u(zc,{ruleId:e.id,cameraName:e=>p.find(t=>t.id===e)?.name??`camera ${String(e)}`})]}),u(mt,{className:`mb-3`,children:Ae.map(e=>u(yt,{value:e.key,children:e.label},e.key))})]}),footer:n(`div`,{className:`flex w-full flex-col gap-3`,children:[Te.length>0&&n(`div`,{"data-testid":`rule-form-dropped`,className:`rounded-md border border-border bg-surface-subtle px-3 py-2 text-[11px] text-foreground-subtle space-y-1 text-left`,children:[n(`p`,{className:`text-foreground`,children:[`Saving drops `,Te.length,` condition`,Te.length===1?``:`s`,` this kind of rule cannot use:`]}),Te.map(e=>n(`p`,{children:[u(`span`,{className:`text-foreground`,children:e.conditionId}),` — `,e.reason]},e.conditionId))]}),F&&de.length>0?u(`div`,{"data-testid":`rule-form-problems`,className:`rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-[11px] text-warning space-y-1 text-left`,children:de.map(e=>u(`p`,{children:e},e))}):null,u(`div`,{className:`flex justify-end gap-2`,children:n(W,{size:`sm`,type:`button`,disabled:B.isPending,onClick:()=>{I(!0),P(null),!(!Ut(j,ne,new Set(v.map(e=>e.id)))||B.isPending)&&B.mutate()},children:[B.isPending&&u(b,{className:`h-3.5 w-3.5 animate-spin`}),k?O(`system.notificationRules.saveChanges`,`Save changes`):O(`system.notificationRules.createRule`,`Create rule`)]})})]}),children:[n(Y,{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:O(`system.notificationRules.name`,`Name`)}),u(q,{value:j.name,onChange:e=>z({name:e.target.value}),placeholder:O(`system.notificationRules.eGFrontDoorPackage`,`e.g. Front door package`)})]}),n(`label`,{className:`flex items-center gap-2 pb-1.5 text-[11px] font-medium text-foreground`,children:[u(ct,{checked:j.enabled,onCheckedChange:e=>z({enabled:e}),"aria-label":`enabled`}),O(`system.notificationRules.enabled`,`Enabled`)]})]}),n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:O(`system.notificationRules.trigger`,`Trigger`)}),u(G,{value:oe,onChange:e=>{let t=Jt(e.target.value);t&&M(e=>$n(e,t))},options:le.map(e=>({value:e.value,label:e.label}))}),ue&&u(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:ue}),se&&n(`div`,{className:`mt-2`,children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:O(`notificationRules.grouping.seconds`,`Group for (seconds)`)}),u(q,{type:`number`,min:5,max:60,step:1,value:ce,"data-testid":`rule-grouping-sec`,onChange:e=>{let t=yr(e.target.value);t!==void 0&&z({groupingSec:t})}}),u(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:O(`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:O(`notificationRules.grouping.scopedHint`,{n:ce,defaultValue:`A subject not recognised within {{n}} s is not notified.`}).replaceAll(`{{n}}`,ce)})]}),oe===`immediate`&&ke&&u(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:O(`notificationRules.grouping.plainRecognitionHint`,`Fires only if the name is already known when an event is written — choose Immediate, grouped to wait for it.`)})]}),!k&&he!==void 0&&u(Os,{family:he,onChange:e=>M(t=>Zt(t,e))}),u(rt,{label:O(`system.notificationRules.deliveryTargets`,`Delivery targets`),targets:o,value:j.targetIds,onChange:e=>M(t=>({...t,targetIds:e})),emptyMessage:O(`system.notificationRules.noDeliveryTargetsConfiguredAdd`,`No delivery targets configured. Add one under the Targets tab first.`),testIdPrefix:`rule-target`}),u(bt,{mode:`multi`,options:ae,value:j.targetUsers,onChange:e=>z({targetUsers:e}),searchable:!0,creatable:!1,label:O(`system.notificationRules.notifyUsers`,`Notify users`),description:O(`system.notificationRules.deliversToTheTargetsEach`,`Delivers to the targets each user owns, only for cameras that user can access.`),emptyMessage:O(`system.notificationRules.noUsersToNotify`,`No users to notify.`),placeholder:O(`system.notificationRules.searchUsers`,`Search users…`),testId:`rule-notify-users`,optionTestIdPrefix:`rule-user`,listboxId:`rule-notify-users-listbox`})]}),n(Y,{value:`devices`,className:`space-y-4`,children:[U&&u(`p`,{className:`text-[10px] text-foreground-subtle`,"data-testid":`rule-devices-compat-loading`,children:O(`notificationRules.devices.compatLoading`,`Checking which devices this rule's kind can use…`)}),ve&&u(`p`,{className:`text-[10px] text-foreground-subtle`,"data-testid":`rule-devices-compat-failed`,children:O(`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(is,{devices:_e,scope:j.deviceScope,onChange:e=>z({deviceScope:e}),listState:_.state,savedScope:A.deviceScope,exceptOffered:kt(s,`devicesExclude`,j)})]}),u(Y,{value:`actions`,className:`space-y-4`,children:u(Eo,{value:j.actions,onChange:e=>z({actions:e}),devices:g,devicesState:_.state,sequences:v,onCreateSequence:y,showProblems:F})}),n(Y,{value:`advanced`,className:`space-y-4`,children:[u(Us,{catalog:s,delivery:j.delivery,conditions:j.conditions,onConditionsChange:e=>z({conditions:e})}),n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:O(`system.notificationRules.cooldownSeconds`,`Cooldown (seconds)`)}),u(q,{type:`number`,min:0,max:dn,step:1,value:String(j.cooldownSec),"data-testid":`rule-cooldown`,onChange:e=>{let t=hn(e.target.value);t!==void 0&&z({cooldownSec:t})}}),n(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:[fe?O(`system.notificationRules.aCameraThatFlapsOr`,`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.`):O(`system.notificationRules.theShortestGapBetweenTwo`,`The shortest gap between two deliveries of this rule, counted as chosen below.`),` `,`Any whole number from 0 (deliver every match) to `,String(dn),` (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:O(`system.notificationRules.cooldownCounted`,`Cooldown counted`)}),u(G,{value:j.cooldownScope,onChange:e=>{let t=Bt(e.target.value);t!==void 0&&z({cooldownScope:t})},options:Mt.map(e=>({value:e.value,label:e.label})),"data-testid":`rule-cooldown-scope`}),u(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:O(`system.notificationRules.perDeviceADeliveryAbout`,`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:O(`system.notificationRules.acrossObjectClasses`,`Across object classes`)}),u(G,{value:j.cooldownGranularity??`per-class`,onChange:e=>z({cooldownGranularity:yn(e.target.value)}),options:Lr.map(e=>({value:e.value,label:e.label})),"data-testid":`rule-cooldown-granularity`}),u(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:O(`system.notificationRules.separateDefaultADogAfter`,`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(ct,{checked:j.snoozeAllowGlobal,onCheckedChange:e=>z({snoozeAllowGlobal:e}),"aria-label":O(`system.notificationRules.allowGlobalSnooze`,`allow global snooze`),disabled:De}),O(`system.notificationRules.anyoneMaySnoozeThisRule`,`Anyone may snooze this rule for everyone`)]}),u(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:O(`system.notificationRules.aSnoozeIsPersonalBy`,`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.`)})]}),!De&&n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:O(`system.notificationRules.snoozeButtons`,`Snooze buttons`)}),n(a,{children:[u(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:Dt.map(e=>{let t=j.snoozeOptions??tr,n=t.includes(e);return u(W,{type:`button`,size:`sm`,variant:n?`primary`:`outline`,onClick:()=>z({snoozeOptions:n?t.filter(t=>t!==e):[...t,e].toSorted((e,t)=>e-t)}),children:Vt(e)},e)})}),u(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:j.snoozeOptions===void 0?O(`system.notificationRules.notSetTheNotificationOffers`,`Not set — the notification offers the defaults ({{value1}}). A pause opened from a button silences this camera for this class of subject, only for whoever received the notification, and sends no summary.`,{value1:tr.map(Vt).join(`, `)}):j.snoozeOptions.length===0?O(`system.notificationRules.noSnoozeButtonsOnThis`,`No snooze buttons on this rule. That is an explicit choice: the notification cannot be silenced from the lock screen.`):O(`system.notificationRules.fourAtMostEverySnooze`,`Four at most. Every snooze button takes space from the rule’s action buttons — ntfy accepts three in total.`)}),j.snoozeOptions!==void 0&&u(W,{type:`button`,size:`sm`,variant:`ghost`,className:`mt-1`,onClick:()=>z({snoozeOptions:void 0}),children:O(`system.notificationRules.backToTheDefaults`,`Back to the defaults`)})]})]}),k&&e&&!De&&n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:O(`system.notificationRules.silenceItNow`,`Silence it now`)}),u(rc,{ruleId:e.id,ruleName:e.name,exempt:De,variant:`full`})]})]}),n(Y,{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:O(`system.notificationRules.priority`,`Priority`)}),u(G,{value:String(j.priority),onChange:e=>z({priority:Number(e.target.value)}),options:nr.map(e=>({value:String(e.value),label:e.label}))})]}),!me.carriesMedia&&u(`div`,{className:`rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,"data-testid":`rule-media-none`,children:me.mediaBlurb??O(`system.notificationRules.aSystemEventCarriesNo`,`A system event carries no image: there is no camera frame behind "a node went offline". This rule sends text only.`)}),me.carriesMedia&&pe===`sensor`&&u(`div`,{className:`rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:O(`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.`)}),me.carriesMedia&&pe!==`sensor`&&me.mediaBlurb!==void 0&&u(`div`,{className:`rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:me.mediaBlurb}),me.carriesMedia&&pe!==`sensor`&&n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:O(`system.notificationRules.mediaAttachment`,`Media attachment`)}),u(G,{value:j.mediaAttach,onChange:e=>{let t=Cn(e.target.value);t&&z({mediaAttach:t})},options:Pt.map(e=>({value:e.value,label:e.label}))}),u(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:Pt.find(e=>e.value===j.mediaAttach)?.description}),n(`div`,{className:`mt-2 space-y-1`,children:[me.carriesSubjectCrop&&n(`label`,{className:`flex items-center gap-2 text-xs text-foreground cursor-pointer`,children:[u(`input`,{type:`checkbox`,checked:j.mediaZoneCrop,onChange:e=>z({mediaZoneCrop:e.target.checked}),className:`accent-primary`}),O(`system.notificationRules.cropTheImageToThe`,`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:j.mediaGif,onChange:e=>z({mediaGif:e.target.checked}),className:`accent-primary`}),O(`system.notificationRules.attachAGifAroundThe`,`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:j.mediaClip,onChange:e=>z({mediaClip:e.target.checked}),className:`accent-primary`}),O(`system.notificationRules.attachAnMp4ClipAround`,`Attach an MP4 clip around the event`)]})]}),(j.mediaGif||j.mediaClip)&&n(`div`,{className:`mt-2`,children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:O(`system.notificationRules.videoQuality`,`Video quality`)}),u(G,{value:j.mediaProfile??``,onChange:e=>z({mediaProfile:_n(e.target.value)}),options:zr.map(e=>({value:e.value,label:e.label}))}),u(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:O(`system.notificationRules.aNotificationIsWatchedOn`,`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:O(`system.notificationRules.playbackSpeed`,`Playback speed`)}),u(G,{value:j.mediaClipSpeed===void 0?``:String(j.mediaClipSpeed),onChange:e=>z({mediaClipSpeed:Ht(e.target.value)}),options:Nn.map(e=>({value:e.value,label:e.label}))}),u(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:O(`system.notificationRules.aNotificationClipIsGlanced`,`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.`)})]})]}),pe===`sensor`&&me.carriesMedia&&n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:O(`system.notificationRules.linkedCameras`,`Linked cameras`)}),u(G,{value:j.mediaLinkedCameras??``,onChange:e=>z({mediaLinkedCameras:Kt(e.target.value)}),options:It.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:O(`system.notificationRules.whenTheSensorIsLinked`,`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.`)})]}),me.carriesMedia&&pe!==`sensor`&&me.carriesSubjectCrop&&n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:O(`system.notificationRules.imageFrame`,`Image frame`)}),u(G,{value:j.mediaFrame??``,onChange:e=>z({mediaFrame:xn(e.target.value)}),options:Fr.map(e=>({value:e.value,label:e.label}))}),u(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:O(`system.notificationRules.whatTheAttachedStillShows`,`What the attached still shows. "Automatic" leaves it to the attachment mode above.`)})]})]}),n(`div`,{className:`space-y-2`,children:[u(ho,{label:O(`system.notificationRules.notificationTitle`,`Notification title`),value:j.templateTitle,onChange:e=>z({templateTitle:e}),vars:Ce(`title`),testId:`rule-template-title`}),u(ho,{label:O(`system.notificationRules.notificationBody`,`Notification body`),value:j.templateBody,onChange:e=>z({templateBody:e}),vars:Ce(`body`),multiline:!0,testId:`rule-template-body`}),u(`p`,{className:`text-[10px] text-foreground-subtle`,children:O(`system.notificationRules.leaveBothBlankForThe`,`Leave both blank for the hub's own wording (editable on the Texts tab).`)}),mn(j)!==null&&u(`p`,{className:`text-[10px] text-warning`,"data-testid":`rule-template-summary-warning`,children:mn(j)}),u(go,{context:Se(`body`),title:j.templateTitle,body:j.templateBody,testId:`rule-template-preview`})]})]}),n(Y,{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:fe?O(`system.notificationRules.whichSystemEvents`,`Which system events`):Ir(j.conditions)??O(`system.notificationRules.conditions`,`Conditions`)}),j.conditions.audio!==void 0&&u(`p`,{className:`mb-2 text-[10px] text-foreground-subtle`,children:O(`system.notificationRules.thisIsASoundRule`,`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).`)}),j.conditions.occupancy!==void 0&&u(`p`,{className:`mb-2 text-[10px] text-foreground-subtle`,children:O(`system.notificationRules.thisIsAnOccupancyRule`,`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.`)}),fe&&u(`p`,{className:`mb-2 text-[10px] text-foreground-subtle`,children:O(`system.notificationRules.pickTheEventsThisRule`,`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:O(`system.notificationRules.conditionCatalogUnavailableThisRule`,`Condition catalog unavailable — this rule matches on its trigger and targets alone.`)}):u(ks,{catalog:cn(j)?s.filter(e=>e.id!==`schedule`):s,taxonomy:d,delivery:j.delivery,conditions:j.conditions,classScope:j.classScope,onClassScopeChange:e=>z({classScope:e}),actions:vr(j.actions),sequenceActionsOf:e=>v.find(t=>t.id===e)?.actions,savedConditions:A.conditions,schedule:j.schedule,deviceIds:rn(j),zoneCameraIds:Ko(j.deviceScope,p),cameras:p,fleet:_,allDevices:g,gateable:m,gateableScenes:h,onConditionsChange:e=>z({conditions:e}),onScheduleChange:e=>z({schedule:e})})]}),fe&&u(Yf,{value:j.systemEventDelivery,family:he,onChange:e=>z({systemEventDelivery:e}),draft:()=>Ft(j,ne,s)}),k&&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:O(`system.notificationRules.testThisRuleForReal`,`Test this rule for real`)}),u(Yc,{ruleId:e.id,ruleName:e.name,variant:`full`,showResult:!0,...rn(j)[0]===void 0?{}:{fallbackDeviceId:rn(j)[0]}})]}),u(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:O(`system.notificationRules.buildsTheEventThisRule`,`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.`)})]}),!fe&&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:O(`system.notificationRules.testRule`,`Test rule`)}),n(W,{size:`sm`,variant:`outline`,type:`button`,disabled:V.isPending||!Ut(j,ne,new Set(v.map(e=>e.id))),onClick:()=>{P(null),V.mutate()},children:[V.isPending?u(b,{className:`h-3.5 w-3.5 animate-spin`}):u(w,{className:`h-3.5 w-3.5`}),O(`system.notificationRules.dryRunLast60Min`,`Dry-run (last 60 min)`)]})]}),u(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:O(`system.notificationRules.evaluateTheCurrentUnsavedRule`,`Evaluate the CURRENT (unsaved) rule against recently persisted records — no notification is sent.`)}),L!==null&&u(pp,{delivery:j.delivery,results:L,targetNames:re})]})]})]})}):u(fp,{rule:e,onCancel:T})}function fp({rule:e,onCancel:t}){let{t:r}=Z(),i=Object.keys(e?.conditions??{});return n(wt,{open:!0,onClose:t,title:e?.name??r(`system.notificationRules.rule`,`Rule`),icon:f,width:`lg`,children:[u(J,{variant:`warning`,className:`mb-3`,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:r(`system.notificationRules.trigger`,`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:r(`system.notificationRules.enabled`,`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:r(`system.notificationRules.targets`,`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:r(`system.notificationRules.conditions`,`Conditions`)}),u(`dd`,{className:`text-foreground`,children:i.length>0?i.join(`, `):`none`})]})]})]})}function pp({delivery:e,results:t,targetNames:r}){let{t:i}=Z();if(e===`device-event`)return u(`p`,{className:`mt-2 text-[11px] text-foreground-subtle`,children:i(`system.notificationRules.deviceEventRulesCannotBe`,`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:i(`system.notificationRules.noRecordsInTheLast`,`No records in the last 60 minutes matched — nothing to evaluate.`)});let a=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:[a,` 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(C,{className:`h-3.5 w-3.5 shrink-0 text-success`}):u(D,{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 mp=`mt-1 w-full rounded border border-border bg-background px-2 py-1 text-xs`,hp=`block text-[11px] font-medium text-foreground`,gp=[{value:`cap`,label:`Do`},{value:`wait`,label:`Wait`}],_p=[[`notificationRules`,`listSequences`]],vp=[`sequence`,`new`];function yp(){return{name:``,minDelaySec:``,actions:[wn()]}}function bp(e){return{id:e.id,name:e.name,minDelaySec:e.minDelaySec===void 0?``:String(e.minDelaySec),actions:[...e.actions]}}function xp(e){return e instanceof Error?e.message:String(e)}function Sp(e){let t=[],n=0;for(;n<e.length;){if(e[n].kind===`wait`){t.push({start:n,kind:`wait`,length:1}),n+=1;continue}let r=wo(e,n);t.push({start:n,kind:`cap`,length:r.length}),n+=r.length}return t}function Cp(e){let t=e.actions.length,n=e.minDelaySec===void 0?``:` · min delay ${String(e.minDelaySec)}s`;return`${String(t)} step${t===1?``:`s`}${n}`}function wp({draft:e,devices:t,fleetView:r,onChange:i}){let{t:a}=Z(),o=Sp(e.actions);return n(`div`,{className:`space-y-3`,children:[n(`div`,{className:`flex flex-wrap items-end gap-2`,children:[n(`div`,{className:`min-w-0 flex-1`,children:[u(`label`,{className:hp,children:a(`system.notificationSequences.name`,`Name`)}),u(q,{className:`mt-1`,value:e.name,onChange:t=>i({...e,name:t.target.value})})]}),n(`div`,{className:`w-28`,children:[u(`label`,{className:hp,children:a(`system.notificationSequences.minDelayS`,`Min delay (s)`)}),u(`input`,{type:`number`,min:0,className:mp,value:e.minDelaySec,onChange:t=>i({...e,minDelaySec:t.target.value})})]})]}),n(`div`,{className:`space-y-2 border-l-2 border-border-subtle pl-3`,children:[o.map(o=>{let s=e.actions[o.start];if(o.kind===`wait`&&s.kind===`wait`)return u(Ep,{step:s,devices:t,listState:r.state,fleet:r,onChange:t=>i({...e,actions:e.actions.map((e,n)=>n===o.start?t:e)}),onRemove:()=>i({...e,actions:e.actions.filter((e,t)=>t!==o.start)})},`s-${String(o.start)}`);let c=wo(e.actions,o.start);return n(`div`,{className:`flex flex-wrap items-start gap-2`,children:[n(`div`,{className:`w-24`,children:[u(`label`,{className:hp,children:a(`system.notificationSequences.step`,`Step`)}),u(G,{className:mp,value:`cap`,options:[...gp],onChange:t=>{t.target.value===`wait`&&i({...e,actions:[...e.actions.slice(0,o.start),{kind:`wait`,seconds:5},...e.actions.slice(o.start+o.length)]})}})]}),u(qr,{value:c.wire,devices:t,listState:r.state,fleet:r,allowMultiSameFamily:!0,onChange:t=>{let n=So(t);i({...e,actions:[...e.actions.slice(0,o.start),...n,...e.actions.slice(o.start+o.length)]})}}),u(W,{size:`sm`,variant:`ghost`,type:`button`,title:a(`common.remove`,`Remove`),onClick:()=>i({...e,actions:[...e.actions.slice(0,o.start),...e.actions.slice(o.start+o.length)]}),children:u(p,{className:`h-3.5 w-3.5`})})]},`s-${String(o.start)}`)}),n(W,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>i({...e,actions:[...e.actions,wn()]}),children:[u(g,{className:`h-3.5 w-3.5`}),` Step`]})]})]})}function Tp({createRequested:e=!1,onCreateConsumed:t,headerOwnsCreate:i=!1}={}){let{t:a}=Z(),s=o(),l=lt({}),f=xt(),p=gt(),m=ht(),{state:h,openNew:_,openEdit:v,close:y}=Ke({editKey:`sequence`,newKey:`new`}),[b,x]=c(null),[S,C]=c(null);d(()=>{e&&(C(null),_(),t?.())},[e]);let w=pt({projection:`slim`}),T=St(w),E=r(()=>(w.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)),[w.data]),D=l.data?.sequences??[],O=l.data!==void 0&&D.length===0,k=h.mode!==`closed`,A=f.isPending||p.isPending;d(()=>{if(h.mode===`closed`){x(null),C(null);return}if(h.mode===`new`){x(e=>e!==null&&e.id===void 0?e:yp());return}let e=D.find(e=>e.id===h.id);e!==void 0&&x(t=>t?.id===h.id?t:bp(e))},[h,D]);let j=()=>{s.invalidateQueries({queryKey:_p})},M=()=>{f.reset(),p.reset(),C(null),x(null),y()},N=async()=>{if(b===null||b.name.trim()===``||b.actions.length===0)return;let e={name:b.name.trim(),...b.minDelaySec===``?{}:{minDelaySec:Number(b.minDelaySec)},actions:b.actions};try{b.id===void 0?await f.mutateAsync({sequence:e}):await p.mutateAsync({sequenceId:b.id,sequence:e}),M(),j()}catch(e){C(xp(e))}},P=r(()=>[{key:`name`,header:a(`system.notificationSequences.name`,`Name`),nowrap:!1,sortValue:e=>e.name,render:e=>u(ef,{name:e.name,enabled:!0,onOpen:()=>v(e.id),openTestId:`sequence-open-${e.id}`})},{key:`steps`,header:a(`system.notificationSequences.steps`,`Steps`),nowrap:!0,sortValue:e=>e.actions.length,render:e=>u(`span`,{className:`text-[11px] text-foreground-subtle`,children:Cp(e)})},{key:`actions`,header:``,align:`right`,nowrap:!0,notSortableReason:`Row actions`,render:e=>n(Xd,{className:`flex items-center justify-end gap-1`,children:[u(W,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>v(e.id),children:a(`common.edit`,`Edit`)}),u(tf,{pending:m.isPending,title:a(`system.notificationSequences.deleteThisSequence`,`Delete this sequence?`),message:a(`system.notificationSequences.willBeRemovedRulesAnd`,`“{{name}}” will be removed. Rules and buttons that bind to it keep the id until you re-point them.`,{name:e.name}),ariaLabel:a(`system.notificationSequences.delete`,`Delete {{name}}`,{name:e.name}),testId:`sequence-delete-${e.id}`,onConfirm:()=>{m.mutateAsync({sequenceId:e.id}).then(j)}})]})}],[m,v,a]);return n(Jr,{embedded:!0,icon:I,title:a(`system.notificationSequences.sequences`,`Sequences`),subtitle:a(`system.notificationSequences.namedStepListsSharedBy`,`Named step lists shared by notification rules and buttons. A rule binds to one by id; two rules sharing a gate share its throttle.`),children:[i?null:u(`div`,{className:`mb-3 flex justify-end`,children:n(W,{size:`sm`,type:`button`,onClick:()=>{C(null),_()},children:[u(g,{className:`h-3.5 w-3.5`}),` New sequence`]})}),l.error!=null&&u(K,{title:a(`system.notificationSequences.couldNotReadSequences`,`Could not read sequences`),message:xp(l.error),onRetry:()=>void l.refetch()}),l.isPending&&u(Zd,{}),O&&u(Qd,{testId:`sequences-empty`,children:a(`system.notificationSequences.noSequencesYetCreateOne`,`No sequences yet. Create one, then bind it from a rule's Actions tab.`)}),D.length>0&&u($d,{columns:P,rows:D,rowKey:e=>e.id,minWidthPx:480,onRowClick:e=>v(e.id)}),u(wt,{open:k&&b!==null,onClose:M,title:b?.id===void 0?a(`system.notificationSequences.newSequence`,`New sequence`):a(`system.notificationSequences.edit`,`Edit {{value1}}`,{value1:b.name||`sequence`}),icon:I,width:`xl`,error:S,testId:`sequence-editor-panel`,footer:u(W,{size:`sm`,type:`button`,disabled:A||b===null||b.name.trim()===``||b.actions.length===0,onClick:()=>void N(),children:A?a(`system.notificationSequences.saving`,`Saving…`):a(`common.save`,`Save`)}),children:b!==null&&u(wp,{draft:b,devices:E,fleetView:T,onChange:x})}),m.error!=null&&u(K,{message:xp(m.error)})]})}function Ep({step:e,devices:t,listState:r,fleet:i,onChange:a,onRemove:o}){let{t:s}=Z();return n(`div`,{className:`flex flex-wrap items-start gap-2`,children:[n(`div`,{className:`w-24`,children:[u(`label`,{className:hp,children:s(`system.notificationSequences.step`,`Step`)}),u(G,{className:mp,value:`wait`,options:[...gp],onChange:n=>a(n.target.value===`wait`?{kind:`wait`,seconds:e.seconds}:{kind:`cap`,deviceId:t[0]?.id??0,cap:``,method:``})})]}),n(`div`,{className:`w-28`,children:[u(`label`,{className:hp,children:s(`system.notificationSequences.seconds`,`Seconds`)}),u(`input`,{type:`number`,min:0,max:300,className:mp,value:e.seconds,onChange:e=>a({kind:`wait`,seconds:Number(e.target.value)})})]}),u(W,{size:`sm`,variant:`ghost`,type:`button`,onClick:o,title:s(`common.remove`,`Remove`),children:u(p,{className:`h-3.5 w-3.5`})})]})}var Dp=[{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 Op(e){return Dp.find(t=>t.value===e)?.value}function kp(e){return e===`object-event`||e===`audio-event`?`immediate`:e===`occupancy-event`?`device-event`:e}function Ap(e){return``}var jp={x:.25,y:.25,w:.5,h:.5},Mp={zoneId:``,zoneName:``,className:``,count:1,previousCount:0,occupied:!0,threshold:1};function Np(){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:jp,occupancy:Mp,timestampLocal:``,onlyRuleId:``,bypassCooldown:!1,bypassMute:!1,runActions:!1,still:`live`}}function Pp(e){return e.deviceId!==null}function Fp(e){if(e.trim().length===0)return;let t=Number(e);return Number.isFinite(t)?t:void 0}function Ip(e){if(e.trim().length===0)return;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}function Lp(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 Rp(e){if(e.deviceId===null)return null;let t=e.trigger,n=Ip(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:zp(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 zp(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 Bp(e){return Math.min(1,Math.round((e+.05)*100)/100)}function Vp(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 Hp(e){let t=Np(),n=e.conditions,r=Vp(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:Bp(n.minConfidence)},...n.minLabelConfidence===void 0?{}:{labelConfidence:Bp(n.minLabelConfidence)},...n.minImportance===void 0?{}:{importance:Bp(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:Ap(r),...n.customZones!==void 0&&n.customZones.length>0?{bboxEnabled:!0}:{},...n.occupancy===void 0?{}:{occupancy:Up(n.occupancy)},onlyRuleId:e.id}}function Up(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 Wp(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 Gp(e){return{form:Hp(e),caveats:Wp(e),ruleName:e.name}}var Kp=null;function qp(e){Kp=e}function Jp(){return Kp}function Yp(){Kp=null}var Xp=[`n/a`,`clear`,`suppressed`,`bypassed`],Zp=[`live`,`none`,`unavailable`,`unattachable`];function Qp(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function $p(e,t){let n=e[t];return typeof n==`string`?n:void 0}function em(e,t){let n=e[t];return Array.isArray(n)?n.filter(e=>typeof e==`string`):[]}function tm(e){if(!Qp(e))return null;let t=$p(e,`ruleId`),n=$p(e,`ruleName`),r=$p(e,`cooldown`),i=Xp.find(e=>e===r);if(t===void 0||n===void 0||i===void 0||typeof e.matched!=`boolean`)return null;let a=$p(e,`failedCondition`),o=Array.isArray(e.matchedOn)?em(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:em(e,`targetIds`)}}function nm(e){if(!Qp(e))return null;let t=$p(e,`recordId`),n=$p(e,`delivery`),r=$p(e,`still`),i=Zp.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=tm(e);t!==null&&o.push(t)}let s=$p(e,`droppedBy`);return{recordId:t,origin:`synthetic`,delivery:n,candidates:typeof e.candidates==`number`?e.candidates:0,outcomes:o,still:i,notes:em(e,`notes`),...s===void 0?{}:{droppedBy:s}}}function rm(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 im=new Set([`sensor`,`control`,`custom`]);function am({form:e,cameras:t,taxonomy:r,kinds:i,kindsLoading:a,onPatch:o}){let{t:s}=Z(),c=e.deviceId===null?[]:[e.deviceId],l=ve(`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:s(`system.notificationSimulateFields.whatHappened`,`What happened`)}),u(om,{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:s(`system.notificationSimulateFields.whatHappened`,`What happened`)}),n(`div`,{children:[u(`label`,{className:Q,children:s(`system.notificationSimulateFields.audioClasses`,`Audio classes`)}),u(Et,{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:s(`system.notificationSimulateFields.audioClassId`,`Audio class id…`)})]}),n(`div`,{children:[u(`label`,{className:Q,children:s(`system.notificationSimulateFields.zones`,`Zones`)}),u(Rr,{deviceIds:c,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:s(`system.notificationSimulateFields.whatHappened`,`What happened`)}),u(sm,{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:s(`system.notificationSimulateFields.whatHappened`,`What happened`)}),n(`div`,{children:[u(`label`,{className:Q,children:s(`system.notificationSimulateFields.detectedClasses`,`Detected classes`)}),l===null?u(En,{value:e.classNames,placeholder:s(`system.notificationSimulateFields.classIdPersonCar`,`Class id (person, car…)`),onChange:e=>o({classNames:e})}):u(Mr,{picker:l,value:e.classNames,onChange:e=>o({classNames:e})})]}),n(`div`,{children:[u(`label`,{className:Q,children:s(`system.notificationSimulateFields.zonesTheSubjectIsIn`,`Zones the subject is in`)}),u(Rr,{deviceIds:c,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:s(`system.notificationSimulateFields.packagePhase`,`Package phase`)}),u(G,{value:e.packagePhase,options:[{value:``,label:s(`system.notificationSimulateFields.none`,`— none —`)},{value:`delivered`,label:s(`system.notificationSimulateFields.delivered`,`Delivered`)},{value:`picked-up`,label:s(`system.notificationSimulateFields.pickedUp`,`Picked up`)}],onChange:e=>o({packagePhase:e.target.value===`delivered`?`delivered`:e.target.value===`picked-up`?`picked-up`:``})})]})]})}function om({form:e,kinds:t,loading:r,onPatch:i}){let{t:o}=Z(),s=t.filter(e=>im.has(e.category)),c=s.find(t=>t.kind===e.sensorKind);return n(a,{children:[n(`div`,{children:[u(`label`,{className:Q,children:o(`system.notificationSimulateFields.eventKind`,`Event kind`)}),u(G,{value:e.sensorKind,options:[{value:``,label:r?o(`system.notificationSimulateFields.loadingKinds`,`Loading kinds…`):o(`system.notificationSimulateFields.pickAKind`,`— pick a kind —`)},...s.map(e=>({value:e.kind,label:`${e.label} (${e.category})`}))],onChange:e=>{let t=s.find(t=>t.kind===e.target.value);i({sensorKind:t?.kind??``,sourceDeviceId:t?.source.deviceId??null})}}),!r&&s.length===0&&u(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:e.deviceId===null?o(`system.notificationSimulateFields.pickACameraFirstSensor`,`Pick a camera first — sensor and control kinds come from the devices linked to it.`):o(`system.notificationSimulateFields.thisCameraHasNoLinked`,`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:Q,children:o(`system.notificationSimulateFields.sourceDevice`,`Source device`)}),u(q,{type:`number`,value:e.sourceDeviceId===null?``:String(e.sourceDeviceId),placeholder:o(`system.notificationSimulateFields.theCameraItself`,`the camera itself`),onChange:e=>i({sourceDeviceId:Fp(e.target.value)??null})}),u(`p`,{className:Ln,children:c===void 0?o(`system.notificationSimulateFields.theLinkedDeviceWhoseState`,`The linked device whose state changed. Filled in for you when you pick a kind.`):o(`system.notificationSimulateFields.filledInFromContributedBy`,`Filled in from "{{label}}" — contributed by device #{{deviceId}} via the {{capName}} capability.`,{label:c.label,deviceId:c.source.deviceId,capName:c.source.capName})})]}),n(`div`,{children:[u(`label`,{className:Q,children:o(`system.notificationSimulateFields.eventTypeToken`,`Event type token`)}),u(q,{value:e.eventType,placeholder:o(`system.notificationSimulateFields.pressPressLong`,`press, press_long…`),onChange:e=>i({eventType:e.target.value})}),u(`p`,{className:Ln,children:o(`system.notificationSimulateFields.onlyEventEmitterSourcesCarry`,`Only event-emitter sources carry one. A passive sensor emits none, and a rule gating on a token would fail closed for it.`)})]})]})]})}function sm({form:e,cameras:t,taxonomy:r,onPatch:i}){let{t:o}=Z(),s=e.deviceId===null?[]:[e.deviceId],c=ve(`occupancy`,r),l=c===null?[]:c.groups.flatMap(e=>e.options),d=e.occupancy,f=e=>i({occupancy:{...d,...e}});return n(a,{children:[n(`div`,{children:[u(`label`,{className:Q,children:o(`system.notificationSimulateFields.zone`,`Zone`)}),u(Rr,{deviceIds:s,cameras:t,value:d.zoneId===``?[]:[d.zoneId],onChange:e=>f({zoneId:e[e.length-1]??``})}),u(`p`,{className:Ln,children:o(`system.notificationSimulateFields.leaveEmptyForTheWhole`,`Leave empty for the whole frame.`)})]}),n(`div`,{className:`max-w-[14rem]`,children:[u(`label`,{className:Q,children:o(`system.notificationSimulateFields.class`,`Class`)}),u(G,{value:d.className,options:[{value:``,label:o(`system.notificationSimulateFields.anyClass`,`— any class —`)},...l.map(e=>({value:e.value,label:e.label}))],onChange:e=>f({className:e.target.value})})]}),n(`div`,{className:`flex flex-wrap items-end gap-3`,children:[n(`label`,{className:`text-[11px] text-foreground-subtle`,children:[o(`system.notificationSimulateFields.countNow`,`Count now`),u(q,{type:`number`,min:0,className:`w-20`,value:String(d.count),onChange:e=>f({count:Fp(e.target.value)??0})})]}),n(`label`,{className:`text-[11px] text-foreground-subtle`,children:[o(`system.notificationSimulateFields.countBefore`,`Count before`),u(q,{type:`number`,min:0,className:`w-20`,value:String(d.previousCount),onChange:e=>f({previousCount:Fp(e.target.value)??0})})]}),n(`label`,{className:`text-[11px] text-foreground-subtle`,children:[o(`system.notificationSimulateFields.threshold`,`Threshold`),u(q,{type:`number`,min:1,className:`w-20`,value:String(d.threshold),onChange:e=>f({threshold:Fp(e.target.value)??1})})]}),n(`label`,{className:`flex items-center gap-2 pb-1 text-[11px] text-foreground`,children:[u(ct,{checked:d.occupied,onCheckedChange:e=>f({occupied:e}),"aria-label":`occupied`}),o(`system.notificationSimulateFields.occupied`,`Occupied`)]})]})]})}function cm({form:e,cameras:t,onPatch:r}){let{t:i}=Z(),a=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:i(`system.notificationSimulateFields.advanced`,`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(ct,{checked:e.crossingEnabled,onCheckedChange:e=>r({crossingEnabled:e}),"aria-label":i(`system.notificationSimulateFields.zoneCrossing`,`zone crossing`)}),i(`system.notificationSimulateFields.thisEventIsAConfirmed`,`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(G,{value:e.crossingDirection,options:[{value:`enter`,label:i(`system.notificationSimulateFields.enteredTheZone`,`Entered the zone`)},{value:`exit`,label:i(`system.notificationSimulateFields.leftTheZone`,`Left the zone`)}],onChange:e=>r({crossingDirection:e.target.value===`exit`?`exit`:`enter`})})}),u(Rr,{deviceIds:a,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(ct,{checked:e.bboxEnabled,onCheckedChange:e=>r({bboxEnabled:e}),"aria-label":i(`system.notificationSimulateFields.boundingBox`,`bounding box`)}),i(`system.notificationSimulateFields.carryABoundingBox`,`Carry a bounding box`)]}),u(`p`,{className:Ln,children:i(`system.notificationSimulateFields.normalized01TopLeft`,"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(q,{type:`number`,min:0,max:1,step:.05,className:`w-20`,value:String(e.bbox[t]),onChange:n=>r({bbox:{...e.bbox,[t]:Fp(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:Q,children:i(`system.notificationSimulateFields.happenedAt`,`Happened at`)}),n(`div`,{className:`flex items-center gap-2`,children:[u(q,{type:`datetime-local`,value:e.timestampLocal,onChange:e=>r({timestampLocal:e.target.value})}),e.timestampLocal===``?u(W,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>r({timestampLocal:Lp(Date.now())}),children:i(`system.notificationSimulateFields.set`,`Set`)}):u(W,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>r({timestampLocal:``}),children:i(`system.notificationSimulateFields.now`,`Now`)})]}),u(`p`,{className:Ln,children:i(`system.notificationSimulateFields.emptyNowSetItTo`,`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:Q,children:i(`system.notificationSimulateFields.detectionSource`,`Detection source`)}),u(G,{value:e.source,options:[{value:``,label:i(`system.notificationSimulateFields.unsetReadsAsPipeline`,`— unset (reads as pipeline) —`)},{value:`pipeline`,label:i(`system.notificationSimulateFields.pipeline`,`Pipeline`)},{value:`onboard`,label:i(`system.notificationSimulateFields.onboardCamera`,`Onboard (camera)`)},{value:`sensor`,label:i(`system.notificationSimulateFields.sensor`,`Sensor`)},{value:`audio`,label:i(`system.notificationSimulateFields.audio`,`Audio`)}],onChange:e=>{let t=e.target.value;r({source:t===`pipeline`||t===`onboard`||t===`sensor`||t===`audio`?t:``})}})]})]})]})]})}function lm({checked:e,label:t,hint:r,danger:i=!1,onChange:a}){let{t:o}=Z();return n(`div`,{children:[n(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[u(ct,{checked:e,onCheckedChange:a,"aria-label":t}),t,i&&u(J,{variant:`danger`,children:o(`system.notificationSimulateFields.actuatesDevices`,`actuates devices`)})]}),u(`p`,{className:Ln,children:r})]})}t();var um={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.`},dm={"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 fm({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:rm(e)}),n(`div`,{className:`flex flex-wrap items-center gap-2 text-[11px] text-foreground-subtle`,children:[u(pm,{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:um[e.still],children:[`still `,u(`span`,{className:`text-foreground`,children:e.still})]}),e.droppedBy!==void 0&&n(J,{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(mm,{outcome:e,targetName:t},e.ruleId))})]})}function pm({recordId:e}){let{t}=Z(),[r,i]=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(W,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>{let t=navigator.clipboard;t!==void 0&&t.writeText(e).then(()=>{i(!0),setTimeout(()=>i(!1),1500)},()=>i(!1))},title:t(`system.notificationSimulateResult.copyRecordId`,`Copy record id`),children:u(y,{className:`h-3 w-3`})}),r&&u(`span`,{className:`text-[10px] text-success`,children:`copied`})]})}function mm({outcome:e,targetName:t}){let{t:r}=Z();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(C,{className:`h-3.5 w-3.5 shrink-0 text-success`}):u(D,{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:dm[e.cooldown],children:[`cooldown: `,e.cooldown]})]}),!e.matched&&u(`p`,{className:`pl-5 text-[11px] text-foreground-subtle`,children:e.failedCondition===void 0?r(`system.notificationSimulateResult.didNotMatchTheEngine`,`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 hm=`pipeline-analytics`,gm=`nc.injectTestEvent`;function _m(){let{t:e}=Z(),t=E(),[a,o]=c(()=>Jp()?.form??Np()),[s,f]=c(()=>Jp()?.caveats??[]),[p,m]=c(()=>Jp()?.ruleName??null);d(()=>Yp(),[]);let[g,_]=c(null),[v,y]=c(!1),[x,S]=c(null),C=e=>o(t=>({...t,...e})),T=pt({projection:`slim`}),D=i({queryKey:op,queryFn:()=>t.trpcClient.notificationRules.getConditionCatalog.query({})}),O=i({queryKey:ip,queryFn:async()=>(await t.trpcClient.notificationRules.listRules.query({})).rules}),k=i({queryKey:ap,queryFn:()=>t.trpcClient.notificationOutput.listTargets.query({})}),A=a.deviceId,j=i({queryKey:[[`pipelineAnalytics`,`listEventKindsBatch`],{deviceId:A}],enabled:A!==null,staleTime:6e4,queryFn:async()=>A===null?[]:(await t.trpcClient.pipelineAnalytics.listEventKindsBatch.query({deviceIds:[A]})).flatMap(e=>[...e.kinds])}),M=r(()=>(T.data??[]).filter(e=>e.type===ce.Camera).map(e=>({id:e.id,name:e.name})),[T.data]),N=D.data?.taxonomy,P=j.data??[],F=r(()=>{let e=new Map;for(let t of k.data??[])e.set(t.id,t.name);return e},[k.data]),I=l({mutationFn:async()=>{let e=Rp(a);if(e===null)throw Error(`Pick a camera first.`);return t.trpcClient.addons.custom.mutate({addonId:hm,action:gm,input:e})},onMutate:()=>{_(null),y(!1),S(null)},onSuccess:e=>{let t=nm(e);_(t),y(t===null)},onError:e=>S(e instanceof Error?e.message:`The simulation failed.`)}),L=kp(a.trigger),ee=O.data?.find(e=>e.id===a.onlyRuleId);return n(Jr,{embedded:!0,icon:w,title:e(`system.notificationSimulate.simulateAnEvent`,`Simulate an event`),subtitle:e(`system.notificationSimulate.injectASyntheticDetectionDoorbell`,`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:[T.isError&&u(K,{title:e(`system.notificationSimulate.failedToLoadCameras`,`Failed to load cameras`),message:T.error instanceof Error?T.error.message:e(`system.notificationSimulate.unknownError`,`Unknown error`),onRetry:()=>void T.refetch()}),p!==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:p}),`. Only that rule will be evaluated — clear "Evaluate only one rule" below to run the whole rule set.`]}),s.length>0&&u(`div`,{className:`space-y-1 rounded-md border border-warning/40 bg-warning/5 px-3 py-2`,children:s.map(e=>n(`p`,{className:`flex gap-1.5 text-[11px] text-foreground`,children:[u(h,{className:`mt-0.5 h-3 w-3 shrink-0 text-warning`}),u(`span`,{children:e.note})]},e.conditionId))}),n(qe,{className:`space-y-4`,children:[n(`div`,{children:[u(`label`,{className:Q,children:e(`system.notificationSimulate.ruleToSimulate`,`Rule to simulate`)}),u(G,{"data-testid":`simulate-seed-rule`,value:a.onlyRuleId,options:[{value:``,label:e(`system.notificationSimulate.pickARuleToPrefill`,`— pick a rule to prefill trigger + conditions —`)},...(O.data??[]).map(e=>({value:e.id,label:`${e.name} · ${e.delivery}`}))],onChange:e=>{let t=e.target.value;if(t.length===0){o(Np()),f([]),m(null);return}let n=O.data?.find(e=>e.id===t);if(n===void 0){C({onlyRuleId:t});return}o(Hp(n)),f(Wp(n)),m(n.name)}}),u(`p`,{className:Ln,children:e(`system.notificationSimulate.picksTheTriggerThatRule`,`Picks the trigger that rule listens for and fills the fields from its conditions. Edit any value below, then inject.`)})]}),n(`div`,{children:[u(`label`,{className:Q,children:e(`system.notificationSimulate.camera`,`Camera`)}),u(G,{"data-testid":`simulate-camera`,value:a.deviceId===null?``:String(a.deviceId),options:[{value:``,label:M.length===0?e(`system.notificationSimulate.loadingCameras`,`Loading cameras…`):e(`system.notificationSimulate.pickACamera`,`— pick a camera —`)},...M.map(e=>({value:String(e.id),label:e.name}))],onChange:e=>{C({deviceId:Fp(e.target.value)??null,zones:[],crossingZoneId:``,sensorKind:``,sourceDeviceId:null,occupancy:{...a.occupancy,zoneId:``}})}}),u(`p`,{className:Ln,children:e(`system.notificationSimulate.theCameraTheEventIs`,`The camera the event is attributed to — what a notification shows.`)})]}),n(`div`,{children:[u(`label`,{className:Q,children:e(`system.notificationSimulate.trigger`,`Trigger`)}),u(G,{"data-testid":`simulate-trigger`,value:a.trigger,options:Dp.map(e=>({value:e.value,label:e.label})),onChange:e=>{let t=Op(e.target.value);if(!t)return;let n=Ap(a.trigger);C({trigger:t,source:a.source===``||a.source===n?Ap(t):a.source})}}),n(`p`,{className:Ln,children:[Dp.find(e=>e.value===a.trigger)?.hint,` Only rules whose trigger is `,u(`span`,{className:`text-foreground`,children:L}),` are candidates.`]})]}),u(am,{form:a,cameras:M,taxonomy:N,kinds:P,kindsLoading:j.isLoading,onPatch:C}),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:e(`system.notificationSimulate.quality`,`Quality`)}),n(`div`,{className:`mt-2 space-y-3`,children:[u(`p`,{className:Ln,children:e(`system.notificationSimulate.everyFieldHereCanBe`,`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:Q,children:e(`system.notificationSimulate.labelIdentityNamePlateSubclass`,`Label (identity name / plate / subclass)`)}),u(q,{value:a.label,placeholder:e(`system.notificationSimulate.eGMarcoAb123cd`,`e.g. Marco, AB123CD`),onChange:e=>C({label:e.target.value})})]}),n(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[n(`div`,{children:[u(`label`,{className:Q,children:e(`system.notificationSimulate.detectionConfidence`,`Detection confidence`)}),u(hr,{value:a.confidence,min:0,max:1,step:.05,onChange:e=>C({confidence:e})})]}),n(`div`,{children:[u(`label`,{className:Q,children:e(`system.notificationSimulate.labelMatchConfidence`,`Label-match confidence`)}),u(hr,{value:a.labelConfidence,min:0,max:1,step:.05,onChange:e=>C({labelConfidence:e})})]}),n(`div`,{children:[u(`label`,{className:Q,children:e(`system.notificationSimulate.importance`,`Importance`)}),u(hr,{value:a.importance,min:0,max:1,step:.05,onChange:e=>C({importance:e})})]}),n(`div`,{children:[u(`label`,{className:Q,children:e(`system.notificationSimulate.dwellSeconds`,`Dwell (seconds)`)}),u(hr,{value:a.dwellSeconds,min:0,step:1,onChange:e=>C({dwellSeconds:e})})]})]})]})]}),u(cm,{form:a,cameras:M,onPatch:C}),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:e(`system.notificationSimulate.howToRunIt`,`How to run it`)}),u(lm,{checked:a.bypassCooldown,label:e(`system.notificationSimulate.ignoreTheCooldown`,`Ignore the cooldown`),hint:e(`system.notificationSimulate.aRuleThatAlreadyFired`,`A rule that already fired recently is normally silenced. Turn this on to fire anyway; leave it off to SEE the suppression.`),onChange:e=>C({bypassCooldown:e})}),u(lm,{checked:a.bypassMute,label:e(`system.notificationSimulate.ignoreMutesAndSnoozes`,`Ignore mutes and snoozes`),hint:e(`system.notificationSimulate.aMutedCameraOrA`,`A muted camera or a snoozed rule drops the event before any rule is consulted.`),onChange:e=>C({bypassMute:e})}),u(lm,{checked:a.runActions,danger:!0,label:e(`system.notificationSimulate.runTheRuleSActions`,`Run the rule's actions — this actuates real devices`),hint:e(`system.notificationSimulate.aMatchedRuleSOntrigger`,`A matched rule's onTrigger sequences run for real: locks unlock, lights switch, sirens sound. Off unless you mean it.`),onChange:e=>C({runActions:e})}),n(`div`,{className:`max-w-[14rem]`,children:[u(`label`,{className:Q,children:e(`system.notificationSimulate.stillImage`,`Still image`)}),u(G,{value:a.still,options:[{value:`live`,label:e(`system.notificationSimulate.liveSnapshotOfTheCamera`,`Live snapshot of the camera`)},{value:`none`,label:e(`system.notificationSimulate.noImage`,`No image`)}],onChange:e=>C({still:e.target.value===`none`?`none`:`live`})})]}),n(`div`,{children:[u(`label`,{className:Q,children:e(`system.notificationSimulate.evaluateOnlyOneRule`,`Evaluate only one rule`)}),u(G,{value:a.onlyRuleId,options:[{value:``,label:e(`system.notificationSimulate.everyEnabledRule`,`— every enabled rule —`)},...(O.data??[]).map(e=>({value:e.id,label:e.name}))],onChange:e=>C({onlyRuleId:e.target.value})}),a.onlyRuleId.length>0&&ee===void 0&&n(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:[`Rule `,u(`code`,{children:a.onlyRuleId}),` is not in the current list — it may have been deleted. The run will find no candidate.`]})]})]}),x!==null&&u(`div`,{className:`rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger`,children:x}),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:e(`system.notificationSimulate.nothingIsPersistedNoTrack`,`Nothing is persisted: no track, no event row, no stored media. Delivery is real.`)}),n(W,{size:`sm`,type:`button`,disabled:I.isPending||!Pp(a),onClick:()=>I.mutate(),children:[I.isPending?u(b,{className:`h-3.5 w-3.5 animate-spin`}):u(w,{className:`h-3.5 w-3.5`}),e(`system.notificationSimulate.injectEvent`,`Inject event`)]})]})]}),v&&u(`div`,{className:`rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-[11px] text-foreground`,children:e(`system.notificationSimulate.theHubAnsweredButThis`,`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.`)}),g!==null&&u(fm,{result:g,targetName:e=>F.get(e)??e})]})}var vm=e=>typeof e==`string`&&e.length>0;function ym(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 bm(e,t){return e.format.includes(t)?t:e.format[0]??`text`}function xm(e,t){let n=[];for(let r of e.attachments.mediaTypes){if(n.length>=e.attachments.max)break;let i=t[r];vm(i)&&n.push({mediaType:r,url:i})}return n}function Sm(e,t){if(e.actions<=0)return[];let n=[];for(let r of t){if(n.length>=e.actions)break;let t=vm(r.label),i=vm(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 Cm(e,t){let n=e.levels.some(e=>e.id===t.level)?t.level:void 0,r=xm(e,t.attachmentUrls),i=Sm(e,t.actions),a=e.ttl&&vm(t.ttl)?Number(t.ttl):void 0;return{body:t.body,format:bm(e,t.format),priority:wm(t.priority),...vm(t.title)?{title:t.title}:{},...n?{level:n}:{},...r.length>0?{attachments:r}:{},...i.length>0?{actions:i}:{},...e.clickUrl&&vm(t.clickUrl)?{clickUrl:t.clickUrl}:{},...e.sound&&vm(t.sound)?{sound:t.sound}:{},...a!==void 0&&Number.isFinite(a)?{ttl:a}:{},...vm(t.tag)?{tag:t.tag}:{}}}function wm(e){return Number.isFinite(e)?Math.min(5,Math.max(1,Math.round(e))):3}function Tm(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 Em(e){return{level:``,priority:3,format:e.format[0]??`text`,title:``,body:``,attachmentUrls:{},actions:[],clickUrl:``,sound:``,ttl:``,tag:``}}var Dm={image:v(`/addon/notifiers/samples/image`),video:v(`/addon/notifiers/samples/video`),gif:v(`/addon/notifiers/samples/gif`),audio:v(`/addon/notifiers/samples/audio`),icon:v(`/addon/notifiers/samples/icon`)};function Om(e,t){return e.attachments.max>0&&e.attachments.mediaTypes.includes(t)}function km(e){let t=[`text`];for(let n of[`image`,`gif`,`video`,`audio`])Om(e,n)&&t.push(n);return e.actions>0&&t.push(`actions`),e.levels.length>0&&t.push(`critical`),t.push(`overflow`),t}function Am(e,t,n){let r=Em(e);return Om(e,t)?{...r,body:n,attachmentUrls:{[t]:Dm[t]}}:{...r,body:n}}function jm(e,t){let n=Em(e);switch(t){case`text`:return{...n,title:`CamStack`,body:`Test notification — text only.`};case`image`:return Am(e,`image`,`Test notification with an image.`);case`gif`:return Am(e,`gif`,`Test notification with an animation.`);case`video`:return Am(e,`video`,`Test notification with a video.`);case`audio`:return Am(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=Tm(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 Mm={text:`Text only`,image:`With image`,gif:`With GIF`,video:`With video`,audio:`With audio`,actions:`With buttons`,critical:`Critical`,overflow:`Overflow (advanced)`},Nm=`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`,Pm=`block text-[11px] font-medium text-foreground mb-1`;function Fm({target:e,kind:t,open:i,onClose:a}){let{t:o}=Z(),s=E(),d=r(()=>ym(t.caps),[t.caps]),f=r(()=>km(t.caps),[t.caps]),[p,m]=c(()=>Em(t.caps)),[h,g]=c(null),_=r(()=>Cm(t.caps,p),[t.caps,p]),v=p.body.length,y=v>d.bodyMaxLen,x=e=>m(t=>({...t,...e})),S=l({mutationFn:()=>s.trpcClient.notificationOutput.testTarget.mutate({addonId:e.addonId,targetId:e.id,sample:Cm(t.caps,p)}),onMutate:()=>g(null),onSuccess:e=>g(e),onError:e=>g({success:!1,error:e instanceof Error?e.message:`Test failed`})}),C=e=>{m(jm(t.caps,e)),g(null)},w=(e,t,n)=>{let r=p.actions.length>0?[...p.actions]:[];for(;r.length<=e;)r.push({label:``,url:``});r[e]={...r[e],[t]:n},x({actions:r})};return u(Xe,{open:i,onOpenChange:e=>!e&&a(),children:n(He,{width:`lg`,className:`!max-w-2xl`,scroll:`body`,children:[u(Ve,{children:n(ut,{children:[`Test "`,e.name,`" (`,t.label,`)`]})}),n(Ue,{className:`space-y-4 pr-1`,children:[u(`div`,{className:`flex flex-wrap gap-1.5`,children:f.map(e=>u(W,{size:`sm`,variant:`outline`,type:`button`,onClick:()=>C(e),children:Mm[e]},e))}),n(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[d.levels.length>0&&n(`div`,{children:[u(`label`,{className:Pm,children:o(`system.notificationTestPanel.level`,`Level`)}),n(`select`,{className:Nm,value:p.level,onChange:e=>x({level:e.target.value}),children:[u(`option`,{value:``,children:o(`system.notificationTestPanel.deriveFromPriority`,`— derive from priority —`)}),d.levels.map(e=>n(`option`,{value:e.id,children:[e.label,e.ordinal===null?` (qualitative)`:` (p${e.ordinal})`]},e.id))]}),(()=>{let e=d.levels.find(e=>e.id===p.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(J,{variant:`danger`,"data-testid":`flag-critical`,children:`critical`}),e.flags?.silent&&u(J,{variant:`info`,children:`silent`}),e.flags?.noPush&&u(J,{variant:`warning`,children:`no-push`})]}),e.requires&&e.requires.length>0&&n(`p`,{className:`text-[10px] text-warning`,children:[o(`system.notificationTestPanel.requiresTargetConfig`,`Requires target config:`),` `,e.requires.join(`, `)]})]}):null})()]}),n(`div`,{children:[n(`label`,{className:Pm,children:[o(`system.notificationTestPanel.priorityOrdinal`,`Priority (ordinal):`),` `,p.priority]}),u(`input`,{type:`range`,min:1,max:5,step:1,value:p.priority,onChange:e=>x({priority:Number(e.target.value)}),className:`w-full accent-primary`,"aria-label":`priority`})]})]}),d.formats.length>0&&n(`div`,{children:[u(`label`,{className:Pm,children:o(`system.notificationTestPanel.format`,`Format`)}),u(`div`,{className:`flex flex-wrap gap-2`,children:d.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:p.format===e,onChange:()=>x({format:e})}),e]},e))})]}),n(`div`,{children:[u(`label`,{className:Pm,children:o(`system.notificationTestPanel.title`,`Title`)}),u(`input`,{className:Nm,value:p.title,onChange:e=>x({title:e.target.value})})]}),n(`div`,{children:[n(`label`,{className:Pm,children:[`Body`,` `,n(`span`,{className:y?`text-danger`:`text-foreground-subtle`,children:[`(`,v,`/`,d.bodyMaxLen,y?` — overflow`:``,`)`]})]}),u(`textarea`,{className:`${Nm} min-h-[80px] resize-y`,value:p.body,onChange:e=>x({body:e.target.value})})]}),d.attachmentSlots.length>0&&n(`div`,{children:[n(`label`,{className:Pm,children:[`Attachments`,` `,n(`span`,{className:`text-foreground-subtle`,children:[o(`system.notificationTestPanel.mode`,`(mode:`),` `,d.attachmentMode,`, max`,` `,d.attachmentMax,d.attachmentMaxBytes?o(`system.notificationTestPanel.mb`,`, ≤{{value1}}MB`,{value1:Math.round(d.attachmentMaxBytes/1024/1024)}):``,`)`]})]}),u(`div`,{className:`space-y-1.5`,children:d.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:Nm,placeholder:o(`system.notificationTestPanel.url`,`{{mt}} URL`,{mt:e}),value:p.attachmentUrls[e]??``,onChange:t=>x({attachmentUrls:{...p.attachmentUrls,[e]:t.target.value}})})]},e))})]}),d.showActions&&n(`div`,{children:[n(`label`,{className:Pm,children:[`Actions (up to `,d.maxActions,`)`]}),u(`div`,{className:`space-y-1.5`,children:Array.from({length:Math.min(d.maxActions,3)},(e,t)=>n(`div`,{className:`flex items-center gap-2`,children:[u(`input`,{className:Nm,placeholder:`label`,value:p.actions[t]?.label??``,onChange:e=>w(t,`label`,e.target.value)}),u(`input`,{className:Nm,placeholder:`url`,value:p.actions[t]?.url??``,onChange:e=>w(t,`url`,e.target.value)})]},t))})]}),n(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[d.showClickUrl&&n(`div`,{children:[u(`label`,{className:Pm,children:o(`system.notificationTestPanel.clickUrl`,`Click URL`)}),u(`input`,{className:Nm,value:p.clickUrl,onChange:e=>x({clickUrl:e.target.value})})]}),d.showSound&&n(`div`,{children:[u(`label`,{className:Pm,children:o(`system.notificationTestPanel.sound`,`Sound`)}),u(`input`,{className:Nm,value:p.sound,onChange:e=>x({sound:e.target.value})})]}),d.showTtl&&n(`div`,{children:[u(`label`,{className:Pm,children:o(`system.notificationTestPanel.ttlSeconds`,`TTL (seconds)`)}),u(`input`,{className:Nm,type:`number`,value:p.ttl,onChange:e=>x({ttl:e.target.value})})]}),d.showTag&&n(`div`,{children:[u(`label`,{className:Pm,children:o(`system.notificationTestPanel.tag`,`Tag`)}),u(`input`,{className:Nm,value:p.tag,onChange:e=>x({tag:e.target.value})})]})]}),h&&u(Im,{result:h}),n(`details`,{className:`text-[10px]`,children:[u(`summary`,{className:`cursor-pointer text-foreground-subtle`,children:o(`system.notificationTestPanel.payloadPreview`,`Payload preview`)}),u(`pre`,{className:`mt-1 overflow-x-auto rounded bg-surface p-2 text-foreground-subtle`,children:JSON.stringify(_,null,2)})]})]}),n(dt,{children:[u(W,{variant:`secondary`,size:`sm`,type:`button`,onClick:a,children:o(`common.close`,`Close`)}),n(W,{size:`sm`,type:`button`,disabled:S.isPending||p.body.length===0,onClick:()=>S.mutate(),children:[S.isPending?u(b,{className:`h-3.5 w-3.5 animate-spin`}):u(L,{className:`h-3.5 w-3.5`}),o(`system.notificationTestPanel.sendTest`,`Send test`)]})]})]})})}function Im({result:e}){let{t}=Z(),r=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(C,{className:`h-3.5 w-3.5 text-success`}):u(D,{className:`h-3.5 w-3.5 text-danger`}),u(`span`,{children:e.success?t(`system.notificationTestPanel.delivered`,`Delivered`):t(`system.notificationTestPanel.failed`,`Failed`)})]}),e.error&&u(`p`,{className:`mt-1 text-danger`,children:e.error}),r&&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:t(`system.notificationTestPanel.resolvedLevel`,`Resolved level`)}),u(`dd`,{className:`text-foreground`,children:r.level}),u(`dt`,{children:t(`system.notificationTestPanel.formatSent`,`Format sent`)}),u(`dd`,{className:`text-foreground`,children:r.format}),u(`dt`,{children:t(`system.notificationTestPanel.attachmentsSent`,`Attachments sent`)}),u(`dd`,{className:`text-foreground`,children:r.attachmentsSent}),u(`dt`,{children:t(`system.notificationTestPanel.actionsSent`,`Actions sent`)}),u(`dd`,{className:`text-foreground`,children:r.actionsSent}),u(`dt`,{children:t(`system.notificationTestPanel.truncated`,`Truncated`)}),u(`dd`,{className:`text-foreground`,children:r.truncated?`yes`:`no`}),u(`dt`,{children:t(`system.notificationTestPanel.dropped`,`Dropped`)}),u(`dd`,{className:`text-foreground`,children:r.dropped.length>0?r.dropped.join(`, `):`—`})]})]})}function Lm(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 Rm(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 zm(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 Bm=`••••••••`;function Vm(e){return e===`••••••••`||e===`__redacted__`}function Hm(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===``||Vm(n)||(i[t]=n)}return i}function Um(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!==``?Bm:``}return r}function Wm(e){return{...e}}var Gm=[`Refusing to reuse the stored secret`,`Re-enter the secret`];function Km(e){return Gm.some(t=>e.includes(t))}function qm(e){return e==null||e===``?``:typeof e==`string`?e:JSON.stringify(e)}function Jm(e,t,n){let r=new Set(n);return[...new Set([...Object.keys(e),...Object.keys(t)])].filter(n=>!r.has(n)&&qm(e[n])!==qm(t[n]))}function Ym(e,t,n,r){if(r===void 0)return Jm(e,t,n);let i=new Set(n),a=Hm(e,t,n);return r.filter(n=>i.has(n)?n in a:qm(e[n])!==qm(t[n]))}function Xm(e,t,n){let r=Hm(e,t,n);return n.filter(e=>!(e in r))}function Zm(e,t){return e.map(e=>e.type===`password`&&t.has(e.key)?{...e,required:!0}:e.type===`group`?{...e,fields:Zm(e.fields,t)}:e.type===`sub-tabs`?{...e,tabs:e.tabs.map(e=>({...e,fields:Zm(e.fields,t)}))}:e)}function Qm(e,t){if(t.length===0)return e;let n=new Set(t);return{...e,sections:e.sections.map(e=>({...e,fields:Zm(e.fields,n)}))}}function $m(e){let t=e.trim();return t.length===0?`Copy`:`${t} Copy`}function eh(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:eh(e.fields,t)}:e.type===`sub-tabs`?{...e,tabs:e.tabs.map(e=>({...e,fields:eh(e.fields,t)}))}:e)}function th(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:eh(e.fields,r)}))}}var nh=`target`,rh=`kind`,ih=[nh,rh];function ah({refusal:e,edited:t,reenter:r}){let{t:i}=Z(),a=r.length>0?`Re-type: ${r.join(`, `)}.`:null;return e===null?t.length===0||a===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. `,a]}):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:i(`system.targetSecretNotice.theHubNeedsTheSecret`,`The hub needs the secret again — nothing was saved.`)}),u(`p`,{className:`mt-1`,children:e}),a===null?null:u(`p`,{className:`mt-1 font-medium`,children:a})]})}t();var oh=[`notificationOutput`,`listTargets`],sh=[`notificationOutput`,`listTargetKinds`],ch=[`userManagement`,`listUsers`],lh=`ownerUserId`;function uh(e){let t=e.config[lh];return typeof t==`string`&&t.length>0?t:null}function dh(e){return[{key:`name`,header:X.t(`system.notificationTargets.target`,`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(fh,{kind:r,imgClassName:`h-5 w-5 object-contain`,fallbackClassName:``})}),u(ef,{name:t.name,enabled:t.enabled,...r===void 0?{}:{onOpen:()=>e.onOpen(t,r)}})]})}},{key:`kind`,header:X.t(`system.notificationTargets.kind`,`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:X.t(`system.notificationTargets.owner`,`Owner`),nowrap:!0,render:t=>{let n=uh(t);return n===null?u(J,{variant:`default`,children:`system`}):u(`span`,{className:`text-[11px] text-foreground`,children:e.userNameById.get(n)??n})}},{key:`enabled`,header:X.t(`system.notificationTargets.on`,`On`),align:`center`,nowrap:!0,render:t=>u(Xd,{children:u(ct,{checked:t.enabled,onCheckedChange:n=>e.onToggle(t,n),"aria-label":X.t(`system.notificationTargets.toggle`,`toggle {{name}}`,{name:t.name})})})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:t=>{let r=e.kindByKey.get(t.kind);return n(Xd,{className:`flex items-center justify-end gap-1`,children:[u(W,{size:`sm`,variant:`ghost`,type:`button`,disabled:!r,onClick:()=>e.onTest(t),title:X.t(`system.notificationTargets.test`,`Test`),children:u(L,{className:`h-3.5 w-3.5`})}),u(W,{size:`sm`,variant:`ghost`,type:`button`,disabled:!r,onClick:()=>r&&e.onDuplicate(t,r),title:X.t(`system.notificationTargets.duplicate`,`Duplicate`),children:u(y,{className:`h-3.5 w-3.5`})}),u(W,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onDelete(t),title:X.t(`common.delete`,`Delete`),children:u(p,{className:`h-3.5 w-3.5 text-danger`})})]})}}]}function fh({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 ph({createRequested:t=!1,onCreateConsumed:a,headerOwnsCreate:o=!1}={}){let{t:s}=Z(),f=E(),{state:p,openEdit:m,close:h}=Ke({editKey:`target`}),[v,y]=Je(rh),[b,x]=c({mode:`closed`}),[S,C]=c(null),w=e(null),T=i({queryKey:oh,queryFn:()=>f.trpcClient.notificationOutput.listTargets.query({})}),D=i({queryKey:sh,queryFn:async()=>(await f.trpcClient.notificationOutput.listTargetKinds.query({})).map(e=>{let t=e.iconUrl;return{...e,configSchema:e.configSchema,iconUrl:t}})}),O=r(()=>D.data??[],[D.data]),k=r(()=>{let e=new Map;for(let t of O)e.set(t.kind,t);return e},[O]),A=i({queryKey:ch,queryFn:()=>f.trpcClient.userManagement.listUsers.query()}),j=r(()=>{let e=new Map;for(let t of A.data??[])e.set(t.id,t.username);return e},[A.data]),M=l({mutationFn:e=>f.trpcClient.notificationOutput.setTargetEnabled.mutate({addonId:e.target.addonId,targetId:e.target.id,enabled:e.enabled}),onSuccess:()=>void T.refetch()}),N=l({mutationFn:e=>f.trpcClient.notificationOutput.deleteTarget.mutate({addonId:e.addonId,targetId:e.id}),onSuccess:()=>void T.refetch()}),P=S?k.get(S.kind):void 0,F=()=>{p.mode===`edit`&&(w.current=p.id),x({mode:`closed`}),h(),y(null)},I=()=>{w.current=`new`,x({mode:`pick-kind`}),m(`new`),y(null)};d(()=>{t&&(I(),a?.())},[t]);let L=e=>{w.current=`new:${e.kind}`,x({mode:`form`,kind:e,target:null,cloneFrom:null}),m(`new`),y(e.kind)},ee=(e,t)=>{w.current=e.id,x({mode:`form`,kind:t,target:e,cloneFrom:null}),m(e.id),y(null)};return d(()=>{if(b.mode!==`closed`)return;if(p.mode!==`edit`){p.mode===`closed`&&(w.current=null);return}let e=p.id;if(w.current===e)return;if(e===`new`){if(v===null||v.length===0){w.current=`new`,x({mode:`pick-kind`});return}let e=k.get(v);if(e===void 0)return;w.current=`new:${v}`,x({mode:`form`,kind:e,target:null,cloneFrom:null});return}let t=T.data?.find(t=>t.id===e);if(t===void 0)return;let n=k.get(t.kind);n!==void 0&&(w.current=e,x({mode:`form`,kind:n,target:t,cloneFrom:null}))},[b.mode,p,v,T.data,k]),n(Jr,{embedded:!0,icon:_,title:s(`system.notificationTargets.notificationTargets`,`Notification Targets`),subtitle:s(`system.notificationTargets.deliverNotificationsToNtfyPushover`,`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.`),children:[o?null:u(`div`,{className:`mb-3 flex justify-end`,children:n(W,{size:`sm`,type:`button`,onClick:I,children:[u(g,{className:`h-3.5 w-3.5`}),s(`system.notificationTargets.addTarget`,`Add target`)]})}),T.isLoading&&u(Zd,{}),T.isError&&!T.isLoading&&u(K,{title:s(`system.notificationTargets.failedToLoadTargets`,`Failed to load targets`),message:T.error instanceof Error?T.error.message:s(`system.notificationTargets.unknownError`,`Unknown error`),onRetry:()=>void T.refetch()}),!T.isLoading&&!T.isError&&(T.data??[]).length===0&&u(Qd,{children:s(`system.notificationTargets.noNotificationTargetsYetClick`,`No notification targets yet. Click "Add target" to configure one.`)}),(T.data??[]).length>0&&u($d,{columns:dh({kindByKey:k,userNameById:j,onToggle:(e,t)=>M.mutate({target:e,enabled:t}),onTest:C,onOpen:ee,onDuplicate:(e,t)=>{w.current=`new:${t.kind}`,x({mode:`form`,kind:t,target:null,cloneFrom:e}),m(`new`),y(t.kind)},onDelete:e=>N.mutate(e)}),rows:T.data??[],rowKey:e=>e.id,minWidthPx:720,onRowClick:e=>{let t=k.get(e.kind);t!==void 0&&ee(e,t)}}),b.mode===`pick-kind`&&u(mh,{kinds:O,onCancel:F,onPick:L}),b.mode===`form`&&u(hh,{kind:b.kind,target:b.target,cloneFrom:b.cloneFrom,users:A.data??[],onCancel:F,onSaved:()=>{F(),T.refetch()}},b.target?.id??(b.cloneFrom===null?`new:${b.kind.kind}`:`dup:${b.cloneFrom.id}`)),S&&P&&u(Fm,{target:S,kind:P,open:!0,onClose:()=>C(null)})]})}function mh({kinds:e,onPick:t,onCancel:i}){let{t:a}=Z(),o=r(()=>Lm(e),[e]);return u(wt,{open:!0,onClose:i,title:a(`system.notificationTargets.chooseANotificationKind`,`Choose a notification kind`),width:`lg`,children:n(`div`,{className:`space-y-4`,children:[o.length===0&&u(`p`,{className:`text-xs text-foreground-subtle`,children:a(`system.notificationTargets.noNotificationProvidersAreInstalled`,`No notification providers are installed. Install the notifiers addon (or connect Home Assistant) to add targets.`)}),o.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(fh,{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 hh({kind:e,target:t,cloneFrom:i,users:o,onSaved:s,onCancel:f}){let{t:p}=Z(),m=E(),h=r(()=>Rm(e.configSchema),[e.configSchema]),g=t??i,v=t?.id??i?.id,[y,x]=c(()=>i===null?t?.name??e.label:$m(i.name)),[S,C]=c(()=>g?.config??{}),[w,T]=c(()=>g?Um(g.config,h):{}),[D,O]=c(v===void 0),[k,A]=c(null),[j,M]=c(null),[N,P]=c(g?uh(g)??``:``);d(()=>{if(v===void 0)return;let t=!1;return m.trpcClient.notificationOutput.getTarget.query({addonId:e.addonId,targetId:v}).then(e=>{if(t)return;let n=Wm(e.config);C(n),T(n),P(uh(e)??``),O(!0)}).catch(e=>{t||(A(e instanceof Error?e.message:`Failed to load target secrets`),O(!0))}),()=>{t=!0}},[v,e.addonId,m.trpcClient]);let F=()=>Hm(w,S,h),[I,ee]=c(null),te=e.kind===`whatsapp`,R=l({mutationFn:()=>m.trpcClient.notificationOutput.probeTargetConfig.mutate({addonId:e.addonId,kind:e.kind,config:F(),...v===void 0?{}:{targetId:v}}),onSuccess:e=>ee(e),onError:e=>{ee(null),A(e instanceof Error?e.message:`Connection test failed`)}}),z=l({mutationFn:()=>{let{[lh]:n,...r}=Hm(w,S,h),a=N===``?r:{...r,[lh]:N},o={id:t?.id??`${e.kind}-${Date.now()}`,name:y,kind:e.kind,addonId:e.addonId,enabled:t?.enabled??!0,config:a};return m.trpcClient.notificationOutput.upsertTarget.mutate({addonId:e.addonId,target:o,...i===null?{}:{cloneSecretsFrom:i.id}})},onSuccess:s,onError:e=>{let t=e instanceof Error?e.message:`Save failed`;Km(t)?M(t):A(t)}}),ne=r(()=>zm(e.configSchema),[e.configSchema]),B=r(()=>v===void 0?[]:Ym(w,S,h,e.destinationKeys),[v,w,S,h,e.destinationKeys]),V=r(()=>v!==void 0&&(j!==null||B.length>0)?Xm(w,S,h):[],[v,j,B,w,S,h]),re=r(()=>th(Qm(e.configSchema,V),S,h),[e.configSchema,V,S,h]),ie=e=>ne.get(e)??e;return u(wt,{open:!0,onClose:f,title:t?`Edit ${t.name}`:i?`Duplicate ${i.name}`:`Add ${e.label} target`,icon:_,width:`lg`,testId:`target-form-dialog`,beforeBody:n(a,{children:[k!=null&&k!==``&&u(`div`,{className:`mb-3 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger`,"data-testid":`target-form-error`,children:k}),n(`div`,{className:`mb-3 flex items-center gap-2 text-xs text-foreground-subtle`,children:[u(fh,{kind:e,imgClassName:`h-5 w-5 object-contain shrink-0`,fallbackClassName:`text-lg leading-5`}),u(`span`,{children:e.label})]})]}),footer:n(W,{size:`sm`,type:`button`,disabled:z.isPending||!D||y.trim().length===0,onClick:()=>{A(null),M(null),z.mutate()},children:[z.isPending||!D?u(b,{className:`h-3.5 w-3.5 animate-spin`}):null,t?p(`system.notificationTargets.saveChanges`,`Save changes`):p(`system.notificationTargets.createTarget`,`Create target`)]}),children:n(`div`,{className:`space-y-4`,children:[n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:p(`system.notificationTargets.name`,`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:y,onChange:e=>x(e.target.value)})]}),n(`div`,{children:[u(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:p(`system.notificationTargets.owner`,`Owner`)}),u(G,{value:N,options:[{value:``,label:p(`system.notificationTargets.systemSharedAdminManaged`,`System (shared, admin-managed)`)},...o.map(e=>({value:e.id,label:e.username}))],onChange:e=>P(e.target.value)}),u(`p`,{className:`mt-0.5 text-[10px] text-foreground-subtle`,children:p(`system.notificationTargets.aUserOwnedTargetBelongs`,`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.`)})]}),h.length>0&&v!==void 0&&u(`p`,{className:`text-[10px] text-foreground-subtle`,children:p(`system.notificationTargets.storedSecretsLoadIntoThe`,`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(ah,{refusal:j,edited:B.map(ie),reenter:V.map(ie)}),u(et,{schema:re,values:w,onChange:T}),te&&n(`div`,{className:`space-y-2`,children:[n(W,{size:`sm`,variant:`outline`,type:`button`,disabled:R.isPending,onClick:()=>{A(null),ee(null),R.mutate()},children:[R.isPending?u(b,{className:`h-3.5 w-3.5 animate-spin`}):u(L,{className:`h-3.5 w-3.5`}),p(`system.notificationTargets.testConnection`,`Test connection`)]}),I!==null&&n(`p`,{className:I.ok?`text-[11px] text-success`:`text-[11px] text-danger`,"data-testid":`target-probe-result`,children:[I.ok?p(`system.notificationTargets.connected`,`Connected — {{value1}}`,{value1:I.stateInstance??`authorized`}):I.error??p(`system.notificationTargets.connectionFailed`,`Connection failed`),I.resolvedUrl.length>0?` · ${I.resolvedUrl}`:``]})]})]})})}t();var gh=`notificationTexts`,_h=`Every sentence the Notification Center can print — and your wording for it.`;function vh({entry:e,value:t,busy:r,onChange:i,onReset:a}){let{t:o}=Z(),s=Ll(e),c=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}),c?u(J,{variant:`info`,children:`customised`}):null,e.source===`fallback`?u(J,{variant:`warning`,children:o(`system.notificationTexts.englishFallback`,`English fallback`)}):null]}),n(`div`,{className:`flex items-start gap-2`,children:[u(`div`,{className:`flex-1`,children:u(ho,{label:``,value:t,onChange:i,vars:Il(e),disabled:r,testId:`text-input-${e.key}`})}),u(W,{variant:`ghost`,size:`sm`,disabled:r||!c&&t===e.shipped,onClick:a,title:o(`system.notificationTexts.resetToTheShippedWording`,`Reset to the shipped wording`),"data-testid":`text-reset-${e.key}`,children:u(k,{className:`h-3.5 w-3.5`})})]}),n(`p`,{className:`text-xs text-foreground-subtle`,children:[u(`span`,{className:`font-medium`,children:o(`system.notificationTexts.shipped`,`Shipped:`)}),` `,u(`span`,{className:`font-mono`,children:e.shipped})]}),s===null?null:u(`p`,{className:`text-xs text-warning`,children:s})]})}function yh(){let{t:e}=Z(),t=E(),a=o(),[s,d]=c(null),[f,p]=c(``),[m,h]=c(new Map),[g,_]=c(!1),v=i({queryKey:[gh,s??`hub`],queryFn:async()=>{let e=jl(await t.trpcClient.addons.custom.mutate({addonId:xl,action:Sl,input:s===null?{}:{language:s}}));return _(e===null),e}}),y=()=>{h(new Map),a.invalidateQueries({queryKey:[gh]})},x=l({mutationFn:e=>t.trpcClient.addons.custom.mutate({addonId:xl,action:Cl,input:{language:e}}),onSuccess:y}),C=l({mutationFn:e=>t.trpcClient.addons.custom.mutate({addonId:xl,action:wl,input:e}),onSuccess:y}),w=v.data??null,T=r(()=>w===null?[]:Fl(w.entries,f),[w,f]);if(v.isLoading)return u(Jr,{embedded:!0,icon:P,title:e(`system.notificationTexts.texts`,`Texts`),subtitle:_h,children:u(b,{className:`h-5 w-5 animate-spin`})});if(v.isError||w===null)return u(Jr,{embedded:!0,icon:P,title:e(`system.notificationTexts.texts`,`Texts`),subtitle:_h,children:u(K,{title:e(`system.notificationTexts.theNotificationTextCatalogIs`,`The notification text catalog is not available on this hub`),message:g?e(`system.notificationTexts.theHubAnsweredSomethingThis`,`The hub answered something this admin build does not understand. Update both and reload.`):e(`system.notificationTexts.thisHubHasNotBeen`,`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 D=w.language,O=x.isPending||C.isPending,k=Nl(w.entries,m),A=Pl(w.entries,m),j=w.entries.filter(e=>e.override!==null).length,M=w.languages.map(e=>({value:e,label:Tl[e]})),N=(e,t)=>h(n=>new Map(n).set(e,t)),F=e=>N(e.key,e.shipped);return u(Jr,{embedded:!0,icon:P,title:e(`system.notificationTexts.texts`,`Texts`),subtitle:_h,children:n(`div`,{className:`flex flex-col gap-4`,children:[x.isError?u(K,{title:e(`system.notificationTexts.couldNotChangeTheLanguage`,`Could not change the language`),message:String(x.error)}):null,C.isError?u(K,{title:e(`system.notificationTexts.couldNotSave`,`Could not save`),message:String(C.error)}):null,n(qe,{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:e(`system.notificationTexts.hubLanguage`,`Hub language`)}),u(`div`,{className:`w-44`,children:u(G,{value:w.activeLanguage,disabled:O,options:M,onChange:e=>{let t=e.target.value;El(t)&&x.mutate(t)},"data-testid":`texts-hub-language`})}),u(`p`,{className:`text-xs text-foreground-subtle`,children:e(`system.notificationTexts.everyNotificationIsWrittenIn`,`Every notification is written in this language.`)})]}),n(`div`,{className:`flex flex-col gap-1`,children:[u(`label`,{className:`text-sm font-medium`,children:e(`system.notificationTexts.editing`,`Editing`)}),u(`div`,{className:`w-44`,children:u(G,{value:D,disabled:O,options:M,onChange:e=>{let t=e.target.value;El(t)&&(h(new Map),d(t))},"data-testid":`texts-editing-language`})}),u(`p`,{className:`text-xs text-foreground-subtle`,children:D===w.activeLanguage?e(`system.notificationTexts.ofTextsCustomised`,`{{overriddenCount}} of {{length}} texts customised.`,{overriddenCount:j,length:w.entries.length}):e(`system.notificationTexts.thisHubDoesNotSpeak`,`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:e(`system.notificationTexts.aRuleThatWritesIts`,`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(S,{className:`absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-foreground-muted`}),u(q,{value:f,placeholder:e(`system.notificationTexts.searchAKeyOrA`,`Search a key or a sentence…`),onChange:e=>p(e.target.value),className:`pl-7`,"data-testid":`texts-search`})]}),n(`span`,{className:`text-xs text-foreground-subtle whitespace-nowrap`,children:[T.length,` of `,w.entries.length]}),n(W,{className:`ml-auto`,disabled:O||A===0,onClick:()=>C.mutate({language:D,overrides:k}),"data-testid":`texts-save`,children:[O?u(b,{className:`h-3.5 w-3.5 animate-spin`}):null,A===0?e(`common.save`,`Save`):e(`system.notificationTexts.save`,`Save {{pending}}`,{pending:A})]})]}),u(`div`,{className:`flex max-h-[60vh] flex-col gap-2 overflow-y-auto pr-1`,"data-testid":`texts-rows`,children:T.length===0?u(`p`,{className:`text-sm text-foreground-subtle`,children:e(`system.notificationTexts.noTextMatchesThatSearch`,`No text matches that search.`)}):T.map(e=>u(vh,{entry:e,value:Ml(e,m),busy:O,onChange:t=>N(e.key,t),onReset:()=>F(e)},e.key))})]})})}t();var bh=`simulate`,xh=`rules`,Sh=new Set([`targets`,xh,`sequences`]);function Ch(e){return e===`summaries`?`summary`:e===`timelapses`?`timelapse`:e===`calendar-events`?`calendar-events`:null}function wh(e,t,r){if(e===`mixed`)return;if(e===`all`)return n(W,{size:`sm`,type:`button`,"data-testid":`rules-new-menu`,onClick:t,children:[u(g,{className:`h-3.5 w-3.5`}),X.t(`systemPage.notifications.newRule`,`New rule`)]});if(hf(e)){let t=_f(e),i=Ch(e);return i===null?void 0:n(W,{size:`sm`,type:`button`,onClick:()=>r(i),"data-testid":e===`summaries`?`summary-new`:e===`timelapses`?`timelapse-new`:`calendar-events-new`,children:[u(g,{className:`h-3.5 w-3.5`}),t.newLabel]})}let i=Ot.find(t=>t.key===e);if(!(i===void 0||!i.creatable))return n(W,{size:`sm`,type:`button`,onClick:()=>r(e),"data-testid":`rules-new-${e}`,children:[u(g,{className:`h-3.5 w-3.5`}),i.newRuleLabel]})}function Th(){let{t:e}=Z(),[t,r]=Wr(),[i,a]=c(!1),[o,s]=c(null);d(()=>{let e=t.get(`tab`);if(e===null||!hf(e))return;let n=new URLSearchParams(t);n.set(`tab`,xh),n.set(`section`,e),r(n,{replace:!0})},[t,r]);let l=t.get(`tab`)??`targets`,[f]=Je(`section`),p=gf(f)??`all`,m=e=>{qp(Gp(e));let n=new URLSearchParams(t);n.set(`tab`,bh),r(n,{replace:!0})},h=e=>{r(Ia(t,e.id),{replace:!0})},v=Hr(`/system/notifications`,{t:e,isAdmin:!0})??{icon:_,title:e(`system.notifications`,`Notifications`)},y=()=>a(!1),b=(()=>{if(l===`targets`)return n(W,{size:`sm`,type:`button`,"data-testid":`notifications-add-target`,onClick:()=>a(!0),children:[u(g,{className:`h-3.5 w-3.5`}),e(`systemPage.notifications.addTarget`,`Add target`)]});if(l===`sequences`)return n(W,{size:`sm`,type:`button`,"data-testid":`notifications-add-sequence`,onClick:()=>a(!0),children:[u(g,{className:`h-3.5 w-3.5`}),e(`systemPage.notifications.newSequence`,`New sequence`)]});if(l===xh)return wh(p,()=>a(!0),e=>s(e))})();return d(()=>{Sh.has(l)||(a(!1),s(null))},[l]),u(Kr,{icon:v.icon,title:v.title,defaultSection:`targets`,sectionsLabel:`${v.title} sections`,actions:b,sections:[{id:`targets`,label:e(`systemPage.notifications.targets`,`Targets`),content:u(ph,{headerOwnsCreate:!0,createRequested:l===`targets`&&i,onCreateConsumed:y}),ownedParams:ih},{id:xh,label:e(`systemPage.notifications.rules`,`Rules`),content:u(lp,{onSimulateRule:m,onOpenHistory:h,headerOwnsCreate:!0,createRequested:l===xh&&i,onCreateConsumed:y,createTypeRequested:l===xh?o:null,onCreateTypeConsumed:()=>s(null)}),ownedParams:[`section`,`rule`,`editTab`]},{id:`sequences`,label:e(`systemPage.notifications.sequences`,`Sequences`),content:u(Tp,{headerOwnsCreate:!0,createRequested:l===`sequences`&&i,onCreateConsumed:y}),ownedParams:vp},{id:bh,label:e(`systemPage.notifications.simulate`,`Simulate`),content:u(_m,{})},{id:Aa,label:e(`systemPage.notifications.history`,`History`),content:u(qa,{}),ownedParams:Ma},{id:`alarm`,label:e(`systemPage.notifications.alarm`,`Alarm`),content:u(ka,{})},{id:`texts`,label:e(`systemPage.notifications.texts`,`Texts`),content:u(yh,{})}]})}export{Th as NotificationsPage,Th as default};
|