@camstack/addon-admin-ui 1.2.502 → 1.2.504
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/CHANGELOG.md +12 -0
- package/dist/assets/{AddonAssetIcon-BE4IRtcr.js → AddonAssetIcon-NEsi-wOP.js} +1 -1
- package/dist/assets/Addons-BBTz7bMK.js +5 -0
- package/dist/assets/{AdminPage-DO4TvyzZ.js → AdminPage-aCyydhgN.js} +1 -1
- package/dist/assets/{AdminSectionedPage-DbSVTTH0.js → AdminSectionedPage-DQApNUvC.js} +1 -1
- package/dist/assets/{AiProfiles-DlLpJu6R.js → AiProfiles-BE-rCiys.js} +1 -1
- package/dist/assets/{BrokerEditorDialog-ZqEB1OeF.js → BrokerEditorDialog-DaJ4BMP-.js} +1 -1
- package/dist/assets/{Build-D-kordXj.js → Build-BEJ9LiOb.js} +3 -3
- package/dist/assets/{Calendars-CPKyT4jY.js → Calendars-DwmEazlr.js} +1 -1
- package/dist/assets/{Cluster-2uEFOeHM.js → Cluster-DXvpkuQ_.js} +1 -1
- package/dist/assets/{CompositionBlockEditor-Ch4cyhPp.js → CompositionBlockEditor-Dn1dNrUj.js} +1 -1
- package/dist/assets/{CompositionEditorPage-mWPEX9E1.js → CompositionEditorPage-BAtIrfop.js} +1 -1
- package/dist/assets/{Data-DHfi_Lpj.js → Data-CxbvhxJ0.js} +2 -2
- package/dist/assets/DeviceDetail-1SsTjU6R.js +2 -0
- package/dist/assets/{DeviceDoActionFields-BjxeF1AZ.js → DeviceDoActionFields-CbeCW7Ej.js} +1 -1
- package/dist/assets/{Devices-BIokWQGH.js → Devices-P2Awkb88.js} +1 -1
- package/dist/assets/{EmbedPlayerPage-BAopgKNa.js → EmbedPlayerPage-DHx71JZg.js} +1 -1
- package/dist/assets/{HelperWizard-BVEjPQvM.js → HelperWizard-dV1HzKlU.js} +2 -2
- package/dist/assets/History-COrccgVX.js +1 -0
- package/dist/assets/{Identity-Do-Unn14.js → Identity-DwNJielZ.js} +1 -1
- package/dist/assets/IntegrationDetail-B62OySBK.js +1 -0
- package/dist/assets/{IntegrationHub-cywGK2Wp.js → IntegrationHub-DkSP6wag.js} +1 -1
- package/dist/assets/Integrations-BOcxxDmP.js +1 -0
- package/dist/assets/Integrations-qJr63PpD.js +1 -0
- package/dist/assets/{Library-DCcWEFFl.js → Library-BV1qzsuk.js} +1 -1
- package/dist/assets/{Locations-CYrSAzVs.js → Locations-CZB5AlmP.js} +1 -1
- package/dist/assets/{Logs-CfwzwwGK.js → Logs-GyrX39DG.js} +1 -1
- package/dist/assets/{MaskShapeCanvas-DtFd99MF.js → MaskShapeCanvas-Cn8yntgZ.js} +1 -1
- package/dist/assets/{MotionZonesSettings-CQl2EA6N.js → MotionZonesSettings-ar2Pege0.js} +1 -1
- package/dist/assets/MyAccess-CX7W9s59.js +2 -0
- package/dist/assets/Network-hBrZTqKM.js +1 -0
- package/dist/assets/{NodeAddonsSettingsPanel-D3T2zuD1.js → NodeAddonsSettingsPanel-DcAc9h3n.js} +1 -1
- package/dist/assets/Notifications-CVo2lV8_.js +1 -0
- package/dist/assets/{Pipeline-Bq6O6mrO.js → Pipeline-ULrA6vbR.js} +1 -1
- package/dist/assets/{PrivacyMaskSettings-qYOg-1SO.js → PrivacyMaskSettings-w3Z1Pmp0.js} +1 -1
- package/dist/assets/{Recordings-NipGCr6f.js → Recordings-O3tK-kRN.js} +1 -1
- package/dist/assets/{ScanNetworkModal-CWiM9HWV.js → ScanNetworkModal-DRTFnUxd.js} +1 -1
- package/dist/assets/{SceneMonitorEditor-Ba9gLNWL.js → SceneMonitorEditor-BbGTvgFe.js} +1 -1
- package/dist/assets/{SessionsList-DWm1_JRD.js → SessionsList-CmkI6hmY.js} +2 -2
- package/dist/assets/{Showroom-ChlaT6Cm.js → Showroom-PcX3gurw.js} +1 -1
- package/dist/assets/{System-Cby1MNlk.js → System-74cpSs_X.js} +1 -1
- package/dist/assets/{Terminal-BrONi7mZ.js → Terminal-BzqwEea0.js} +1 -1
- package/dist/assets/{Viewer-C5qA4uKO.js → Viewer-DhjS-14b.js} +1 -1
- package/dist/assets/{_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-BTGIQmuA.js → _virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-Bj_EUdNV.js} +1 -1
- package/dist/assets/{addon-icons-context-BZhSRQ2k.js → addon-icons-context-BfGPQ4xZ.js} +1 -1
- package/dist/assets/{archive-BJkTmC56.js → archive-B8nHeizN.js} +1 -1
- package/dist/assets/{assignment-candidates-DJLitZnD.js → assignment-candidates-BWSRqjeY.js} +1 -1
- package/dist/assets/{authed-media-BC_02usb.js → authed-media-CCu_0Mkk.js} +1 -1
- package/dist/assets/{bell-off-DMGqFkTx.js → bell-off-B8qGTZJe.js} +1 -1
- package/dist/assets/{board-model-CCAK2YmC.js → board-model-D0x2o-FF.js} +1 -1
- package/dist/assets/{boxes-Bajlyp9F.js → boxes-DTEgIla8.js} +1 -1
- package/dist/assets/circle-slash--9TzZJnc.js +1 -0
- package/dist/assets/client-C6c46gRD.js +674 -0
- package/dist/assets/{cloud-upload-BXAu0WA_.js → cloud-upload-CrsNLt4y.js} +1 -1
- package/dist/assets/crop-Cf_bbG5R.js +1 -0
- package/dist/assets/{device-integration-icon-DLda0bDE.js → device-integration-icon-RKJ1i9-y.js} +1 -1
- package/dist/assets/device-picker-model-CCtDoCaE.js +1 -0
- package/dist/assets/{dist-B3iqcRcx.js → dist-DhM3TUvu.js} +1 -1
- package/dist/assets/dist-Dwc9xFn1.js +674 -0
- package/dist/assets/{eraser-BP7I6n2j.js → eraser-B6GapSNa.js} +1 -1
- package/dist/assets/{format-XZs_xh1r.js → format-BrcsXZgx.js} +1 -1
- package/dist/assets/framework-packages-B7oma9J4.js +1 -0
- package/dist/assets/{hard-drive-download-bSbR-kqh.js → hard-drive-download-CKtXN4eq.js} +1 -1
- package/dist/assets/{hostInit-CqBL2ZCP.js → hostInit-C9UJbeBX.js} +1 -1
- package/dist/assets/i18n-DNh4GW93.js +1 -0
- package/dist/assets/{icons-C3RUxRxL.js → icons-IUDDHPfU.js} +1 -1
- package/dist/assets/index-DOFPItyi.css +2 -0
- package/dist/assets/{index-BGJbArko.js → index-Dm-ruGxs.js} +3 -3
- package/dist/assets/{key-D2U0s0LY.js → key-B1puhv1a.js} +1 -1
- package/dist/assets/{key-round-D8xR5lTT.js → key-round-DmUg5DWL.js} +1 -1
- package/dist/assets/{layers-sqZU1Efj.js → layers--KlhvTig.js} +1 -1
- package/dist/assets/{linked-devices-model-DQCmeWmy.js → linked-devices-model-Bd2asZR8.js} +1 -1
- package/dist/assets/{list-ordered-BGulzxMx.js → list-ordered-pBVZh-hF.js} +1 -1
- package/dist/assets/{location-owned-usage-CLPPrh2c.js → location-owned-usage-AoW2HSuk.js} +1 -1
- package/dist/assets/{log-in-D88bsbT9.js → log-in-DtNu6ihw.js} +1 -1
- package/dist/assets/{memory-stick-DuklOVmZ.js → memory-stick-s804jcfZ.js} +1 -1
- package/dist/assets/{message-square-plus-CrWXPaYo.js → message-square-plus-Cl5QQyI7.js} +1 -1
- package/dist/assets/{mf-entry-bootstrap-0-d28584aa.js → mf-entry-bootstrap-0-44b53b1c.js} +2 -2
- package/dist/assets/{mic-off-LpAoBdO7.js → mic-off-Bl1AxZQ6.js} +1 -1
- package/dist/assets/{monitor-off-BaVOrPeY.js → monitor-off-Du7HEr2h.js} +1 -1
- package/dist/assets/{monitor-smartphone-COSQV55Z.js → monitor-smartphone-DJqsZ1_F.js} +1 -1
- package/dist/assets/mount-CCtDoCaE.js +1 -0
- package/dist/assets/{player-overlays-DDvKn1W0.js → player-overlays-B4lehTI4.js} +1 -1
- package/dist/assets/{recycle-CD8ymUv3.js → recycle-Clfv9-vM.js} +1 -1
- package/dist/assets/remoteEntry-CFFHRTAl.js +1 -0
- package/dist/assets/{scan-eye-CdfmPhrl.js → scan-eye-k8IsYrRV.js} +1 -1
- package/dist/assets/{scissors-Bl3fg6Ss.js → scissors-DSR_hX9P.js} +1 -1
- package/dist/assets/{search-x-CZruDJ75.js → search-x-CJK6g57h.js} +1 -1
- package/dist/assets/{send-Cdk8pNT7.js → send-BXMUOnLc.js} +1 -1
- package/dist/assets/{settings-2-DqKxa0Hf.js → settings-2-D_d4vkzK.js} +1 -1
- package/dist/assets/{sigma-ByejGGJ9.js → sigma-C5zYB6Cq.js} +1 -1
- package/dist/assets/{speaker-B-TcfLx7.js → speaker-BCuags2o.js} +1 -1
- package/dist/assets/{src-TayryneI.js → src-DY9QaWNW.js} +8 -8
- package/dist/assets/{step-inspector-model-B6yVCl09.js → step-inspector-model-_xqNTlQX.js} +1 -1
- package/dist/assets/{table-2-C753-50s.js → table-2-DecfWh5K.js} +1 -1
- package/dist/assets/{timer-reset-CF7cF_Ga.js → timer-reset-CdW4OGWJ.js} +1 -1
- package/dist/assets/{unlink-C3Qb_GTc.js → unlink-Chgtl9c5.js} +1 -1
- package/dist/assets/{usb-CTHiJtrH.js → usb-DSG8UHuC.js} +1 -1
- package/dist/assets/{use-scenes-feed-onSFrxVP.js → use-scenes-feed-Co3WLAh1.js} +1 -1
- package/dist/assets/{use-stationary-objects-CpKg50zN.js → use-stationary-objects-o-ZgylqM.js} +1 -1
- package/dist/assets/useEventInvalidation-CCtDoCaE.js +1 -0
- package/dist/assets/{useNodeUrlSelection-B-S1kSBF.js → useNodeUrlSelection--XA1ndxK.js} +1 -1
- package/dist/assets/user-round-CsUnuDee.js +1 -0
- package/dist/assets/{user-x-BaEc4WgN.js → user-x-Ddy9Al8t.js} +1 -1
- package/dist/assets/{variable-b7iNWVN7.js → variable-BGeMjiqk.js} +1 -1
- package/dist/assets/{video-CF2QZpF3.js → video-B-2RwuDj.js} +1 -1
- package/dist/assets/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-B0_zurpm.js → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-CX8JLNds.js} +2 -2
- package/dist/index.html +10 -10
- package/dist/server/addon.js +102 -116
- package/package.json +1 -1
- package/dist/assets/Addons-BpGMIVwu.js +0 -5
- package/dist/assets/DeviceDetail-Dj663lX6.js +0 -2
- package/dist/assets/History-DJR_LsxX.js +0 -1
- package/dist/assets/IntegrationDetail-Dbw98oyP.js +0 -1
- package/dist/assets/Integrations-C0ckAtmU.js +0 -1
- package/dist/assets/Integrations-DeVdSE8D.js +0 -1
- package/dist/assets/MyAccess-DD7nAn5h.js +0 -2
- package/dist/assets/Network-BYuL-L4z.js +0 -1
- package/dist/assets/Notifications-CzX3nzZP.js +0 -1
- package/dist/assets/circle-slash-Dng6-XsF.js +0 -1
- package/dist/assets/client-BqE1zM9p.js +0 -674
- package/dist/assets/crop-CLBowvwG.js +0 -1
- package/dist/assets/device-picker-model-CHicgClc.js +0 -1
- package/dist/assets/dist-KDpN_XDi.js +0 -674
- package/dist/assets/i18n-uD14huY2.js +0 -1
- package/dist/assets/index-WAVCQxxk.css +0 -2
- package/dist/assets/mount-CHicgClc.js +0 -1
- package/dist/assets/remoteEntry-Br1rMgc-.js +0 -1
- package/dist/assets/useEventInvalidation-CHicgClc.js +0 -1
- package/dist/assets/user-round-D_ZjF5gh.js +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{C as e,J as t,K as n,S as r,V as i,Y as a,a as o,et as s,o as c,p as l,t as u,x as d}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEyXHAdg.js";import{Dn as f,En as p,Fn as m,Ht as h,Q as g,Tn as _,Tr as v,Ui as y,Vr as b,Wi as x,bi as S,br as C,dt as w,fr as T,pa as E,pn as D,ri as O,st as k,vn as A,xi as j,z as M,zt as N}from"./player-overlays-DDvKn1W0.js";import{A as P,Ar as ee,B as F,C as I,Ct as te,D as L,E as ne,Er as R,H as z,J as B,K as re,M as ie,Mt as ae,O as oe,Ot as se,P as ce,Q as le,R as ue,S as de,Sn as fe,St as pe,Tt as me,U as he,V as ge,X as _e,Y as ve,_t as V,bt as ye,dn as be,ft as xe,gt as Se,jr as Ce,jt as we,la as Te,lt as Ee,mt as De,q as Oe,st as ke,ut as Ae,w as je,xt as Me,yt as Ne,z as Pe}from"./client-BqE1zM9p.js";import{D as Fe,F as Ie,M as Le,O as Re,j as ze,v as Be,y as Ve}from"./__vite-browser-external-BlMfPwfH.js";import{t as He}from"./bell-off-DMGqFkTx.js";import{h as Ue}from"./video-CF2QZpF3.js";import{n as We,t as Ge}from"./send-Cdk8pNT7.js";import{n as Ke,r as qe,t as Je}from"./list-ordered-BGulzxMx.js";import{B as Ye,Bn as Xe,Cn as Ze,Do as Qe,Ec as $e,G as et,H as tt,Hn as nt,Ir as rt,K as it,L as at,Ma as ot,Qr as st,R as ct,Rn as lt,Sc as ut,Sn as dt,Tr as H,U as ft,Un as pt,V as mt,Vn as ht,W as gt,Yr as U,Zr as _t,_r as vt,ar as yt,br as bt,dd as W,dr as xt,fr as St,ft as Ct,gd as G,gr as wt,hr as Tt,kt as Et,mt as Dt,or as Ot,pr as kt,pt as At,ri as K,tn as jt,wc as Mt,xc as Nt,xt as Pt,z as Ft,zn as q}from"./src-TayryneI.js";import{t as J}from"./i18n-uD14huY2.js";import{t as Y}from"./useTranslation-BJr-n0es.js";import"./mount-CHicgClc.js";import{$ as It,$t as Lt,An as Rt,At as zt,B as Bt,Bn as Vt,Bt as Ht,C as Ut,Cn as Wt,Ct as Gt,Dn as Kt,Dt as qt,En as Jt,Et as Yt,F as Xt,Fn as Zt,Ft as Qt,G as $t,Gn as en,Gt as tn,H as nn,Hn as rn,Ht as an,I as on,In as sn,It as cn,J as ln,Jn as un,Jt as dn,K as X,Kn as fn,Kt as pn,L as mn,Ln as hn,Lt as gn,Mn as _n,Mt as vn,Nn as yn,Nt as bn,On as xn,Ot as Sn,Pn as Cn,Pt as wn,Q as Tn,Qn as En,Qt as Dn,R as On,Rn as kn,Rt as An,S as jn,Sn as Mn,St as Nn,Tn as Pn,Tt as Fn,U as In,Un as Ln,Ut as Rn,V as zn,Vn as Bn,Vt as Vn,W as Hn,Wn as Un,Wt as Wn,X as Gn,Xn as Kn,Xt as qn,Y as Jn,Yn,Yt as Xn,Z as Zn,Zn as Qn,Zt as $n,_n as er,_t as tr,an as nr,at as rr,bn as ir,bt as ar,cn as or,ct as sr,dn as cr,dr as lr,dt as ur,en as dr,et as fr,fn as pr,ft as mr,gn as hr,gr,gt as _r,hn as vr,ht as yr,in as br,it as xr,jn as Sr,jt as Cr,kn as wr,kt as Tr,ln as Er,lt as Dr,mn as Or,mt as kr,nn as Ar,nt as jr,on as Mr,ot as Nr,pn as Pr,pt as Fr,q as Ir,qn as Lr,qt as Rr,rn as zr,rt as Br,sn as Vr,st as Hr,tn as Ur,tt as Wr,un as Gr,ur as Kr,ut as qr,vn as Jr,vt as Yr,wn as Xr,wt as Zr,xn as Qr,xt as $r,yn as ei,yt as ti,z as ni,zn as ri,zt as ii}from"./index-BGJbArko.js";import{t as ai}from"./AdminSectionedPage-DbSVTTH0.js";import{n as oi}from"./format-XZs_xh1r.js";import{t as si}from"./DeviceDoActionFields-BjxeF1AZ.js";import"./device-picker-model-CHicgClc.js";import{t as ci}from"./AdminPage-DO4TvyzZ.js";import{t as li}from"./use-scenes-feed-onSFrxVP.js";s();var ui=[`contact`,`cover`,`lock-control`,`switch`];function di(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 fi(e){let t=new Set(di(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 pi(e){return e.ids.length>0||e.unresolved?null:`no-opening`}function mi(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=>tt([e],r,t)[0];return{nameOf:e=>{let t=a(e);return i(e)??(t===void 0?J.t(`uiLibrary.devicePicker.deviceId`,{id:e}):Ye(t,`device`,Ut))},isRemoved:e=>i(e)===null&&a(e)?.removed===!0}}function hi(e){let t=e.name.trim();return t===``?J.t(`uiLibrary.devicePicker.deviceId`,{id:e.deviceId}):t}function gi(e){return e===0?J.t(`helpers.alarmNonblocking.refusedNoName`):J.t(`helpers.alarmNonblocking.refusedOpen`)}var _i={home:`Home`,away:`Away`,night:`Night`};function vi(e){return _i[e]??e}function yi(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?J.t(`helpers.notificationAlarm.delayMin`,{minutes:n}):J.t(`helpers.notificationAlarm.delayMinSec`,{minutes:n,seconds:r})}function bi(e,t){if(e.ruleCount===0)return J.t(`helpers.notificationAlarm.armsNothing`);if(e.allDevices&&e.allDevicesExcept.length>0){let n=e.allDevicesExcept.map(t);return J.t(`helpers.notificationAlarm.allExcept`,{count:n.length,names:n.join(`, `)})}return e.allDevices?J.t(`helpers.notificationAlarm.everyDevice`,{count:e.ruleCount}):e.deviceIds.length===0?J.t(`helpers.notificationAlarm.noRestriction`,{count:e.ruleCount}):e.deviceIds.map(t).join(`, `)}function xi(e,t){if(e.length===0)return``;let n=e.map(e=>`${t(e.deviceId)} (${Si[e.reason]})`);return J.t(`helpers.notificationAlarm.skipped`,{count:e.length,parts:n.join(`, `)})}var Si={muted:`notifications muted`,"detection-off":`detection off`,offline:`offline`};function Ci(e){return e.ruleCount===0}function wi(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 Ti=2e3,Ei=15e3,Di=new Set([`arming`,`pending`,`triggered`]);function Oi(e){return e!==void 0&&Di.has(e)?Ti:Ei}var ki={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 Ai(e){let t=ki[e.state];return e.state===`disarmed`||e.targetMode===null?t:`${t} — ${vi(e.targetMode)}`}function ji(e){return e!==`disarmed`}function Mi(e){return e===`open`?J.t(`helpers.notificationAlarm.phaseOpen`):J.t(`helpers.notificationAlarm.phaseClosed`)}function Ni(e,t){return(e.nonBlocking??[]).find(e=>e.mode===t)?.deviceIds??[]}function Pi(e,t){return(e.blocking??[]).find(e=>e.mode===t)?.deviceIds??[]}function Fi(e,t){return(e.secureOnArmOff??[]).find(e=>e.mode===t)?.deviceIds??[]}function Ii(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 Li(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 Ri(e,t,n,r){let i=Ii(e,t,n);return r==="default"?i===void 0?null:Li(t,n,null):i===r?null:Li(t,n,r)}function zi(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 Bi(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 Vi=[`unknown-refusal`,`stale`,`expired`,`used`];function Hi(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ui(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(!Hi(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 Wi(e){if(!Hi(e))return null;let t=e.outcome;if(t===`armed`||t===`arming`){let n=Ui(e.excluded);return n===null?null:{outcome:t,excluded:n}}if(t===`refused`){let n=Ui(e.blocking),r=e.refusalId;return n===null||typeof r!=`string`||r===``?null:{outcome:t,refusalId:r,blocking:n}}if(t===`rejected`){let n=Vi.find(t=>t===e.reason);return n===void 0?null:{outcome:t,reason:n}}return t===`outside-schedule`?{outcome:t}:null}var Gi={"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 Ki(e){return Gi[e]}function qi(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 Ji=`pipeline-analytics`,Yi=`The hub answered something this build cannot read — refresh after updating.`;function Xi(e){return e instanceof Error?e.message:String(e)}function Zi(e){return e.map(e=>`${hi(e)} (${e.state})`).join(`, `)}function Qi({live:t,onChanged:n}){let{t:i}=Y(),o=w(),[s,c]=a(null),[l,d]=a(null),[f,p]=a(null),m=(e,t)=>o.trpcClient.addons.custom.mutate({addonId:Ji,action:e,input:t}),h=e=>{if(e===null){d(Yi);return}if(e.outcome===`refused`){c({refusalId:e.refusalId,blocking:e.blocking});return}if(c(null),e.outcome===`rejected`){d(`Arm anyway was not accepted: ${Ki(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: ${Zi(e.excluded)}.`)},g=()=>{d(null),p(null)},_=u({mutationFn:async e=>Wi(await m(`nc.armAlarm`,{mode:e})),onMutate:g,onSuccess:h,onError:e=>d(Xi(e)),onSettled:n}),v=u({mutationFn:async e=>Wi(await m(`nc.armAlarmAnyway`,{refusalId:e})),onMutate:g,onSuccess:h,onError:e=>d(Xi(e)),onSettled:n}),y=u({mutationFn:async()=>m(`nc.disarmAlarm`,{}),onMutate:()=>{g(),c(null)},onSuccess:()=>p(`Disarmed.`),onError:e=>d(Xi(e)),onSettled:n});if(t===void 0)return e(bt,{className:`p-4`,children:[r(`h3`,{className:`text-sm font-semibold mb-1`,children:i(`system.alarmLiveCard.panel`,`Panel`)}),r(`p`,{className:`text-sm text-foreground-subtle`,children:i(`system.alarmLiveCard.thisHubDoesNotReport`,`This hub does not report the panel's live state yet — update it to arm from here.`)})]});let b=_.isPending||v.isPending||y.isPending;return e(bt,{className:`p-4`,children:[e(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[e(`div`,{children:[r(`h3`,{className:`text-sm font-semibold`,children:i(`system.alarmLiveCard.panel`,`Panel`)}),r(`p`,{className:`text-lg font-medium`,"data-testid":`alarm-state`,children:Ai(t)})]}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[b?r(T,{className:`h-4 w-4 animate-spin`}):null,t.availableModes.map(e=>r(U,{type:`button`,size:`md`,variant:`outline`,disabled:b,onClick:()=>_.mutate(e),"data-testid":`alarm-arm-${e}`,children:i(`system.alarmLiveCard.arm`,{mode:vi(e)})},e)),r(U,{type:`button`,size:`md`,variant:ji(t.state)?`danger`:`secondary`,disabled:b,onClick:()=>y.mutate(),"data-testid":`alarm-disarm`,children:i(`system.alarmLiveCard.disarm`,`Disarm`)})]})]}),l===null?null:r(`div`,{className:`mt-3`,children:r(H,{title:i(`system.alarmLiveCard.thePanelDidNotDo`,`The panel did not do that`),message:l})}),f===null?null:r(`p`,{className:`mt-3 text-sm text-foreground-subtle`,children:f}),s===null?null:e(`div`,{className:`mt-3 rounded border border-warning p-3`,"data-testid":`alarm-refused`,children:[r(`p`,{className:`text-sm font-medium`,children:gi(s.blocking.length)}),s.blocking.length>0?r(`ul`,{className:`mt-1 list-disc pl-5 text-sm`,children:s.blocking.map(t=>e(`li`,{children:[hi(t),` `,e(`span`,{className:`text-foreground-subtle`,children:[`(`,t.state,`)`]})]},t.deviceId))}):null,e(`div`,{className:`mt-2 flex flex-wrap items-center gap-2`,children:[r(U,{type:`button`,size:`md`,variant:`danger`,disabled:b,onClick:()=>v.mutate(s.refusalId),children:i(`system.alarmLiveCard.armAnyway`,`Arm anyway`)}),r(`span`,{className:`text-xs text-foreground-subtle`,children:i(`system.alarmLiveCard.eachOpenDeviceIsIgnored`,`Each open device is ignored until it closes, then monitored again.`)})]})]}),e(`div`,{className:`mt-4`,"data-testid":`alarm-exclusions`,children:[r(`h4`,{className:`text-xs font-semibold uppercase text-foreground-subtle`,children:i(`system.alarmLiveCard.excludedSensors`,`Excluded sensors`)}),t.exclusions.length===0?r(`p`,{className:`text-sm text-foreground-subtle`,children:i(`system.alarmLiveCard.noSensorIsExcluded`,`No sensor is excluded.`)}):r(`ul`,{className:`mt-1 flex flex-col gap-1 text-sm`,children:t.exclusions.map(t=>e(`li`,{children:[hi(t),` —`,` `,r(`span`,{className:`text-foreground-subtle`,children:Mi(t.phase)})]},t.deviceId))})]})]})}s();var $i=[{field:`exitDelaySec`,key:`exit`,labelKey:`system.alarmDelay.exitLabel`,hintKey:`system.alarmDelay.exitHint`,max:600,zeroMeansKey:`system.alarmDelay.exitZero`},{field:`entryDelaySec`,key:`entry`,labelKey:`system.alarmDelay.entryLabel`,hintKey:`system.alarmDelay.entryHint`,max:600,zeroMeansKey:`system.alarmDelay.entryZero`},{field:`triggeredDurationSec`,key:`siren`,labelKey:`system.alarmDelay.sirenLabel`,hintKey:`system.alarmDelay.sirenHint`,max:R,zeroMeansKey:`system.alarmDelay.sirenZero`}];function ea(e){return J.t(`system.alarmDelay.rangeError`,{max:e})}function ta(e,t){let n=e.trim();return`${n===``?`Nothing was entered, so nothing was saved`:`${n} was not saved`} — ${ea(t)}`}function na({label:t,value:n,max:i,zeroMeans:o,disabled:s,testId:c,hint:l,adornment:u,onCommit:d}){let[f,p]=a(null),[m,h]=a(null),g=f??String(n),_=f!==null&&f.trim()!==``&&wi(f,i)===null,v=yi(n,o),y=()=>{let e=f===null?null:wi(f,i);p(null),e===null?f!==null&&h(f):(h(null),d(e))};return e(Pt,{label:t,...l===void 0?{}:{description:l},..._?{error:ea(i)}:m===null?{}:{error:ta(m,i)},children:[e(`div`,{className:`flex items-center gap-2`,children:[r(G,{type:`number`,min:0,max:i,value:g,disabled:s,state:_||m!==null?`error`:`default`,"aria-label":t,onChange:e=>{h(null),p(e.target.value)},onBlur:y,className:`w-20`,"data-testid":c}),r(`span`,{className:`text-xs text-foreground-subtle`,children:`s`}),u]}),v===`${n} s`?null:r(`span`,{className:`text-[10px] text-foreground-subtle`,children:v})]})}function ra(e,t){let n=e?.trim()??``;if(n===``)return``;if(t.state===`answered`){let e=it(n),r=t.zones.find(t=>t.locationKeys.includes(e));if(r!==void 0)return`${r.label} · ${n}`}return n}function ia(e){switch(e.kind){case`checking`:return{word:J.t(`system.alarmSensorTable.cellChecking`),note:null};case`hub-too-old`:return{word:J.t(`system.alarmSensorTable.cellUnknown`),note:J.t(`system.alarmSensorTable.cellHubTooOld`)};case`read-failed`:return{word:J.t(`system.alarmSensorTable.cellUnknown`),note:J.t(`system.alarmSensorTable.cellReadFailedError`,{error:e.error})};case`open`:case`closed`:return{word:e.word,note:e.offline?J.t(`system.alarmSensorTable.cellOfflineLastKnown`):null};case`unknown`:return{word:J.t(`system.alarmSensorTable.cellUnknown`),note:e.why===`not-answered`?J.t(`system.alarmSensorTable.cellNotAnswered`):e.why===`read-failed`?J.t(`system.alarmSensorTable.cellReadFailed`):J.t(`system.alarmSensorTable.cellNoState`)};case`not-opening`:return{word:J.t(`system.alarmSensorTable.cellNotOpening`),note:null};case`removed`:return{word:J.t(`system.alarmSensorTable.cellRemoved`),note:J.t(`system.alarmSensorTable.cellRemovedNote`)}}}function aa(){return J.t(`system.alarmSensorTable.listedUncovered`)}function oa(e){return e.listedUncovered?{word:J.t(`system.alarmSensorTable.cellNo`),note:aa()}:sa(e.coverage)}function sa(e){switch(e.kind){case`arm-checked`:return{word:J.t(`system.alarmSensorTable.cellYes`),note:null};case`arm-checked-skipped`:{let t=e.reason===`detection-off`?J.t(`system.alarmSensorTable.detectionOff`):e.reason;return{word:J.t(`system.alarmSensorTable.cellSkipped`),note:J.t(`system.alarmSensorTable.cellSkippedNote`,{why:t})}}case`unscoped`:return{word:J.t(`system.alarmSensorTable.cellAllDevices`),note:J.t(`system.alarmSensorTable.cellNeverBlocks`)};case`not-covered`:return{word:J.t(`system.alarmSensorTable.cellNo`),note:J.t(`system.alarmSensorTable.cellNeverBlocks`)}}}function ca(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 la(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 ua({name:t,variant:n,words:i}){return e(`span`,{"data-testid":`alarm-cell-${t}`,className:`flex flex-col items-start gap-0.5`,children:[r(K,{variant:n,"data-testid":`alarm-cell-${t}-badge`,children:i.word}),i.note===null?null:r(`span`,{className:`text-[10px] text-foreground-subtle`,"data-testid":`alarm-cell-${t}-note`,children:i.note})]})}var da=`hidden sm:table-cell`;function fa({id:e,stored:t}){return r(`span`,{className:`truncate text-xs font-medium text-foreground`,children:rt(e,`compact`,t)})}function pa(e){let t=rt(e.deviceId,`compact`,e.storedName);return r(nt,{checked:e.checked,onCheckedChange:e.onCheckedChange,disabled:e.disabled,"data-device-id":String(e.deviceId),"data-testid":e.testId,"aria-label":J.t(e.phraseKey,e.phraseFallback,{name:t}),"aria-busy":e.busy?!0:void 0,"aria-disabled":e.waiting?!0:void 0,className:e.waiting?`opacity-50`:void 0,...e.title===void 0?{}:{title:e.title}})}function ma(t){let{mode:n,inFlight:i,onSwitch:a,zones:o,disabled:s}=t;return[{key:`name`,header:J.t(`system.alarmSensorTable.name`,`Name`),cell:t=>{let n=ra(t.device.location,o);return e(`span`,{className:`flex min-w-0 flex-col`,"data-testid":`alarm-cell-name`,"data-muted":t.listedUncovered?`true`:void 0,children:[r(fa,{id:t.device.id,stored:t.device.name}),n===``?null:r(`span`,{className:`truncate text-[10px] text-foreground-subtle`,"data-testid":`alarm-cell-zone`,children:n})]})}},{key:`type`,header:J.t(`system.alarmSensorTable.type`,`Type`),headerClassName:da,cellClassName:`${da} text-[11px] text-foreground-subtle`,cell:e=>et(e.device.type??null,Ut)},{key:`state`,header:J.t(`system.alarmSensorTable.state`,`State`),cell:e=>r(ua,{name:`state`,variant:ca(e.cell),words:ia(e.cell)})},{key:`coverage`,header:J.t(`system.alarmSensorTable.checkedWhenArming`,`Checked when arming`),headerClassName:da,cellClassName:da,cell:e=>r(ua,{name:`coverage`,variant:la(e),words:oa(e)})},{key:`blocks`,header:J.t(`system.alarmSensorTable.blocksArming`,`Blocks arming`),headerClassName:`text-right`,cellClassName:`text-right`,cell:t=>{let o=i!==null&&i.mode===n&&i.deviceId===t.device.id&&i.kind===`blocks`,c=i!==null&&!o;return e(`span`,{className:`inline-flex items-center justify-end gap-1`,children:[o?r(T,{className:`h-3 w-3 animate-spin`}):null,r(pa,{deviceId:t.device.id,storedName:t.device.name,phraseKey:`system.alarmSensorTable.blocksArming2`,phraseFallback:`Blocks arming: {{name}}`,checked:t.blocks,onCheckedChange:e=>a(t,`blocks`,e),disabled:s,testId:`alarm-switch-blocks`,busy:o,waiting:c})]})}},{key:`secure`,header:r(`span`,{title:J.t(`system.alarmSensorTable.closeLockOrTurnOff`,`Close, lock, or turn off when this mode arms`),children:J.t(`system.alarmSensorTable.secureOnArm`,`Secure on arm`)}),headerClassName:`text-right`,cellClassName:`text-right`,cell:t=>{if(!t.controllable)return r(`span`,{className:`text-[10px] text-foreground-subtle`,children:`—`});let o=i!==null&&i.mode===n&&i.deviceId===t.device.id&&i.kind===`secureOnArm`,c=i!==null&&!o;return e(`span`,{className:`inline-flex items-center justify-end gap-1`,children:[o?r(T,{className:`h-3 w-3 animate-spin`}):null,r(pa,{deviceId:t.device.id,storedName:t.device.name,phraseKey:`system.alarmSensorTable.secureOnArmCloseLock`,phraseFallback:`Secure on arm (close/lock/off): {{name}}`,checked:t.secureOnArm,onCheckedChange:e=>a(t,`secureOnArm`,e),disabled:s,testId:`alarm-switch-secure`,busy:o,waiting:c,title:J.t(`system.alarmSensorTable.closeLockOrTurnOff`,`Close, lock, or turn off when this mode arms`)})]})}}]}function ha(t){let{t:n}=Y(),i=E(),{mode:a,rows:o,sensorsRetry:s,zones:c}=t;return e(`div`,{className:`space-y-2`,"data-testid":`alarm-sensors-${a}`,children:[s===null?null:e(`div`,{className:`flex items-center gap-2 text-xs text-warning`,"data-testid":`alarm-sensors-failed`,children:[r(`span`,{children:n(`system.alarmSensorTable.couldNotReadTheSensor`,`Could not read the sensor states.`)}),r(U,{type:`button`,size:`sm`,variant:`outline`,onClick:s,children:n(`common.retry`,`Retry`)})]}),r(Et,{mode:`generic`,items:o,getKey:e=>String(e.device.id),getSearchText:e=>[e.device.name,ra(e.device.location,c),et(e.device.type??null,i)].join(` `),getFilterType:e=>et(e.device.type??null,i),columns:ma(t),rowClassName:e=>e.listedUncovered?`opacity-60`:``,searchPlaceholder:n(`system.alarmSensorTable.searchSensors`,`Search sensors`),emptyLabel:`No sensor matches.`})]})}var ga=[/has no (?:handler for )?custom action ["']nc\.getAlarmSensors["']/,/No "query"-procedure on path "notificationRules\.getAlarmSensors"/,/method 'getAlarmSensors' not found on provider 'notification-rules'/];function _a(e){return ga.some(t=>t.test(e))}function va(e,t,n){if(n)return{kind:`removed`};if(e.status===`pending`)return{kind:`checking`};if(e.status===`failed`)return _a(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 ya(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 ba(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 xa(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=ba(e.coverage,r.id),a=ya(e.sensors,r.id,t,r.type),o=ve({controllable:a,deviceId:r.id,nonBlocking:e.nonBlocking,blocking:e.blocking}),s=_e({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&&xa(i)&&(!o||c)&&c;!t&&xa(i)&&!c||n.push({device:r,removed:t,cell:va(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 wa(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 Ta(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 Ea(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 Da(e,t){return re(Ea(e),t)?{kind:`landed`}:{kind:`not-landed`}}var Oa=[{field:`notifyDuringEntryDelay`,key:`duringEntryDelay`},{field:`notifySensorRewatched`,key:`rewatched`},{field:`notifySensorIgnored`,key:`ignored`}];function ka({coverage:t,settings:n,disabled:i,onNotifyEdit:a}){let{t:o}=Y(),s=B(n,t.mode);return e(`div`,{className:`space-y-2`,"data-testid":`alarm-notify-${t.mode}`,children:[r(`label`,{className:`block text-[11px] font-medium text-foreground`,children:o(`notificationRules.alarmNotify.title`)}),Oa.map(({field:n,key:c})=>e(`div`,{className:`flex items-start justify-between gap-3`,children:[e(`div`,{className:`min-w-0`,children:[r(`p`,{className:`text-xs text-foreground`,children:o(`notificationRules.alarmNotify.${c}`)}),r(`p`,{className:`text-[10px] text-foreground-subtle`,children:o(`notificationRules.alarmNotify.${c}Hint`)})]}),r(nt,{checked:s[n],onCheckedChange:e=>a(n,e),disabled:i,"data-testid":`alarm-notify-${t.mode}-${n}`,"aria-label":o(`notificationRules.alarmNotify.${c}`)})]},n))]})}function Aa({coverage:t,rows:n,names:i}){let{t:a}=Y(),o=n.filter(e=>e.coverage.kind.startsWith(`arm-checked`)).length,s=bi(t,i.nameOf);return e(`div`,{className:`flex flex-wrap items-center gap-1.5`,"data-testid":`alarm-badges-${t.mode}`,children:[Ci(t)?r(K,{variant:`warning`,title:s,"data-testid":`alarm-arms-nothing`,children:a(`system.alarmModeCard.armsNothingNoEnabledRule`,`Arms nothing — no enabled rule is gated on this mode`)}):r(K,{variant:`default`,title:s,"data-testid":`alarm-covers`,children:a(`system.alarmModeCard.checksSensors`,{count:o})}),t.skippedDevices.length>0?r(K,{variant:`warning`,title:xi(t.skippedDevices,i.nameOf),"data-testid":`alarm-skipped`,children:a(`system.alarmModeCard.notNotified`,{count:t.skippedDevices.length})}):null]})}function ja(e){return e.status===`answered`?e.openingIds:null}function Ma({check:t,view:n}){let{t:i}=Y();return n.unresolved?t.status===`pending`?e(`p`,{className:`flex items-center gap-1 text-xs text-foreground-subtle`,"data-testid":`alarm-openings-checking`,children:[r(T,{className:`h-3 w-3 animate-spin`}),i(`system.alarmModeCard.checkingWhichDevicesAreOpenings`,`Checking which devices are openings…`)]}):t.status===`failed`?e(`div`,{className:`flex flex-wrap items-center gap-2 text-xs text-warning`,"data-testid":`alarm-openings-check-failed`,children:[r(`span`,{children:i(`system.alarmModeCard.openingsCheckFailed`,{error:t.error})}),r(U,{type:`button`,size:`sm`,variant:`outline`,onClick:t.retry,children:i(`common.retry`,`Retry`)})]}):null:null}var Na=[{value:`rearmAfter`,labelKey:`system.alarmModeCard.postRearm`},{value:`disableAfter`,labelKey:`system.alarmModeCard.postDisarm`},{value:`doNothing`,labelKey:`system.alarmModeCard.postNothing`}];function Pa({coverage:t,settings:n,disabled:i,onDelayEdit:a,onPostTriggeredEdit:o,onScheduleEdit:s}){let{t:c}=Y(),l=t.mode,u=Oe(n,l),d=u.source.postTriggeredAction==="default",f=u.postTriggeredAction!==`doNothing`,p=(n.modeDelays??[]).find(e=>e.mode===l)?.schedule;return e(`div`,{className:`space-y-3`,"data-testid":`alarm-delays-${l}`,children:[e(`div`,{className:`grid grid-cols-2 gap-3 sm:grid-cols-4`,children:[$i.filter(e=>e.field!==`triggeredDurationSec`).map(e=>{let t=u.source[e.field]==="default";return r(na,{label:c(e.labelKey),value:u[e.field],max:e.max,zeroMeans:c(e.zeroMeansKey),disabled:i,testId:`alarm-delay-${l}-${e.key}`,onCommit:t=>a(e.field,t),adornment:t?r(K,{variant:`default`,title:c(`system.alarmModeCard.usesTheSystemDefaultS`,`Uses the system default ({{value1}} s)`,{value1:n[e.field]}),children:c(`system.alarmModeCard.default`,`Default`)}):r(U,{type:`button`,size:`sm`,variant:`ghost`,disabled:i,title:c(`system.alarmModeCard.useTheDefault`,`Use the default`),"aria-label":c(`system.alarmModeCard.useTheDefault2`,`{{label}}: use the default`,{label:c(e.labelKey)}),onClick:()=>a(e.field,`default`),"data-testid":`alarm-delay-${l}-${e.key}-default`,children:r(_,{className:`h-3.5 w-3.5`})})},e.field)}),e(`div`,{children:[e(`label`,{className:`mb-1 block text-[11px] font-medium text-foreground`,children:[c(`system.alarmModeCard.afterTrigger`,`After trigger`),d?r(K,{variant:`default`,className:`ml-1.5 align-middle`,title:c(`system.alarmModeCard.usesTheSystemDefault`,`Uses the system default`),children:c(`system.alarmModeCard.default`,`Default`)}):r(U,{type:`button`,size:`sm`,variant:`ghost`,className:`ml-1 align-middle`,disabled:i,title:c(`system.alarmModeCard.useTheDefault`,`Use the default`),"aria-label":c(`system.alarmModeCard.afterTriggerUseTheDefault`,`After trigger: use the default`),onClick:()=>o(`default`),"data-testid":`alarm-delay-${l}-post-default`,children:r(_,{className:`h-3.5 w-3.5`})})]}),r(`select`,{className:`mt-1 w-full rounded border border-border bg-background px-2 py-1 text-xs`,value:u.postTriggeredAction,disabled:i,"data-testid":`alarm-delay-${l}-post`,onChange:e=>{let t=ee.safeParse(e.target.value);t.success&&o(t.data)},children:Na.map(e=>r(`option`,{value:e.value,children:c(e.labelKey)},e.value))})]}),f?$i.filter(e=>e.field===`triggeredDurationSec`).map(e=>{let t=u.source[e.field]==="default";return r(na,{label:c(e.labelKey),value:u[e.field],max:e.max,zeroMeans:c(e.zeroMeansKey),disabled:i,testId:`alarm-delay-${l}-${e.key}`,onCommit:t=>a(e.field,t),adornment:t?r(K,{variant:`default`,title:c(`system.alarmModeCard.usesTheSystemDefaultS`,`Uses the system default ({{value1}} s)`,{value1:n[e.field]}),children:c(`system.alarmModeCard.default`,`Default`)}):r(U,{type:`button`,size:`sm`,variant:`ghost`,disabled:i,title:c(`system.alarmModeCard.useTheDefault`,`Use the default`),"aria-label":c(`system.alarmModeCard.useTheDefault2`,`{{label}}: use the default`,{label:c(e.labelKey)}),onClick:()=>a(e.field,`default`),"data-testid":`alarm-delay-${l}-${e.key}-default`,children:r(_,{className:`h-3.5 w-3.5`})})},e.field)}):null]}),e(`div`,{"data-testid":`alarm-schedule-${l}`,children:[r(`label`,{className:`mb-1 block text-[11px] font-medium text-foreground`,children:c(`system.alarmModeCard.activationSchedule`,`Activation schedule`)}),r(`p`,{className:`mb-1 text-[10px] text-foreground-subtle`,children:c(`system.alarmModeCard.whenThisModeMayBe`,`When this mode may be armed. Empty means any day and time.`)}),r(`fieldset`,{disabled:i,className:`min-w-0 border-0 p-0`,children:r(Xt,{value:p,onChange:s,emptyHint:`Always allowed — add a window to restrict when this mode can be armed.`})})]})]})}var Fa={"no-opening":`This household has no contact, cover or lock.`};function Ia({coverage:t,live:n,settings:i,names:a,openingsCheck:o,rows:s,sensorsRetry:c,inFlight:l,onSwitch:u,zones:d,onDelayEdit:f,onPostTriggeredEdit:p,onScheduleEdit:m,onNotifyEdit:h,disabled:g}){let{t:_}=Y(),v=fi({live:n,listed:Ni(i,t.mode),openingIds:ja(o)}),y=pi(v),b=Ca({rowCount:s.length,candidatesComplete:!v.unresolved});return e(`div`,{className:`flex flex-col gap-3`,"data-mode":t.mode,"data-empty":Ci(t)?`true`:`false`,children:[r(Aa,{coverage:t,rows:s,names:a}),r(Pa,{coverage:t,settings:i,disabled:g,onDelayEdit:f,onPostTriggeredEdit:p,onScheduleEdit:m}),r(`p`,{className:`text-[10px] text-foreground-subtle`,"data-testid":`alarm-delays-hint`,children:_(`system.alarmModeCard.delaysHint`,{seconds:30})}),r(ka,{coverage:t,settings:i,disabled:g,onNotifyEdit:h}),e(`div`,{className:`flex flex-col gap-2`,"data-testid":`alarm-nonblocking-${t.mode}`,children:[r(Ma,{check:o,view:v}),y===null?null:r(`p`,{className:`text-xs text-foreground-subtle`,children:Fa[y]}),b===`none`&&y===null?r(`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`?r(ha,{mode:t.mode,rows:s,sensorsRetry:c,inFlight:l,onSwitch:u,zones:d,disabled:g}):null]})]})}s();function La({profiles:t,busy:n,onActivate:i,onCreate:o,onClone:s,onRename:c,onDelete:l}){let{t:u}=Y(),[f,p]=a(``),[g,_]=a(!1),v=t.items.find(e=>e.id===t.activeId)??t.items[0],y=v!==void 0&&!v.isDefault,b=f.trim(),x=()=>{b.length!==0&&(o(b),p(``))},S=()=>{b.length===0||v===void 0||(s(v.id,b),p(``))},C=()=>{b.length===0||v===void 0||(c(v.id,b),p(``),_(!1))};return e(`div`,{className:`flex flex-col gap-2 rounded-md border border-border bg-surface-1 p-3`,"data-testid":`alarm-profiles`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[r(`label`,{className:`text-xs font-medium text-foreground-muted`,htmlFor:`alarm-profile-select`,children:u(`system.alarmProfileBar.profile`,`Profile`)}),r(`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:n,value:t.activeId,onChange:e=>i(e.target.value),children:t.items.map(t=>e(`option`,{value:t.id,children:[t.name,t.isDefault?` (${u(`system.alarmProfileBar.defaultSuffix`)})`:``]},t.id))}),y?r(U,{type:`button`,variant:`ghost`,size:`sm`,disabled:n,"data-testid":`alarm-profile-delete`,title:u(`system.alarmProfileBar.deleteThisProfile`,`Delete this profile`),onClick:()=>{v!==void 0&&l(v.id)},children:r(h,{className:`h-3.5 w-3.5`})}):null]}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[r(G,{className:`h-8 max-w-[14rem]`,"data-testid":`alarm-profile-name`,placeholder:g?u(`system.alarmProfileBar.newName`,`New name`):u(`system.alarmProfileBar.newProfileName`,`New profile name`),value:f,disabled:n,onChange:e=>p(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(g?C():x())}}),g?e(d,{children:[r(U,{type:`button`,size:`sm`,disabled:n||b.length===0,"data-testid":`alarm-profile-rename-save`,onClick:C,children:u(`system.alarmProfileBar.rename`,`Rename`)}),r(U,{type:`button`,variant:`ghost`,size:`sm`,disabled:n,"data-testid":`alarm-profile-rename-cancel`,onClick:()=>{_(!1),p(``)},children:u(`common.cancel`,`Cancel`)})]}):e(d,{children:[e(U,{type:`button`,size:`sm`,disabled:n||b.length===0,"data-testid":`alarm-profile-create`,title:u(`system.alarmProfileBar.createWithSystemDefaults`,`Create with system defaults`),onClick:x,children:[r(m,{className:`mr-1 h-3.5 w-3.5`}),u(`system.alarmProfileBar.create`,`Create`)]}),e(U,{type:`button`,size:`sm`,variant:`secondary`,disabled:n||b.length===0||v===void 0,"data-testid":`alarm-profile-clone`,title:u(`system.alarmProfileBar.cloneTheSelectedProfile`,`Clone the selected profile`),onClick:S,children:[r(O,{className:`mr-1 h-3.5 w-3.5`}),u(`system.alarmProfileBar.clone`,`Clone`)]}),r(U,{type:`button`,size:`sm`,variant:`ghost`,disabled:n||v===void 0,"data-testid":`alarm-profile-rename`,onClick:()=>{_(!0),p(v?.name??``)},children:u(`system.alarmProfileBar.rename`,`Rename`)})]})]}),r(`p`,{className:`text-[11px] text-foreground-subtle`,children:u(`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.`)})]})}s();var Ra=[`notificationRules`,`getAlarmConfig`],za=[`notificationRules`,`getAlarmSensors`],Ba=[`deviceManager`,`listDeviceIdsByCaps`,`alarm-openings`],Va=6e4;function Ha(e){return e instanceof Error?e.message:String(e)}function Ua({notice:e}){let{t}=Y();switch(e.kind){case`refused`:return r(`p`,{className:`text-xs text-warning`,role:`alert`,"data-testid":`alarm-switch-refused`,children:t(`system.notificationAlarm.refused`,{name:e.inFlight.name,mode:vi(e.inFlight.mode)})});case`not-landed`:return r(`p`,{className:`text-xs text-warning`,role:`alert`,"data-testid":`alarm-switch-not-landed`,children:t(`system.notificationAlarm.notLanded`,{name:e.write.name,mode:vi(e.write.mode)})});case`failed`:return r(`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:vi(e.write.mode),error:e.error})})}}function Wa(){let{t:i}=Y(),s=w(),d=c(),f=o({queryKey:Ra,queryFn:async()=>s.trpcClient.notificationRules.getAlarmConfig.query({}),refetchInterval:e=>Oi(e.state.data?.live?.state)}),p=Qe({projection:`slim`}),[m,h]=a(!1),g=u({mutationFn:e=>s.trpcClient.notificationRules.setAlarmConfig.mutate({patch:e}),onSuccess:(e,t)=>{d.setQueryData(Ra,e),h(!re(t,e.settings))}}),_=u({mutationFn:async e=>{switch(e.kind){case`activate`:return s.trpcClient.notificationRules.activateAlarmProfile.mutate({id:e.id});case`create`:return s.trpcClient.notificationRules.createAlarmProfile.mutate({name:e.name});case`clone`:return s.trpcClient.notificationRules.createAlarmProfile.mutate({name:e.name,cloneFromId:e.fromId});case`rename`:return s.trpcClient.notificationRules.renameAlarmProfile.mutate({id:e.id,name:e.name});case`delete`:return s.trpcClient.notificationRules.deleteAlarmProfile.mutate({id:e.id})}},onSuccess:e=>{d.setQueryData(Ra,e),h(!1)}}),v=()=>d.invalidateQueries({queryKey:Ra}),y=n(()=>{let e=new Map;for(let t of p.data??[])e.set(t.id,t.name);return e},[p.data]),b=f.data?.live,x=o({queryKey:Ba,staleTime:Va,queryFn:async()=>new Set(await s.trpcClient.deviceManager.listDeviceIdsByCaps.query({capNames:[...ui]}))}),S=n(()=>(p.data??[]).map(e=>({id:e.id,name:e.name,type:String(e.type),location:e.location??null})),[p.data]),C=n(()=>new Map(S.map(e=>[e.id,e])),[S]),E=x.isError?{status:`failed`,error:x.error instanceof Error?x.error.message:String(x.error),retry:()=>void x.refetch()}:x.data===void 0?{status:`pending`}:{status:`answered`,openingIds:x.data},O=n(()=>{let e=new Map;for(let t of b?.openings??[])for(let n of t.devices)e.set(n.deviceId,hi(n));return mi(y,mt(p),e)},[b,y,p]),k=ft(!0),[A,j]=a(null),M=n(()=>{let e=new Map,t=f.data;if(t===void 0)return e;for(let n of t.coverage)e.set(n.mode,fi({live:t.live,listed:Ni(t.settings,n.mode),openingIds:x.data??null}).ids);return e},[f.data,x.data]),N=n(()=>{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=o({queryKey:[...za,N],enabled:N.length>0,placeholderData:l,refetchOnWindowFocus:!0,refetchInterval:e=>e.state.error!==null&&_a(Ha(e.state.error))?!1:b!==void 0&&ji(b.state)?5e3:15e3,retry:(e,t)=>!_a(Ha(t))&&e<2,queryFn:async()=>{let e=[];for(let t of wa(N,500))e.push(await s.trpcClient.notificationRules.getAlarmSensors.query({deviceIds:[...t]}));return{sensors:e.flatMap(e=>e.sensors),readAt:Math.min(...e.map(e=>e.readAt))}}}),ee=P.isError?{status:`failed`,error:Ha(P.error)}:P.data===void 0?{status:`pending`}:{status:`answered`,sensors:P.data.sensors},F=t(null),[I,te]=a(null),[L,ne]=a(null),R=async e=>{try{let t=await s.trpcClient.notificationRules.setAlarmConfig.mutate({patch:Ea(e)});Da(e,t.settings).kind===`landed`?d.setQueryData(Ra,t):(ne({kind:`not-landed`,write:e}),d.invalidateQueries({queryKey:Ra}))}catch(t){ne({kind:`failed`,write:e,error:Ha(t)}),d.invalidateQueries({queryKey:Ra})}finally{F.current=null,te(null),ne(e=>e?.kind===`refused`?null:e)}},z=(e,t,n,r)=>{let i=Ta(F.current,e,t,n,r);if(i.kind===`refused`){ne({kind:`refused`,inFlight:i.inFlight});return}F.current=i.write,te(i.write),ne(null),R(i.write)};if(f.isLoading)return r(ci,{embedded:!0,icon:D,title:i(`system.notificationAlarm.alarm`,`Alarm`),subtitle:i(`system.notificationAlarm.panelDelaysAndModeCoverage`,`Panel delays and mode coverage.`),children:r(T,{className:`h-5 w-5 animate-spin`})});let B=f.data;if(B===void 0||f.isError)return r(ci,{embedded:!0,icon:D,title:i(`system.notificationAlarm.alarm`,`Alarm`),subtitle:i(`system.notificationAlarm.panelDelaysAndModeCoverage`,`Panel delays and mode coverage.`),children:r(H,{title:i(`system.notificationAlarm.alarmSettingsAreNotAvailable`,`Alarm settings are not available`),message:i(`system.notificationAlarm.thisHubHasNotBeen`,`This hub has not been updated to serve the alarm configuration yet.`)})});if(B.deviceId===null)return r(ci,{embedded:!0,icon:D,title:i(`system.notificationAlarm.alarm`,`Alarm`),subtitle:i(`system.notificationAlarm.panelDelaysAndModeCoverage`,`Panel delays and mode coverage.`),children:r(bt,{className:`p-4`,children:r(`p`,{className:`text-sm text-foreground-subtle`,children:i(`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 ie=B.settings,ae=g.isPending||_.isPending,oe=e=>{h(!1),g.mutate(e)},se=(e,t,n)=>{let r=Ri(ie,e,t,n);r!==null&&oe({modeDelays:[r]})},ce=(e,t)=>{let n=zi(ie,e,t);n!==null&&oe({modeDelays:[n]})},le=(e,t)=>{let n=Bi(ie,e,t);n!==null&&oe({modeDelays:[n]})},ue=(e,t,n)=>{let r=qi(ie,e,t,n);r!==null&&oe({modeDelays:[r]})},de=new Map(B.coverage.map(e=>[e.mode,Sa({candidates:(M.get(e.mode)??[]).map(e=>({...C.get(e),id:e,name:O.nameOf(e)})),removedIds:new Set((M.get(e.mode)??[]).filter(O.isRemoved)),coverage:e,nonBlocking:Ni(ie,e.mode),blocking:Pi(ie,e.mode),secureOnArmOff:Fi(ie,e.mode),sensors:ee})])),fe=B.coverage.find(e=>e.mode===A)??B.coverage.find(e=>(de.get(e.mode)?.length??0)>0)??B.coverage[0],pe=fe?.mode??``;return e(ci,{embedded:!0,icon:D,title:i(`system.notificationAlarm.alarm`,`Alarm`),subtitle:i(`system.notificationAlarm.thePanelWhatEachMode`,`The panel, what each mode arms, and who hears about it.`),children:[g.isError?r(H,{title:i(`system.notificationAlarm.couldNotSave`,`Could not save`),message:String(g.error)}):null,_.isError?r(H,{title:i(`system.notificationAlarm.couldNotUpdateProfile`,`Could not update profile`),message:String(_.error)}):null,m?r(`div`,{"data-testid":`alarm-save-not-landed`,children:r(H,{variant:`warning`,title:i(`system.notificationAlarm.notApplied`,`Not applied`),message:i(`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:r(La,{profiles:B.profiles,busy:ae,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})}),r(Qi,{live:B.live,onChanged:v}),e(bt,{className:`p-4`,"data-testid":`alarm-coverage`,children:[r(lt,{value:pe,onValueChange:e=>{let t=B.coverage.find(t=>t.mode===e);t!==void 0&&j(t.mode)},children:r(Xe,{className:`mb-3`,children:B.coverage.map(t=>e(ht,{value:t.mode,"data-testid":`alarm-tab-${t.mode}`,children:[vi(t.mode),r(`span`,{className:`ml-1.5 text-[10px] text-foreground-subtle`,children:de.get(t.mode)?.length??0})]},t.mode))})}),L===null?null:r(Ua,{notice:L}),fe===void 0?null:r(Ia,{coverage:fe,live:B.live,settings:ie,names:O,openingsCheck:E,rows:de.get(fe.mode)??[],sensorsRetry:ee.status===`failed`&&!_a(ee.error)?()=>void P.refetch():null,inFlight:I,onSwitch:(e,t,n)=>z(fe.mode,e,t,n),zones:k,onDelayEdit:(e,t)=>se(fe.mode,e,t),onPostTriggeredEdit:e=>ce(fe.mode,e),onScheduleEdit:e=>le(fe.mode,e),onNotifyEdit:(e,t)=>ue(fe.mode,e,t),disabled:ae},fe.mode)]})]})}var Ga=`history`,Ka=`ruleId`,qa=[Ka],Ja=24,Ya=0,Xa=100;function Za(e,t){let n=new URLSearchParams(e);return n.set(`tab`,Ga),n.set(Ka,t),n}function Qa(e,t){let n=new URLSearchParams(e);return t===``?n.delete(Ka):n.set(Ka,t),n}function $a(e){let t=e.get(`ruleId`)??``;return{ruleId:t,deviceId:``,status:``,windowHours:t===``?Ja:Ya,limit:Xa}}function eo(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?J.t(`helpers.notificationHistory.deletedRule`,{id:e.selected}):e.selected}]:[];return[{value:``,label:J.t(`helpers.notificationHistory.allRules`)},...t,...n]}s();var to=[{value:1,labelKey:`system.notificationHistory.windowLastHour`},{value:24,labelKey:`system.notificationHistory.windowLast24h`},{value:168,labelKey:`system.notificationHistory.windowLast7d`},{value:0,labelKey:`system.notificationHistory.windowAllTime`}],no=[{value:``,labelKey:`system.notificationHistory.statusAny`},{value:`pending`,labelKey:`system.notificationHistory.statusPending`},{value:`sent`,labelKey:`system.notificationHistory.statusSent`},{value:`dead`,labelKey:`system.notificationHistory.statusDead`}],ro=[50,100,250,500];function io(e){return e===`pending`||e===`sent`||e===`dead`?e:void 0}function ao(e){switch(e){case`pending`:return`info`;case`sent`:return`success`;case`dead`:return`danger`}}function oo(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 so({entry:t,cameraName:n,onClose:i}){let{t:a}=Y(),o=oo(t),s=t.subject.systemEvent;return r(xt,{open:!0,onOpenChange:e=>!e&&i(),children:e(kt,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,"data-testid":`history-delivery-detail`,children:[r(wt,{children:r(vt,{className:`min-w-0 break-words`,children:o.title||t.ruleName})}),r(St,{children:e(`dl`,{className:`space-y-3`,children:[e(`div`,{children:[r(`dt`,{className:`text-[10px] font-medium uppercase tracking-wide text-foreground-subtle`,children:a(`system.notificationHistory.body`,`Body`)}),r(`dd`,{className:`mt-1 whitespace-pre-wrap text-sm text-foreground`,children:o.body.length>0?o.body:`—`})]}),e(`div`,{className:`grid grid-cols-2 gap-3 text-[11px]`,children:[e(`div`,{children:[r(`dt`,{className:`font-medium text-foreground-subtle`,children:a(`system.notificationHistory.when`,`When`)}),r(`dd`,{className:`text-foreground`,children:new Date(t.createdAt).toLocaleString()})]}),e(`div`,{children:[r(`dt`,{className:`font-medium text-foreground-subtle`,children:a(`system.notificationHistory.status`,`Status`)}),r(`dd`,{className:`text-foreground`,children:t.status})]}),e(`div`,{children:[r(`dt`,{className:`font-medium text-foreground-subtle`,children:a(`system.notificationHistory.rule`,`Rule`)}),r(`dd`,{className:`text-foreground`,children:t.ruleName})]}),e(`div`,{children:[r(`dt`,{className:`font-medium text-foreground-subtle`,children:a(`system.notificationHistory.device`,`Device`)}),r(`dd`,{className:`text-foreground`,children:n})]}),s===void 0?null:e(`div`,{className:`col-span-2`,children:[r(`dt`,{className:`font-medium text-foreground-subtle`,children:a(`system.notificationHistory.kind`,`Kind`)}),r(`dd`,{className:`text-foreground`,children:s.kind})]}),t.error===void 0?null:e(`div`,{className:`col-span-2`,children:[r(`dt`,{className:`font-medium text-foreground-subtle`,children:a(`common.error`,`Error`)}),r(`dd`,{className:`text-danger`,children:t.error})]})]})]})}),r(Tt,{children:r(U,{type:`button`,size:`sm`,variant:`secondary`,onClick:i,children:a(`common.close`,`Close`)})})]})})}function co(){let{t}=Y(),i=w(),[s,c]=gr(),[l,u]=a(()=>$a(s)),[d,f]=a(null),m=e=>u(t=>({...t,...e})),h=e=>{m({ruleId:e}),c(Qa(s,e),{replace:!0})},g=o({queryKey:[`notificationRules`,`listRules`,`forHistory`],queryFn:async()=>(await i.trpcClient.notificationRules.listRules.query({})).rules}),_=Qe({projection:`slim`}),y=Date.now(),b=o({queryKey:[`notificationRules`,`getHistory`,l],retry:!1,queryFn:async()=>{let e=l.windowHours>0?y-l.windowHours*36e5:void 0;return(await i.trpcClient.notificationRules.getHistory.query({filter:{limit:l.limit,...l.ruleId?{ruleId:l.ruleId}:{},...l.deviceId?{deviceId:Number(l.deviceId)}:{},...io(l.status)?{status:io(l.status)}:{},...e===void 0?{}:{since:e}}})).entries}}),x=n(()=>{let e=new Map;for(let t of _.data??[])t.type===Te.Camera&&e.set(t.id,t.name);return e},[_.data]),S=e=>x.get(e)??t(`system.notificationHistory.cameraFallback`,{deviceId:e}),C=b.data??[],E=b.isError;return e(ci,{embedded:!0,icon:v,title:t(`system.notificationHistory.deliveryHistory`,`Delivery history`),subtitle:t(`system.notificationHistory.aSearchableLogOfEvery`,`A searchable log of every notification the rules delivered (or failed to deliver).`),children:[e(`div`,{className:`mb-4 grid grid-cols-2 gap-2 sm:grid-cols-5`,children:[e(`div`,{children:[r(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:t(`system.notificationHistory.rule`,`Rule`)}),r(W,{"data-testid":`history-rule-filter`,value:l.ruleId,onChange:e=>h(e.target.value),options:[...eo({rules:g.data??[],answered:g.isSuccess,selected:l.ruleId})]})]}),e(`div`,{children:[r(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:t(`system.notificationHistory.camera`,`Camera`)}),r(W,{value:l.deviceId,onChange:e=>m({deviceId:e.target.value}),options:[{value:``,label:t(`system.notificationHistory.allCameras`,`All cameras`)},...(_.data??[]).map(e=>({value:String(e.id),label:e.name}))]})]}),e(`div`,{children:[r(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:t(`system.notificationHistory.status`,`Status`)}),r(W,{value:l.status,onChange:e=>m({status:e.target.value}),options:no.map(e=>({value:e.value,label:t(e.labelKey)}))})]}),e(`div`,{children:[r(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:t(`system.notificationHistory.window`,`Window`)}),r(W,{value:String(l.windowHours),onChange:e=>m({windowHours:Number(e.target.value)}),options:to.map(e=>({value:String(e.value),label:t(e.labelKey)}))})]}),e(`div`,{children:[r(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:t(`system.notificationHistory.limit`,`Limit`)}),r(W,{value:String(l.limit),onChange:e=>m({limit:Number(e.target.value)}),options:ro.map(e=>({value:String(e),label:String(e)}))})]})]}),b.isLoading&&r(`div`,{className:`flex items-center justify-center py-16`,children:r(T,{className:`h-6 w-6 animate-spin text-primary`})}),E&&!b.isLoading&&r(bt,{children:e(`div`,{className:`flex flex-col items-center gap-2 px-4 py-14 text-center`,children:[r(v,{className:`h-6 w-6 text-foreground-subtle`}),r(`div`,{className:`text-sm font-medium text-foreground`,children:t(`system.notificationHistory.deliveryHistoryRequiresAServer`,`Delivery history requires a server update`)}),r(`p`,{className:`max-w-md text-xs text-foreground-subtle`,children:t(`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.`)}),e(`button`,{type:`button`,onClick:()=>void b.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:[r(p,{className:`h-3 w-3`}),` `,t(`common.retry`)]})]})}),!E&&!b.isLoading&&C.length===0&&r(`div`,{className:`py-16 text-center text-xs text-foreground-subtle`,children:t(`system.notificationHistory.noDeliveriesMatchTheseFilters`,`No deliveries match these filters.`)}),!E&&C.length>0&&r(bt,{children:r(dt,{columns:lo(S),rows:C,rowKey:e=>e.id,minWidthPx:720,bordered:!1,maxBodyHeight:`max-h-[60vh]`,onRowClick:e=>f(e)})}),d!==null&&r(so,{entry:d,cameraName:S(d.deviceId),onClose:()=>f(null)})]})}function lo(t){return[{key:`when`,header:J.t(`system.notificationHistory.when`,`When`),nowrap:!0,render:e=>r(`span`,{className:`text-[11px] text-foreground-subtle`,children:new Date(e.createdAt).toLocaleString()})},{key:`rule`,header:J.t(`system.notificationHistory.rule`,`Rule`),render:e=>r(`span`,{className:`text-xs font-medium text-foreground`,children:e.ruleName})},{key:`camera`,header:J.t(`system.notificationHistory.camera`,`Camera`),nowrap:!0,render:e=>r(`span`,{className:`text-[11px] text-foreground-subtle`,children:t(e.deviceId)})},{key:`subject`,header:J.t(`system.notificationHistory.notification`,`Notification`),render:t=>{let n=oo(t);return e(`span`,{className:`block max-w-[18rem]`,children:[r(`span`,{className:`block truncate text-[11px] font-medium text-foreground`,children:n.title.length>0?n.title:t.subject.label??t.subject.className}),n.body.length>0?r(`span`,{className:`block truncate text-[10px] text-foreground-subtle`,children:n.body}):null]})}},{key:`status`,header:J.t(`system.notificationHistory.status`,`Status`),nowrap:!0,render:t=>e(`span`,{className:`flex items-center gap-1.5`,children:[r(K,{variant:ao(t.status),children:t.status}),t.attempts>1?e(`span`,{className:`text-[10px] text-foreground-subtle`,children:[`×`,t.attempts]}):null]})},{key:`error`,header:J.t(`system.notificationHistory.detail`,`Detail`),render:e=>e.error?r(`span`,{className:`text-[11px] text-danger`,children:e.error}):r(`span`,{className:`text-[11px] text-foreground-subtle`,children:`—`})}]}var uo=/\{\{\s*(\w+)\s*\}\}/g,fo=[`subject`,`place`,`time`,`rule`,`occupancy`,`sound`,`sensor`,`system`,`digest`,`ai`];function po(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 mo(e){let t=`{{${e.name}}}`;return{text:t,cursorOffset:e.dynamic?t.length-2:t.length}}function ho(e){return[...e.matchAll(uo)].map(e=>e[1]??``).filter(e=>e.length>0)}function go(e,t){return t.some(t=>t.dynamic?e.startsWith(t.dynamic.prefix)&&e.length>t.dynamic.prefix.length:t.name===e)}function _o(e,t){return[...new Set(ho(e))].filter(e=>!go(e,t))}var vo={previewText:[`camera`,`rule`,`from`,`to`],captionText:[`rule`,`from`,`to`]};function yo(e){return e.map(e=>{let t=Pe.find(t=>t.name===e.name),n=e.systemEventKinds;if(t?.systemEventKinds===void 0||n===void 0)return e;let r=t.systemEventKinds.filter(e=>n.includes(e)||ue.includes(e)),i=n.filter(e=>!r.includes(e));return{...e,systemEventKinds:[...r,...i]}})}function bo(e){let t=new Set(e.map(e=>e.name)),n=Pe.filter(e=>F(e)&&!t.has(e.name));return[...e,...n]}function xo(e,t){if(t.field===`previewText`||t.field===`captionText`){let n=vo[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)||!z(e.kinds,t.kind)||e.deliveries&&t.delivery!==void 0&&!e.deliveries.includes(t.delivery)?!1:he(e,t)&&ge(e,t))}function So(e){return fo.map(t=>({group:t,vars:e.filter(e=>e.group===t)})).filter(e=>e.vars.length>0)}var Co=[`nc`,`template-catalog`],wo=400;function To(){let e=w();return o({queryKey:Co,staleTime:5*6e4,queryFn:async()=>bo(yo((await e.trpcClient.notificationRules.getTemplateCatalog.query({})).vars))})}function Eo(e,t,n){let r=w(),i=jt(t.title??``,wo),a=jt(t.body??``,wo);return o({queryKey:[`nc`,`template-preview`,e,i,a],enabled:n&&(i.length>0||a.length>0),staleTime:3e4,queryFn:()=>r.trpcClient.notificationRules.previewTemplate.mutate({context:e,template:{...i?{title:i}:{},...a?{body:a}:{}}})})}s();var Do={subject:`Subject`,place:`Place`,time:`Time`,rule:`Rule`,occupancy:`Occupancy`,sound:`Sound`,sensor:`Sensor`,system:`System event`,digest:`Digest`,ai:`AI`},Oo=`block text-[11px] font-medium text-foreground mb-1`,ko=`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 Ao({label:n,value:i,onChange:a,vars:o,multiline:s=!1,placeholder:c,disabled:l=!1,testId:u}){let{t:d}=Y(),f=t(null),p=t(null),m=o?_o(i,o):[],h=e=>{let t=s?p.current:f.current,n={start:t?.selectionStart??i.length,end:t?.selectionEnd??i.length},r=mo(e),o=po(i,n,r.text);a(o.value);let c=o.cursor-r.text.length+r.cursorOffset;requestAnimationFrame(()=>{t?.focus(),t?.setSelectionRange(c,c)})},g=e=>a(e.target.value);return e(`div`,{className:`space-y-1`,children:[r(`label`,{className:Oo,children:n}),s?r(`textarea`,{ref:p,value:i,rows:2,disabled:l,placeholder:c,onChange:g,className:ko,"data-testid":`${u}-input`}):r(G,{ref:f,value:i,disabled:l,placeholder:c,onChange:g,"data-testid":`${u}-input`}),o&&o.length===0?r(`p`,{className:`text-[10px] text-foreground-subtle`,children:d(`notifications.templateField.noVariablesForThisField`,`No variables for this field.`)}):null,o&&o.length>0?r(`div`,{className:`flex flex-wrap gap-x-3 gap-y-1`,children:So(o).map(t=>e(`div`,{className:`flex flex-wrap items-center gap-1`,"data-testid":`${u}-group-${t.group}`,children:[r(`span`,{className:`text-[10px] uppercase text-foreground-subtle`,children:Do[t.group]}),t.vars.map(e=>r(`button`,{type:`button`,disabled:l,onMouseDown:e=>e.preventDefault(),onClick:()=>h(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":`${u}-chip-${e.name}`,children:e.dynamic?d(`notifications.templateField.class`,`{{name}}<class>`,{name:e.name}):e.name},e.name))]},t.group))}):null,m.length>0?e(`p`,{className:`flex items-center gap-1 text-[10px] text-warning`,"data-testid":`${u}-unknown`,children:[r(N,{className:`h-3 w-3`}),d(`notifications.templateField.willBeEmpty`,{names:m.map(e=>`{{${e}}}`).join(` `)})]}):null]})}function jo({context:t,title:n,body:i,testId:a}){let{t:o}=Y(),s=Eo(t,{title:n,body:i},!0);return s.data?e(`div`,{className:`rounded-md border border-border bg-surface-subtle px-2.5 py-1.5 text-xs`,"data-testid":a,children:[r(`p`,{className:`text-[10px] uppercase text-foreground-subtle`,children:o(`notifications.templateField.previewExampleValues`,`Preview (example values)`)}),s.data.title===null?null:r(`p`,{className:`font-medium`,children:s.data.title}),s.data.body===null?null:r(`p`,{className:`whitespace-pre-wrap`,children:s.data.body})]}):null}var Mo=`mt-1 w-full rounded border border-border bg-background px-2 py-1 text-xs`,No=`block text-[11px] font-medium text-foreground`;function Po({title:t,description:n,children:i}){return e(`div`,{className:`flex flex-col gap-2`,children:[e(`div`,{children:[r(`h4`,{className:`text-xs font-semibold text-foreground`,children:t}),r(`p`,{className:`text-[11px] text-foreground-subtle`,children:n})]}),i!==void 0&&r(`div`,{className:`flex flex-wrap items-center gap-1`,children:i})]})}function Fo(e){return typeof e==`number`?e>0?[e]:[]:Array.isArray(e)?e.filter(e=>e>0):[]}function Io(e,t){return{kind:`cap`,deviceId:t,cap:e.cap,method:e.method,...e.args===void 0?{}:{args:{...e.args}}}}function Lo(e){let t=Fo(e.deviceId);return t.length===0?[Io(e,0)]:t.map(t=>Io(e,t))}function Ro(e){return Lo(e).map(e=>({kind:`do`,action:e}))}function zo(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 Bo(e,t){let n=e[t];return n===void 0||n.kind!==`do`?{wire:{deviceId:0,cap:``,method:``},length:1}:zo(e.slice(t).map(e=>e.kind===`do`?e.action:{kind:`wait`,seconds:0}),0)}function Vo({value:t,onChange:n,devices:i,devicesState:a,sequences:o=[],showProblems:s=!0}){let{t:c}=Y(),l=bn(t,new Set(o.map(e=>e.id))),u=(e,r)=>n({...t,[e]:r}),d=(e,r)=>n({...t,buttons:t.buttons.map((t,n)=>n===e?r:t)});return e(`div`,{className:`space-y-4`,children:[s&&l.length>0?r(`div`,{className:`space-y-1 rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-[11px] text-warning`,children:l.map(e=>r(`p`,{children:e.message},e.message))}):null,Yt.map(e=>r(Ho,{hookKey:e,bindings:t[e],sequences:o,devices:i,devicesState:a,onChange:t=>u(e,t)},e)),e(`section`,{className:`space-y-2`,children:[r(Po,{title:c(`system.notificationRuleActions.buttonsOnTheNotification`,`Buttons on the notification`),description:c(`system.notificationRuleActions.eachButtonRunsOneShared`,`Each button runs one shared sequence when tapped.`),children:e(U,{size:`sm`,variant:`ghost`,type:`button`,disabled:o.length===0,onClick:()=>n({...t,buttons:[...t.buttons,Tr(t.buttons.length,o[0]?.id??``)]}),children:[r(m,{className:`h-3.5 w-3.5 shrink-0`}),` `,c(`system.notificationRuleActions.button`)]})}),t.buttons.length>0&&e(`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:[r(N,{className:`mt-0.5 h-3.5 w-3.5 shrink-0`}),r(`span`,{children:r(Kr,{i18nKey:`system.notificationRuleActions.buttonLinkNote`,components:{b:r(`strong`,{})}})})]}),o.length===0?r(`p`,{className:`rounded border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:c(`system.notificationRuleActions.createASequenceOnThe`,`Create a sequence on the Sequences tab first — a button runs one, it does not define its own steps.`)}):t.buttons.length===0?r(`p`,{className:`rounded border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:c(`system.notificationRuleActions.noButtonsTheNotificationArrives`,`No buttons. The notification arrives with nothing to tap.`)}):t.buttons.map((e,i)=>r(Uo,{button:e,sequences:o,onChange:e=>d(i,e),onRemove:()=>n({...t,buttons:t.buttons.filter((e,t)=>t!==i)})},`btn-${String(i)}`))]})]})}function Ho({hookKey:t,bindings:n,sequences:i,devices:a,devicesState:o,onChange:s}){let{t:c}=Y(),l=qt[t],u=[],d=0;for(;d<n.length;){if(n[d].kind===`sequence`){u.push({start:d,kind:`sequence`,length:1}),d+=1;continue}let e=Bo(n,d);u.push({start:d,kind:`do`,length:e.length}),d+=e.length}return e(`section`,{className:`space-y-2`,children:[e(Po,{title:l.title,description:l.hint,children:[e(U,{size:`sm`,variant:`ghost`,type:`button`,disabled:n.length>=4||i.length===0,onClick:()=>s([...n,Cr(i[0]?.id??``)]),children:[r(m,{className:`h-3.5 w-3.5`}),` `,c(`system.notificationRuleActions.sequence`)]}),e(U,{size:`sm`,variant:`ghost`,type:`button`,disabled:n.length>=4,onClick:()=>s([...n,zt()]),children:[r(m,{className:`h-3.5 w-3.5`}),` `,c(`system.notificationRuleActions.singleAction`)]})]}),n.length===0?r(`p`,{className:`rounded border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:c(`system.notificationRuleActions.nothingOnThisEdge`,`Nothing on this edge.`)}):u.map(t=>{if(t.kind===`sequence`){let a=n[t.start];return a.kind===`sequence`?e(`div`,{className:`flex flex-wrap items-end gap-2 rounded-md border border-border p-3`,children:[e(`div`,{className:`min-w-0 flex-1`,children:[r(`label`,{className:No,children:c(`system.notificationRuleActions.sequence`,`Sequence`)}),r(`select`,{className:Mo,value:a.sequenceId,onChange:e=>{let r=[...n];r[t.start]={kind:`sequence`,sequenceId:e.target.value},s(r)},children:i.map(e=>r(`option`,{value:e.id,children:e.name},e.id))})]}),r(U,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>s(n.filter((e,n)=>n!==t.start)),title:c(`common.remove`,`Remove`),children:r(h,{className:`h-3.5 w-3.5`})})]},`seq-${String(t.start)}`):null}return r(`div`,{className:`space-y-2 rounded-md border border-border p-3`,children:e(`div`,{className:`flex items-start justify-between gap-2`,children:[r(`div`,{className:`min-w-0 flex-1`,children:r(si,{value:Bo(n,t.start).wire,devices:a,listState:o,allowMultiSameFamily:!0,onChange:e=>{let r=Ro(e);s([...n.slice(0,t.start),...r,...n.slice(t.start+t.length)])}})}),r(U,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>s([...n.slice(0,t.start),...n.slice(t.start+t.length)]),title:c(`common.remove`,`Remove`),children:r(h,{className:`h-3.5 w-3.5`})})]})},`do-${String(t.start)}`)})]})}function Uo({button:t,sequences:n,onChange:i,onRemove:a}){let{t:o}=Y();return e(`div`,{className:`flex flex-wrap items-end gap-2 rounded-md border border-border p-3`,children:[e(`div`,{className:`w-28`,children:[r(`label`,{className:No,children:o(`system.notificationRuleActions.id`,`Id`)}),r(G,{className:`mt-1`,value:t.id,onChange:e=>i({...t,id:e.target.value})})]}),e(`div`,{className:`min-w-0 flex-1`,children:[r(`label`,{className:No,children:o(`system.notificationRuleActions.label`,`Label`)}),r(G,{className:`mt-1`,value:t.label,onChange:e=>i({...t,label:e.target.value})})]}),e(`div`,{className:`min-w-0 flex-1`,children:[r(`label`,{className:No,children:o(`system.notificationRuleActions.sequence`,`Sequence`)}),r(`select`,{className:Mo,value:t.sequenceId,onChange:e=>i({...t,sequenceId:e.target.value}),children:n.map(e=>r(`option`,{value:e.id,children:e.name},e.id))})]}),e(`div`,{className:`w-32`,children:[r(`label`,{className:No,children:o(`system.notificationRuleActions.icon`,`Icon`)}),e(`select`,{className:Mo,value:t.icon??``,onChange:e=>{let n={...t};e.target.value===``?delete n.icon:n.icon=e.target.value,i(n)},children:[r(`option`,{value:``,children:`—`}),Fn.map(e=>r(`option`,{value:e.value,children:e.label},e.value))]})]}),r(U,{size:`sm`,variant:`ghost`,type:`button`,onClick:a,title:o(`common.remove`,`Remove`),children:r(h,{className:`h-3.5 w-3.5`})})]})}var Wo=new Set([`devices`,`devicesExclude`,`customZones`,`source`,`crossing`]),Go=[[`classes`,`classesExclude`],[`zones`,`zonesExclude`],[`identities`,`identitiesExclude`]],Ko={minConfidence:`class`},qo=[{id:`system`,get label(){return J.t(`notificationRules.groups.system`)}},{id:`class`,get label(){return J.t(`notificationRules.groups.class`)}},{id:`zones`,get label(){return J.t(`notificationRules.groups.zones`)}},{id:`label`,get label(){return J.t(`notificationRules.groups.label`)}},{id:`quality`,get label(){return J.t(`notificationRules.groups.quality`)}},{id:`scope`,get label(){return J.t(`notificationRules.groups.scope`)}},{id:`device`,get label(){return J.t(`notificationRules.groups.device`)}},{id:`package`,get label(){return J.t(`notificationRules.groups.package`)}},{id:`occupancy`,get label(){return J.t(`notificationRules.groups.occupancy`)}},{id:`audio`,get label(){return J.t(`notificationRules.groups.audio`)}},{id:`schedule`,get label(){return J.t(`notificationRules.groups.schedule`)}}];function Jo(e){let t=new Set(e.map(e=>e.id)),n=new Set;for(let[e,r]of Go)t.has(e)&&n.add(r);return n}function Yo(e){return Ko[e.id]??e.group}function Xo(e){let t=e.replace(/[-_]/g,` `);return t.charAt(0).toUpperCase()+t.slice(1)}function Zo(e){let t=Jo(e),n=e.filter(e=>!Wo.has(e.id)&&!t.has(e.id)),r=new Set(qo.map(e=>e.id)),i=[],a=e=>n.filter(t=>Yo(t)===e);for(let e of qo){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=Yo(e);!r.has(t)&&!o.includes(t)&&o.push(t)}for(let e of o)i.push({id:e,label:Xo(e),descriptors:a(e)});return i}function Qo(e,t){switch(e){case`zones`:return An(t.zones?.ids,t.zonesExclude);case`labels`:return An(t.labelEquals,void 0);case`identities`:return $o(t)}}function $o(e){let t=e.identities,n=[...e.identitiesExclude??[]];return t===void 0?An(void 0,n):{mode:`only`,include:[...t],exclude:n,legacyBoth:n.length>0}}function es(e,t,n){switch(e){case`zones`:return ts(t,n);case`labels`:return ns(t,n);case`identities`:return rs(t,n)}}function ts(e,t){let{zones:n,zonesExclude:r,...i}=e,a=Qt(t);return{...i,...a.include===void 0?{}:{zones:{ids:[...a.include]}},...a.exclude===void 0?{}:{zonesExclude:[...a.exclude]}}}function ns(e,t){let{labelEquals:n,...r}=e,i=Qt(t);return{...r,...i.include===void 0?{}:{labelEquals:[...i.include]}}}function rs(e,t){let{identities:n,identitiesExclude:r,...i}=e;if(t.mode===`only`){let e=ii(t);return{...i,identities:[...t.include],...e.length>0?{identitiesExclude:[...e]}:{}}}let a=Qt(t);return{...i,...a.exclude===void 0?{}:{identitiesExclude:[...a.exclude]}}}var is={all:`All`,only:`Only these`,except:`All except these`},as={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 os({draft:t,onChange:n,exceptOffered:i,plural:a,renderPicker:o,describe:s,testId:c}){let{t:l}=Y(),u=(e,t,n)=>l(e,{items:n,defaultValue:t}).replaceAll(`{{items}}`,n),d=l(`ruleScope.items.${a}`,as[a].items),f=wn.filter(e=>e!==`except`||i||t.mode===`except`),p=ii(t),m=gn(t),h=t.mode===`all`?null:t.mode;return e(`div`,{className:`mt-1 space-y-1.5`,"data-testid":c,children:[r(`div`,{role:`radiogroup`,"aria-label":u(`ruleScope.which`,`Which {{items}}`,d),className:`inline-flex flex-wrap items-center gap-1`,children:f.map(e=>{let i=e===t.mode;return r(`button`,{type:`button`,role:`radio`,"aria-checked":i,"data-testid":`scope-mode-${e}`,onClick:()=>n(an(t,e)),className:i?`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:l(`ruleScope.mode.${e}`,is[e])},e)})}),h===null?r(`p`,{className:`text-[11px] text-foreground-subtle`,children:l(`ruleScope.every.${a}`,as[a].every)}):o(Ht(t),e=>n(Vn(t,e)),h),p.length>0&&e(`p`,{className:`text-[11px] text-warning`,"data-testid":`scope-legacy-exclusions`,children:[u(`ruleScope.legacy`,`This rule also excludes {{items}} — kept when you save.`,p.map(s).join(`, `)),` `,r(`button`,{type:`button`,className:`underline hover:no-underline`,onClick:()=>n(cn(t)),children:l(`ruleScope.removeExclusions`,`Remove exclusions`)})]}),m.length>0&&r(`p`,{className:`text-[11px] text-foreground-subtle`,"data-testid":`scope-cleared-on-save`,children:u(`ruleScope.cleared`,`Saving in this mode clears {{items}} from the rule.`,m.map(s).join(`, `))})]})}function ss(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 cs(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})}s();function ls(e,t,n){let[r,i]=a(()=>Qo(e,t));return[r,r=>{i(r),n(es(e,t,r))}]}function us(e,t){return t?`failed`:e?`pending`:`answered`}function ds({conditions:e,onConditionsChange:t,exceptOffered:i,cameraIds:a,cameras:o}){let{t:s}=Y(),[c,l]=ls(`zones`,e,t),{options:u,loading:d,failed:f}=sn(a,o),p=n(()=>cs(u),[u]),m=us(d,!1),h=f?{state:`failed`,devices:void 0}:{state:m,devices:m===`answered`?p:void 0},g=n(()=>new Map(p.map(e=>[e.id,e.name])),[p]);return r(os,{draft:c,onChange:l,exceptOffered:i,plural:`zones`,describe:e=>g.get(e)??e,testId:`rule-zone-scope`,renderPicker:(e,t,n)=>a.length===0?r(`p`,{className:$t,children:s(`notificationRules.zones.noCameras`,`This rule covers no camera, so it has no zones.`)}):r(ct,{devices:p,listState:m,fleet:h,value:e,onChange:t,emptyMeansAll:!0,noun:`zone`,groupTitle:e=>e.type??s(`notificationRules.zones.group`,`Zones`),testId:`zone-picker`},n)})}function fs({conditions:e,onConditionsChange:t,exceptOffered:i}){let{t:a}=Y(),[o,s]=ls(`identities`,e,t),{options:c,loading:l,failed:u}=Zt(),d=n(()=>c.map(e=>({id:e.value,name:e.label})),[c]),f=n(()=>new Map(d.map(e=>[e.id,e.name])),[d]);return r(os,{draft:o,onChange:s,exceptOffered:i,plural:`faces`,describe:e=>f.get(e)??e,testId:`rule-identity-scope`,renderPicker:(e,t,n)=>r(ct,{devices:d,listState:us(l,u),value:e,onChange:t,emptyMeansAll:n===`except`,...n===`only`?{emptyLabel:a(`notificationRules.faces.anyKnown`,`Any known face — nobody in particular`)}:{},noun:`face`,groupTitle:()=>a(`notificationRules.faces.group`,`Known faces`),testId:`identity-picker`},n)})}function ps({conditions:e,onConditionsChange:t}){let{t:n}=Y(),[i,a]=ls(`labels`,e,t);return r(os,{draft:i,onChange:a,exceptOffered:!1,plural:`labels`,describe:e=>e,testId:`rule-label-scope`,renderPicker:(e,t)=>r(Zn,{value:e,placeholder:n(`notificationRules.labels.add`,`Add a label…`),onChange:t})})}function ms(e){let t=ae(e);return t===null?null:t.groups.flatMap(e=>e.options.map(t=>({id:t.value,name:t.label,type:e.fallbackLabel})))}function hs(e){return e.type??J.t(`helpers.classPickerItems.other`)}s();function gs({taxonomy:e,scope:t,onChange:i,exceptOffered:a}){let{t:o}=Y(),s=n(()=>ms(e),[e]),c=n(()=>new Map((s??[]).map(e=>[e.id,e.name])),[s]);return r(os,{draft:t,onChange:i,exceptOffered:a,plural:`classes`,describe:e=>c.get(e)??e,testId:`rule-class-scope`,renderPicker:(e,t,n)=>s===null?r(Zn,{value:e,placeholder:o(`system.notificationClassScopeField.addValue`,`Add value…`),onChange:t}):r(ct,{devices:s,listState:`answered`,value:e,onChange:t,emptyMeansAll:!0,noun:`class`,groupTitle:hs,testId:`class-picker`},n)})}function _s(e){return{id:e.id,name:e.name,type:e.type,location:e.location,...e.parentName===void 0?{}:{detail:e.parentName}}}function vs({devices:e,value:t,onChange:n,listState:i,savedHadDevices:a}){return r(ct,{devices:e.map(_s),listState:i,value:t,onChange:n,emptyMeansAll:!0,savedHadDevices:a,noun:`device`,showAll:!0})}function ys({devices:e,scope:t,onChange:n,listState:i,savedScope:a,exceptOffered:o}){let s=new Map(e.map(e=>[e.id,e.name]));return r(os,{draft:t,onChange:n,exceptOffered:o,plural:`devices`,describe:e=>s.get(e)??J.t(`uiLibrary.devicePicker.deviceId`,{id:e}),testId:`rule-device-scope`,renderPicker:(t,n,o)=>r(vs,{devices:e,value:t,onChange:n,listState:i,savedHadDevices:(o===`only`?a.include:a.exclude).length>0},o)})}function bs(e){return e.data===void 0?e.isError?`failed`:`pending`:`answered`}function xs(e,t){return t===`answered`?e?.complete===!0?`answered`:`failed`:t}function Ss(e){let t=bs(e),n=e.data===void 0?[]:ne(e.data.nodes),r=xs(e.data,t);return{items:n,listState:t,fleet:{state:r,devices:r===`answered`?n:void 0}}}function Cs(e){let t=bs(e),n=e.data===void 0?[]:L(e.data);return{items:n,listState:t,fleet:{state:t,devices:t===`answered`?n:void 0}}}var ws=[`nc-pickers`,`node-directory`],Ts=[`nc-pickers`,`package-list`],Es=6e4,Ds={get hub(){return J.t(`system.scopePickers.roleHub`)},get agent(){return J.t(`system.scopePickers.roleAgents`)}},Os={get server(){return J.t(`system.scopePickers.pkgServer`)},get framework(){return J.t(`system.scopePickers.pkgFramework`)},get wrapper(){return J.t(`system.scopePickers.pkgWrapper`)},get addon(){return J.t(`system.scopePickers.pkgAddons`)}};function ks(e){let t=Ds[e.type??``]??J.t(`system.scopePickers.roleNodes`);return e.location===`offline`?J.t(`system.scopePickers.offlineSuffix`,{role:t}):t}function As(e){return Os[e.type??``]??J.t(`system.scopePickers.pkgPackages`)}function js({value:t,onChange:n,testId:i}){let{t:a}=Y(),s=w().trpcClient,c=o({queryKey:ws,staleTime:Es,queryFn:()=>s.nodes.directory.query()}),l=Ss(c);return e(`div`,{children:[r(ct,{devices:l.items,listState:l.listState,fleet:l.fleet,value:t,onChange:n,emptyMeansAll:!0,noun:`node`,groupTitle:ks,...i===void 0?{}:{testId:i}}),c.data?.complete===!1&&r(`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 Ms({value:e,onChange:t,testId:n}){let i=w().trpcClient,a=Cs(o({queryKey:Ts,staleTime:Es,queryFn:()=>i.addons.listPackages.query()}));return r(ct,{devices:a.items,listState:a.listState,fleet:a.fleet,value:e,onChange:t,emptyMeansAll:!0,noun:`package`,groupTitle:As,...n===void 0?{}:{testId:n}})}var Ns={context:{family:`rule`,field:`body`,kind:`device-events`,systemEventKinds:[`device-consumable-low`]},template:{body:`{{deviceName}}`}};function Ps(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 Fs(e,t){return e===`pending`?`pending`:e===`success`?`current`:Ps(t)===`BAD_REQUEST`?`outdated`:`unknown`}function Is(e){let t=w(),n=o({queryKey:[`nc`,`hub-rule-schema-probe`],enabled:e,staleTime:5*6e4,retry:!1,queryFn:()=>t.trpcClient.notificationRules.previewTemplate.mutate(Ns)});return e?Fs(n.status,n.error):`pending`}s();var Ls=`/system/settings`,Rs=`/system/notifications?tab=alarm`,zs=`text-primary underline-offset-2 hover:underline`;function Bs(e,t){let n=Qt(t);return Rr(e,{deviceIds:n.include,excludeDeviceIds:n.exclude})}function Vs({family:t,value:i,cameras:o,allDevices:s,fleet:c,savedHadDevices:l,onChange:u,summary:d=!1}){let{t:f}=Y(),p=n(()=>i?.kinds??[],[i]),m=n(()=>s===void 0?o:s.map(_s),[s,o]),h=n(()=>o.map(e=>({id:e.id,name:e.name,type:`camera`})),[o]),g=qn(t,p),_=Is(t===`device-events`),v=t===`alarm`,[y,b]=a(()=>An(i?.deviceIds,i?.excludeDeviceIds)),[x]=a(()=>An(i?.deviceIds,i?.excludeDeviceIds)),S=n(()=>{let e=new Map;for(let t of v?h:m)e.set(t.id,t.name);return e},[h,v,m]);return e(`div`,{className:`mt-1 space-y-3`,"data-testid":`system-event-field`,children:[r(`p`,{className:$t,"data-testid":`system-event-class-hint`,children:d?f(`system.notificationSystemEventField.summaryClassHint`,`At the scheduled time you get the list of what is in the bad state, not each change.`):f(`system.notificationSystemEventField.instantClassHint`,`A paired event tells you both when it goes wrong and when it comes back.`)}),Dn(t).map(n=>e(`div`,{children:[r(`div`,{className:`text-[10px] font-semibold uppercase tracking-wide text-foreground-subtle`,children:n.label}),r(`div`,{className:`mt-1 flex flex-wrap gap-1.5`,children:$n(n,d).map(e=>{let n=dr(p,e),a=e.noSnapshot===!0?`${e.label} — ${f(`system.notificationSystemEventField.noSnapshot`,`no state snapshot, reports nothing`)}`:e.label;return r(`button`,{type:`button`,role:`checkbox`,"aria-checked":n,"aria-label":a,onClick:()=>u(Ur(i,e,t)),className:n?`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:a},e.key)})})]},n.id)),t===`device-events`&&e(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,"data-testid":`system-event-device-alert-settings`,children:[f(`system.notificationSystemEventField.theBatteryThresholdAndThe`,`The battery threshold and the reminder interval are cluster settings (the consumable threshold is this rule’s own, below):`),` `,r(lr,{to:Ls,target:`_blank`,rel:`noreferrer`,className:zs,children:f(`system.notificationSystemEventField.settingsBatteryOfflineAlerts`,`Settings → Battery & offline alerts`)}),`.`]}),t===`alarm`&&e(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,"data-testid":`system-event-alarm-settings`,children:[r(lr,{to:Rs,target:`_blank`,rel:`noreferrer`,className:zs,children:f(`system.notificationSystemEventField.alarmSettings`,`Alarm settings`)}),p.includes(`alarm-triggered`)&&r(`span`,{className:`ml-1`,children:f(`system.notificationSystemEventField.alarmPictures`)})]}),_===`outdated`&&r(`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:f(`system.notificationSystemEventField.hubOutdated`,{percent:15})}),_===`unknown`&&r(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,"data-testid":`system-event-hub-unchecked`,children:f(`system.notificationSystemEventField.couldNotCheckWhetherThis`,`Could not check whether this hub’s server knows per-rule consumable thresholds and tank alerts.`)}),g.consumableThreshold&&e(`div`,{children:[r(`label`,{className:`block text-[11px] font-medium text-foreground`,htmlFor:`system-event-consumable-threshold`,children:f(`system.notificationSystemEventField.consumableLowAt`,`Consumable low at (%)`)}),r(G,{id:`system-event-consumable-threshold`,"data-testid":`system-event-consumable-threshold`,type:`number`,min:1,max:Rn,step:1,placeholder:`15`,value:i?.consumableLowPercent??``,className:`mt-1 max-w-[8rem]`,onChange:e=>{let t=pn(e.target.value);t.kind!==`invalid`&&u(Rr(i,{consumableLowPercent:t.kind===`set`?t.value:void 0}))}})]}),g.deviceTypes&&e(`div`,{children:[r(`label`,{className:`block text-[11px] font-medium text-foreground`,children:f(`system.notificationSystemEventField.deviceTypes`,`Device types`)}),r(Cn,{options:Wn,value:i?.deviceTypes??[],onChange:e=>u(Rr(i,{deviceTypes:e})),emptyHint:`No device types listed — the rule watches every type.`,placeholder:f(`system.notificationSystemEventField.deviceType`,`Device type…`)})]}),tn(i)&&r(`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:f(`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.`)}),g.devices&&e(`div`,{children:[r(os,{draft:y,onChange:e=>{b(e),u(Bs(i,e))},exceptOffered:g.excludeDevices,plural:`devices`,describe:e=>S.get(e)??f(`uiLibrary.devicePicker.deviceId`,{id:e}),testId:`system-event-device-scope`,renderPicker:(e,t,n)=>r(ct,{devices:v?h:m,listState:c.state,fleet:c,emptyMeansAll:!0,savedHadDevices:(n===`only`?x.include:x.exclude).length>0||n===`only`&&l,noun:v?`camera`:`device`,value:e,onChange:t,testId:n===`only`?`system-event-include`:`system-event-exclude`},n)}),l&&y.mode===`all`&&r(Ft,{noun:v?`camera`:`device`})]}),g.nodes&&e(`div`,{children:[r(`label`,{className:`block text-[11px] font-medium text-foreground`,children:f(`system.notificationSystemEventField.nodes`,`Nodes`)}),r(js,{value:i?.nodeIds??[],onChange:e=>u(Rr(i,{nodeIds:e})),testId:`system-event-nodes`})]}),g.packages&&e(`div`,{children:[r(`label`,{className:`block text-[11px] font-medium text-foreground`,children:f(`system.notificationSystemEventField.packages`,`Packages`)}),r(Ms,{value:i?.packageNames??[],onChange:e=>u(Rr(i,{packageNames:e})),testId:`system-event-packages`})]})]})}function Hs({value:t}){let{t:n}=Y(),i=t?.kinds??[];return e(`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:[r(`p`,{children:n(`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.`)}),i.length>0&&r(`p`,{className:`mt-1 text-foreground`,children:i.map(Lt).join(`, `)})]})}function Us({family:t,onChange:n}){let{t:i}=Y();return e(`div`,{"data-testid":`system-family-select`,children:[r(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:i(`system.notificationSystemEventField.kindOfSystemRule`,`Kind of system rule`)}),r(W,{value:t,"aria-label":i(`system.notificationSystemEventField.kindOfSystemRule`,`Kind of system rule`),onChange:e=>{let t=e.target.value;se(t)&&n(t)},options:me.map(e=>({value:e,label:ye(e).label}))}),r(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:i(`system.notificationSystemEventField.oneRuleAnswersOneQuestion`,`One rule answers one question: about devices, about the installation, or about the alarm. Changing it starts the event list over.`)})]})}s();function Ws({catalog:t,taxonomy:i,delivery:a,conditions:o,classScope:s,onClassScopeChange:c,actions:l,sequenceActionsOf:u,savedConditions:d,schedule:f,deviceIds:p,zoneCameraIds:m,cameras:h,fleet:g,allDevices:_,gateable:v,gateableScenes:y,onConditionsChange:b,onScheduleChange:x,summary:S}){let{t:C}=Y(),w=(e,t)=>{let n={...o};t===void 0?delete n[e]:n[e]=t,b(n)},T=Ne({delivery:a,conditions:o}),E=n(()=>t.filter(e=>xe(e,a,T)&&vr(e.id,o)),[t,a,T,o]),D=n(()=>Zo(E),[E]),O=e=>E.some(t=>t.id===e),k=e=>Gs.has(e.id)?r(gs,{taxonomy:i,scope:s,onChange:c,exceptOffered:O(`classesExclude`)}):Ks.has(e.id)?r(ds,{conditions:o,onConditionsChange:b,exceptOffered:O(`zonesExclude`),cameraIds:m??p,cameras:h}):qs.has(e.id)?r(fs,{conditions:o,onConditionsChange:b,exceptOffered:O(`identitiesExclude`)}):e.id===`labelEquals`?r(ps,{conditions:o,onConditionsChange:b}):null;return r(`div`,{className:`space-y-4`,children:D.map(t=>e(`div`,{className:`space-y-2.5`,"data-testid":`condition-group-${t.id}`,children:[r(`div`,{className:`text-[11px] font-semibold uppercase tracking-wide text-foreground-subtle`,children:C(`notificationRules.groups.${t.id}`,t.label)}),t.descriptors.map(t=>{let n=k(t);return e(`div`,{"data-testid":`condition-${t.id}`,children:[r(`label`,{className:X,children:Js(t,C)}),n??r(Zs,{descriptor:t,kind:T,summary:S===!0,taxonomy:i,conditions:o,actions:l,sequenceActionsOf:u,savedConditions:d,schedule:f,deviceIds:p,cameras:h,fleet:g,..._===void 0?{}:{allDevices:_},gateable:v,gateableScenes:y,onFieldChange:w,onScheduleChange:x}),Ys(t,C)!==void 0&&r(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:Ys(t,C)})]},t.id)})]},t.id))})}var Gs=new Set([`classes`,`classesExclude`]),Ks=new Set([`zones`,`zonesExclude`]),qs=new Set([`identities`,`identitiesExclude`]);function Js(e,t){return Gs.has(e.id)?t(`notificationRules.labels.classes`,`Object classes`):Ks.has(e.id)?t(`notificationRules.labels.zones`,`Zones`):qs.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 Ys(e,t){if(!Xs.has(e.id))return e.id===`scene`?t(`notificationRules.scene.hint`,`Only fire while a scene is matched or diverged.`):e.description}var Xs=new Set([...Gs,...Ks,...qs,`labelEquals`,`crossing`]);function Zs({descriptor:t,kind:n,taxonomy:i,conditions:a,actions:o,sequenceActionsOf:s,savedConditions:c,schedule:l,deviceIds:u,cameras:f,fleet:p,allDevices:m,gateable:h,gateableScenes:g,onFieldChange:_,onScheduleChange:v,summary:y}){let{t:b}=Y();switch(t.valueType){case`deviceIdList`:{if(!ri(t.id))break;let e=t.id,n=a[e]??[];return r(nn,{cameras:f,fleet:p,emptyMeansAll:!0,savedHadDevices:(c?.[e]?.length??0)>0,value:n,onChange:t=>_(e,t.length>0?t:void 0)})}case`stringList`:{if(!Yn(t.id))break;let e=t.id,n=t=>_(e,t.length>0?t:void 0);if(e===`eventTypeTokens`)return r(Hn,{deviceIds:u,value:En(a,e),onChange:n});let o=we(e,i);return o===null?r(Zn,{value:En(a,e),placeholder:b(`system.notificationRuleConditions.addValue`,`Add value…`),onChange:n}):r(Tn,{picker:o,value:En(a,e),onChange:n})}case`number01`:{if(!Bn(t.id))break;let e=t.id;return r(Ir,{value:Qn(a,e),min:0,max:1,step:.05,onChange:t=>_(e,t)})}case`number`:{if(!rn(t.id))break;let e=t.id;return r(Ir,{value:Qn(a,e),min:0,step:1,onChange:t=>_(e,t)})}case`sourceSelect`:{if(!un(t.id))break;let e=t.id;return nc(t,a[e],t=>_(e,t))}case`systemEvent`:{if(!Kn(t.id))break;let e=t.id,i=te(n);return i===void 0?r(Hs,{value:a[e]}):r(Vs,{family:i,value:a[e],cameras:f,fleet:p,...m===void 0?{}:{allDevices:m},savedHadDevices:(c?.[e]?.deviceIds?.length??0)>0,onChange:t=>_(e,t),summary:y===!0})}case`deviceState`:if(!Vt(t.id))break;return r(In,{gateable:h,value:a.deviceState,onChange:e=>_(`deviceState`,e)});case`scene`:if(!fn(t.id))break;return r(Gn,{scenes:g,value:a.scene,onChange:e=>_(`scene`,e)});case`crossingSelect`:{if(!kn(t.id))break;let e=t.id;return rc(t,a[e],t=>_(e,t))}case`packagePhase`:{if(!Un(t.id))break;let e=t.id;return r(W,{value:a[e]??``,options:[{value:``,label:b(`system.notificationRuleConditions.anyPhase`,`— any phase —`)},...ei(t,Gr).map(e=>({value:e.value,label:e.label}))],onChange:t=>_(e,tc(t.target.value))})}case`sensorTransition`:{if(!Lr(t.id))break;let n=t.id,i=le({conditions:a,...o===void 0?{}:{actions:o},...s===void 0?{}:{sequenceActionsOf:s}});return e(d,{children:[r(W,{value:a[n]??``,options:ei(t,Pr).map(e=>({value:e.value,label:e.label})),onChange:e=>_(n,_n(e.target.value))}),i&&r(`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(!en(t.id))break;let e=t.id;return r(Jn,{value:a[e],onChange:t=>_(e,t)})}case`occupancy`:{if(!Ln(t.id))break;let e=t.id;return r(ln,{deviceIds:u,cameras:f,classOptions:Qs(i),value:a[e],onChange:t=>_(e,t)})}case`audio`:{if(!hn(t.id))break;let e=t.id;return r(Bt,{taxonomy:i,value:a[e],onChange:t=>_(e,t)})}case`schedule`:return r(Xt,{value:l,onChange:v});default:break}return r($s,{descriptor:t,conditions:a})}function Qs(e){let t=we(`occupancy`,e);return t===null?[]:t.groups.flatMap(e=>e.options)}function $s({descriptor:t,conditions:n}){let{t:r}=Y(),i=Object.entries(n).find(([e])=>e===t.id);return e(`p`,{className:$t,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.`),` `,e(`span`,{className:`text-foreground-muted`,children:[`(`,t.valueType,`)`]})]})}function ec(e){if(e===`pipeline`||e===`onboard`||e===`sensor`||e===`any`)return e}function tc(e){return Gr.find(t=>t.value===e)?.value}function nc(e,t,n){return r(W,{value:t??`any`,options:ei(e,Or).map(e=>({value:e.value,label:e.label})),onChange:e=>n(ec(e.target.value))})}function rc(e,t,n){return r(zn,{value:t,onChange:n,...e.options?{options:e.options}:{}})}function ic({catalog:t,delivery:n,conditions:i,onConditionsChange:a}){let{t:o}=Y(),s=Ne({delivery:n,conditions:i}),c=(e,t)=>{let n={...i};t===void 0?delete n[e]:n[e]=t,a(n)},l=e=>t.find(t=>t.id===e&&xe(t,n,s)&&vr(e,i)),u=l(`source`),d=l(`crossing`);return u===void 0&&d===void 0?null:e(`div`,{className:`space-y-2.5`,"data-testid":`rule-advanced-conditions`,children:[u&&un(u.id)&&e(`div`,{"data-testid":`condition-source`,children:[r(`label`,{className:`block text-[11px] font-medium text-foreground`,children:Js(u,o)}),nc(u,i.source,e=>c(`source`,e)),Ys(u,o)!==void 0&&r(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:Ys(u,o)})]}),d&&kn(d.id)&&e(`div`,{"data-testid":`condition-crossing`,children:[r(`label`,{className:`block text-[11px] font-medium text-foreground`,children:Js(d,o)}),rc(d,i.crossing,e=>c(`crossing`,e)),Ys(d,o)!==void 0&&r(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:Ys(d,o)})]})]})}var ac=[`notificationRules`,`getRuleLastRuns`],oc=3e4;function sc(){let e=w(),t=o({queryKey:ac,queryFn:()=>e.trpcClient.notificationRules.getRuleLastRuns.query({}),retry:!1,staleTime:oc});return{status:t.status,data:t.data,error:t.error}}var cc={sent:`bg-success`,pending:`bg-info`,dead:`bg-danger`};function lc({cell:t}){let{t:n}=Y();switch(t.kind){case`pending`:return r(`span`,{"data-testid":`rule-last-run-pending`,"aria-label":n(`system.notificationRuleLastRun.lastRunLoading`,`Last run loading`),className:`inline-block h-3 w-14 animate-pulse rounded bg-surface-hover`});case`failed`:return r(`span`,{"data-testid":`rule-last-run-failed`,title:n(`system.notificationRuleLastRun.lastRunCouldNotBe`,`Last run could not be read: {{reason}}`,{reason:t.reason}),className:`text-[11px] text-foreground-subtle`,children:`—`});case`absent`:return r(`span`,{className:`text-[11px] text-foreground-subtle`,children:t.phrase});case`ran`:return e(`span`,{className:`flex items-center gap-1.5`,title:new Date(t.lastAt).toLocaleString(),children:[r(`span`,{"data-testid":`rule-last-run-dot`,title:t.status,className:`inline-block h-2 w-2 rounded-full ${cc[t.status]}`}),r(`span`,{className:`text-[11px] text-foreground-subtle`,children:oi(t.lastAt)})]})}}function uc({rule:e,onOpenHistory:t}){let{t:n}=Y();return r(U,{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:r(v,{className:`h-3.5 w-3.5`})})}s();var dc=[`notificationRules`,`listSnoozes`],fc=[10,30,60,120];function pc({ruleId:t,ruleName:n,exempt:i=!1,variant:o=`icon`}){let{t:s}=Y(),l=w(),d=c(),[f,p]=a(30),[m,h]=a(null),g=u({mutationFn:e=>l.trpcClient.notificationRules.createSnooze.mutate({snooze:{scope:`rule`,ruleId:t,durationMinutes:e}}),onMutate:()=>h(null),onSuccess:()=>d.invalidateQueries({queryKey:dc}),onError:e=>h(e instanceof Error?e.message:`The snooze could not be opened.`)});return i?o===`icon`?null:r(`p`,{className:`text-[10px] text-foreground-subtle`,children:s(`system.notificationRuleSnoozeControl.thisRuleConcernsOrTriggers`,`This rule concerns — or triggers — the alarm panel, so no snooze window can silence it.`)}):o===`icon`?r(U,{size:`sm`,variant:`ghost`,type:`button`,disabled:g.isPending,onClick:()=>g.mutate(30),title:s(`system.notificationRuleSnoozeControl.silenceThisRuleForIt`,`Silence this rule for {{value1}} — it appears under "Silenced right now"`,{value1:Nn(30)}),"aria-label":s(`system.notificationRuleSnoozeControl.snooze`,`snooze {{ruleName}}`,{ruleName:n}),"data-testid":`nc-rule-snooze-now`,children:g.isPending?r(T,{className:`h-3.5 w-3.5 animate-spin`}):r(He,{className:`h-3.5 w-3.5`})}):e(`div`,{className:`space-y-1`,children:[e(`div`,{className:`flex items-end gap-2`,children:[r(`div`,{className:`w-32`,children:r(W,{value:String(f),onChange:e=>{let t=Number(e.target.value);Number.isFinite(t)&&t>0&&p(t)},options:fc.map(e=>({value:String(e),label:Nn(e)}))})}),e(U,{size:`sm`,variant:`outline`,type:`button`,disabled:g.isPending,onClick:()=>g.mutate(f),"data-testid":`nc-rule-snooze-now`,children:[g.isPending?r(T,{className:`h-3.5 w-3.5 animate-spin`}):r(He,{className:`h-3.5 w-3.5`}),s(`system.notificationRuleSnoozeControl.silenceThisRuleNow`,`Silence this rule now`)]})]}),r(`p`,{className:`text-[10px] text-foreground-subtle`,children:s(`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&&r(`p`,{className:`text-[10px] text-danger`,children:m})]})}s();function mc(e,t,n){return e.filter(e=>e.scope===`rule`&&e.ruleId===t&&n>=e.startedAt&&n<e.expiresAt).map(e=>e.id)}function hc(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 gc(e,t){let[,n]=a(0);i(()=>{let r=hc(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 _c(){let e=w();return o({queryKey:dc,queryFn:async()=>(await e.trpcClient.notificationRules.listSnoozes.query({})).snoozes}).data??[]}function vc({rule:t,snoozes:n,exempt:i}){let{t:a}=Y(),o=w(),s=c();gc(n,t.id);let l=mc(n,t.id,Date.now()),d=()=>s.invalidateQueries({queryKey:dc}),f=u({mutationFn:()=>o.trpcClient.notificationRules.createSnooze.mutate({snooze:{scope:`rule`,ruleId:t.id,durationMinutes:30}}),onSuccess:d}),p=u({mutationFn:async e=>{for(let t of e)await o.trpcClient.notificationRules.cancelSnooze.mutate({snoozeId:t})},onSuccess:d});if(i)return null;let m=f.isError||p.isError;return e(`span`,{className:`inline-flex flex-col items-center gap-0.5`,children:[r(nt,{checked:l.length>0,disabled:!t.enabled||f.isPending||p.isPending,onCheckedChange:e=>e?f.mutate():p.mutate(l),"aria-label":a(`notificationRules.snooze.aria`,`snooze {{name}}`).replaceAll(`{{name}}`,t.name),title:a(`notificationRules.snooze.title`,{minutes:30,defaultValue:`Silence this rule for {{minutes}} minutes`}).replaceAll(`{{minutes}}`,`30`),"data-testid":`nc-rule-snooze-switch`}),m&&r(`span`,{className:`text-[10px] text-danger`,role:`alert`,children:a(`notificationRules.snooze.failed`,`The snooze could not be changed.`)})]})}var yc=`pipeline-analytics`,bc=`nc.getRuleStatus`,xc=`nc.testRule`;function Sc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Z(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function Cc(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:void 0}function wc(e){if(!Sc(e))return;let t=Cc(e,`id`),n=Cc(e,`downloadPath`),r=Z(e,`capturedAt`);if(!(t===void 0||n===void 0||r===void 0))return{id:t,mediaType:Cc(e,`mediaType`)??`video`,sizeBytes:Z(e,`sizeBytes`)??0,capturedAt:r,downloadPath:n}}function Tc(e){if(!Sc(e))return;let t=Z(e,`startMs`),n=Z(e,`endMs`);if(!(t===void 0||n===void 0))return{startMs:t,endMs:n}}function Ec(e){if(!Sc(e))return null;let t=Z(e,`deviceId`);if(t===void 0)return null;let n=Z(e,`lastGeneratedAt`),r=wc(e.lastArtifact),i=e.rendering,a=Sc(i)?{startedAt:Z(i,`startedAt`)??0,windowStartMs:Z(i,`windowStartMs`)??0,windowEndMs:Z(i,`windowEndMs`)??0}:void 0;return{deviceId:t,...n===void 0?{}:{lastGeneratedAt:n},...r===void 0?{}:{lastArtifact:r},...a===void 0?{}:{rendering:a}}}function Dc(e){if(!Sc(e))return null;let t=Z(e,`deviceId`),n=Cc(e,`windowKey`),r=Z(e,`openedAt`),i=Z(e,`closesAt`),a=Z(e,`members`),o=Z(e,`pending`);return t===void 0||n===void 0||r===void 0||i===void 0||a===void 0||o===void 0?null:{deviceId:t,windowKey:n,openedAt:r,closesAt:i,members:a,pending:o}}function Oc(e){if(!Sc(e))return null;let t=Cc(e,`kind`);if(t===`none`)return{kind:`none`,reason:Cc(e,`reason`)??``};if(t===`occupancy`){let t=Z(e,`deviceId`),n=Z(e,`threshold`),r=Z(e,`sustainSeconds`);if(t===void 0||n===void 0||r===void 0)return null;let i=Cc(e,`unavailable`),a=i===`no-snapshot`||i===`zone-absent`?i:void 0,o=Z(e,`count`),s=Z(e,`observedAt`),c=Z(e,`since`),l=Cc(e,`scope`),u=Cc(e,`className`),d=Cc(e,`warning`);return{kind:`occupancy`,deviceId:t,threshold:n,sustainSeconds:r,...l===void 0?{}:{scope:l},...u===void 0?{}:{className:u},...o===void 0?{}:{count:o},...typeof e.occupied==`boolean`?{occupied:e.occupied}:{},...s===void 0?{}:{observedAt:s},...c===void 0?{}:{since:c},...a===void 0?{}:{unavailable:a},...d===void 0?{}:{warning:d}}}if(t===`grouped`){let t=Z(e,`groupingSec`);if(t===void 0)return null;if(e.openWindows===null){let n=Cc(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=Dc(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=Ec(e);t!==null&&n.push(t)}let r=Tc(e.lastWindow),i=e.nextWindow,a=Sc(i)?{startMs:Z(i,`startMs`)??0,endMs:Z(i,`endMs`)??null}:void 0;return{kind:`timelapse`,devices:n,...r===void 0?{}:{lastWindow:r},...a===void 0?{}:{nextWindow:a},settleMs:Z(e,`settleMs`)??0}}return null}function kc(e){let t=Math.max(0,Math.floor(e/6e4));if(t<1)return J.t(`helpers.notificationRuleStatus.lessThanMinute`);if(t<60)return J.t(`helpers.notificationRuleStatus.durMin`,{count:t});let n=Math.floor(t/60),r=t%60;if(n<24)return r===0?J.t(`helpers.notificationRuleStatus.durH`,{count:n}):J.t(`helpers.notificationRuleStatus.durHMin`,{hours:n,minutes:r});let i=Math.floor(n/24),a=n%24;return a===0?J.t(`helpers.notificationRuleStatus.durD`,{count:i}):J.t(`helpers.notificationRuleStatus.durDH`,{days:i,hours:a})}function Ac(e){if(e<1024)return`${String(e)} B`;let t=e/1024;if(t<1024)return J.t(`helpers.notificationRuleStatus.sizeKb`,{value:t.toFixed(0)});let n=t/1024;return n<1024?J.t(`helpers.notificationRuleStatus.sizeMb`,{value:n.toFixed(1)}):J.t(`helpers.notificationRuleStatus.sizeGb`,{value:(n/1024).toFixed(2)})}function jc(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 ${kc(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 Mc(e,t,n){if(e.rendering!==void 0)return J.t(`helpers.notificationRuleStatus.tlRendering`,{camera:t,duration:kc(Math.max(0,n-e.rendering.startedAt)),from:new Date(e.rendering.windowStartMs).toLocaleString(),to:new Date(e.rendering.windowEndMs).toLocaleString()});if(e.lastGeneratedAt===void 0)return J.t(`helpers.notificationRuleStatus.tlNever`,{camera:t});let r=new Date(e.lastGeneratedAt).toLocaleString(),i=e.lastArtifact;return i===void 0?J.t(`helpers.notificationRuleStatus.tlGone`,{camera:t,when:r}):J.t(`helpers.notificationRuleStatus.tlLast`,{camera:t,when:r,size:Ac(i.sizeBytes)})}function Nc(e){return{windows:e.length,waiting:e.reduce((e,t)=>e+t.pending,0)}}var Pc=`nc.listPrunes`;function Fc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Ic=new Set([`rule`,`timelapse`,`summary`]),Lc=new Set([`removed`,`kept-disabled`,`kept`,`sequence-removed`,`binding-removed`]);function Rc(e){return typeof e==`string`&&Ic.has(e)}function zc(e){return typeof e==`string`&&Lc.has(e)}function Bc(e){return e===`device`||e===`target`}function Vc(e){if(!Fc(e))return null;let{kind:t,ruleId:n,subjectKind:r,subject:i,field:a,outcome:o,at:s}=e;return!Rc(t)||!Bc(r)||!zc(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 Hc(e){return!Fc(e)||!Array.isArray(e.prunes)?null:e.prunes.map(Vc).filter(e=>e!==null)}function Uc(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 Wc(e,t){let n=t(e.at);return e.subjectKind===`device`?J.t(`helpers.notificationPrunes.lastDevice`,{when:n,subject:e.subject}):J.t(`helpers.notificationPrunes.lastTarget`,{when:n,subject:e.subject})}function Gc(e){return new Date(e).toLocaleDateString()}function Kc({kind:t,ruleId:n,enabled:i,updatedAt:a}){let s=w(),c=o({queryKey:[`pipelineAnalytics`,Pc],enabled:!i,staleTime:3e4,retry:!1,queryFn:async()=>Hc(await s.trpcClient.addons.custom.mutate({addonId:yc,action:Pc,input:{}}))}).data;if(c==null)return null;let l=Uc(c,t,n,i,a);return l===null?null:e(`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:[r(C,{className:`mt-0.5 h-3.5 w-3.5 shrink-0 text-warning`}),r(`span`,{children:Wc(l,Gc)})]})}var qc=5e3;function Jc({status:t,now:n,name:i}){let{t:a}=Y();if(t.openWindows===null)return e(`p`,{className:`flex items-start gap-1.5`,children:[r(f,{className:`mt-0.5 h-3 w-3 shrink-0 text-border`}),r(`span`,{"data-testid":`nc-grouped-status-headline`,children:a(`notificationRules.status.grouped.unknown`,{reason:t.reason??``,defaultValue:`Open windows unknown — {{reason}}`})})]});let o=t.openWindows,{windows:s,waiting:c}=Nc(o);return e(d,{children:[e(`p`,{className:`flex items-start gap-1.5`,children:[r(f,{className:`mt-0.5 h-3 w-3 shrink-0 ${s>0?`text-primary`:`text-border`}`}),r(`span`,{"data-testid":`nc-grouped-status-headline`,children:s===0?a(`notificationRules.status.grouped.none`,`No window open`):`${a(`notificationRules.status.grouped.windows`,{count:s,defaultValue_one:`{{count}} open window`,defaultValue_other:`{{count}} open windows`})} · ${a(`notificationRules.status.grouped.waiting`,{count:c,defaultValue:`{{count}} waiting`})}`})]}),o.map(t=>e(`p`,{className:`flex items-start gap-1.5`,children:[r(`span`,{className:`mt-0.5 h-3 w-3 shrink-0`}),r(`span`,{children:a(`notificationRules.status.grouped.windowLine`,{camera:i(t.deviceId),members:t.members,pending:t.pending,seconds:Math.max(0,Math.ceil((t.closesAt-n)/1e3)),defaultValue:`{{camera}} · {{members}} in the window · {{pending}} waiting · closes within {{seconds}} s`})})]},t.windowKey))]})}function Yc({ruleId:t,cameraName:n}){let{t:i}=Y(),a=w(),s=o({queryKey:[`pipelineAnalytics`,`nc.getRuleStatus`,t],refetchInterval:qc,queryFn:async()=>Oc(await a.trpcClient.addons.custom.mutate({addonId:yc,action:bc,input:{ruleId:t}}))}).data;if(s==null||s.kind===`none`)return null;let c=Date.now(),l=e=>n?.(e)??i(`system.notificationRuleStatus.cameraFallback`,{deviceId:e});return e(`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`&&e(`p`,{className:`flex items-start gap-1.5`,children:[s.unavailable!==void 0||s.warning!==void 0?r(N,{className:`mt-0.5 h-3 w-3 shrink-0 text-warning`}):r(f,{className:`mt-0.5 h-3 w-3 shrink-0 text-primary`}),e(`span`,{children:[r(`span`,{className:`text-foreground`,children:l(s.deviceId)}),` —`,` `,jc(s,c)]})]}),s.kind===`grouped`&&r(Jc,{status:s,now:c,name:l}),s.kind===`timelapse`&&e(d,{children:[s.devices.map(t=>e(`p`,{className:`flex items-start gap-1.5`,children:[r(f,{className:`mt-0.5 h-3 w-3 shrink-0 ${t.rendering===void 0?`text-border`:`text-primary animate-pulse`}`}),e(`span`,{children:[Mc(t,l(t.deviceId),c),t.lastArtifact!==void 0&&e(d,{children:[` · `,r(`a`,{className:`text-primary hover:underline`,href:`/${t.lastArtifact.downloadPath.replace(/^\//,``)}`,target:`_blank`,rel:`noreferrer`,children:i(`common.open`)})]})]})]},t.deviceId)),e(`p`,{className:`flex items-start gap-1.5`,children:[r(`span`,{className:`mt-0.5 h-3 w-3 shrink-0`}),e(`span`,{children:[s.nextWindow===void 0?i(`system.notificationRuleStatus.noFurtherWindowOpensIn`,`No further window opens in the next nine days`):i(`system.notificationRuleStatus.nextWindowOpens`,`Next window opens {{value1}}`,{value1:new Date(s.nextWindow.startMs).toLocaleString()}),s.settleMs>0&&` · ${i(`system.notificationRuleStatus.settled`,{minutes:Math.round(s.settleMs/6e4)})}`]})]})]})]})}function Xc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Zc(e,t){let n=e[t];return typeof n==`string`&&n.length>0?n:void 0}function Qc(e,t){let n=e[t];return Array.isArray(n)?n.filter(e=>typeof e==`string`):[]}function $c(e){if(!Xc(e))return null;let t=Zc(e,`ruleId`),n=Zc(e,`ruleName`);if(t===void 0||n===void 0||typeof e.matched!=`boolean`)return null;let r=Zc(e,`failedCondition`);return{ruleId:t,ruleName:n,matched:e.matched,...r===void 0?{}:{failedCondition:r},cooldown:Zc(e,`cooldown`)??`n/a`,enqueued:typeof e.enqueued==`number`?e.enqueued:0,targetIds:Qc(e,`targetIds`)}}function el(e){if(!Xc(e))return null;let t=Zc(e,`conditionId`),n=Zc(e,`note`);return t===void 0||n===void 0?null:{conditionId:t,note:n}}function tl(e){if(!Xc(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(!Xc(t))continue;let e=Zc(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(!Xc(t))continue;let e=Zc(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 nl(e){if(!Xc(e))return null;let t=Zc(e,`recordId`),n=Zc(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=$c(t);e!==null&&r.push(e)}let i=[];for(let t of Array.isArray(e.planNotes)?e.planNotes:[]){let e=el(t);e!==null&&i.push(e)}let a=Zc(e,`droppedBy`),o=tl(e.stateSummary);return{recordId:t,delivery:n,trigger:Zc(e,`trigger`)??n,candidates:typeof e.candidates==`number`?e.candidates:0,outcomes:r,still:Zc(e,`still`)??`none`,notes:Qc(e,`notes`),...a===void 0?{}:{droppedBy:a},planNotes:i,...o===void 0?{}:{stateSummary:o}}}function rl(e){if(e.stateSummary!==void 0)return il(e,e.stateSummary);if(e.droppedBy!==void 0)return J.t(`helpers.notificationRuleTest.dropped`,{reason:e.droppedBy});let t=e.outcomes[0];if(t===void 0)return J.t(`helpers.notificationRuleTest.notCandidate`,{trigger:e.trigger});if(!t.matched)return t.failedCondition===void 0?J.t(`helpers.notificationRuleTest.noMatchOwn`):J.t(`helpers.notificationRuleTest.noMatchCond`,{condition:t.failedCondition});if(t.enqueued===0)return J.t(`helpers.notificationRuleTest.matchedNoQueue`);let n=e.still===`live`?` ${J.t(`helpers.notificationRuleTest.stillLive`)}`:e.still===`unavailable`?` ${J.t(`helpers.notificationRuleTest.stillUnavailable`)}`:e.still===`unattachable`?` ${J.t(`helpers.notificationRuleTest.stillUnattachable`)}`:``;return J.t(`helpers.notificationRuleTest.matched`,{queued:t.enqueued,targets:t.targetIds.length,still:n})}function il(e,t){if(t.nothingToReport){let e=t.sections.map(e=>`${e.id}: ${e.status===`unavailable`?J.t(`helpers.notificationRuleTest.unavailable`):J.t(`helpers.notificationRuleTest.noneOpen`)}`).join(`, `);return J.t(`helpers.notificationRuleTest.nothingToReport`,{reads:e})}let n=t.rows.reduce((e,t)=>e+t.enqueued,0),r=e.outcomes[0]?.targetIds.length??0;if(n===0)return J.t(`helpers.notificationRuleTest.summaryNoQueue`);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`?` (${J.t(`helpers.notificationRuleTest.perCategory`,{sections:i.join(`, `)})})`:``;return J.t(`helpers.notificationRuleTest.summaryBuilt`,{queued:n,perCategory:a,targets:r})}s();function al({ruleId:t,ruleName:n,fallbackDeviceId:i,variant:o=`icon`,showResult:s=!1}){let{t:c}=Y(),l=w(),[f,p]=a(null),[m,h]=a(null),g=u({mutationFn:async()=>nl(await l.trpcClient.addons.custom.mutate({addonId:yc,action:xc,input:{ruleId:t,...i===void 0?{}:{deviceId:i}}})),onMutate:()=>{p(null),h(null)},onSuccess:e=>p(e),onError:e=>h(e instanceof Error?e.message:`The test could not be run.`)}),_=f===null?m===null?void 0:m:rl(f);return e(d,{children:[e(U,{size:`sm`,variant:o===`icon`?`ghost`:`outline`,type:`button`,disabled:g.isPending,onClick:()=>g.mutate(),title:_??c(`system.notificationRuleTestButton.testNowFiresThisRule`,`Test now — fires this rule and really sends the notification`),"aria-label":c(`system.notificationRuleTestButton.testNow`,`test {{ruleName}} now`,{ruleName:n}),"data-testid":`nc-rule-test-now`,children:[g.isPending?r(T,{className:`h-3.5 w-3.5 animate-spin`}):r(Ge,{className:`h-3.5 w-3.5`}),o===`full`&&c(`system.notificationRuleTestButton.testNow2`,`Test now`)]}),s&&m!==null&&r(`div`,{className:`mt-2 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-[11px] text-danger`,children:m}),s&&f!==null&&e(`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:[r(`p`,{className:`text-foreground`,children:rl(f)}),f.planNotes.map(t=>e(`p`,{className:`flex gap-1.5`,children:[r(N,{className:`mt-0.5 h-3 w-3 shrink-0 text-warning`}),r(`span`,{children:t.note})]},t.conditionId)),f.notes.map(t=>e(`p`,{children:[`· `,t]},t))]})]})}s();var ol=[`notificationRules`,`listSnoozes`],sl=3e4;function cl(e,t){return Math.max(0,Math.ceil((e.expiresAt-t)/6e4))}function ll(e){if(e===0)return J.t(`system.notificationSnoozes.remEnding`);if(e<60)return J.t(`system.notificationSnoozes.remMin`,{count:e});let t=Math.floor(e/60),n=e%60;return n===0?J.t(`system.notificationSnoozes.remHour`,{count:t}):J.t(`system.notificationSnoozes.remHourMin`,{hours:t,minutes:n})}function ul({rules:t}){let{t:i}=Y(),a=w(),s=c(),l=o({queryKey:ol,refetchInterval:sl,queryFn:async()=>(await a.trpcClient.notificationRules.listSnoozes.query({})).snoozes}),d=u({mutationFn:e=>a.trpcClient.notificationRules.cancelSnooze.mutate({snoozeId:e}),onSuccess:()=>s.invalidateQueries({queryKey:ol})}),f=n(()=>{let e=new Map;for(let n of t)e.set(n.id,n.name);return e},[t]),p=Date.now(),m=(l.data??[]).filter(e=>p>=e.startedAt&&p<e.expiresAt);return e(bt,{className:`p-4`,children:[e(`div`,{className:`flex items-center gap-2 mb-3`,children:[r(He,{className:`h-4 w-4 text-foreground-subtle`}),r(`h3`,{className:`text-sm font-medium text-foreground`,children:i(`system.notificationSnoozes.silencedRightNow`,`Silenced right now`)})]}),m.length===0&&r(`p`,{className:`text-[11px] text-foreground-subtle`,children:i(`system.notificationSnoozes.nothingIsSilencedASnooze`,`Nothing is silenced. A snooze opened from the app or from a notification button appears here until its clock runs out.`)}),r(`div`,{className:`max-h-64 space-y-2 overflow-y-auto`,children:m.map(t=>e(`div`,{className:`flex items-center justify-between gap-3 rounded-md border border-border px-3 py-2`,children:[e(`div`,{className:`min-w-0`,children:[e(`div`,{className:`flex items-center gap-2`,children:[r(`span`,{className:`text-xs text-foreground truncate`,children:t.scope===`all`?`Everything`:t.scope===`device`?`Camera ${t.deviceId??`?`}`:f.get(t.ruleId??``)??`A rule`}),t.global&&r(K,{variant:`warning`,className:`text-[10px]`,children:i(`common.everyone`)}),t.classes!==void 0&&t.classes.length>0&&r(K,{variant:`info`,className:`text-[10px]`,children:t.classes.join(`, `)}),!t.summary&&r(K,{variant:`default`,className:`text-[10px]`,children:i(`system.notificationSnoozes.noSummary`,`no summary`)})]}),r(`span`,{className:`text-[10px] text-foreground-subtle`,children:i(`system.notificationSnoozes.setBy`,{user:t.userId,remaining:ll(cl(t,p))})})]}),r(U,{size:`sm`,variant:`outline`,disabled:d.isPending,onClick:()=>d.mutate(t.id),children:i(`system.notificationSnoozes.endNow`,`End now`)})]},t.id))})]})}var Q=`block text-[11px] font-medium text-foreground mb-1`,dl=`mt-1 text-[10px] text-foreground-subtle`;function $({title:t,hint:n,children:i}){return e(`div`,{className:`rounded-md border border-border px-3 py-3`,children:[r(`div`,{className:`mb-2 text-[11px] font-semibold text-foreground`,children:t}),n!==void 0&&r(`p`,{className:`mb-2 text-[10px] text-foreground-subtle`,children:n}),r(`div`,{className:`space-y-3`,children:i})]})}function fl({problems:t,testId:n=`digest-problems`}){let{t:i}=Y();return t.length===0?null:e(`div`,{className:`rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-[11px] text-danger`,"data-testid":n,children:[e(`div`,{className:`mb-1 flex items-center gap-1.5 font-medium`,children:[r(N,{className:`h-3.5 w-3.5`}),i(`system.notificationDigestFields.thisRuleCouldNeverProduce`,`This rule could never produce anything, so it cannot be saved:`)]}),r(`ul`,{className:`list-disc space-y-0.5 pl-4`,children:t.map(e=>r(`li`,{children:e},e))})]})}function pl({warnings:t,testId:n=`digest-warnings`}){let{t:i}=Y();return t.length===0?null:e(`div`,{className:`rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-[11px] text-warning`,"data-testid":n,children:[e(`div`,{className:`mb-1 flex items-center gap-1.5 font-medium`,children:[r(C,{className:`h-3.5 w-3.5`}),i(`system.notificationDigestFields.worthKnowing`,`Worth knowing:`)]}),r(`ul`,{className:`list-disc space-y-0.5 pl-4`,children:t.map(e=>r(`li`,{children:e},e))})]})}function ml({cameras:t,value:n,onChange:i,fleet:a,hint:o}){return e(`div`,{className:`space-y-1`,children:[r(ct,{devices:t,listState:a.state,fleet:a,value:n,onChange:i,emptyLabel:`No camera selected`,testId:`digest-camera-picker`}),o!==void 0&&r(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:o})]})}function hl(e){let{t}=Y();return r(_t,{...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 gl({label:t,value:n,onChange:i,min:a,max:o,step:s,hint:c,emptyPlaceholder:l,testId:u,disabled:d=!1}){return e(`div`,{children:[r(`label`,{className:Q,children:t}),r(G,{type:`number`,value:n===void 0?``:String(n),disabled:d,...a===void 0?{}:{min:a},...o===void 0?{}:{max:o},...s===void 0?{}:{step:s},...l===void 0?{}:{placeholder:l},...u===void 0?{}:{"data-testid":u},onChange:e=>{let t=e.target.value.trim();if(t.length===0){i(void 0);return}let n=Number(t);Number.isFinite(n)&&i(n)}}),c!==void 0&&r(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:c})]})}function _l({label:t,checked:n,onChange:i,hint:a,testId:o}){return e(`div`,{children:[e(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[r(nt,{checked:n,onCheckedChange:i,"aria-label":t,...o===void 0?{}:{"data-testid":o}}),t]}),a!==void 0&&r(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:a})]})}function vl({title:t,body:n,onTitleChange:i,onBodyChange:a,family:o,testIdPrefix:s}){let{t:c}=Y(),l=To(),u=e=>l.data?xo(l.data,{family:o,field:e}):void 0;return e(`div`,{className:`space-y-2`,children:[r(Ao,{label:c(`system.notificationDigestFields.notificationTitle`,`Notification title`),value:t,onChange:i,vars:u(`title`),testId:`${s}-title`}),r(Ao,{label:c(`system.notificationDigestFields.notificationBody`,`Notification body`),value:n,onChange:a,vars:u(`body`),multiline:!0,testId:`${s}-body`}),r(`p`,{className:`text-[10px] text-foreground-subtle`,children:c(`system.notificationDigestFields.leaveBothBlankToUse`,`Leave both blank to use the hub's own wording (editable on the Texts tab).`)}),r(jo,{context:{family:o,field:`body`},title:t,body:n,testId:`${s}-preview`})]})}function yl({open:t,ruleName:n,windowDescription:i,targetDescription:a,pending:o,onConfirm:s,onCancel:c,extra:l,confirmDisabled:u=!1}){let{t:d}=Y();return t?r(xt,{open:!0,onOpenChange:e=>!e&&c(),children:r(kt,{width:`sm`,children:e(`div`,{className:`space-y-3`,"data-testid":`digest-test-confirm`,children:[e(`h3`,{className:`flex items-center gap-2 text-sm font-semibold text-foreground`,children:[r(Ge,{className:`h-4 w-4 text-warning`}),d(`system.notificationDigestFields.sendARealNotificationNow`,`Send a real notification now?`)]}),r(`p`,{className:`text-xs text-foreground-subtle`,children:d(`system.notificationDigestFields.confirmSend`,{rule:n,window:i,target:a})}),r(`p`,{className:`text-[11px] text-foreground-subtle`,children:d(`system.notificationDigestFields.itDoesNotConsumeThe`,`It does not consume the schedule: the next scheduled run still happens.`)}),l,e(`div`,{className:`flex justify-end gap-2`,children:[r(U,{size:`sm`,variant:`secondary`,type:`button`,onClick:c,children:d(`common.cancel`,`Cancel`)}),r(U,{size:`sm`,type:`button`,disabled:o||u,onClick:s,"data-testid":`digest-test-confirm-send`,children:o?d(`system.notificationDigestFields.sending`,`Sending…`):d(`system.notificationDigestFields.produceAndSend`,`Produce and send`)})]})]})})}):null}function bl(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 xl=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function Sl(e){let t=Math.floor(e/60),n=e%60;return`${String(t).padStart(2,`0`)}:${String(n).padStart(2,`0`)}`}function Cl(e){let t=e.windows[0];if(t===void 0)return J.t(`helpers.notificationDigest.noWindow`);let n=t.days.toSorted((e,t)=>e-t).map(e=>xl[e]??String(e)).join(` `),r=t.startMinute>t.endMinute?` (overnight)`:``,i=e.windows.length-1,a=e.invert===!0?` · outside`:``;return`${n} ${Sl(t.startMinute)}–${Sl(t.endMinute)}${r}${i>0?` +${i}`:``}${a}`}function wl(e,t,n){if(e===void 0||e<=0)return n;let r=Math.max(0,t-e);return J.t(`helpers.notificationDigest.ago`,{duration:bl(Math.round(r/1e3))})}function Tl(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function El(e){return Array.isArray(e)?`[${e.map(El).join(`,`)}]`:Tl(e)?`{${Object.keys(e).toSorted().map(t=>`${JSON.stringify(t)}:${El(e[t])}`).join(`,`)}}`:JSON.stringify(e)??`null`}function Dl(e,t){return El(e)===El(t)}function Ol(e){return e.map(e=>({targetId:e}))}var kl=`pipeline-analytics`,Al=`nc.getTexts`,jl=`nc.setLanguage`,Ml=`nc.setTextOverrides`,Nl={en:`English`,it:`Italiano`};function Pl(e){return e===`en`||e===`it`}function Fl(e){return e===`override`||e===`shipped`||e===`fallback`}function Il(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ll(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 Rl(e){if(!Il(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`||!Pl(r)||!Fl(o)||i!==null&&typeof i!=`string`)return null;let s=Ll(e.placeholders),c=Ll(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 zl(e){if(!Il(e))return null;let{language:t,activeLanguage:n}=e;if(!Pl(t)||!Pl(n))return null;let r=Ll(e.languages);if(r===null||r.length===0)return null;let i=[];for(let e of r)Pl(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=Rl(e);if(t===null)return null;o.push(t)}return{language:t,activeLanguage:n,languages:i,entries:o}}function Bl(e,t){return t.get(e.key)??e.override??e.shipped}function Vl(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 Hl(e,t){return Object.keys(Vl(e,t)).length}function Ul(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 Wl(e){return e.placeholders.map(e=>({name:e,label:e,example:`{{${e}}}`,group:`rule`,families:[`rule`]}))}function Gl(e){return e.pluralCategories.length===0?null:J.t(`helpers.notificationTexts.pluralWarning`,{categories:e.pluralCategories.join(`, `)})}var Kl=[`notificationCalendarEvents`,`list`],ql=`nc.listCalendarEventsRules`,Jl=`nc.upsertCalendarEventsRule`,Yl=`nc.deleteCalendarEventsRule`,Xl=Re({timezone:Le().min(1),windows:Be(Re({days:Be(Fe().int().min(0).max(6)).min(1),startMinute:Fe().int().min(0).max(1439),endMinute:Fe().int().min(0).max(1439)})).min(1),invert:Ve().optional()}),Zl=Re({targetId:Le().min(1),params:ze(Le(),Ie()).optional()}),Ql=Re({rules:Be(Re({id:Le().min(1),name:Le().min(1),enabled:Ve(),schedule:Xl,calendars:Be(Le().min(1)).max(64).optional(),calendarsExclude:Be(Le().min(1)).max(64).optional(),horizonDays:Fe().int(),deliverEmpty:Ve(),targets:Be(Zl).min(1),template:Re({title:Le().optional(),body:Le().optional()}).optional(),priority:Fe().int(),generatedAt:Fe().optional(),readOnly:Ve().optional()}))});function $l(e){let t=Ql.safeParse(e);return t.success?t.data.rules:null}function eu(e){return e.readOnly!==!0}var tu=[{key:`basics`,get label(){return J.t(`helpers.notificationCalendarEvents.tab_basics`)}},{key:`schedule`,get label(){return J.t(`helpers.notificationCalendarEvents.tab_schedule`)}},{key:`calendars`,get label(){return J.t(`helpers.notificationCalendarEvents.tab_calendars`)}},{key:`targets`,get label(){return J.t(`helpers.notificationCalendarEvents.tab_targets`)}},{key:`template`,get label(){return J.t(`helpers.notificationCalendarEvents.tab_template`)}}],nu=`basics`;function ru(){return P([{days:[0,1,2,3,4,5,6],minute:420}],Intl.DateTimeFormat().resolvedOptions().timeZone||`UTC`)}function iu(e){let t=ie(e);if(t===null||t.length===0)return Cl(e);let n=t[0];if(n===void 0)return Cl(e);let r=String(Math.floor(n.minute/60)).padStart(2,`0`),i=String(n.minute%60).padStart(2,`0`),a=t.length>1?` +${t.length-1}`:``;return J.t(`helpers.notificationCalendarEvents.scheduleAt`,{time:`${r}:${i}`,more:a})}function au(){return{name:`Morning calendar`,enabled:!0,horizonDays:7,deliverEmpty:!1,priority:3,schedule:ru(),calendars:[],calendarsExclude:[],targetIds:[],templateTitle:``,templateBody:``}}function ou(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 su(e){return e.name.trim().length>0&&e.targetIds.length>0&&e.horizonDays>=1&&e.horizonDays<=30&&e.schedule.windows.length>0}function cu(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 lu(e,t){let n=cu(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 uu(e){return J.t(`helpers.notificationCalendarEvents.horizon`,{count:e})}function du(e){return e.calendars!==void 0&&e.calendars.length>0?J.t(`helpers.notificationCalendarEvents.calendars`,{count:e.calendars.length}):e.calendarsExclude!==void 0&&e.calendarsExclude.length>0?J.t(`helpers.notificationCalendarEvents.allExcept`,{count:e.calendarsExclude.length}):J.t(`helpers.notificationCalendarEvents.allCalendars`)}s();function fu({rule:t,targets:n,onSaved:i,onCancel:o}){let{t:s}=Y(),c=w(),l=ot(),[d,f]=a(()=>t===null?au():ou(t)),[p,m]=a(()=>An(t===null?void 0:t.calendars,t===null?void 0:t.calendarsExclude)),[h,g]=a(nu),[_,v]=a(null),y=e=>f(t=>({...t,...e})),b=u({mutationFn:async()=>{let e=Qt(p),n={...d,calendars:e.include??[],calendarsExclude:e.exclude??[]};if(!su(n))throw Error(`Name, at least one target, and a schedule are required`);let r=t===null?{rule:cu(n)}:{ruleId:t.id,patch:lu(n,t)};await c.trpcClient.addons.custom.mutate({addonId:kl,action:Jl,input:r})},onSuccess:()=>i(),onError:e=>{v(e instanceof Error?e.message:String(e))}}),x=(l.data??[]).map(e=>({id:e.id,name:e.name}));return r(xt,{open:!0,onOpenChange:e=>!e&&o(),children:e(kt,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,"data-testid":`calendar-events-editor`,children:[e(`div`,{className:`mb-3 flex shrink-0 items-center justify-between gap-2 pr-10`,children:[e(`div`,{className:`flex min-w-0 items-center gap-2`,children:[r(Ue,{className:`h-4 w-4 shrink-0 text-foreground-subtle`}),r(`h3`,{className:`truncate text-sm font-semibold text-foreground`,children:t===null?s(`system.notificationCalendarEventsEditor.newCalendarEvents`,`New calendar events`):d.name})]}),r(U,{size:`sm`,type:`button`,disabled:b.isPending,onClick:()=>{v(null),b.mutateAsync()},"data-testid":`calendar-events-save`,children:b.isPending?r(T,{className:`h-3.5 w-3.5 animate-spin`}):s(`common.save`,`Save`)})]}),e(lt,{value:h,onValueChange:e=>{let t=tu.find(t=>t.key===e);t!==void 0&&g(t.key)},children:[r(Xe,{className:`mb-3`,children:tu.map(e=>r(ht,{value:e.key,children:e.label},e.key))}),e(St,{className:`space-y-4 pr-1`,children:[_===null?null:r(`p`,{className:`text-sm text-destructive`,children:_}),r(q,{value:`basics`,className:`space-y-3`,children:e($,{title:s(`system.notificationCalendarEventsEditor.basics`,`Basics`),children:[e(`label`,{className:`block text-sm`,children:[s(`system.notificationCalendarEventsEditor.name`,`Name`),r(G,{className:`mt-1`,value:d.name,onChange:e=>y({name:e.target.value}),"data-testid":`calendar-events-name`})]}),r(gl,{label:s(`system.notificationCalendarEventsEditor.horizonDays`,`Horizon (days)`),value:d.horizonDays,min:1,max:30,onChange:e=>{e!==void 0&&y({horizonDays:e})}}),r(gl,{label:s(`system.notificationCalendarEventsEditor.priority`,`Priority`),value:d.priority,min:1,max:5,onChange:e=>{e!==void 0&&y({priority:e})}}),r(_l,{label:s(`system.notificationCalendarEventsEditor.enabled`,`Enabled`),checked:d.enabled,onChange:e=>y({enabled:e})}),r(_l,{label:s(`system.notificationCalendarEventsEditor.deliverWhenEmpty`,`Deliver when empty`),checked:d.deliverEmpty,onChange:e=>y({deliverEmpty:e})})]})}),r(q,{value:`schedule`,className:`space-y-3`,children:e($,{title:s(`system.notificationCalendarEventsEditor.schedule`,`Schedule`),children:[r(Xt,{mode:`times`,value:d.schedule,onChange:e=>y({schedule:e})}),r(`p`,{className:`text-[11px] text-foreground-subtle`,children:s(`system.notificationCalendarEventsEditor.oneSendTimePerRow`,`One send time per row. The digest fires at that minute.`)})]})}),r(q,{value:`calendars`,className:`space-y-3`,children:r($,{title:s(`system.notificationCalendarEventsEditor.calendars`,`Calendars`),children:r(os,{draft:p,onChange:m,exceptOffered:!0,plural:`calendars`,describe:e=>x.find(t=>t.id===e)?.name??e,testId:`calendar-events-scope`,renderPicker:(e,t,n)=>r(ct,{devices:x,listState:l.isPending?`pending`:`answered`,value:e,onChange:t,emptyMeansAll:!0,noun:`calendar`,testId:`calendar-picker`},n)})})}),r(q,{value:`targets`,className:`space-y-3`,children:r($,{title:s(`system.notificationCalendarEventsEditor.targets`,`Targets`),children:r(hl,{targets:n,value:d.targetIds,onChange:e=>y({targetIds:e})})})}),r(q,{value:`template`,className:`space-y-3`,children:e($,{title:s(`system.notificationCalendarEventsEditor.template`,`Template`),children:[e(`p`,{className:`text-[11px] text-foreground-subtle`,children:[s(`system.notificationCalendarEventsEditor.optionalLeaveBlankForThe`,`Optional. Leave blank for the default digest body (tomorrow highlighted, then later days). Variables:`),` `,s(`system.notificationCalendarEventsEditor.templateVars`,{ruleVar:`{{rule}}`,countVar:`{{count}}`,horizonVar:`{{horizonDays}}`,eventsVar:`{{events}}`})]}),e(`label`,{className:`block text-sm`,children:[s(`system.notificationCalendarEventsEditor.title`,`Title`),r(G,{className:`mt-1`,value:d.templateTitle,onChange:e=>y({templateTitle:e.target.value})})]}),e(`label`,{className:`block text-sm`,children:[s(`system.notificationCalendarEventsEditor.body`,`Body`),r(`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 pu=`nc.listSummaryRules`,mu=`nc.upsertSummaryRule`,hu=`nc.deleteSummaryRule`,gu=`nc.testSummaryRule`,_u=3600,vu=86400,yu=3600,bu=3600,xu=3*36e5,Su=[`importance`,`recency`,`dwell`],Cu={importance:`Most important`,recency:`Most recent`,dwell:`Longest stay`},wu=[`none`,`tiles`,`all`],Tu=`none`,Eu={none:`Images only — no text anywhere`,tiles:`A label under each tile`,all:`Tile labels and a caption across the top`},Du=[`en`,`it`],Ou=[`deliver-without-text`,`skip`],ku=2048,Au=2e3;function ju(e){return e.window.kind!==`unsupported`&&!e.readOnly}function Mu(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Nu(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 Pu(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 Fu(e){if(e!==void 0)return typeof e==`string`?e:null}function Iu(e){if(e!==void 0)return typeof e==`number`&&Number.isFinite(e)?e:null}function Lu(e){return Su.some(t=>t===e)}function Ru(e){return e===void 0?Tu:wu.find(t=>t===e)??null}function zu(e){if(!Mu(e)||!Array.isArray(e.windows)||e.windows.length===0)return null;let t=[];for(let n of e.windows){if(!Mu(n))return null;let e=Nu(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=Fu(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 Bu(e){if(!Mu(e)||typeof e.kind!=`string`)return null;if(e.kind===`schedule`){let t=zu(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 Vu(e){if(e==null)return;if(!Mu(e))return null;let t=e.classes===void 0?void 0:Pu(e.classes),n=e.classesExclude===void 0?void 0:Pu(e.classesExclude),r=e.zones===void 0?void 0:Pu(e.zones);if(t===null||n===null||r===null)return null;let i=Iu(e.minImportance),a=Iu(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 Hu(e){if(e==null)return;if(!Mu(e))return null;let t=Fu(e.title),n=Fu(e.body);return t===null||n===null?null:{...t===void 0?{}:{title:t},...n===void 0?{}:{body:n}}}function Uu(e){return Du.some(t=>t===e)}function Wu(e){return Ou.some(t=>t===e)}function Gu(e){if(e==null)return;if(!Mu(e)||typeof e.enabled!=`boolean`)return null;let t=Fu(e.profileId),n=Fu(e.prompt);if(t===null||n===null)return null;let r=Iu(e.maxImagePx),i=Iu(e.timeoutMs);if(r===null||i===null)return null;let a=e.language;if(a!==void 0&&!Uu(a))return null;let o=e.onFailure;return o!==void 0&&!Wu(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 Ku(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(!Mu(n)||typeof n.targetId!=`string`)return null;let e=n.params;if(e!==void 0&&!Mu(e))return null;t.push({targetId:n.targetId,...e===void 0?{}:{params:e}})}return t}function qu(e){if(!Mu(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`||!Lu(o)||typeof s!=`number`||typeof c!=`boolean`||typeof e.priority!=`number`)return null;let l=Nu(e.deviceIds),u=Bu(e.window),d=Ku(e.targets);if(l===null||u===null||d===null)return null;let f=Vu(e.filters),p=Hu(e.template);if(f===null||p===null)return null;let m=Fu(e.captionText),h=Iu(e.generatedAt),g=Iu(e.updatedAt);if(m===null||h===null||g===null)return null;let _=Ru(e.captions);if(_===null)return null;let v=Gu(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 Ju(e){if(!Mu(e)||!Array.isArray(e.rules))return null;let t=[];for(let n of e.rules){let e=qu(n);if(e===null)return null;t.push(e)}return t}function Yu(e){if(!Mu(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=Iu(e[r]);if(t===null)return null;t!==void 0&&(n[r]=t)}for(let t of[`windowStartMs`,`windowEndMs`]){let r=Iu(e[t]);if(r===null)return null;r!==void 0&&(n[t]=r)}for(let t of[`mosaicUrl`,`error`,`aiText`,`aiFailure`]){let r=Fu(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 Xu(){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:Tu,captionText:``,deliverEmpty:!1,priority:3,aiEnabled:!1,aiProfileId:``,aiPrompt:``,aiLanguage:``,aiMaxImagePx:void 0,aiTimeoutSeconds:void 0,aiOnFailure:`deliver-without-text`}}function Zu(e){let t=Xu(),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 Qu(e){return e.windowKind===`schedule`&&e.schedule!==void 0?{kind:`schedule`,schedule:e.schedule}:{kind:`motion`,quietSeconds:e.quietSeconds,maxWindowSeconds:e.maxWindowSeconds}}function $u(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 ed(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 td(e){return Ol(e.targetIds)}function nd(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 rd(e){let t=$u(e),n=ed(e),r=nd(e),i=e.captionText.trim();return{name:e.name.trim(),enabled:e.enabled,deviceIds:[...e.deviceIds],window:Qu(e),...t===void 0?{}:{filters:t},maxTiles:e.maxTiles,maxAiImages:e.maxAiImages,rank:e.rank,barrierSeconds:e.barrierSeconds,targets:td(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 id(e,t){let n=rd(e),r={};return n.name!==t.name&&(r.name=n.name),n.enabled!==t.enabled&&(r.enabled=n.enabled),Dl(n.deviceIds,t.deviceIds)||(r.deviceIds=n.deviceIds),Dl(n.window,t.window)||(r.window=n.window),Dl(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),Dl(n.targets,t.targets)||(r.targets=n.targets),Dl(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),Dl(n.ai,t.ai)||(r.ai=n.ai??null),r}function ad(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 ${_u}s.`),(e.maxWindowSeconds<60||e.maxWindowSeconds>86400)&&t.push(`The longest window must be between 60s and ${vu}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 ${yu}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 ${bu}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 ${Au} 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 ${ku} 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 od(e){return ad(e).length===0}function sd(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 cd=[{key:`rule`,get label(){return J.t(`helpers.notificationSummaries.tab_rule`)},fields:[`name`,`enabled`,`deviceIds`]},{key:`window`,get label(){return J.t(`helpers.notificationSummaries.tab_window`)},fields:[`windowKind`,`schedule`,`quietSeconds`,`maxWindowSeconds`,`barrierSeconds`]},{key:`content`,get label(){return J.t(`helpers.notificationSummaries.tab_content`)},fields:[`classes`,`classesExclude`,`zones`,`minImportance`,`minDwellSeconds`,`includeStationary`]},{key:`mosaic`,get label(){return J.t(`helpers.notificationSummaries.tab_mosaic`)},fields:[`maxTiles`,`rank`,`mosaicCaptions`,`captionText`]},{key:`ai`,label:`AI`,fields:[`aiEnabled`,`aiProfileId`,`aiPrompt`,`aiLanguage`,`aiMaxImagePx`,`aiTimeoutSeconds`,`aiOnFailure`,`maxAiImages`]},{key:`delivery`,get label(){return J.t(`helpers.notificationSummaries.tab_delivery`)},fields:[`targetIds`,`priority`,`deliverEmpty`,`templateTitle`,`templateBody`]}],ld=`rule`;function ud(e){return cd.find(t=>t.key===e)?.key}function dd(e){return e.kind===`motion`?J.t(`helpers.notificationSummaries.winMotion`,{quiet:bl(e.quietSeconds),max:bl(e.maxWindowSeconds)}):e.kind===`unsupported`?J.t(`helpers.notificationSummaries.winUnsupported`,{raw:e.raw}):J.t(`helpers.notificationSummaries.winSchedule`,{schedule:Cl(e.schedule)})}function fd(e,t){return wl(e,t,`Never run`)}function pd(e){if(e===void 0)return J.t(`helpers.notificationSummaries.allPassages`);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(J.t(`helpers.notificationSummaries.filterNot`,{classes:e.classesExclude.join(`, `)})),e.zones!==void 0&&e.zones.length>0&&t.push(J.t(`helpers.notificationSummaries.filterZones`,{count:e.zones.length})),e.minImportance!==void 0&&t.push(J.t(`helpers.notificationSummaries.filterImportance`,{value:e.minImportance})),e.minDwellSeconds!==void 0&&t.push(J.t(`helpers.notificationSummaries.filterStay`,{value:bl(e.minDwellSeconds)})),e.includeStationary===!0&&t.push(J.t(`helpers.notificationSummaries.filterParked`)),t.length===0?J.t(`helpers.notificationSummaries.allPassages`):t.join(` · `)}function md(e){return{windowStartMs:e-xu,windowEndMs:e}}s();var hd={"deliver-without-text":`Deliver the digest anyway, without the text`,skip:`Hold the whole digest — deliver nothing`},gd={en:`English`,it:`Italiano`};function _d(e){return Su.find(t=>t===e)}function vd(e){return wu.find(t=>t===e)}function yd(e){return Du.find(t=>t===e)??``}function bd(e){return Ou.find(t=>t===e)}function xd({rule:t,cameras:i,fleet:s,targets:c,taxonomy:l,onSaved:d,onCancel:f}){let{t:p}=Y(),m=w(),[h,g]=a(()=>t===null?Xu():Zu(t)),[_,v]=a(null),[y,b]=a(t!==null),[x,S]=a(ld),C=e=>g(t=>({...t,...e})),E=n(()=>{let e=we(`occupancy`,l);return e===null?[]:e.groups.flatMap(e=>e.options)},[l]),{options:D,loading:O}=sn(h.deviceIds,i.map(e=>({id:e.id,name:e.name}))),k=o({queryKey:[`llm`,`listProfiles`,`summary-editor`],queryFn:()=>m.trpcClient.llm.listProfiles.query({}),retry:!1}),A=(k.data??[]).filter(e=>e.supportsVision),j=u({mutationFn:async()=>{let e=t===null?{rule:rd(h)}:{ruleId:t.id,patch:id(h,t)};await m.trpcClient.addons.custom.mutate({addonId:kl,action:mu,input:e})},onSuccess:d,onError:e=>v(e instanceof Error?e.message:`Save failed`)}),M=To(),N=M.data?xo(M.data,{family:`summary`,field:`captionText`}):void 0,P=h.mosaicCaptions===`all`,ee=ad(h),F=sd(h),I=cd.some(e=>e.key===x)?x:ld;return r(xt,{open:!0,onOpenChange:e=>!e&&f(),children:e(kt,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,children:[r(`div`,{className:`mb-3 flex shrink-0 items-center gap-2 pr-10`,children:e(`h3`,{className:`flex min-w-0 items-center gap-2 text-sm font-semibold text-foreground`,children:[r(qe,{className:`h-4 w-4 shrink-0 text-foreground-subtle`}),r(`span`,{className:`truncate`,children:t===null?p(`system.notificationSummaryEditor.newSummary`,`New summary`):p(`system.notificationSummaryEditor.edit`,`Edit {{name}}`,{name:t.name})})]})}),_!==null&&r(`div`,{className:`mb-3 shrink-0 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger`,children:_}),e(`div`,{className:`shrink-0 space-y-2`,children:[t!==null&&r(Kc,{kind:`summary`,ruleId:t.id,enabled:t.enabled,updatedAt:t.updatedAt??1/0}),y?r(fl,{problems:ee,testId:`summary-problems`}):null,r(pl,{warnings:F,testId:`summary-warnings`})]}),e(lt,{value:I,onValueChange:e=>S(ud(e)??x),className:`mt-3 flex min-h-0 flex-1 flex-col`,children:[r(Xe,{className:`mb-3 shrink-0`,children:cd.map(e=>r(ht,{value:e.key,children:e.label},e.key))}),e(St,{className:`pr-1`,children:[e(q,{value:`rule`,className:`space-y-3`,children:[r($,{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:e(`div`,{className:`flex items-end gap-3`,children:[e(`div`,{className:`min-w-0 flex-1`,children:[r(`label`,{className:Q,children:p(`system.notificationSummaryEditor.name`,`Name`)}),r(G,{value:h.name,onChange:e=>C({name:e.target.value}),placeholder:p(`system.notificationSummaryEditor.eGOvernightSweep`,`e.g. Overnight sweep`),"data-testid":`summary-name`})]}),r(`div`,{className:`pb-1.5`,children:r(_l,{label:p(`system.notificationSummaryEditor.enabled`,`Enabled`),checked:h.enabled,onChange:e=>C({enabled:e}),testId:`summary-enabled`})})]})}),r($,{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:r(ml,{cameras:i,value:h.deviceIds,fleet:s,onChange:e=>C({deviceIds:e}),hint:p(`system.notificationSummaryEditor.theFirstCameraSelectedOwns`,`The first camera selected owns the delivered notification.`)})})]}),r(q,{value:`window`,className:`space-y-3`,children:e($,{title:p(`system.notificationSummaryEditor.whenTheWindowCloses`,`When the window closes`),children:[e(`div`,{children:[r(`label`,{className:Q,children:p(`system.notificationSummaryEditor.window`,`Window`)}),r(W,{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=>C({windowKind:e.target.value===`schedule`?`schedule`:`motion`}),"data-testid":`summary-window-kind`})]}),h.windowKind===`motion`?e(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[r(gl,{label:p(`system.notificationSummaryEditor.quietPeriodSeconds`,`Quiet period (seconds)`),value:h.quietSeconds,min:30,max:_u,onChange:e=>C({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`}),r(gl,{label:p(`system.notificationSummaryEditor.longestWindowSeconds`,`Longest window (seconds)`),value:h.maxWindowSeconds,min:60,max:vu,onChange:e=>C({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`})]}):e(`div`,{children:[r(`label`,{className:Q,children:p(`system.notificationSummaryEditor.weeklyWindows`,`Weekly windows`)}),r(Xt,{value:h.schedule,onChange:e=>C({schedule:e})}),r(`p`,{className:dl,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.`)})]}),r(gl,{label:p(`system.notificationSummaryEditor.waitForOpenTracksSeconds`,`Wait for open tracks (seconds)`),value:h.barrierSeconds,min:0,max:yu,onChange:e=>C({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`})]})}),r(q,{value:`content`,className:`space-y-3`,children:e($,{title:p(`system.notificationSummaryEditor.whatGoesIn`,`What goes in`),hint:p(`system.notificationSummaryEditor.evaluatedOnTracksOnePassage`,`Evaluated on tracks: one passage is one tile.`),children:[e(`div`,{children:[r(`label`,{className:Q,children:p(`system.notificationSummaryEditor.classes`,`Classes`)}),r(Cn,{options:E,value:h.classes,onChange:e=>C({classes:e}),emptyHint:`No class vocabulary from this hub — leave empty to keep every class.`,placeholder:``,noFreeText:!0}),r(`p`,{className:dl,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.`)})]}),e(`div`,{children:[r(`label`,{className:Q,children:p(`system.notificationSummaryEditor.excludedClasses`,`Excluded classes`)}),r(Cn,{options:E,value:h.classesExclude,onChange:e=>C({classesExclude:e}),emptyHint:`No class vocabulary from this hub.`,placeholder:``,noFreeText:!0})]}),e(`div`,{children:[r(`label`,{className:Q,children:p(`system.notificationSummaryEditor.zones`,`Zones`)}),r(Cn,{options:D,value:h.zones,onChange:e=>C({zones:e}),loading:O,emptyHint:`Pick a camera first — the zones offered are its own.`,placeholder:``,noFreeText:!0}),r(`p`,{className:dl,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.`)})]}),e(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[r(gl,{label:p(`system.notificationSummaryEditor.minimumImportance`,`Minimum importance`),value:h.minImportance,min:0,max:1,step:.05,emptyPlaceholder:`any`,onChange:e=>C({minImportance:e}),hint:p(`system.notificationSummaryEditor.thePipelineSOwnScore`,`The pipeline's own score, 0–1. Empty keeps everything.`),testId:`summary-min-importance`}),r(gl,{label:p(`system.notificationSummaryEditor.minimumStaySeconds`,`Minimum stay (seconds)`),value:h.minDwellSeconds,min:0,max:bu,emptyPlaceholder:`any`,onChange:e=>C({minDwellSeconds:e}),hint:p(`system.notificationSummaryEditor.dropsThePassagesTooBrief`,`Drops the passages too brief to be worth a tile.`),testId:`summary-min-dwell`})]}),r(_l,{label:p(`system.notificationSummaryEditor.includeParkedObjects`,`Include parked objects`),checked:h.includeStationary,onChange:e=>C({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`})]})}),r(q,{value:`mosaic`,className:`space-y-3`,children:e($,{title:p(`system.notificationSummaryEditor.theMosaic`,`The mosaic`),children:[e(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[r(gl,{label:p(`system.notificationSummaryEditor.tiles`,`Tiles`),value:h.maxTiles,min:1,max:24,onChange:e=>C({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`}),e(`div`,{children:[r(`label`,{className:Q,children:p(`system.notificationSummaryEditor.whenThereAreMoreTracks`,`When there are more tracks than tiles`)}),r(W,{value:h.rank,options:Su.map(e=>({value:e,label:Cu[e]})),onChange:e=>{let t=_d(e.target.value);t!==void 0&&C({rank:t})},"data-testid":`summary-rank`}),r(`p`,{className:dl,children:p(`system.notificationSummaryEditor.everyContributingCameraKeepsIts`,`Every contributing camera keeps its single best tile first; the remaining slots go to this ranking.`)})]})]}),e(`div`,{children:[r(`label`,{className:Q,children:p(`system.notificationSummaryEditor.textOnTheMosaic`,`Text on the mosaic`)}),r(W,{value:h.mosaicCaptions,options:wu.map(e=>({value:e,label:Eu[e]})),onChange:e=>{let t=vd(e.target.value);t!==void 0&&C({mosaicCaptions:t})},"data-testid":`summary-captions`}),r(`p`,{className:dl,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.`)})]}),e(`div`,{children:[r(Ao,{label:p(`system.notificationSummaryEditor.captionBurnedOntoTheMosaic`,`Caption burned onto the mosaic`),value:h.captionText,disabled:!P,onChange:e=>C({captionText:e}),placeholder:p(`system.notificationSummaryEditor.leaveEmptyForNoCaption`,`Leave empty for no caption`),vars:N,testId:`summary-caption`}),r(`p`,{className:dl,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.`)})]})]})}),r(q,{value:`ai`,className:`space-y-3`,children:e($,{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:[r(_l,{label:p(`system.notificationSummaryEditor.haveAModelDescribeThe`,`Have a model describe the window`),checked:h.aiEnabled,onChange:e=>C({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&&r(`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.`)}),e(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[e(`div`,{children:[r(`label`,{className:Q,children:p(`system.notificationSummaryEditor.visionProfile`,`Vision profile`)}),r(W,{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=>C({aiProfileId:e.target.value}),"data-testid":`summary-ai-profile`}),r(`p`,{className:dl,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.`)})]}),e(`div`,{children:[r(`label`,{className:Q,children:p(`system.notificationSummaryEditor.answerIn`,`Answer in`)}),r(W,{value:h.aiLanguage,disabled:!h.aiEnabled,options:[{value:``,label:p(`system.notificationSummaryEditor.donTAskForA`,`Don’t ask for a language`)},...Du.map(e=>({value:e,label:gd[e]}))],onChange:e=>C({aiLanguage:yd(e.target.value)}),"data-testid":`summary-ai-language`}),r(`p`,{className:dl,children:p(`system.notificationSummaryEditor.nothingIsAddedToThe`,`Nothing is added to the prompt unless you pick one, and these models answer in English on their own.`)})]})]}),e(`div`,{children:[r(`label`,{className:Q,children:p(`system.notificationSummaryEditor.yourQuestionOptional`,`Your question (optional)`)}),r(`textarea`,{value:h.aiPrompt,rows:3,maxLength:Au,disabled:!h.aiEnabled,onChange:e=>C({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`}),r(`p`,{className:dl,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.`)})]}),e(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[r(gl,{label:p(`system.notificationSummaryEditor.framesTheModelMayLook`,`Frames the model may look at`),value:h.maxAiImages,min:1,max:8,disabled:!h.aiEnabled,onChange:e=>C({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`}),r(gl,{label:p(`system.notificationSummaryEditor.timeLimitSeconds`,`Time limit (seconds)`),value:h.aiTimeoutSeconds,min:10,max:600,emptyPlaceholder:`180`,disabled:!h.aiEnabled,onChange:e=>C({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`})]}),e(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[r(gl,{label:p(`system.notificationSummaryEditor.frameSizeSentPixels`,`Frame size sent (pixels)`),value:h.aiMaxImagePx,min:64,max:ku,emptyPlaceholder:`448`,disabled:!h.aiEnabled,onChange:e=>C({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`}),e(`div`,{children:[r(`label`,{className:Q,children:p(`system.notificationSummaryEditor.ifTheModelGivesNo`,`If the model gives no answer`)}),r(W,{value:h.aiOnFailure,disabled:!h.aiEnabled,options:Ou.map(e=>({value:e,label:hd[e]})),onChange:e=>{let t=bd(e.target.value);t!==void 0&&C({aiOnFailure:t})},"data-testid":`summary-ai-on-failure`}),r(`p`,{className:dl,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.`)})]})]})]})}),r(q,{value:`delivery`,className:`space-y-3`,children:e($,{title:p(`system.notificationSummaryEditor.delivery`,`Delivery`),children:[r(hl,{targets:c,value:h.targetIds,onChange:e=>C({targetIds:e})}),e(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[r(gl,{label:p(`system.notificationSummaryEditor.priority`,`Priority`),value:h.priority,min:1,max:5,onChange:e=>C({priority:e??3}),testId:`summary-priority`}),r(_l,{label:p(`system.notificationSummaryEditor.deliverAWindowThatMatched`,`Deliver a window that matched nothing`),checked:h.deliverEmpty,onChange:e=>C({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`})]}),r(vl,{title:h.templateTitle,body:h.templateBody,onTitleChange:e=>C({templateTitle:e}),onBodyChange:e=>C({templateBody:e}),family:`summary`,testIdPrefix:`summary-template`}),r(`p`,{className:dl,children:r(Kr,{i18nKey:`system.notificationSummaryEditor.aiToken`,values:{token:`{{ai}}`},components:{code:r(`code`,{})}})})]})})]})]}),e(`div`,{className:`mt-3 flex shrink-0 justify-end gap-2`,children:[r(U,{size:`sm`,variant:`secondary`,type:`button`,onClick:f,children:p(`common.cancel`,`Cancel`)}),e(U,{size:`sm`,type:`button`,disabled:j.isPending,onClick:()=>{b(!0),!(!od(h)||j.isPending)&&j.mutate()},children:[j.isPending&&r(T,{className:`h-3.5 w-3.5 animate-spin`}),t===null?p(`system.notificationSummaryEditor.create`,`Create`):p(`common.save`,`Save`)]})]})]})})}var Sd=`nc.listTimelapseRules`,Cd=`nc.upsertTimelapseRule`,wd=`nc.deleteTimelapseRule`,Td=`nc.testTimelapseRule`,Ed=3600,Dd=3600,Od=30,kd=1,Ad=[`image`,`gif`],jd={image:`Still frame`,gif:`Short animation (GIF)`},Md=Re({rules:Be(je.extend({readOnly:Ve().optional()}))});function Nd(e){let t=Md.safeParse(e);return t.success?t.data.rules:null}function Pd(e){return e.readOnly!==!0}var Fd=Re({produced:Fe(),exportId:Le().optional(),coveragePercent:Fe().optional(),enqueued:Fe().optional(),windowStartMs:Fe().optional(),windowEndMs:Fe().optional(),error:Le().optional()});function Id(e){let t=Fd.safeParse(e);return t.success?t.data:null}function Ld(){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 Rd(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 zd={windows:[{days:[1],startMinute:0,endMinute:60}]};function Bd(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 Vd(e){let t=Bd(e);return{name:e.name.trim(),enabled:e.enabled,deviceIds:[...e.deviceIds],schedule:e.schedule??zd,cadenceSec:e.cadenceSec,framerate:e.framerate,...e.denseCadenceSec===void 0?{}:{denseCadenceSec:e.denseCadenceSec},...e.minDwellSec===void 0?{}:{minDwellSec:e.minDwellSec},targets:Ol(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 Hd(e,t){let n=Vd(e),r={};return n.name!==t.name&&(r.name=n.name),n.enabled!==t.enabled&&(r.enabled=n.enabled),Dl(n.deviceIds,t.deviceIds)||(r.deviceIds=n.deviceIds),Dl(n.schedule,t.schedule)||(r.schedule=n.schedule),n.cadenceSec!==t.cadenceSec&&(r.cadenceSec=n.cadenceSec),n.framerate!==t.framerate&&(r.framerate=n.framerate),n.denseCadenceSec!==t.denseCadenceSec&&(r.denseCadenceSec=n.denseCadenceSec??Ud(n.cadenceSec)),n.minDwellSec!==t.minDwellSec&&n.minDwellSec!==void 0&&(r.minDwellSec=n.minDwellSec),Dl(n.targets,t.targets)||(r.targets=n.targets),Dl(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),Dl(n.reportClasses,t.reportClasses)||(r.reportClasses=n.reportClasses??[]),n.priority!==t.priority&&(r.priority=n.priority),r}function Ud(e){return Math.max(kd,e/Od)}function Wd(e,t,n){return t<=0||n<=0?0:e/t/n}function Gd(e,t){return e*t*I}function Kd(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 ${Ed}.`),(!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 ${I}s and ${Dd}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 qd(e){return Kd(e).length===0}function Jd(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=Gd(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 Yd(e){return Cl(e)}function Xd(e,t){return wl(e,t,`Never run`)}function Zd(e){return e.denseCadenceSec===void 0?{seconds:Ud(e.cadenceSec),derived:!0}:{seconds:e.denseCadenceSec,derived:!1}}var Qd=[{key:`rule`,get label(){return J.t(`helpers.notificationTimelapse.tab_rule`)},fields:[`name`,`enabled`,`deviceIds`]},{key:`window`,get label(){return J.t(`helpers.notificationTimelapse.tab_window`)},fields:[`schedule`]},{key:`sampling`,get label(){return J.t(`helpers.notificationTimelapse.tab_sampling`)},fields:[`cadenceSec`,`framerate`,`denseCadenceSec`,`minDwellSec`]},{key:`delivery`,get label(){return J.t(`helpers.notificationTimelapse.tab_delivery`)},fields:[`targetIds`,`priority`,`previewMode`,`previewText`,`previewTextSet`,`templateTitle`,`templateBody`,`reportClasses`]}],$d=`rule`;function ef(e){return Qd.find(t=>t.key===e)?.key}s();var tf=7;function nf(e){return Ad.find(t=>t===e)}function rf({rule:t,cameras:n,fleet:i,targets:o,onSaved:s,onCancel:c}){let{t:l}=Y(),f=w(),[p,m]=a(()=>t===null?Ld():Rd(t)),[h,g]=a(null),[_,v]=a(t!==null),[y,x]=a($d),S=e=>m(t=>({...t,...e})),C=To(),E=C.data?xo(C.data,{family:`timelapse`,field:`previewText`}):void 0,D=u({mutationFn:async()=>{let e=t===null?{rule:Vd(p)}:{ruleId:t.id,patch:Hd(p,t)};await f.trpcClient.addons.custom.mutate({addonId:kl,action:Cd,input:e})},onSuccess:s,onError:e=>g(e instanceof Error?e.message:`Save failed`)}),O=Kd(p),k=Jd(p),A=Zd(p),j=Wd(tf,A.seconds,p.framerate),M=Qd.some(e=>e.key===y)?y:$d;return r(xt,{open:!0,onOpenChange:e=>!e&&c(),children:e(kt,{width:`lg`,placement:`sheet-on-mobile`,scroll:`body`,children:[r(`div`,{className:`mb-3 flex shrink-0 items-center gap-2 pr-10`,children:e(`h3`,{className:`flex min-w-0 items-center gap-2 text-sm font-semibold text-foreground`,children:[r(b,{className:`h-4 w-4 shrink-0 text-foreground-subtle`}),r(`span`,{className:`truncate`,children:t===null?l(`system.notificationTimelapseEditor.newTimelapse`,`New timelapse`):l(`system.notificationTimelapseEditor.edit`,`Edit {{name}}`,{name:t.name})})]})}),h!==null&&r(`div`,{className:`mb-3 shrink-0 rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger`,children:h}),e(`div`,{className:`shrink-0 space-y-2`,children:[t!==null&&r(Kc,{kind:`timelapse`,ruleId:t.id,enabled:t.enabled,updatedAt:t.updatedAt}),_?r(fl,{problems:O,testId:`timelapse-problems`}):null,r(pl,{warnings:k,testId:`timelapse-warnings`})]}),e(lt,{value:M,onValueChange:e=>x(ef(e)??y),className:`mt-3 flex min-h-0 flex-1 flex-col`,children:[r(Xe,{className:`mb-3 shrink-0`,children:Qd.map(e=>r(ht,{value:e.key,children:e.label},e.key))}),e(St,{className:`pr-1`,children:[e(q,{value:`rule`,className:`space-y-3`,children:[r($,{title:l(`system.notificationTimelapseEditor.whatItIs`,`What it is`),hint:l(`system.notificationTimelapseEditor.oneVideoPerCameraAssembled`,`One video per camera, assembled from that camera's RECORDED footage when the window closes.`),children:e(`div`,{className:`flex items-end gap-3`,children:[e(`div`,{className:`min-w-0 flex-1`,children:[r(`label`,{className:Q,children:l(`system.notificationTimelapseEditor.name`,`Name`)}),r(G,{value:p.name,onChange:e=>S({name:e.target.value}),placeholder:l(`system.notificationTimelapseEditor.eGNightDriveway`,`e.g. Night driveway`),"data-testid":`timelapse-name`})]}),r(`div`,{className:`pb-1.5`,children:r(_l,{label:l(`system.notificationTimelapseEditor.enabled`,`Enabled`),checked:p.enabled,onChange:e=>S({enabled:e}),testId:`timelapse-enabled`})})]})}),r($,{title:l(`system.notificationTimelapseEditor.cameras`,`Cameras`),children:r(ml,{cameras:n,value:p.deviceIds,fleet:i,onChange:e=>S({deviceIds:e}),hint:l(`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.`)})})]}),r(q,{value:`window`,className:`space-y-3`,children:r($,{title:l(`system.notificationTimelapseEditor.when`,`When`),children:e(`div`,{children:[r(`label`,{className:Q,children:l(`system.notificationTimelapseEditor.weeklyWindows`,`Weekly windows`)}),r(Xt,{value:p.schedule,onChange:e=>S({schedule:e})}),r(`p`,{className:dl,children:l(`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.`)})]})})}),r(q,{value:`sampling`,className:`space-y-3`,children:e($,{title:l(`system.notificationTimelapseEditor.sampling`,`Sampling`),hint:l(`system.notificationTimelapseEditor.twoRatesABaseRate`,`Two rates: a base rate for the whole window, and a denser one inside the ranges where something was detected.`),children:[e(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[r(gl,{label:l(`system.notificationTimelapseEditor.baseCadenceSeconds`,`Base cadence (seconds)`),value:p.cadenceSec,min:2,max:Ed,onChange:e=>S({cadenceSec:e??0}),hint:l(`system.notificationTimelapseEditor.oneFrameEveryNSeconds`,`One frame every N seconds across the quiet parts of the window.`),testId:`timelapse-cadence`}),r(gl,{label:l(`system.notificationTimelapseEditor.outputFrameRateFps`,`Output frame rate (fps)`),value:p.framerate,min:1,max:60,onChange:e=>S({framerate:e??0}),hint:l(`system.notificationTimelapseEditor.howFastTheAssembledVideo`,`How fast the assembled video plays.`),testId:`timelapse-framerate`})]}),e(`div`,{children:[r(`label`,{className:Q,children:l(`system.notificationTimelapseEditor.denseCadenceNearTheDetections`,`Dense cadence, near the detections`)}),e(`div`,{className:`flex items-center gap-2`,children:[r(W,{value:p.denseCadenceSec===void 0?`auto`:`explicit`,options:[{value:`auto`,label:l(`system.notificationTimelapseEditor.automaticS`,`Automatic ({{seconds}}s)`,{seconds:A.seconds})},{value:`explicit`,label:l(`system.notificationTimelapseEditor.setItMyself`,`Set it myself`)}],onChange:e=>S({denseCadenceSec:e.target.value===`auto`?void 0:Zd(p).seconds}),"data-testid":`timelapse-dense-mode`}),p.denseCadenceSec!==void 0&&r(G,{type:`number`,className:`w-28`,min:.1,step:.1,value:String(p.denseCadenceSec),onChange:e=>{let t=Number(e.target.value);Number.isFinite(t)&&S({denseCadenceSec:t})},"data-testid":`timelapse-dense-seconds`})]}),e(`p`,{className:dl,"data-testid":`timelapse-dense-hint`,children:[l(`system.notificationTimelapseEditor.denseHint`,{seconds:A.seconds,fps:p.framerate,passage:tf,onScreen:j.toFixed(2)}),` `,A.derived?l(`system.notificationTimelapseEditor.denseDerived`):l(`system.notificationTimelapseEditor.denseFixed`,{seconds:Zd({...p,denseCadenceSec:void 0}).seconds})]})]}),r(gl,{label:l(`system.notificationTimelapseEditor.minimumSecondsOfVideoPer`,`Minimum seconds of video per detection (optional)`),value:p.minDwellSec,min:0,max:60,step:.5,emptyPlaceholder:`no guarantee`,onChange:e=>S({minDwellSec:e}),hint:l(`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`})]})}),r(q,{value:`delivery`,className:`space-y-3`,children:e($,{title:l(`system.notificationTimelapseEditor.theNotification`,`The notification`),children:[r(hl,{targets:o,value:p.targetIds,onChange:e=>S({targetIds:e})}),e(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[e(`div`,{children:[r(`label`,{className:Q,children:l(`system.notificationTimelapseEditor.preview`,`Preview`)}),r(W,{value:p.previewMode,options:Ad.map(e=>({value:e,label:jd[e]})),onChange:e=>{let t=nf(e.target.value);t!==void 0&&S({previewMode:t})},"data-testid":`timelapse-preview-mode`})]}),r(gl,{label:l(`system.notificationTimelapseEditor.priority`,`Priority`),value:p.priority,min:1,max:5,onChange:e=>S({priority:e??3}),testId:`timelapse-priority`})]}),e(`div`,{children:[r(Ao,{label:l(`system.notificationTimelapseEditor.captionOnThePreviewFrame`,`Caption on the preview frame`),value:p.previewTextSet?p.previewText:``,placeholder:l(`system.notificationTimelapseEditor.shippedDefault`,`{{DEFAULT_TIMELAPSE_PREVIEW_TEXT}} (shipped default)`,{DEFAULT_TIMELAPSE_PREVIEW_TEXT:de}),onChange:e=>S({previewText:e,previewTextSet:!0}),vars:E,testId:`timelapse-preview-text`}),e(`p`,{className:dl,children:[p.previewTextSet&&p.previewText.length===0?l(`system.notificationTimelapseEditor.emptyAndSetThePreview`,`Empty and set: the preview frame carries NO caption.`):l(`system.notificationTimelapseEditor.leaveUntouchedForTheShipped`,`Leave untouched for the shipped caption ({{DEFAULT_TIMELAPSE_PREVIEW_TEXT}}).`,{DEFAULT_TIMELAPSE_PREVIEW_TEXT:de}),p.previewTextSet&&e(d,{children:[` `,r(`button`,{type:`button`,className:`underline`,onClick:()=>S({previewText:``,previewTextSet:!1}),"data-testid":`timelapse-preview-text-reset`,children:l(`system.notificationTimelapseEditor.backToTheShippedCaption`,`Back to the shipped caption`)})]})]})]}),r(vl,{title:p.templateTitle,body:p.templateBody,onTitleChange:e=>S({templateTitle:e}),onBodyChange:e=>S({templateBody:e}),family:`timelapse`,testIdPrefix:`timelapse-template`}),r(`p`,{className:`text-[10px] text-foreground-subtle`,children:r(Kr,{i18nKey:`system.notificationTimelapseEditor.detectionSummaryNote`,values:{token:`{{detectionSummary}}`},components:{code:r(`code`,{})}})})]})})]})]}),e(`div`,{className:`mt-3 flex shrink-0 justify-end gap-2`,children:[r(U,{size:`sm`,variant:`secondary`,type:`button`,onClick:c,children:l(`common.cancel`,`Cancel`)}),e(U,{size:`sm`,type:`button`,disabled:D.isPending,onClick:()=>{v(!0),!(!qd(p)||D.isPending)&&D.mutate()},children:[D.isPending&&r(T,{className:`h-3.5 w-3.5 animate-spin`}),t===null?l(`system.notificationTimelapseEditor.create`,`Create`):l(`common.save`,`Save`)]})]})]})})}function af({children:e,className:t}){return r(`span`,{className:t,onClick:e=>e.stopPropagation(),children:e})}function of(){return r(`div`,{className:`flex items-center justify-center py-16`,children:r(T,{className:`h-6 w-6 animate-spin text-primary`})})}function sf({children:e,testId:t}){return r(`div`,{className:`text-xs text-foreground-subtle text-center py-16`,...t===void 0?{}:{"data-testid":t},children:e})}function cf({columns:e,rows:t,rowKey:n,minWidthPx:i,onRowClick:a}){return r(bt,{children:r(dt,{columns:e,rows:t,rowKey:n,minWidthPx:i,bordered:!1,maxBodyHeight:Ze,...a===void 0?{}:{onRowClick:a}})})}function lf({name:t,enabled:n,onOpen:i,badges:a,openTestId:o}){let{t:s}=Y();return e(`span`,{className:`flex flex-wrap items-center gap-2`,children:[i===void 0?r(`span`,{className:`truncate text-sm font-medium text-foreground`,children:t}):r(af,{children:r(`button`,{type:`button`,onClick:i,className:`truncate rounded text-left text-sm font-medium text-foreground hover:underline focus-visible:outline focus-visible:outline-2 focus-visible:outline-primary`,...o===void 0?{}:{"data-testid":o},children:t})}),!n&&r(K,{variant:`warning`,children:s(`common.disabled`)}),a]})}function uf({disabled:e=!1,pending:t=!1,title:n,message:i,confirmLabel:a=`Delete`,cancelLabel:o=`Cancel`,ariaLabel:s,testId:c,onConfirm:l}){let u=k(),d=async()=>{await u({title:n,message:i,confirmLabel:a,cancelLabel:o,variant:`danger`})&&l()};return r(`button`,{type:`button`,title:a,"aria-label":s,disabled:e||t,className:`inline-flex h-7 items-center rounded-md px-2 hover:bg-surface-hover disabled:opacity-50`,onClick:()=>void d(),...c===void 0?{}:{"data-testid":c},children:r(h,{className:`h-3.5 w-3.5 text-danger`})})}s();var df=[`notificationSummaries`,`listSummaryRules`];function ff(t){return[{key:`name`,header:J.t(`system.notificationSummaries.digest`,`Digest`),render:n=>r(lf,{name:n.name,enabled:n.enabled,...ju(n)?{onOpen:()=>t.onOpen(n)}:{},openTestId:`summary-edit-${n.id}`,badges:e(d,{children:[!ju(n)&&r(K,{variant:`warning`,children:`read-only`}),n.ai?.enabled===!0&&r(K,{variant:`info`,children:`AI`}),n.ai!==void 0&&!n.ai.enabled&&r(K,{variant:`default`,children:J.t(`system.notificationSummaries.aiOff`,`AI off`)})]})})},{key:`cameras`,header:J.t(`system.notificationSummaries.cameras`,`Cameras`),align:`center`,nowrap:!0,render:e=>r(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.deviceIds.length})},{key:`window`,header:J.t(`system.notificationSummaries.window`,`Window`),render:e=>r(`span`,{className:`text-[11px] text-foreground-subtle`,children:dd(e.window)})},{key:`filters`,header:J.t(`system.notificationSummaries.keeps`,`Keeps`),render:e=>r(`span`,{className:`text-[11px] text-foreground-subtle`,children:pd(e.filters)})},{key:`mosaic`,header:J.t(`system.notificationSummaries.mosaic`,`Mosaic`),nowrap:!0,render:e=>r(`span`,{className:`text-[11px] text-foreground-subtle`,children:J.t(`system.notificationSummaries.tilesRank`,{count:e.maxTiles,rank:e.rank})})},{key:`targets`,header:J.t(`system.notificationSummaries.targets`,`Targets`),render:e=>{let n=e.targets[0],i=n?t.targetNameById.get(n.targetId)??n.targetId:null;return r(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.targets.length===1&&i!==null?i:J.t(`common.targetCount`,{count:e.targets.length})})}},{key:`lastRun`,header:J.t(`system.notificationSummaries.lastRun`,`Last run`),nowrap:!0,render:e=>r(`span`,{className:`text-[11px] text-foreground-subtle`,"data-testid":`summary-last-${e.id}`,children:fd(e.generatedAt,t.nowMs)})},{key:`enabled`,header:J.t(`system.notificationSummaries.on`,`On`),align:`center`,nowrap:!0,render:e=>r(af,{children:r(nt,{checked:e.enabled,disabled:e.readOnly,onCheckedChange:n=>t.onToggle(e,n),"aria-label":J.t(`system.notificationSummaries.toggle`,`toggle {{name}}`,{name:e.name})})})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:n=>e(af,{className:`flex items-center justify-end gap-1`,children:[r(U,{size:`sm`,variant:`ghost`,type:`button`,disabled:n.readOnly,onClick:()=>t.onTest(n),title:J.t(`system.notificationSummaries.produceThisDigestNowAnd`,`Produce this digest now and DELIVER it`),"aria-label":J.t(`system.notificationSummaries.test`,`test {{name}}`,{name:n.name}),"data-testid":`summary-test-${n.id}`,children:r(We,{className:`h-3.5 w-3.5`})}),r(uf,{disabled:n.readOnly,pending:t.deletePending,title:J.t(`system.notificationSummaries.deleteThisSummary`,`Delete this summary?`),message:J.t(`system.notificationSummaries.thisWillPermanentlyDeleteThis`,`This will permanently delete "{{name}}". This action cannot be undone.`,{name:n.name}),ariaLabel:J.t(`system.notificationSummaries.delete`,`delete {{name}}`,{name:n.name}),testId:`summary-delete-${n.id}`,onConfirm:()=>t.onConfirmDelete(n)})]})}]}s();var pf=[`notificationTimelapses`,`listTimelapseRules`];function mf(t){return[{key:`name`,header:J.t(`system.notificationTimelapses.timelapse`,`Timelapse`),render:e=>r(lf,{name:e.name,enabled:e.enabled,...Pd(e)?{onOpen:()=>t.onOpen(e),openTestId:`timelapse-edit-${e.id}`}:{},badges:Pd(e)?null:r(K,{variant:`warning`,children:`read-only`})})},{key:`cameras`,header:J.t(`system.notificationTimelapses.cameras`,`Cameras`),render:e=>r(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.deviceIds.length===1?t.cameraNameById.get(e.deviceIds[0]??-1)??`#${e.deviceIds[0]}`:J.t(`system.notificationTimelapses.cameras2`,`{{length}} cameras`,{length:e.deviceIds.length})})},{key:`schedule`,header:J.t(`system.notificationTimelapses.window`,`Window`),render:e=>r(`span`,{className:`text-[11px] text-foreground-subtle`,children:Yd(e.schedule)})},{key:`sampling`,header:J.t(`system.notificationTimelapses.sampling`,`Sampling`),nowrap:!0,render:t=>{let n=Zd(Rd(t));return e(`span`,{className:`text-[11px] text-foreground-subtle`,children:[J.t(n.derived?`system.notificationTimelapses.ruleSummaryAuto`:`system.notificationTimelapses.ruleSummary`,{cadence:t.cadenceSec,fps:t.framerate,dense:n.seconds}),t.minDwellSec===void 0?``:` · ${J.t(`system.notificationTimelapses.ruleDwell`,{sec:t.minDwellSec})}`]})}},{key:`targets`,header:J.t(`system.notificationTimelapses.targets`,`Targets`),render:e=>{let n=e.targets[0],i=n?t.targetNameById.get(n.targetId)??n.targetId:null;return r(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.targets.length===1&&i!==null?i:J.t(`common.targetCount`,{count:e.targets.length})})}},{key:`lastRun`,header:J.t(`system.notificationTimelapses.lastRun`,`Last run`),nowrap:!0,render:e=>r(`span`,{className:`text-[11px] text-foreground-subtle`,"data-testid":`timelapse-last-${e.id}`,children:Xd(e.lastGeneratedAt,t.nowMs)})},{key:`enabled`,header:J.t(`system.notificationTimelapses.on`,`On`),align:`center`,nowrap:!0,render:e=>r(af,{children:r(nt,{checked:e.enabled,disabled:!Pd(e),onCheckedChange:n=>t.onToggle(e,n),"aria-label":J.t(`system.notificationTimelapses.toggle`,`toggle {{name}}`,{name:e.name})})})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:n=>e(af,{className:`flex items-center justify-end gap-1`,children:[r(U,{size:`sm`,variant:`ghost`,type:`button`,disabled:!Pd(n),onClick:()=>t.onTest(n),title:J.t(`system.notificationTimelapses.renderThisRuleSLast`,`Render this rule's last closed window now and DELIVER it`),"aria-label":J.t(`system.notificationTimelapses.test`,`test {{name}}`,{name:n.name}),"data-testid":`timelapse-test-${n.id}`,children:r(We,{className:`h-3.5 w-3.5`})}),r(uf,{disabled:!Pd(n),pending:t.deletePending,title:J.t(`system.notificationTimelapses.deleteThisTimelapse`,`Delete this timelapse?`),message:J.t(`system.notificationTimelapses.thisWillPermanentlyDeleteThis`,`This will permanently delete "{{name}}". This action cannot be undone.`,{name:n.name}),ariaLabel:J.t(`system.notificationTimelapses.delete`,`delete {{name}}`,{name:n.name}),testId:`timelapse-delete-${n.id}`,onConfirm:()=>t.onConfirmDelete(n)})]})}]}s();var hf={summary:{titleKey:`system.notificationProducerRules.summaryUnavailableTitle`,messageKey:`system.notificationProducerRules.summaryUnavailableMessage`},timelapse:{titleKey:`system.notificationProducerRules.timelapseUnavailableTitle`,messageKey:`system.notificationProducerRules.timelapseUnavailableMessage`},"calendar-events":{titleKey:`system.notificationProducerRules.calendarEventsUnavailableTitle`,messageKey:`system.notificationProducerRules.calendarEventsUnavailableMessage`}},gf=`system.notificationProducerRules.unreadableMessage`;function _f(e){return e===`summaries`?`summary`:e===`timelapses`?`timelapse`:e===`calendar-events`?`calendar-events`:null}function vf({cameras:t,fleet:n,targets:i,taxonomy:s}){let{t:c}=Y(),l=w(),[f,p]=a({mode:`closed`}),[m,h]=a(null),[g,_]=a(null),[v,y]=a(null),[b,x]=a(null),S=o({queryKey:df,queryFn:async()=>Ju(await l.trpcClient.addons.custom.mutate({addonId:kl,action:pu,input:{}}))}),C=o({queryKey:pf,queryFn:async()=>Nd(await l.trpcClient.addons.custom.mutate({addonId:kl,action:Sd,input:{}}))}),T=o({queryKey:Kl,queryFn:async()=>$l(await l.trpcClient.addons.custom.mutate({addonId:kl,action:ql,input:{}}))}),E=S.data??[],D=C.data??[],O=T.data??[],k=u({mutationFn:e=>l.trpcClient.addons.custom.mutate({addonId:kl,action:mu,input:{ruleId:e.ruleId,patch:{enabled:e.enabled}}}),onSuccess:()=>void S.refetch()}),A=u({mutationFn:e=>l.trpcClient.addons.custom.mutate({addonId:kl,action:hu,input:{ruleId:e}}),onSuccess:()=>void S.refetch()}),j=u({mutationFn:async e=>Yu(await l.trpcClient.addons.custom.mutate({addonId:kl,action:gu,input:{ruleId:e,...md(Date.now())}})),onSuccess:e=>{h(null),_(e)}}),M=u({mutationFn:e=>l.trpcClient.addons.custom.mutate({addonId:kl,action:Cd,input:{ruleId:e.ruleId,patch:{enabled:e.enabled}}}),onSuccess:()=>void C.refetch()}),N=u({mutationFn:e=>l.trpcClient.addons.custom.mutate({addonId:kl,action:wd,input:{ruleId:e}}),onSuccess:()=>void C.refetch()}),P=u({mutationFn:async e=>Id(await l.trpcClient.addons.custom.mutate({addonId:kl,action:Td,input:e})),onSuccess:e=>{y(null),x(e)}}),ee=u({mutationFn:e=>l.trpcClient.addons.custom.mutate({addonId:kl,action:Jl,input:{ruleId:e.ruleId,patch:{enabled:e.enabled}}}),onSuccess:()=>void T.refetch()}),F=u({mutationFn:e=>l.trpcClient.addons.custom.mutate({addonId:kl,action:Yl,input:{ruleId:e}}),onSuccess:()=>void T.refetch()}),I=t.toSorted((e,t)=>e.name.localeCompare(t.name)),te=i.map(e=>({id:e.id,name:e.name,enabled:e.enabled})),L=new Map(te.map(e=>[e.id,e.name])),ne=new Map(I.map(e=>[e.id,e.name])),R=Date.now(),z={summary:{nowMs:R,targetNameById:L,deletePending:A.isPending,onToggle:(e,t)=>k.mutate({ruleId:e.id,enabled:t}),onOpen:e=>{ju(e)&&p({mode:`summary`,rule:e})},onTest:h,onConfirmDelete:e=>A.mutate(e.id)},timelapse:{nowMs:R,cameraNameById:ne,targetNameById:L,deletePending:N.isPending,onToggle:(e,t)=>M.mutate({ruleId:e.id,enabled:t}),onOpen:e=>{Pd(e)&&p({mode:`timelapse`,rule:e})},onTest:e=>y({rule:e,deviceId:e.deviceIds[0]??null}),onConfirmDelete:e=>N.mutate(e.id)},calendar:{nowMs:R,targetNameById:L,deletePending:F.isPending,onToggle:(e,t)=>ee.mutate({ruleId:e.id,enabled:t}),onOpen:e=>{eu(e)&&p({mode:`calendar-events`,rule:e})},onConfirmDelete:e=>F.mutate(e.id)}},B=e=>{switch(e.family){case`summary`:z.summary.onOpen(e.rule);return;case`timelapse`:z.timelapse.onOpen(e.rule);return;case`calendar-events`:z.calendar.onOpen(e.rule);return}},re=e=>{p(e===`summary`?{mode:`summary`,rule:null}:e===`timelapse`?{mode:`timelapse`,rule:null}:{mode:`calendar-events`,rule:null})},ie=e=>{let t=e===`summary`?S:e===`timelapse`?C:T;return t.isLoading?null:t.isError?{unreadable:!1}:t.data===null?{unreadable:!0}:null},ae=e=>{e===`summary`?S.refetch():e===`timelapse`?C.refetch():T.refetch()},oe=e=>{let t=_f(e);return t!==null&&ie(t)!==null},se=t=>{let n=_f(t),i=n===null?null:ie(n);return e(d,{children:[n!==null&&i!==null&&r(H,{title:c(hf[n].titleKey),message:c(i.unreadable?gf:hf[n].messageKey),onRetry:()=>ae(n)}),A.isError&&r(H,{title:c(`system.notificationProducerRules.couldNotDeleteTheRule`,`Could not delete the rule`),message:String(A.error)}),N.isError&&r(H,{title:c(`system.notificationProducerRules.couldNotDeleteTheRule`,`Could not delete the rule`),message:String(N.error)}),F.isError&&r(H,{title:c(`system.notificationProducerRules.couldNotDeleteTheRule`,`Could not delete the rule`),message:String(F.error)}),j.isError&&r(H,{title:c(`system.notificationProducerRules.theTestRunFailed`,`The test run failed`),message:String(j.error)}),P.isError&&r(H,{title:c(`system.notificationProducerRules.theTestRunFailed`,`The test run failed`),message:String(P.error)}),g!==null&&r(yf,{outcome:g,onDismiss:()=>_(null)}),b!==null&&r(bf,{outcome:b,onDismiss:()=>x(null)})]})},ce=()=>p({mode:`closed`}),le=e(d,{children:[f.mode===`summary`&&r(xd,{rule:f.rule,cameras:I,fleet:n,targets:te,taxonomy:s,onCancel:ce,onSaved:()=>{ce(),S.refetch()}}),f.mode===`timelapse`&&r(rf,{rule:f.rule,cameras:I,fleet:n,targets:te,onCancel:ce,onSaved:()=>{ce(),C.refetch()}}),f.mode===`calendar-events`&&r(fu,{rule:f.rule,targets:te,onCancel:ce,onSaved:()=>{ce(),T.refetch()}}),r(yl,{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)}}),r(yl,{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:e(`div`,{children:[r(`label`,{className:`mb-1 block text-[11px] font-medium text-foreground`,children:c(`system.notificationProducerRules.whichCamera`,`Which camera`)}),r(W,{value:v.deviceId===null?``:String(v.deviceId),options:v.rule.deviceIds.map(e=>({value:String(e),label:ne.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:E,timelapses:D,calendarEvents:O,loading:S.isLoading||C.isLoading||T.isLoading,columnDeps:z,open:B,create:re,notices:se,listFailed:oe,overlays:le}}function yf({outcome:t,onDismiss:n}){let{t:i}=Y();return e(`div`,{className:`mb-3 rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,"data-testid":`summary-test-outcome`,children:[t.error===void 0?e(`span`,{children:[i(`system.notificationProducerRules.summaryProduced`,{digests:i(`system.notificationProducerRules.digestCount`,{count:t.produced}),tiles:i(`system.notificationProducerRules.tileCount`,{count:t.tiles??0}),cameras:i(`system.notificationProducerRules.cameraCount`,{count:t.cameras??0}),matched:i(`system.notificationProducerRules.tracksMatched`,{count:t.matched??0}),sent:i(`system.notificationProducerRules.notificationsSent`,{count:t.enqueued??0})}),(t.droppedStationary??0)>0&&r(`span`,{"data-testid":`summary-test-dropped-stationary`,className:`ml-1`,children:i(`system.notificationProducerRules.droppedStationary`,{count:t.droppedStationary})})]}):e(`span`,{className:`text-warning`,children:[i(`system.notificationProducerRules.nothingWasProduced`,`Nothing was produced:`),` `,t.error]}),r(U,{size:`sm`,variant:`ghost`,type:`button`,className:`ml-2`,onClick:n,children:i(`system.notificationProducerRules.dismiss`,`Dismiss`)})]})}function bf({outcome:t,onDismiss:n}){let{t:i}=Y();return e(`div`,{className:`mb-3 rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,"data-testid":`timelapse-test-outcome`,children:[t.error===void 0?r(`span`,{children:i(t.coveragePercent===void 0?`system.notificationProducerRules.timelapseProduced`:`system.notificationProducerRules.timelapseProducedCoverage`,{videos:i(`system.notificationProducerRules.videoCount`,{count:t.produced}),percent:Math.round(t.coveragePercent??0),sent:i(`system.notificationProducerRules.notificationsSent`,{count:t.enqueued??0})})}):e(`span`,{className:`text-warning`,children:[i(`system.notificationProducerRules.nothingWasProduced`,`Nothing was produced:`),` `,t.error]}),r(U,{size:`sm`,variant:`ghost`,type:`button`,className:`ml-2`,onClick:n,children:i(`system.notificationProducerRules.dismiss`,`Dismiss`)})]})}var xf=[{key:`summaries`,get label(){return J.t(`helpers.notificationRulesArea.sumLabel`)},get blurb(){return J.t(`helpers.notificationRulesArea.sumBlurb`)},get newLabel(){return J.t(`helpers.notificationRulesArea.sumNew`)},get emptyHint(){return J.t(`helpers.notificationRulesArea.sumEmpty`)}},{key:`timelapses`,get label(){return J.t(`helpers.notificationRulesArea.tlLabel`)},get blurb(){return J.t(`helpers.notificationRulesArea.tlBlurb`)},get newLabel(){return J.t(`helpers.notificationRulesArea.tlNew`)},get emptyHint(){return J.t(`helpers.notificationRulesArea.tlEmpty`)}},{key:`calendar-events`,get label(){return J.t(`helpers.notificationRulesArea.calLabel`)},get blurb(){return J.t(`helpers.notificationRulesArea.calBlurb`)},get newLabel(){return J.t(`helpers.notificationRulesArea.calNew`)},get emptyHint(){return J.t(`helpers.notificationRulesArea.calEmpty`)}}],Sf=[{type:`detection`,get label(){return J.t(`helpers.notificationRulesArea.opt_detection_label`)},get hint(){return J.t(`helpers.notificationRulesArea.opt_detection_hint`)}},{type:`sensor`,get label(){return J.t(`helpers.notificationRulesArea.opt_sensor_label`)},get hint(){return J.t(`helpers.notificationRulesArea.opt_sensor_hint`)}},{type:`audio`,get label(){return J.t(`helpers.notificationRulesArea.opt_audio_label`)},get hint(){return J.t(`helpers.notificationRulesArea.opt_audio_hint`)}},{type:`occupancy`,get label(){return J.t(`helpers.notificationRulesArea.opt_occupancy_label`)},get hint(){return J.t(`helpers.notificationRulesArea.opt_occupancy_hint`)}},{type:`device-events`,get label(){return J.t(`helpers.notificationRulesArea.opt_deviceEvents_label`)},get hint(){return J.t(`helpers.notificationRulesArea.opt_deviceEvents_hint`)}},{type:`system`,get label(){return J.t(`helpers.notificationRulesArea.opt_system_label`)},get hint(){return J.t(`helpers.notificationRulesArea.opt_system_hint`)}},{type:`alarm`,get label(){return J.t(`helpers.notificationRulesArea.opt_alarm_label`)},get hint(){return J.t(`helpers.notificationRulesArea.opt_alarm_hint`)}},{type:`summary`,get label(){return J.t(`helpers.notificationRulesArea.opt_summary_label`)},get hint(){return J.t(`helpers.notificationRulesArea.opt_summary_hint`)}},{type:`timelapse`,get label(){return J.t(`helpers.notificationRulesArea.opt_timelapse_label`)},get hint(){return J.t(`helpers.notificationRulesArea.opt_timelapse_hint`)}},{type:`calendar-events`,get label(){return J.t(`helpers.notificationRulesArea.opt_calendarEvents_label`)},get hint(){return J.t(`helpers.notificationRulesArea.opt_calendarEvents_hint`)}}];function Cf(e){return e===`summaries`||e===`timelapses`||e===`calendar-events`}function wf(e){if(!(e==null||e.length===0))return Cf(e)?e:Se(e)}function Tf(e){let t=xf.find(t=>t.key===e);if(t===void 0)throw Error(`unknown producer area: ${e}`);return t}function Ef(e){return[...pr.filter(t=>t.key!==`mixed`||(e.get(`mixed`)??0)>0),...xf]}function Df(e){return!Cf(e)}function Of(e){return e!==`summary`&&e!==`timelapse`&&e!==`calendar-events`}s();function kf(e){return[{key:`name`,header:J.t(`system.notificationCalendarEventsPage.rule`,`Rule`),render:t=>r(lf,{name:t.name,enabled:t.enabled,...eu(t)?{onOpen:()=>e.onOpen(t)}:{},openTestId:`calendar-events-edit-${t.id}`,badges:eu(t)?null:r(K,{variant:`warning`,children:`read-only`})})},{key:`schedule`,header:J.t(`system.notificationCalendarEventsPage.when`,`When`),render:e=>r(`span`,{className:`text-[11px] text-foreground-subtle`,children:iu(e.schedule)})},{key:`horizon`,header:J.t(`system.notificationCalendarEventsPage.horizon`,`Horizon`),nowrap:!0,render:e=>r(`span`,{className:`text-[11px] text-foreground-subtle`,children:uu(e.horizonDays)})},{key:`calendars`,header:J.t(`system.notificationCalendarEventsPage.calendars`,`Calendars`),render:e=>r(`span`,{className:`text-[11px] text-foreground-subtle`,children:du(e)})},{key:`targets`,header:J.t(`system.notificationCalendarEventsPage.targets`,`Targets`),render:t=>{let n=t.targets[0],i=n?e.targetNameById.get(n.targetId)??n.targetId:null;return r(`span`,{className:`text-[11px] text-foreground-subtle`,children:t.targets.length===1&&i!==null?i:J.t(`common.targetCount`,{count:t.targets.length})})}},{key:`lastRun`,header:J.t(`system.notificationCalendarEventsPage.lastRun`,`Last run`),nowrap:!0,render:t=>r(`span`,{className:`text-[11px] text-foreground-subtle`,"data-testid":`calendar-events-last-${t.id}`,children:fd(t.generatedAt,e.nowMs)})},{key:`enabled`,header:J.t(`system.notificationCalendarEventsPage.on`,`On`),align:`center`,nowrap:!0,render:t=>r(af,{children:r(nt,{checked:t.enabled,disabled:t.readOnly,onCheckedChange:n=>e.onToggle(t,n),"aria-label":J.t(`system.notificationCalendarEventsPage.toggle`,`toggle {{name}}`,{name:t.name})})})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:t=>r(af,{className:`flex items-center justify-end gap-1`,children:r(uf,{disabled:t.readOnly,pending:e.deletePending,title:J.t(`system.notificationCalendarEventsPage.deleteThisCalendarEventsRule`,`Delete this calendar-events rule?`),message:J.t(`system.notificationCalendarEventsPage.thisWillPermanentlyDeleteThis`,`This will permanently delete "{{name}}". This action cannot be undone.`,{name:t.name}),ariaLabel:J.t(`system.notificationCalendarEventsPage.delete`,`delete {{name}}`,{name:t.name}),testId:`calendar-events-delete-${t.id}`,onConfirm:()=>e.onConfirmDelete(t)})})}]}function Af(e,t){return e.replaceAll(`{{name}}`,t)}function jf(t){return[{key:`name`,header:J.t(`system.notificationRuleColumns.rule`,`Rule`),render:e=>r(lf,{name:e.name,enabled:e.enabled,...Qr(e)?{onOpen:()=>t.onOpen(e)}:{}})},{key:`trigger`,header:J.t(`system.notificationRuleColumns.trigger`,`Trigger`),nowrap:!0,render:n=>e(`span`,{className:`flex items-center gap-1.5`,children:[r(`span`,{className:`text-[11px] text-foreground-subtle`,children:yn(n,t.t(`notificationRules.grouping.choice`,Vr))}),!ir(n.delivery)&&r(K,{variant:`warning`,children:J.t(`common.readOnly`)})]})},{key:`targets`,header:J.t(`system.notificationRuleColumns.targets`,`Targets`),render:e=>{let n=e.targets[0],i=n?t.targetNameById.get(n.targetId)??n.targetId:null;return r(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.targets.length===1&&i?i:J.t(`common.targetCount`,{count:e.targets.length})})}},{key:`lastRun`,header:J.t(`system.notificationRuleColumns.lastRun`,`Last run`),nowrap:!0,render:e=>r(lc,{cell:t.lastRunOf(e.id)})},{key:`priority`,header:J.t(`system.notificationRuleColumns.priority`,`Priority`),align:`center`,nowrap:!0,render:e=>r(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.priority})},{key:`snooze`,header:t.t(`notificationRules.columns.snooze`,`Snooze`),align:`center`,nowrap:!0,render:e=>r(af,{children:r(vc,{rule:e,snoozes:t.snoozes,exempt:tr(e.conditions,yr({onActivation:e.actions?.onActivation??[],onDeactivation:e.actions?.onDeactivation??[],onTrigger:e.actions?.onTrigger??[],onTriggerOff:e.actions?.onTriggerOff??[],buttons:e.actions?.buttons??[]},t.sequences))})})},{key:`enabled`,header:J.t(`system.notificationRuleColumns.on`,`On`),align:`center`,nowrap:!0,render:e=>r(af,{children:r(nt,{checked:e.enabled,onCheckedChange:n=>t.onToggle(e,n),"aria-label":J.t(`system.notificationRuleColumns.toggle`,`toggle {{name}}`,{name:e.name})})})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:n=>Qr(n)?e(af,{className:`flex items-center justify-end gap-1`,children:[r(al,{ruleId:n.id,ruleName:n.name,...n.conditions.devices?.[0]===void 0?{}:{fallbackDeviceId:n.conditions.devices[0]}}),t.onOpenHistory&&r(uc,{rule:n,onOpenHistory:t.onOpenHistory}),t.onTest&&r(U,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>t.onTest?.(n),title:J.t(`system.notificationRuleColumns.openInTheSimulatorDescribe`,`Open in the simulator — describe an event and tune it before injecting`),"aria-label":J.t(`system.notificationRuleColumns.simulate`,`simulate {{name}}`,{name:n.name}),children:r(We,{className:`h-3.5 w-3.5`})}),r(U,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>t.onDuplicate(n),title:J.t(`system.notificationRuleColumns.duplicate`,`Duplicate`),children:r(O,{className:`h-3.5 w-3.5`})}),r(Nf,{rule:n,deps:t})]}):r(Mf,{rule:n,deps:t})}]}function Mf({rule:t,deps:n}){let{t:i}=Y();return e(af,{className:`flex items-center justify-end gap-1`,children:[r(`span`,{title:ye(Ne(t)).blurb,children:r(K,{variant:`warning`,children:i(`system.notificationRuleColumns.recreateAsOneRulePer`,`Recreate as one rule per family`)})}),n.onOpenHistory&&r(uc,{rule:t,onOpenHistory:n.onOpenHistory}),r(Nf,{rule:t,deps:n})]})}function Nf({rule:e,deps:t}){let{t:n}=Y();return r(uf,{pending:t.deletePending,title:n(`notificationRules.delete.confirm`,`Delete this rule?`),message:Af(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:Af(n(`notificationRules.delete.aria`,`delete {{name}}`),e.name),onConfirm:()=>t.onConfirmDelete(e)})}function Pf(e){let t=jf(e),n=e=>t.filter(t=>t.key===e);return[...n(`name`),{key:`events`,header:J.t(`system.notificationRuleColumns.events`,`Events`),render:e=>r(`span`,{className:`text-[11px] text-foreground-subtle`,children:dn(e.conditions.systemEvent?.kinds)})},{key:`scope`,header:J.t(`system.notificationRuleColumns.scope`,`Scope`),nowrap:!0,render:e=>r(`span`,{className:`text-[11px] text-foreground-subtle`,children:Xn(e.conditions.systemEvent)})},{key:`targets`,header:J.t(`system.notificationRuleColumns.targets`,`Targets`),render:t=>{let n=t.targets[0],i=n?e.targetNameById.get(n.targetId)??n.targetId:null;return r(`span`,{className:`text-[11px] text-foreground-subtle`,children:t.targets.length===1&&i?i:J.t(`common.targetCount`,{count:t.targets.length})})}},{key:`cooldown`,header:J.t(`system.notificationRuleColumns.cooldown`,`Cooldown`),nowrap:!0,render:e=>r(`span`,{className:`text-[11px] text-foreground-subtle`,children:hr(e.throttle.cooldownSec)})},...n(`lastRun`),...n(`snooze`),...n(`enabled`),...n(`actions`)]}function Ff(e){switch(e){case`detection`:return J.t(`helpers.unifiedRulesModel.kind_detection`);case`sensor`:return J.t(`helpers.unifiedRulesModel.kind_sensor`);case`sound`:return J.t(`helpers.unifiedRulesModel.kind_sound`);case`occupancy`:return J.t(`helpers.unifiedRulesModel.kind_occupancy`);case`device-events`:return J.t(`helpers.unifiedRulesModel.kind_device_events`);case`system`:return J.t(`helpers.unifiedRulesModel.kind_system`);case`alarm`:return J.t(`helpers.unifiedRulesModel.kind_alarm`);case`mixed`:return J.t(`helpers.unifiedRulesModel.kind_mixed`);case`summary`:return J.t(`helpers.unifiedRulesModel.kind_summary`);case`timelapse`:return J.t(`helpers.unifiedRulesModel.kind_timelapse`);case`calendar-events`:return J.t(`helpers.unifiedRulesModel.kind_calendar_events`)}}function If(e){return{family:`event`,kind:Ne(e),id:e.id,name:e.name,enabled:e.enabled,rule:e}}function Lf(e){return{family:`summary`,kind:`summary`,id:e.id,name:e.name,enabled:e.enabled,rule:e}}function Rf(e){return{family:`timelapse`,kind:`timelapse`,id:e.id,name:e.name,enabled:e.enabled,rule:e}}function zf(e){return{family:`calendar-events`,kind:`calendar-events`,id:e.id,name:e.name,enabled:e.enabled,rule:e}}function Bf(e){return[...e.events.map(If),...e.summaries.map(Lf),...e.timelapses.map(Rf),...e.calendarEvents.map(zf)]}function Vf(e,t){return t===`all`?!0:Cf(t)?t===`summaries`?e.family===`summary`:t===`timelapses`?e.family===`timelapse`:e.family===`calendar-events`:Df(t)&&e.family===`event`?Me(e.rule,t):!1}function Hf(e,t){return Bf(t).filter(t=>Vf(t,e)).toSorted((e,t)=>e.name.localeCompare(t.name))}function Uf(e,t){return Hf(e,t).length}function Wf(e){return e===`all`?900:860}function Gf(e){return e.family===`event`?e.rule:null}function Kf(e){return e.family===`summary`?e.rule:null}function qf(e){return e.family===`timelapse`?e.rule:null}function Jf(e){return e.family===`calendar-events`?e.rule:null}function Yf(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 Xf(e,t){return e.map(e=>Yf(e,t))}function Zf(e,t){return e.find(e=>e.key===t)}function Qf(e,t,n){let r=Zf(jf(n.event),e),i=Zf(ff(n.summary),e),a=Zf(mf(n.timelapse),e),o=Zf(kf(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 $f(e){switch(e.family){case`event`:return null;case`summary`:return dd(e.rule.window);case`timelapse`:return Yd(e.rule.schedule);case`calendar-events`:return iu(e.rule.schedule)}}function ep(e){let t=Zf(jf(e.event),`trigger`);return{key:`when`,header:J.t(`system.unifiedRulesColumns.when`,`When`),render:(e,n)=>{let i=$f(e);return i===null?e.family===`event`?t?.render(e.rule,n)??null:null:r(`span`,{className:`text-[11px] text-foreground-subtle`,children:i})}}}function tp(e){return[Qf(`name`,`Name`,e),{key:`type`,header:J.t(`system.unifiedRulesColumns.type`,`Type`),nowrap:!0,render:e=>r(`span`,{className:`text-[11px] text-foreground-subtle`,"data-testid":`rule-type-${e.id}`,children:Ff(e.kind)})},ep(e),Qf(`targets`,`Targets`,e),Qf(`lastRun`,`Last run`,e),Qf(`snooze`,e.event.t(`notificationRules.columns.snooze`,`Snooze`),e),Qf(`enabled`,`On`,e),Qf(`actions`,``,e)]}function np(e,t){return e===`all`?tp(t):e===`summaries`?Xf(ff(t.summary),Kf):e===`timelapses`?Xf(mf(t.timelapse),qf):e===`calendar-events`?Xf(kf(t.calendar),Jf):Df(e)&&Mn(e)?Xf(Pf(t.event),Gf):Xf(jf(t.event),Gf)}function rp({value:t,family:n,onChange:i,draft:a}){let{t:o}=Y();if(n===void 0||!oe.includes(n))return null;let s=t?.mode===`summary`?t:null;return e(`div`,{className:`rounded-md border border-border px-3 py-3`,"data-testid":`rule-delivery`,children:[r(`div`,{className:`mb-2 text-[11px] font-semibold text-foreground`,children:o(`system.notificationSystemEventDelivery.delivery`,`Delivery`)}),e(`div`,{className:`flex flex-wrap gap-3 text-xs`,children:[e(`label`,{className:`flex items-center gap-1.5`,children:[r(`input`,{type:`radio`,name:`system-event-delivery`,checked:s===null,onChange:()=>i({mode:`instant`}),"data-testid":`rule-delivery-instant`}),o(`system.notificationSystemEventDelivery.instantANotificationPerEvent`,`Instant — a notification per event`)]}),e(`label`,{className:`flex items-center gap-1.5`,children:[r(`input`,{type:`radio`,name:`system-event-delivery`,checked:s!==null,onChange:()=>i({mode:`summary`,schedule:P([on])}),"data-testid":`rule-delivery-summary`}),o(`system.notificationSystemEventDelivery.summaryOnScheduleTheCurrent`,`Summary on schedule — the current state, at set times`)]})]}),s!==null&&r(ip,{value:s,onChange:i,draft:a})]})}function ip({value:t,onChange:n,draft:i}){let{t:a}=Y(),o=t.schedule.timezone,s=ce({systemEventDelivery:t});return e(`div`,{className:`mt-2 space-y-2`,children:[e(`p`,{className:$t,children:[a(`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:`),` `,o??a(`system.notificationSystemEventDelivery.theHubS`,`the hub’s`),`.`]}),r(Xt,{mode:`times`,value:t.schedule,onChange:e=>{e!==void 0&&n(On(t,e))}}),e(`fieldset`,{className:`flex flex-wrap gap-3 text-xs`,"data-testid":`rule-delivery-split`,children:[r(`legend`,{className:`sr-only`,children:a(`system.notificationSystemEventDelivery.howTheSummaryIsSent`,`How the summary is sent`)}),e(`label`,{className:`flex items-center gap-1.5`,children:[r(`input`,{type:`radio`,name:`system-event-summary-split`,checked:s===`rule`,onChange:()=>n(ni(t,`rule`)),"data-testid":`rule-delivery-split-rule`}),a(`system.notificationSystemEventDelivery.oneMessageWithEveryCategory`,`One message with every category`)]}),e(`label`,{className:`flex items-center gap-1.5`,children:[r(`input`,{type:`radio`,name:`system-event-summary-split`,checked:s===`section`,onChange:()=>n(ni(t,`section`)),"data-testid":`rule-delivery-split-section`}),a(`system.notificationSystemEventDelivery.oneNotificationPerCategoryBatteries`,`One notification per category (batteries, consumables, devices…)`)]})]}),r(ap,{draft:i,split:s})]})}function ap({draft:t,split:n}){let{t:i}=Y(),a=w(),o=u({mutationFn:e=>a.trpcClient.notificationRules.previewStateSummary.mutate({rule:e})}),s=mn(o.status,o.data,o.error,n);return e(`div`,{className:`space-y-1.5`,children:[r(U,{size:`sm`,variant:`secondary`,onClick:()=>o.mutate(t()),disabled:o.isPending,"data-testid":`rule-delivery-preview`,children:o.isPending?i(`system.notificationSystemEventDelivery.readingTheState`,`Reading the state…`):i(`system.notificationSystemEventDelivery.previewTheSummaryNow`,`Preview the summary now`)}),s!==null&&r(`div`,{className:`text-[10px] text-foreground-subtle mt-0.5`,"data-testid":`rule-delivery-preview-result`,children:s.lines.map((e,t)=>r(`p`,{className:`whitespace-pre-wrap`,children:e},t))})]})}function op(e,t){if(e.status===`error`)return{kind:`failed`,reason:e.error instanceof Error?e.error.message:J.t(`helpers.notificationRuleLastRun.unknownError`)};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:up(e.data.horizonMs)}:{kind:`ran`,lastAt:n.lastAt,status:n.status,deviceId:n.deviceId}}var sp=6e4,cp=60*sp,lp=24*cp;function up(e){return e===null?J.t(`helpers.notificationRuleLastRun.noDelivery`):e>=lp?J.t(`helpers.notificationRuleLastRun.notInDay`,{count:Math.floor(e/lp)}):e>=cp?J.t(`helpers.notificationRuleLastRun.notInHour`,{count:Math.floor(e/cp)}):e>=sp?J.t(`helpers.notificationRuleLastRun.notInMinute`,{count:Math.floor(e/sp)}):J.t(`helpers.notificationRuleLastRun.notInWindow`)}s();var dp=[`notificationRules`,`listRules`],fp=[`notificationOutput`,`listTargets`,`forRules`],pp=[`notificationRules`,`getConditionCatalog`],mp=[`deviceManager`,`gateableDevices`],hp=Ce.options;function gp({onSimulateRule:s,onOpenHistory:c,createRequested:l=!1,onCreateConsumed:d,createTypeRequested:f=null,onCreateTypeConsumed:p,headerOwnsCreate:h=!1}={}){let g=w(),{t:_}=Y(),{state:v,openEdit:y,close:b}=Ct({editKey:`rule`}),[S,C]=At(`section`),[T,E]=At(`editTab`),[D,O]=a({mode:`closed`}),[k,A]=a(!1),j=wf(S)??`all`,M=e=>{C(e===`all`?null:e)},N=o({queryKey:dp,queryFn:async()=>(await g.trpcClient.notificationRules.listRules.query({})).rules}),P=t(null);i(()=>{if(D.mode!==`closed`)return;if(v.mode!==`edit`){v.mode===`closed`&&(P.current=null);return}let e=v.id;if(e===`new`||P.current===e)return;let t=N.data?.find(t=>t.id===e);t===void 0||!Qr(t)||(P.current=e,O({mode:`form`,rule:t}))},[D.mode,v,N.data]);let ee=o({queryKey:fp,queryFn:()=>g.trpcClient.notificationOutput.listTargets.query({})}),F=o({queryKey:pp,queryFn:()=>g.trpcClient.notificationRules.getConditionCatalog.query({})}),I=Qe({projection:`slim`}),te=sc(),L=n(()=>I.data??[],[I.data]),ne=at(I),R=n(()=>L.map(e=>e.id),[L]),z=o({queryKey:[...mp,R],enabled:R.length>0,queryFn:async()=>{let e=[];for(let t of L){let n=fe(await g.trpcClient.deviceManager.loadRuntimeState.query({deviceId:t.id}),hp);n.length>0&&e.push({id:t.id,name:t.name,states:n})}return e},staleTime:6e4}),B=n(()=>{let e=gt(L);return L.filter(e=>be(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))},[L]),re=n(()=>L.filter(e=>e.type===Te.Camera).map(e=>({id:e.id,name:e.name})),[L]),ie=li(n(()=>re.map(e=>e.id),[re])),ae=n(()=>{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=n(()=>{let e=new Map;for(let t of ee.data??[])e.set(t.id,t.name);return e},[ee.data]),se=u({mutationFn:e=>g.trpcClient.notificationRules.setRuleEnabled.mutate(e),onSuccess:()=>void N.refetch()}),ce=u({mutationFn:e=>g.trpcClient.notificationRules.deleteRule.mutate({ruleId:e}),onSuccess:()=>void N.refetch()}),le=_c(),ue=Mt({}),de=ue.data?.sequences??[],me=Nt(),he=N.data??[],ge=vf({cameras:re,fleet:ne,targets:ee.data??[],taxonomy:F.data?.taxonomy}),_e={events:he,summaries:ge.summaries,timelapses:ge.timelapses,calendarEvents:ge.calendarEvents},ve=Ef(new Map(pr.map(e=>[e.key,Uf(e.key,_e)]))),V=ve.find(e=>e.key===j)??ve[0]??pr[0],ye=Cf(V.key)?Tf(V.key):void 0;Df(V.key)&&V.key;let xe=Hf(V.key,_e),Se=()=>{v.mode===`edit`&&(P.current=v.id),O({mode:`closed`}),b(),E(null)},Ce=e=>{if(!Qr(e))return;let t=e.id.length>0?e.id:`new`;P.current=t,O({mode:`form`,rule:e}),y(t),E(null)},we=e=>{if(Of(e)){P.current=`new`,O({mode:`form`,rule:null,seed:pe(e)}),y(`new`),E(null);return}ge.create(e)};i(()=>{f!==null&&(we(f),p?.())},[f]),i(()=>{l&&(A(!0),d?.())},[l]);let Ee=e=>{if(e.family===`event`){Ce(e.rule);return}ge.open(e)},De={targetNameById:oe,snoozes:le,sequences:de,deletePending:ce.isPending,onToggle:(e,t)=>se.mutate({ruleId:e.id,enabled:t}),onOpen:Ce,t:_,onDuplicate:e=>Ce({...e,id:``,name:`${e.name} (copy)`}),onConfirmDelete:e=>ce.mutate(e.id),...s?{onTest:s}:{},lastRunOf:e=>op(te,e),...c?{onOpenHistory:c}:{}},Oe=np(V.key,{event:De,summary:ge.columnDeps.summary,timelapse:ge.columnDeps.timelapse,calendar:ge.columnDeps.calendar}),ke=ye?.blurb??(`blurb`in V?V.blurb:``),Ae=ye===void 0?`creatable`in V?V.creatable:!1:!0,je=h||!Ae?null:j===`all`?e(U,{size:`sm`,type:`button`,"data-testid":`rules-new-menu`,onClick:()=>A(!0),children:[r(m,{className:`h-3.5 w-3.5`}),_(`system.notificationRules.newRule`,`New rule`)]}):ye===void 0?e(U,{size:`sm`,type:`button`,onClick:()=>we(V.key),"data-testid":`rules-new-${V.key}`,children:[r(m,{className:`h-3.5 w-3.5`}),`newRuleLabel`in V?V.newRuleLabel:_(`system.notificationRules.newRule`,`New rule`)]}):e(U,{size:`sm`,type:`button`,onClick:()=>we(ye.key===`summaries`?`summary`:ye.key===`timelapses`?`timelapse`:`calendar-events`),"data-testid":ye.key===`summaries`?`summary-new`:ye.key===`timelapses`?`timelapse-new`:`calendar-events-new`,children:[r(m,{className:`h-3.5 w-3.5`}),ye.newLabel]});return r(ci,{embedded:!0,icon:x,title:_(`system.notificationRules.rules`,`Rules`),subtitle:ke,children:e(`div`,{className:`flex flex-col gap-3`,children:[je===null?null:r(`div`,{className:`flex justify-end`,children:je}),r(lt,{appearance:`pills`,value:V.key,onValueChange:e=>M(wf(e)??j),children:r(Xe,{children:ve.map(t=>e(ht,{value:t.key,children:[t.label,r(`span`,{className:`ml-1.5 text-[10px] text-foreground-subtle`,children:Uf(t.key,_e)})]},t.key))})}),r(ul,{rules:he}),ge.notices(V.key),(N.isLoading||ge.loading)&&r(of,{}),N.isError&&!N.isLoading&&r(H,{title:_(`system.notificationRules.failedToLoadRules`,`Failed to load rules`),message:N.error instanceof Error?N.error.message:_(`system.notificationRules.unknownError`,`Unknown error`),onRetry:()=>void N.refetch()}),!N.isLoading&&!ge.loading&&!N.isError&&!ge.listFailed(V.key)&&xe.length===0&&r(sf,{children:ye?.emptyHint??(`emptyHint`in V?V.emptyHint:_(`system.notificationRules.noRulesYet`,`No rules yet.`))}),xe.length>0&&r(cf,{columns:Oe,rows:xe,rowKey:e=>`${e.family}:${e.id}`,onRowClick:Ee,minWidthPx:Wf(V.key)}),D.mode===`form`&&r(vp,{rule:D.rule,...D.seed?{seed:D.seed}:{},targets:ee.data??[],actuatable:B,fleet:ne,sequences:de,onCreateSequence:async e=>{let t=await me.mutateAsync({sequence:{name:e.name,...e.minDelaySec===void 0?{}:{minDelaySec:e.minDelaySec},actions:[...e.actions]}});return await ue.refetch(),t.sequence.id},catalog:sr(F.data?.catalog??[]),taxonomy:F.data?.taxonomy,cameras:re,gateable:z.data??[],gateableScenes:ae,initialEditTab:Br(T??``)??`rule`,onEditTabChange:e=>E(e===`rule`?null:e),onCancel:Se,onSaved:()=>{Se(),N.refetch()}}),ge.overlays,k?r(_p,{onCancel:()=>A(!1),onPick:e=>{A(!1),we(e)}}):null]})})}function _p({onPick:t,onCancel:n}){let{t:i}=Y();return r(Dt,{open:!0,onClose:n,title:i(`system.notificationRules.chooseARuleType`,`Choose a rule type`),width:`lg`,children:r(`div`,{className:`grid grid-cols-1 gap-2 sm:grid-cols-2`,children:Sf.map(n=>e(`button`,{type:`button`,"data-testid":`rules-new-${n.type}`,title:n.hint,onClick:()=>t(n.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:[r(`span`,{className:`font-medium text-foreground`,children:n.label}),r(`span`,{className:`text-[10px] font-normal text-foreground-subtle`,children:n.hint})]},n.type))})})}function vp({rule:t,seed:i,targets:s,catalog:c,taxonomy:l,cameras:f,gateable:p,gateableScenes:m,actuatable:h,fleet:g,sequences:_,onCreateSequence:v,initialEditTab:y=fr,onEditTabChange:b,onSaved:S,onCancel:C}){let E=w(),{t:D}=Y(),O=t!=null&&t.id.length>0,[k]=a(()=>t?$r(t):Fr(i?.delivery,i?.conditions)),[A,j]=a(k),[M,N]=a(null),[P,ee]=a(O),[F,I]=a(null),[L,ne]=a(y),R=e=>j(t=>({...t,...e})),z=t?Hr(t):void 0,B=u({mutationFn:async()=>{let e=Nr(A,z,c);if(O&&t){let n=rr(A,c);await E.trpcClient.notificationRules.updateRule.mutate({ruleId:t.id,patch:e,...n.length>0?{clear:n}:{}})}else await E.trpcClient.notificationRules.createRule.mutate({rule:e})},onSuccess:S,onError:e=>N(e instanceof Error?e.message:`Save failed`)}),re=u({mutationFn:async()=>{let e=Nr(A,z,c);return(await E.trpcClient.notificationRules.testRule.mutate({rule:e,lookbackMinutes:60})).results},onMutate:()=>I(null),onSuccess:e=>I(e),onError:e=>N(e instanceof Error?e.message:`Test failed`)}),ie=A.targetIds.map(e=>s.find(t=>t.id===e)?.name??e),ae=o({queryKey:[`userManagement`,`listUsers`],queryFn:()=>E.trpcClient.userManagement.listUsers.query()}).data,oe=n(()=>(ae??[]).map(e=>({value:e.id,label:e.username,...e.isAdmin?{badge:`admin`}:{}})),[ae]),se=er(A),ce=se===`immediate-grouped`,le=String(A.groupingSec??20),ue=Jr(A).map(e=>({...e,label:e.value===`immediate-grouped`?D(`notificationRules.grouping.choice`,e.label):e.label,hint:e.value===`immediate-grouped`?D(`notificationRules.grouping.hint`,{n:le,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}}`,le):e.hint})),de=ue.find(e=>e.value===se)?.hint,fe=ti(A,z),pe=De(A.delivery),me=Ne(A),he=ye(me),ge=ke(me),_e=or.filter(e=>ge.includes(e.value)),ve=Ee(A.conditions).length>0,be=te(me),xe=V(me),Se=o({queryKey:[`deviceManager`,`listDeviceIdsByCaps`,`nc-rule-devices`,xe??[]],enabled:xe!==null,queryFn:async()=>{let e=await Promise.all((xe??[]).map(e=>E.trpcClient.deviceManager.listDeviceIdsByCaps.query({capNames:[...e]})));return new Set(e.flat())},staleTime:6e4}),Ce=n(()=>{if(xe===null||Se.data===void 0)return h;let e=Se.data,t=new Set(Ht(A.deviceScope));return h.filter(n=>e.has(n.id)||t.has(n.id))},[h,xe,Se.data,A.deviceScope]),we=xe!==null&&Se.isLoading,Te=xe!==null&&Se.isError,Oe=To(),je=e=>({family:`rule`,field:e,kind:me,delivery:A.delivery,...Yr(A)?{systemEventDelivery:`summary`}:{},...A.conditions.systemEvent?{systemEventKinds:[...A.conditions.systemEvent.kinds]}:{}}),Me=e=>Oe.data?xo(Oe.data,je(e)):void 0,Pe=jr(A),Fe=tr(A.conditions,yr(A.actions,_)),Ie=A.conditions.identities!==void 0||A.conditions.plates!==void 0,Le=xr(A.delivery,A.conditions),Re=Le.some(e=>e.key===L)?L:fr;return ir(A.delivery)?r(lt,{value:Re,onValueChange:e=>{let t=Br(e);t!==void 0&&(ne(t),b?.(t))},children:e(Dt,{open:!0,onClose:C,title:O?D(`system.notificationRules.edit`,`Edit {{name}}`,{name:t?.name}):D(`system.notificationRules.newNotificationRule`,`New notification rule`),icon:x,error:M,width:`lg`,testId:`rule-form-dialog`,beforeBody:e(d,{children:[O&&t&&e(`div`,{className:`mb-3 space-y-2`,children:[r(Kc,{kind:`rule`,ruleId:t.id,enabled:t.enabled,updatedAt:t.updatedAt}),r(Yc,{ruleId:t.id,cameraName:e=>f.find(t=>t.id===e)?.name??D(`system.notificationRuleStatus.cameraFallback`,{deviceId:e})})]}),r(Xe,{className:`mb-3`,children:Le.map(e=>r(ht,{value:e.key,children:e.label},e.key))})]}),footer:e(`div`,{className:`flex w-full flex-col gap-3`,children:[Pe.length>0&&e(`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:[r(`p`,{className:`text-foreground`,children:D(`system.notificationRules.savingDrops`,{count:Pe.length})}),Pe.map(t=>e(`p`,{children:[r(`span`,{className:`text-foreground`,children:t.conditionId}),` — `,t.reason]},t.conditionId))]}),P&&fe.length>0?r(`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:fe.map(e=>r(`p`,{children:e},e))}):null,r(`div`,{className:`flex justify-end gap-2`,children:e(U,{size:`sm`,type:`button`,disabled:B.isPending,onClick:()=>{ee(!0),N(null),!(!_r(A,z,new Set(_.map(e=>e.id)))||B.isPending)&&B.mutate()},children:[B.isPending&&r(T,{className:`h-3.5 w-3.5 animate-spin`}),O?D(`system.notificationRules.saveChanges`,`Save changes`):D(`system.notificationRules.createRule`,`Create rule`)]})})]}),children:[e(q,{value:`rule`,className:`space-y-4`,children:[e(`div`,{className:`flex items-end gap-3`,children:[e(`div`,{className:`min-w-0 flex-1`,children:[r(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:D(`system.notificationRules.name`,`Name`)}),r(G,{value:A.name,onChange:e=>R({name:e.target.value}),placeholder:D(`system.notificationRules.eGFrontDoorPackage`,`e.g. Front door package`)})]}),e(`label`,{className:`flex items-center gap-2 pb-1.5 text-[11px] font-medium text-foreground`,children:[r(nt,{checked:A.enabled,onCheckedChange:e=>R({enabled:e}),"aria-label":D(`system.notificationRules.enabled`,`Enabled`)}),D(`system.notificationRules.enabled`,`Enabled`)]})]}),e(`div`,{children:[r(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:D(`system.notificationRules.trigger`,`Trigger`)}),r(W,{value:se,onChange:e=>{let t=xn(e.target.value);t&&j(e=>ur(e,t))},options:ue.map(e=>({value:e.value,label:e.label}))}),de&&r(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:de}),ce&&e(`div`,{className:`mt-2`,children:[r(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:D(`notificationRules.grouping.seconds`,`Group for (seconds)`)}),r(G,{type:`number`,min:5,max:60,step:1,value:le,"data-testid":`rule-grouping-sec`,onChange:e=>{let t=wr(e.target.value);t!==void 0&&R({groupingSec:t})}}),r(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:D(`notificationRules.grouping.minNote`,`At least 5 s: subjects arriving together share one message.`)}),Ie&&r(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:D(`notificationRules.grouping.scopedHint`,{n:le,defaultValue:`A subject not recognised within {{n}} s is not notified.`}).replaceAll(`{{n}}`,le)})]}),se===`immediate`&&Ie&&r(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:D(`notificationRules.grouping.plainRecognitionHint`,`Fires only if the name is already known when an event is written — choose Immediate, grouped to wait for it.`)})]}),!O&&be!==void 0&&r(Us,{family:be,onChange:e=>j(t=>mr(t,e))}),r(_t,{label:D(`system.notificationRules.deliveryTargets`,`Delivery targets`),targets:s,value:A.targetIds,onChange:e=>j(t=>({...t,targetIds:e})),emptyMessage:D(`system.notificationRules.noDeliveryTargetsConfiguredAdd`,`No delivery targets configured. Add one under the Targets tab first.`),testIdPrefix:`rule-target`}),r(st,{mode:`multi`,options:oe,value:A.targetUsers,onChange:e=>R({targetUsers:e}),searchable:!0,creatable:!1,label:D(`system.notificationRules.notifyUsers`,`Notify users`),description:D(`system.notificationRules.deliversToTheTargetsEach`,`Delivers to the targets each user owns, only for cameras that user can access.`),emptyMessage:D(`system.notificationRules.noUsersToNotify`,`No users to notify.`),placeholder:D(`system.notificationRules.searchUsers`,`Search users…`),testId:`rule-notify-users`,optionTestIdPrefix:`rule-user`,listboxId:`rule-notify-users-listbox`})]}),e(q,{value:`devices`,className:`space-y-4`,children:[we&&r(`p`,{className:`text-[10px] text-foreground-subtle`,"data-testid":`rule-devices-compat-loading`,children:D(`notificationRules.devices.compatLoading`,`Checking which devices this rule's kind can use…`)}),Te&&r(`p`,{className:`text-[10px] text-foreground-subtle`,"data-testid":`rule-devices-compat-failed`,children:D(`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.`)}),r(ys,{devices:Ce,scope:A.deviceScope,onChange:e=>R({deviceScope:e}),listState:g.state,savedScope:k.deviceScope,exceptOffered:ar(c,`devicesExclude`,A)})]}),r(q,{value:`actions`,className:`space-y-4`,children:r(Vo,{value:A.actions,onChange:e=>R({actions:e}),devices:h,devicesState:g.state,sequences:_,onCreateSequence:v,showProblems:P})}),e(q,{value:`advanced`,className:`space-y-4`,children:[r(ic,{catalog:c,delivery:A.delivery,conditions:A.conditions,onConditionsChange:e=>R({conditions:e})}),e(`div`,{children:[r(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:D(`system.notificationRules.cooldownSeconds`,`Cooldown (seconds)`)}),r(G,{type:`number`,min:0,max:nr,step:1,value:String(A.cooldownSec),"data-testid":`rule-cooldown`,onChange:e=>{let t=Pn(e.target.value);t!==void 0&&R({cooldownSec:t})}}),e(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:[pe?D(`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.`):D(`system.notificationRules.theShortestGapBetweenTwo`,`The shortest gap between two deliveries of this rule, counted as chosen below.`),` `,D(`system.notificationRules.cooldownRange`,{max:String(nr)})]})]}),e(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[e(`div`,{children:[r(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:D(`system.notificationRules.cooldownCounted`,`Cooldown counted`)}),r(W,{value:A.cooldownScope,onChange:e=>{let t=Kt(e.target.value);t!==void 0&&R({cooldownScope:t})},options:Mr.map(e=>({value:e.value,label:e.label})),"data-testid":`rule-cooldown-scope`}),r(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:D(`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.`)})]}),e(`div`,{children:[r(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:D(`system.notificationRules.acrossObjectClasses`,`Across object classes`)}),r(W,{value:A.cooldownGranularity??`per-class`,onChange:e=>R({cooldownGranularity:Jt(e.target.value)}),options:br.map(e=>({value:e.value,label:e.label})),"data-testid":`rule-cooldown-granularity`}),r(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:D(`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.`)})]})]}),e(`div`,{children:[e(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[r(nt,{checked:A.snoozeAllowGlobal,onCheckedChange:e=>R({snoozeAllowGlobal:e}),"aria-label":D(`system.notificationRules.allowGlobalSnooze`,`allow global snooze`),disabled:Fe}),D(`system.notificationRules.anyoneMaySnoozeThisRule`,`Anyone may snooze this rule for everyone`)]}),r(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:D(`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.`)})]}),Zr(A)&&e(`div`,{children:[e(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[r(nt,{checked:A.askVerdict===!0,onCheckedChange:e=>R({askVerdict:e}),"aria-label":D(`system.notificationRules.askVerdictAria`,`ask me to confirm detections`),"data-testid":`rule-ask-verdict`}),D(`system.notificationRules.askVerdict`,`Ask me to confirm detections`)]}),r(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:D(`system.notificationRules.askVerdictHint`,`The notification carries Correct and Wrong. A tap marks the detection for retraining, the same mark as in the Library, and records who was asked and when. Channels with no buttons (email, Pushover, Gotify, WhatsApp, Discord) get the same two choices as links.`)})]}),!Fe&&e(`div`,{children:[r(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:D(`system.notificationRules.snoozeButtons`,`Snooze buttons`)}),e(d,{children:[r(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:qr.map(e=>{let t=A.snoozeOptions??Dr,n=t.includes(e);return r(U,{type:`button`,size:`sm`,variant:n?`primary`:`outline`,onClick:()=>R({snoozeOptions:n?t.filter(t=>t!==e):[...t,e].toSorted((e,t)=>e-t)}),children:Nn(e)},e)})}),r(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:A.snoozeOptions===void 0?D(`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:Dr.map(Nn).join(`, `)}):A.snoozeOptions.length===0?D(`system.notificationRules.noSnoozeButtonsOnThis`,`No snooze buttons on this rule. That is an explicit choice: the notification cannot be silenced from the lock screen.`):D(`system.notificationRules.fourAtMostEverySnooze`,`Four at most. Every snooze button takes space from the rule’s action buttons — ntfy accepts three in total.`)}),A.snoozeOptions!==void 0&&r(U,{type:`button`,size:`sm`,variant:`ghost`,className:`mt-1`,onClick:()=>R({snoozeOptions:void 0}),children:D(`system.notificationRules.backToTheDefaults`,`Back to the defaults`)})]})]}),O&&t&&!Fe&&e(`div`,{children:[r(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:D(`system.notificationRules.silenceItNow`,`Silence it now`)}),r(pc,{ruleId:t.id,ruleName:t.name,exempt:Fe,variant:`full`})]})]}),e(q,{value:`notification`,className:`space-y-4`,children:[e(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[e(`div`,{children:[r(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:D(`system.notificationRules.priority`,`Priority`)}),r(W,{value:String(A.priority),onChange:e=>R({priority:Number(e.target.value)}),options:cr.map(e=>({value:String(e.value),label:e.label}))})]}),!he.carriesMedia&&r(`div`,{className:`rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,"data-testid":`rule-media-none`,children:he.mediaBlurb??D(`system.notificationRules.aSystemEventCarriesNo`,`A system event carries no image: there is no camera frame behind "a node went offline". This rule sends text only.`)}),he.carriesMedia&&he.mediaBlurb!==void 0&&r(`div`,{className:`rounded-md border border-border px-3 py-2 text-[11px] text-foreground-subtle`,children:he.mediaBlurb}),he.carriesMedia&&e(`div`,{children:[r(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:D(`system.notificationRules.notificationImage`,`Image`)}),r(W,{value:A.mediaImage,onChange:e=>{let t=Sr(e.target.value);t&&R({mediaImage:t})},options:_e.map(e=>({value:e.value,label:e.label})),"data-testid":`rule-media-image`}),r(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:_e.find(e=>e.value===A.mediaImage)?.description}),e(`div`,{className:`mt-2 space-y-1`,children:[ve&&A.mediaImage!==`crop`&&A.mediaImage!==`none`&&e(`label`,{className:`flex items-start gap-2 text-xs text-foreground cursor-pointer`,children:[r(`input`,{type:`checkbox`,checked:A.mediaShowTriggerZone,onChange:e=>R({mediaShowTriggerZone:e.target.checked}),className:`accent-primary mt-0.5`,"data-testid":`rule-media-show-trigger-zone`}),e(`span`,{children:[D(`system.notificationRules.showTriggerZone`,`Draw the zone that triggered the rule`),r(`span`,{className:`block text-[10px] text-foreground-subtle`,children:D(`system.notificationRules.showTriggerZoneHelp`,`Outlines the zone on the scene. Not drawn on a subject crop.`)})]})]}),Ae(me)&&A.mediaImage!==`none`&&e(`label`,{className:`flex items-start gap-2 text-xs text-foreground cursor-pointer`,children:[r(`input`,{type:`checkbox`,checked:A.mediaShowSubjectPath,onChange:e=>R({mediaShowSubjectPath:e.target.checked}),className:`accent-primary mt-0.5`,"data-testid":`rule-media-show-subject-path`}),e(`span`,{children:[D(`system.notificationRules.showSubjectPath`,`Show the subject's path`),r(`span`,{className:`block text-[10px] text-foreground-subtle`,children:D(`system.notificationRules.showSubjectPathHelp`,`Draws the line the subject walked, up to the moment of the picture. On a crop, only the part inside it.`)})]})]}),e(`label`,{className:`flex items-center gap-2 text-xs text-foreground cursor-pointer`,children:[r(`input`,{type:`checkbox`,checked:A.mediaGif,onChange:e=>R({mediaGif:e.target.checked}),className:`accent-primary`}),D(`system.notificationRules.attachAGifAroundThe`,`Attach a GIF around the event`)]}),e(`label`,{className:`flex items-center gap-2 text-xs text-foreground cursor-pointer`,children:[r(`input`,{type:`checkbox`,checked:A.mediaClip,onChange:e=>R({mediaClip:e.target.checked}),className:`accent-primary`}),D(`system.notificationRules.attachAnMp4ClipAround`,`Attach an MP4 clip around the event`)]})]}),(A.mediaGif||A.mediaClip)&&e(`div`,{className:`mt-2`,children:[r(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:D(`system.notificationRules.videoQuality`,`Video quality`)}),r(W,{value:A.mediaProfile??``,onChange:e=>R({mediaProfile:Wt(e.target.value)}),options:Ar.map(e=>({value:e.value,label:e.label}))}),r(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:D(`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.`)}),r(`label`,{className:`mt-2 block text-[11px] font-medium text-foreground mb-1`,children:D(`system.notificationRules.playbackSpeed`,`Playback speed`)}),r(W,{value:A.mediaClipSpeed===void 0?``:String(A.mediaClipSpeed),onChange:e=>R({mediaClipSpeed:Xr(e.target.value)}),options:zr.map(e=>({value:e.value,label:e.label}))}),r(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:D(`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.`)})]})]}),me===`sensor`&&he.carriesMedia&&A.mediaImage!==`none`&&e(`div`,{children:[r(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:D(`system.notificationRules.linkedCameras`,`Linked cameras`)}),r(W,{value:A.mediaLinkedCameras??``,onChange:e=>R({mediaLinkedCameras:Rt(e.target.value)}),options:Er.map(e=>({value:e.value,label:e.label})),"data-testid":`rule-media-linked-cameras`}),r(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:D(`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.`)})]})]}),e(`div`,{className:`space-y-2`,children:[r(Ao,{label:D(`system.notificationRules.notificationTitle`,`Notification title`),value:A.templateTitle,onChange:e=>R({templateTitle:e}),vars:Me(`title`),testId:`rule-template-title`}),r(Ao,{label:D(`system.notificationRules.notificationBody`,`Notification body`),value:A.templateBody,onChange:e=>R({templateBody:e}),vars:Me(`body`),multiline:!0,testId:`rule-template-body`}),r(`p`,{className:`text-[10px] text-foreground-subtle`,children:D(`system.notificationRules.leaveBothBlankForThe`,`Leave both blank for the hub's own wording (editable on the Texts tab).`)}),Gt(A)!==null&&r(`p`,{className:`text-[10px] text-warning`,"data-testid":`rule-template-summary-warning`,children:Gt(A)}),r(jo,{context:je(`body`),title:A.templateTitle,body:A.templateBody,testId:`rule-template-preview`})]})]}),e(q,{value:`conditions`,className:`space-y-4`,children:[e(`div`,{className:`rounded-md border border-border px-3 py-3`,children:[r(`div`,{className:`mb-2 text-[11px] font-semibold text-foreground`,children:pe?D(`system.notificationRules.whichSystemEvents`,`Which system events`):Wr(A.conditions)??D(`system.notificationRules.conditions`,`Conditions`)}),A.conditions.audio!==void 0&&r(`p`,{className:`mb-2 text-[10px] text-foreground-subtle`,children:D(`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).`)}),A.conditions.occupancy!==void 0&&r(`p`,{className:`mb-2 text-[10px] text-foreground-subtle`,children:D(`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.`)}),pe&&r(`p`,{className:`mb-2 text-[10px] text-foreground-subtle`,children:D(`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.`)}),c.length===0?r(`p`,{className:`text-[10px] text-foreground-subtle`,children:D(`system.notificationRules.conditionCatalogUnavailableThisRule`,`Condition catalog unavailable — this rule matches on its trigger and targets alone.`)}):r(Ws,{catalog:Yr(A)?c.filter(e=>e.id!==`schedule`):c,taxonomy:l,delivery:A.delivery,conditions:A.conditions,classScope:A.classScope,onClassScopeChange:e=>R({classScope:e}),actions:Sn(A.actions),sequenceActionsOf:e=>_.find(t=>t.id===e)?.actions,savedConditions:k.conditions,schedule:A.schedule,deviceIds:kr(A),zoneCameraIds:ss(A.deviceScope,f),cameras:f,fleet:g,allDevices:h,gateable:p,gateableScenes:m,onConditionsChange:e=>R({conditions:e}),onScheduleChange:e=>R({schedule:e}),summary:Yr(A)})]}),pe&&r(rp,{value:A.systemEventDelivery,family:be,onChange:e=>R({systemEventDelivery:e}),draft:()=>Nr(A,z,c)}),O&&t&&e(`div`,{className:`rounded-md border border-border px-3 py-3`,children:[e(`div`,{className:`flex items-center justify-between gap-2`,children:[r(`div`,{className:`text-[11px] font-semibold text-foreground`,children:D(`system.notificationRules.testThisRuleForReal`,`Test this rule for real`)}),r(al,{ruleId:t.id,ruleName:t.name,variant:`full`,showResult:!0,...kr(A)[0]===void 0?{}:{fallbackDeviceId:kr(A)[0]}})]}),r(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:D(`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.`)})]}),!pe&&e(`div`,{className:`rounded-md border border-border px-3 py-3`,children:[e(`div`,{className:`flex items-center justify-between gap-2`,children:[r(`div`,{className:`text-[11px] font-semibold text-foreground`,children:D(`system.notificationRules.testRule`,`Test rule`)}),e(U,{size:`sm`,variant:`outline`,type:`button`,disabled:re.isPending||!_r(A,z,new Set(_.map(e=>e.id))),onClick:()=>{N(null),re.mutate()},children:[re.isPending?r(T,{className:`h-3.5 w-3.5 animate-spin`}):r(We,{className:`h-3.5 w-3.5`}),D(`system.notificationRules.dryRunLast60Min`,`Dry-run (last 60 min)`)]})]}),r(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:D(`system.notificationRules.evaluateTheCurrentUnsavedRule`,`Evaluate the CURRENT (unsaved) rule against recently persisted records — no notification is sent.`)}),F!==null&&r(bp,{delivery:A.delivery,results:F,targetNames:ie})]})]})]})}):r(yp,{rule:t,onCancel:C})}function yp({rule:t,onCancel:n}){let{t:i}=Y(),a=Object.keys(t?.conditions??{});return e(Dt,{open:!0,onClose:n,title:t?.name??i(`system.notificationRules.rule`,`Rule`),icon:x,width:`lg`,children:[r(K,{variant:`warning`,className:`mb-3`,children:`read-only`}),r(`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:r(Kr,{i18nKey:`system.notificationRules.unsupportedTrigger`,values:{trigger:t?.delivery},components:{code:r(`code`,{})}})}),e(`dl`,{className:`mt-3 space-y-1.5 text-[11px]`,children:[e(`div`,{className:`flex gap-2`,children:[r(`dt`,{className:`w-24 shrink-0 text-foreground-subtle`,children:i(`system.notificationRules.trigger`,`Trigger`)}),r(`dd`,{className:`text-foreground`,children:t?.delivery})]}),e(`div`,{className:`flex gap-2`,children:[r(`dt`,{className:`w-24 shrink-0 text-foreground-subtle`,children:i(`system.notificationRules.enabled`,`Enabled`)}),r(`dd`,{className:`text-foreground`,children:t?.enabled?i(`common.yes`):i(`common.no`)})]}),e(`div`,{className:`flex gap-2`,children:[r(`dt`,{className:`w-24 shrink-0 text-foreground-subtle`,children:i(`system.notificationRules.targets`,`Targets`)}),r(`dd`,{className:`text-foreground`,children:t?.targets.length??0})]}),e(`div`,{className:`flex gap-2`,children:[r(`dt`,{className:`w-24 shrink-0 text-foreground-subtle`,children:i(`system.notificationRules.conditions`,`Conditions`)}),r(`dd`,{className:`text-foreground`,children:a.length>0?a.join(`, `):i(`common.none`)})]})]})]})}function bp({delivery:t,results:n,targetNames:i}){let{t:a}=Y();if(t===`device-event`)return r(`p`,{className:`mt-2 text-[11px] text-foreground-subtle`,children:a(`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(n.length===0)return r(`p`,{className:`mt-2 text-[11px] text-foreground-subtle`,children:a(`system.notificationRules.noRecordsInTheLast`,`No records in the last 60 minutes matched — nothing to evaluate.`)});let o=n.filter(e=>e.wouldFire).length;return e(`div`,{className:`mt-2 space-y-1.5`,children:[r(`div`,{className:`text-[11px] text-foreground-subtle`,children:a(`system.notificationRules.wouldFire`,{firing:o,count:n.length})}),r(`ul`,{className:`divide-y divide-border rounded-md border border-border`,children:n.slice(0,50).map(t=>e(`li`,{className:`flex items-center gap-2 px-2.5 py-1.5 text-[11px]`,children:[t.wouldFire?r(S,{className:`h-3.5 w-3.5 shrink-0 text-success`}):r(j,{className:`h-3.5 w-3.5 shrink-0 text-foreground-subtle`}),r(`span`,{className:`w-32 shrink-0 text-foreground-subtle`,children:new Date(t.timestamp).toLocaleString()}),e(`span`,{className:`w-14 shrink-0 text-foreground-subtle`,children:[`#`,t.deviceId]}),r(`span`,{className:`min-w-0 flex-1 truncate text-foreground`,children:t.label??t.className??a(`system.notificationRules.objectFallback`)}),t.wouldFire?e(`span`,{className:`shrink-0 truncate text-success`,children:[`→ `,i.join(`, `)||a(`system.notificationRules.targetsFallback`)]}):t.failedCondition&&e(`span`,{className:`shrink-0 text-foreground-subtle`,children:[`failed: `,t.failedCondition]})]},t.recordId))})]})}s();var xp=`mt-1 w-full rounded border border-border bg-background px-2 py-1 text-xs`,Sp=`block text-[11px] font-medium text-foreground`,Cp=[{value:`cap`,labelKey:`system.notificationSequences.stepDo`},{value:`wait`,labelKey:`system.notificationSequences.stepWait`}],wp=[[`notificationRules`,`listSequences`]],Tp=[`sequence`,`new`];function Ep(){return{name:``,minDelaySec:``,actions:[vn()]}}function Dp(e){return{id:e.id,name:e.name,minDelaySec:e.minDelaySec===void 0?``:String(e.minDelaySec),actions:[...e.actions]}}function Op(e){return e instanceof Error?e.message:String(e)}function kp(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=zo(e,n);t.push({start:n,kind:`cap`,length:r.length}),n+=r.length}return t}function Ap(e){let t=e.actions.length;return e.minDelaySec===void 0?J.t(`system.notificationSequences.stepsLabel`,{count:t}):J.t(`system.notificationSequences.stepsDelay`,{count:t,delay:e.minDelaySec})}function jp({draft:t,devices:n,fleetView:i,onChange:a}){let{t:o}=Y(),s=kp(t.actions);return e(`div`,{className:`space-y-3`,children:[e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[e(`div`,{className:`min-w-0 flex-1`,children:[r(`label`,{className:Sp,children:o(`system.notificationSequences.name`,`Name`)}),r(G,{className:`mt-1`,value:t.name,onChange:e=>a({...t,name:e.target.value})})]}),e(`div`,{className:`w-28`,children:[r(`label`,{className:Sp,children:o(`system.notificationSequences.minDelayS`,`Min delay (s)`)}),r(`input`,{type:`number`,min:0,className:xp,value:t.minDelaySec,onChange:e=>a({...t,minDelaySec:e.target.value})})]})]}),e(`div`,{className:`space-y-2 border-l-2 border-border-subtle pl-3`,children:[s.map(s=>{let c=t.actions[s.start];if(s.kind===`wait`&&c.kind===`wait`)return r(Np,{step:c,devices:n,listState:i.state,fleet:i,onChange:e=>a({...t,actions:t.actions.map((t,n)=>n===s.start?e:t)}),onRemove:()=>a({...t,actions:t.actions.filter((e,t)=>t!==s.start)})},`s-${String(s.start)}`);let l=zo(t.actions,s.start);return e(`div`,{className:`flex flex-wrap items-start gap-2`,children:[e(`div`,{className:`w-24`,children:[r(`label`,{className:Sp,children:o(`system.notificationSequences.step`,`Step`)}),r(W,{className:xp,value:`cap`,options:Cp.map(e=>({value:e.value,label:o(e.labelKey)})),onChange:e=>{e.target.value===`wait`&&a({...t,actions:[...t.actions.slice(0,s.start),{kind:`wait`,seconds:5},...t.actions.slice(s.start+s.length)]})}})]}),r(si,{value:l.wire,devices:n,listState:i.state,fleet:i,allowMultiSameFamily:!0,onChange:e=>{let n=Lo(e);a({...t,actions:[...t.actions.slice(0,s.start),...n,...t.actions.slice(s.start+s.length)]})}}),r(U,{size:`sm`,variant:`ghost`,type:`button`,title:o(`common.remove`,`Remove`),onClick:()=>a({...t,actions:[...t.actions.slice(0,s.start),...t.actions.slice(s.start+s.length)]}),children:r(h,{className:`h-3.5 w-3.5`})})]},`s-${String(s.start)}`)}),e(U,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>a({...t,actions:[...t.actions,vn()]}),children:[r(m,{className:`h-3.5 w-3.5`}),` `,o(`common.step`)]})]})]})}function Mp({createRequested:t=!1,onCreateConsumed:o,headerOwnsCreate:s=!1}={}){let{t:l}=Y(),u=c(),d=Mt({}),f=Nt(),p=$e(),h=ut(),{state:g,openNew:_,openEdit:v,close:y}=Ct({editKey:`sequence`,newKey:`new`}),[b,x]=a(null),[S,C]=a(null);i(()=>{t&&(C(null),_(),o?.())},[t]);let w=Qe({projection:`slim`}),T=at(w),E=n(()=>(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=d.data?.sequences??[],O=d.data!==void 0&&D.length===0,k=g.mode!==`closed`,A=f.isPending||p.isPending;i(()=>{if(g.mode===`closed`){x(null),C(null);return}if(g.mode===`new`){x(e=>e!==null&&e.id===void 0?e:Ep());return}let e=D.find(e=>e.id===g.id);e!==void 0&&x(t=>t?.id===g.id?t:Dp(e))},[g,D]);let j=()=>{u.invalidateQueries({queryKey:wp})},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(Op(e))}},P=n(()=>[{key:`name`,header:l(`system.notificationSequences.name`,`Name`),nowrap:!1,sortValue:e=>e.name,render:e=>r(lf,{name:e.name,enabled:!0,onOpen:()=>v(e.id),openTestId:`sequence-open-${e.id}`})},{key:`steps`,header:l(`system.notificationSequences.steps`,`Steps`),nowrap:!0,sortValue:e=>e.actions.length,render:e=>r(`span`,{className:`text-[11px] text-foreground-subtle`,children:Ap(e)})},{key:`actions`,header:``,align:`right`,nowrap:!0,notSortableReason:`Row actions`,render:t=>e(af,{className:`flex items-center justify-end gap-1`,children:[r(U,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>v(t.id),children:l(`common.edit`,`Edit`)}),r(uf,{pending:h.isPending,title:l(`system.notificationSequences.deleteThisSequence`,`Delete this sequence?`),message:l(`system.notificationSequences.willBeRemovedRulesAnd`,`“{{name}}” will be removed. Rules and buttons that bind to it keep the id until you re-point them.`,{name:t.name}),ariaLabel:l(`system.notificationSequences.delete`,`Delete {{name}}`,{name:t.name}),testId:`sequence-delete-${t.id}`,onConfirm:()=>{h.mutateAsync({sequenceId:t.id}).then(j)}})]})}],[h,v,l]);return e(ci,{embedded:!0,icon:Je,title:l(`system.notificationSequences.sequences`,`Sequences`),subtitle:l(`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:[s?null:r(`div`,{className:`mb-3 flex justify-end`,children:e(U,{size:`sm`,type:`button`,onClick:()=>{C(null),_()},children:[r(m,{className:`h-3.5 w-3.5`}),` `,l(`system.notificationSequences.newSequence`)]})}),d.error!=null&&r(H,{title:l(`system.notificationSequences.couldNotReadSequences`,`Could not read sequences`),message:Op(d.error),onRetry:()=>void d.refetch()}),d.isPending&&r(of,{}),O&&r(sf,{testId:`sequences-empty`,children:l(`system.notificationSequences.noSequencesYetCreateOne`,`No sequences yet. Create one, then bind it from a rule's Actions tab.`)}),D.length>0&&r(cf,{columns:P,rows:D,rowKey:e=>e.id,minWidthPx:480,onRowClick:e=>v(e.id)}),r(Dt,{open:k&&b!==null,onClose:M,title:b?.id===void 0?l(`system.notificationSequences.newSequence`,`New sequence`):l(`system.notificationSequences.edit`,`Edit {{value1}}`,{value1:b.name||`sequence`}),icon:Je,width:`xl`,error:S,testId:`sequence-editor-panel`,footer:r(U,{size:`sm`,type:`button`,disabled:A||b===null||b.name.trim()===``||b.actions.length===0,onClick:()=>void N(),children:A?l(`system.notificationSequences.saving`,`Saving…`):l(`common.save`,`Save`)}),children:b!==null&&r(jp,{draft:b,devices:E,fleetView:T,onChange:x})}),h.error!=null&&r(H,{message:Op(h.error)})]})}function Np({step:t,devices:n,listState:i,fleet:a,onChange:o,onRemove:s}){let{t:c}=Y();return e(`div`,{className:`flex flex-wrap items-start gap-2`,children:[e(`div`,{className:`w-24`,children:[r(`label`,{className:Sp,children:c(`system.notificationSequences.step`,`Step`)}),r(W,{className:xp,value:`wait`,options:Cp.map(e=>({value:e.value,label:c(e.labelKey)})),onChange:e=>o(e.target.value===`wait`?{kind:`wait`,seconds:t.seconds}:{kind:`cap`,deviceId:n[0]?.id??0,cap:``,method:``})})]}),e(`div`,{className:`w-28`,children:[r(`label`,{className:Sp,children:c(`system.notificationSequences.seconds`,`Seconds`)}),r(`input`,{type:`number`,min:0,max:300,className:xp,value:t.seconds,onChange:e=>o({kind:`wait`,seconds:Number(e.target.value)})})]}),r(U,{size:`sm`,variant:`ghost`,type:`button`,onClick:s,title:c(`common.remove`,`Remove`),children:r(h,{className:`h-3.5 w-3.5`})})]})}var Pp=`alert-center`;function Fp(){let{t}=Y(),n=w();return e(`div`,{className:`space-y-3`,"data-testid":`notification-settings`,children:[r(`p`,{className:M,children:t(`systemPage.notifications.settingsHint`,`Alert storage and retention. Alerts are notified only through notification rules on the alert kinds.`)}),r(yt,{trpc:n.trpcClient,addonId:Pp,nodeId:`hub`,bare:!0})]})}var Ip=[{value:`object-event`,get label(){return J.t(`helpers.notificationSimulateHelpers.objectLabel`)},get hint(){return J.t(`helpers.notificationSimulateHelpers.objectHint`)}},{value:`track-end`,get label(){return J.t(`helpers.notificationSimulateHelpers.trackEndLabel`)},get hint(){return J.t(`helpers.notificationSimulateHelpers.trackEndHint`)}},{value:`device-event`,get label(){return J.t(`helpers.notificationSimulateHelpers.deviceEventLabel`)},get hint(){return J.t(`helpers.notificationSimulateHelpers.deviceEventHint`)}},{value:`package-event`,get label(){return J.t(`helpers.notificationSimulateHelpers.packageEventLabel`)},get hint(){return J.t(`helpers.notificationSimulateHelpers.packageEventHint`)}},{value:`audio-event`,get label(){return J.t(`helpers.notificationSimulateHelpers.audioEventLabel`)},get hint(){return J.t(`helpers.notificationSimulateHelpers.audioEventHint`)}},{value:`occupancy-event`,get label(){return J.t(`helpers.notificationSimulateHelpers.occupancyEdgeLabel`)},get hint(){return J.t(`helpers.notificationSimulateHelpers.occupancyEdgeHint`)}}];function Lp(e){return Ip.find(t=>t.value===e)?.value}function Rp(e){return e===`object-event`||e===`audio-event`?`immediate`:e===`occupancy-event`?`device-event`:e}function zp(e){return``}var Bp={x:.25,y:.25,w:.5,h:.5},Vp={zoneId:``,zoneName:``,className:``,count:1,previousCount:0,occupied:!0,threshold:1};function Hp(){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:Bp,occupancy:Vp,timestampLocal:``,onlyRuleId:``,bypassCooldown:!1,bypassMute:!1,runActions:!1,still:`live`}}function Up(e){return e.deviceId!==null}function Wp(e){if(e.trim().length===0)return;let t=Number(e);return Number.isFinite(t)?t:void 0}function Gp(e){if(e.trim().length===0)return;let t=Date.parse(e);return Number.isFinite(t)?t:void 0}function Kp(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 qp(e){if(e.deviceId===null)return null;let t=e.trigger,n=Gp(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:Jp(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 Jp(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 Yp(e){return Math.min(1,Math.round((e+.05)*100)/100)}function Xp(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 Zp(e){let t=Hp(),n=e.conditions,r=Xp(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:Yp(n.minConfidence)},...n.minLabelConfidence===void 0?{}:{labelConfidence:Yp(n.minLabelConfidence)},...n.minImportance===void 0?{}:{importance:Yp(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:zp(r),...n.customZones!==void 0&&n.customZones.length>0?{bboxEnabled:!0}:{},...n.occupancy===void 0?{}:{occupancy:Qp(n.occupancy)},onlyRuleId:e.id}}function Qp(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 $p(e){let t=[];return e.conditions.deviceState!==void 0&&t.push({conditionId:`deviceState`,note:J.t(`helpers.notificationSimulateHelpers.caveatDevice`,{deviceId:e.conditions.deviceState.deviceId})}),e.conditions.scene!==void 0&&t.push({conditionId:`scene`,note:J.t(`helpers.notificationSimulateHelpers.caveatScene`,{state:e.conditions.scene.requiredState})}),e.conditions.customZones!==void 0&&e.conditions.customZones.length>0&&t.push({conditionId:`customZones`,note:J.t(`helpers.notificationSimulateHelpers.caveatZones`)}),t}function em(e){return{form:Zp(e),caveats:$p(e),ruleName:e.name}}var tm=null;function nm(e){tm=e}function rm(){return tm}function im(){tm=null}var am=[`n/a`,`clear`,`suppressed`,`bypassed`],om=[`live`,`none`,`unavailable`,`unattachable`];function sm(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function cm(e,t){let n=e[t];return typeof n==`string`?n:void 0}function lm(e,t){let n=e[t];return Array.isArray(n)?n.filter(e=>typeof e==`string`):[]}function um(e){if(!sm(e))return null;let t=cm(e,`ruleId`),n=cm(e,`ruleName`),r=cm(e,`cooldown`),i=am.find(e=>e===r);if(t===void 0||n===void 0||i===void 0||typeof e.matched!=`boolean`)return null;let a=cm(e,`failedCondition`),o=Array.isArray(e.matchedOn)?lm(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:lm(e,`targetIds`)}}function dm(e){if(!sm(e))return null;let t=cm(e,`recordId`),n=cm(e,`delivery`),r=cm(e,`still`),i=om.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=um(e);t!==null&&o.push(t)}let s=cm(e,`droppedBy`);return{recordId:t,origin:`synthetic`,delivery:n,candidates:typeof e.candidates==`number`?e.candidates:0,outcomes:o,still:i,notes:lm(e,`notes`),...s===void 0?{}:{droppedBy:s}}}function fm(e){if(e.droppedBy!==void 0)return J.t(`helpers.notificationSimulateHelpers.dropped`,{reason:e.droppedBy});if(e.candidates===0)return J.t(`helpers.notificationSimulateHelpers.noCandidates`,{delivery:e.delivery});let t=e.outcomes.filter(e=>e.matched).length,n=e.outcomes.reduce((e,t)=>e+t.enqueued,0);return t===0?J.t(`helpers.notificationSimulateHelpers.noneMatched`,{count:e.candidates}):J.t(`helpers.notificationSimulateHelpers.matchedSummary`,{matched:t,candidates:e.candidates,enqueued:n})}var pm=new Set([`sensor`,`control`,`custom`]);function mm({form:t,cameras:n,taxonomy:i,kinds:a,kindsLoading:o,onPatch:s}){let{t:c}=Y(),l=t.deviceId===null?[]:[t.deviceId],u=we(`classes`,i);if(t.trigger===`device-event`)return e(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-2`,children:[r(`div`,{className:`text-[11px] font-semibold text-foreground`,children:c(`system.notificationSimulateFields.whatHappened`,`What happened`)}),r(hm,{form:t,kinds:a,loading:o,onPatch:s})]});if(t.trigger===`audio-event`){let i=a.filter(e=>e.category===`audio`&&e.level===`sub`).map(e=>({value:e.kind,label:e.label}));return e(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-2`,children:[r(`div`,{className:`text-[11px] font-semibold text-foreground`,children:c(`system.notificationSimulateFields.whatHappened`,`What happened`)}),e(`div`,{children:[r(`label`,{className:X,children:c(`system.notificationSimulateFields.audioClasses`,`Audio classes`)}),r(Cn,{options:i,value:t.classNames,onChange:e=>s({classNames:e}),loading:o,emptyHint:t.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:c(`system.notificationSimulateFields.audioClassId`,`Audio class id…`)})]}),e(`div`,{children:[r(`label`,{className:X,children:c(`system.notificationSimulateFields.zones`,`Zones`)}),r(It,{deviceIds:l,cameras:n,value:t.zones,onChange:e=>s({zones:e})})]})]})}return t.trigger===`occupancy-event`?e(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-2`,children:[r(`div`,{className:`text-[11px] font-semibold text-foreground`,children:c(`system.notificationSimulateFields.whatHappened`,`What happened`)}),r(gm,{form:t,cameras:n,taxonomy:i,onPatch:s})]}):e(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-2`,children:[r(`div`,{className:`text-[11px] font-semibold text-foreground`,children:c(`system.notificationSimulateFields.whatHappened`,`What happened`)}),e(`div`,{children:[r(`label`,{className:X,children:c(`system.notificationSimulateFields.detectedClasses`,`Detected classes`)}),u===null?r(Zn,{value:t.classNames,placeholder:c(`system.notificationSimulateFields.classIdPersonCar`,`Class id (person, car…)`),onChange:e=>s({classNames:e})}):r(Tn,{picker:u,value:t.classNames,onChange:e=>s({classNames:e})})]}),e(`div`,{children:[r(`label`,{className:X,children:c(`system.notificationSimulateFields.zonesTheSubjectIsIn`,`Zones the subject is in`)}),r(It,{deviceIds:l,cameras:n,value:t.zones,onChange:e=>s({zones:e})})]}),t.trigger===`package-event`&&e(`div`,{className:`max-w-[14rem]`,children:[r(`label`,{className:`block text-[11px] font-medium text-foreground`,children:c(`system.notificationSimulateFields.packagePhase`,`Package phase`)}),r(W,{value:t.packagePhase,options:[{value:``,label:c(`system.notificationSimulateFields.none`,`— none —`)},{value:`delivered`,label:c(`system.notificationSimulateFields.delivered`,`Delivered`)},{value:`picked-up`,label:c(`system.notificationSimulateFields.pickedUp`,`Picked up`)}],onChange:e=>s({packagePhase:e.target.value===`delivered`?`delivered`:e.target.value===`picked-up`?`picked-up`:``})})]})]})}function hm({form:t,kinds:n,loading:i,onPatch:a}){let{t:o}=Y(),s=n.filter(e=>pm.has(e.category)),c=s.find(e=>e.kind===t.sensorKind);return e(d,{children:[e(`div`,{children:[r(`label`,{className:X,children:o(`system.notificationSimulateFields.eventKind`,`Event kind`)}),r(W,{value:t.sensorKind,options:[{value:``,label:i?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);a({sensorKind:t?.kind??``,sourceDeviceId:t?.source.deviceId??null})}}),!i&&s.length===0&&r(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:t.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.`)})]}),e(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[e(`div`,{children:[r(`label`,{className:X,children:o(`system.notificationSimulateFields.sourceDevice`,`Source device`)}),r(G,{type:`number`,value:t.sourceDeviceId===null?``:String(t.sourceDeviceId),placeholder:o(`system.notificationSimulateFields.theCameraItself`,`the camera itself`),onChange:e=>a({sourceDeviceId:Wp(e.target.value)??null})}),r(`p`,{className:$t,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})})]}),e(`div`,{children:[r(`label`,{className:X,children:o(`system.notificationSimulateFields.eventTypeToken`,`Event type token`)}),r(G,{value:t.eventType,placeholder:o(`system.notificationSimulateFields.pressPressLong`,`press, press_long…`),onChange:e=>a({eventType:e.target.value})}),r(`p`,{className:$t,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 gm({form:t,cameras:n,taxonomy:i,onPatch:a}){let{t:o}=Y(),s=t.deviceId===null?[]:[t.deviceId],c=we(`occupancy`,i),l=c===null?[]:c.groups.flatMap(e=>e.options),u=t.occupancy,f=e=>a({occupancy:{...u,...e}});return e(d,{children:[e(`div`,{children:[r(`label`,{className:X,children:o(`system.notificationSimulateFields.zone`,`Zone`)}),r(It,{deviceIds:s,cameras:n,value:u.zoneId===``?[]:[u.zoneId],onChange:e=>f({zoneId:e[e.length-1]??``})}),r(`p`,{className:$t,children:o(`system.notificationSimulateFields.leaveEmptyForTheWhole`,`Leave empty for the whole frame.`)})]}),e(`div`,{className:`max-w-[14rem]`,children:[r(`label`,{className:X,children:o(`system.notificationSimulateFields.class`,`Class`)}),r(W,{value:u.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})})]}),e(`div`,{className:`flex flex-wrap items-end gap-3`,children:[e(`label`,{className:`text-[11px] text-foreground-subtle`,children:[o(`system.notificationSimulateFields.countNow`,`Count now`),r(G,{type:`number`,min:0,className:`w-20`,value:String(u.count),onChange:e=>f({count:Wp(e.target.value)??0})})]}),e(`label`,{className:`text-[11px] text-foreground-subtle`,children:[o(`system.notificationSimulateFields.countBefore`,`Count before`),r(G,{type:`number`,min:0,className:`w-20`,value:String(u.previousCount),onChange:e=>f({previousCount:Wp(e.target.value)??0})})]}),e(`label`,{className:`text-[11px] text-foreground-subtle`,children:[o(`system.notificationSimulateFields.threshold`,`Threshold`),r(G,{type:`number`,min:1,className:`w-20`,value:String(u.threshold),onChange:e=>f({threshold:Wp(e.target.value)??1})})]}),e(`label`,{className:`flex items-center gap-2 pb-1 text-[11px] text-foreground`,children:[r(nt,{checked:u.occupied,onCheckedChange:e=>f({occupied:e}),"aria-label":o(`system.notificationSimulateFields.occupiedLabel`)}),o(`system.notificationSimulateFields.occupiedLabel`,`Occupied`)]})]})]})}function _m({form:t,cameras:n,onPatch:i}){let{t:a}=Y(),o=t.deviceId===null?[]:[t.deviceId];return e(`details`,{className:`rounded-md border border-border px-3 py-2`,children:[r(`summary`,{className:`cursor-pointer text-[11px] font-semibold text-foreground`,children:a(`system.notificationSimulateFields.advanced`,`Advanced`)}),e(`div`,{className:`mt-2 space-y-3`,children:[t.trigger===`object-event`&&e(`div`,{children:[e(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[r(nt,{checked:t.crossingEnabled,onCheckedChange:e=>i({crossingEnabled:e}),"aria-label":a(`system.notificationSimulateFields.zoneCrossing`,`zone crossing`)}),a(`system.notificationSimulateFields.thisEventIsAConfirmed`,`This event is a confirmed zone crossing`)]}),t.crossingEnabled&&e(`div`,{className:`mt-1 space-y-1.5`,children:[r(`div`,{className:`max-w-[12rem]`,children:r(W,{value:t.crossingDirection,options:[{value:`enter`,label:a(`system.notificationSimulateFields.enteredTheZone`,`Entered the zone`)},{value:`exit`,label:a(`system.notificationSimulateFields.leftTheZone`,`Left the zone`)}],onChange:e=>i({crossingDirection:e.target.value===`exit`?`exit`:`enter`})})}),r(It,{deviceIds:o,cameras:n,value:t.crossingZoneId===``?[]:[t.crossingZoneId],onChange:e=>i({crossingZoneId:e[e.length-1]??``})})]})]}),e(`div`,{children:[e(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[r(nt,{checked:t.bboxEnabled,onCheckedChange:e=>i({bboxEnabled:e}),"aria-label":a(`system.notificationSimulateFields.boundingBox`,`bounding box`)}),a(`system.notificationSimulateFields.carryABoundingBox`,`Carry a bounding box`)]}),r(`p`,{className:$t,children:a(`system.notificationSimulateFields.normalized01TopLeft`,"Normalized 0–1, top-left origin. Feeds the `customZones` condition and decides how the still is cropped or boxed.")}),t.bboxEnabled&&r(`div`,{className:`mt-1 flex flex-wrap gap-2`,children:[`x`,`y`,`w`,`h`].map(n=>e(`label`,{className:`text-[11px] text-foreground-subtle`,children:[n,r(G,{type:`number`,min:0,max:1,step:.05,className:`w-20`,value:String(t.bbox[n]),onChange:e=>i({bbox:{...t.bbox,[n]:Wp(e.target.value)??0}})})]},n))})]}),e(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[e(`div`,{children:[r(`label`,{className:X,children:a(`system.notificationSimulateFields.happenedAt`,`Happened at`)}),e(`div`,{className:`flex items-center gap-2`,children:[r(G,{type:`datetime-local`,value:t.timestampLocal,onChange:e=>i({timestampLocal:e.target.value})}),t.timestampLocal===``?r(U,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>i({timestampLocal:Kp(Date.now())}),children:a(`system.notificationSimulateFields.set`,`Set`)}):r(U,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>i({timestampLocal:``}),children:a(`system.notificationSimulateFields.now`,`Now`)})]}),r(`p`,{className:$t,children:a(`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.`)})]}),e(`div`,{children:[r(`label`,{className:X,children:a(`system.notificationSimulateFields.detectionSource`,`Detection source`)}),r(W,{value:t.source,options:[{value:``,label:a(`system.notificationSimulateFields.unsetReadsAsPipeline`,`— unset (reads as pipeline) —`)},{value:`pipeline`,label:a(`system.notificationSimulateFields.pipeline`,`Pipeline`)},{value:`onboard`,label:a(`system.notificationSimulateFields.onboardCamera`,`Onboard (camera)`)},{value:`sensor`,label:a(`system.notificationSimulateFields.sensor`,`Sensor`)},{value:`audio`,label:a(`system.notificationSimulateFields.audio`,`Audio`)}],onChange:e=>{let t=e.target.value;i({source:t===`pipeline`||t===`onboard`||t===`sensor`||t===`audio`?t:``})}})]})]})]})]})}function vm({checked:t,label:n,hint:i,danger:a=!1,onChange:o}){let{t:s}=Y();return e(`div`,{children:[e(`label`,{className:`flex items-center gap-2 text-[11px] font-medium text-foreground`,children:[r(nt,{checked:t,onCheckedChange:o,"aria-label":n}),n,a&&r(K,{variant:`danger`,children:s(`system.notificationSimulateFields.actuatesDevices`,`actuates devices`)})]}),r(`p`,{className:$t,children:i})]})}s();var ym={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.`},bm={"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 xm({result:t,targetName:n}){let{t:i}=Y();return e(`div`,{className:`space-y-3 rounded-md border border-border px-3 py-3`,children:[r(`p`,{className:`text-xs font-medium text-foreground`,children:fm(t)}),e(`div`,{className:`flex flex-wrap items-center gap-2 text-[11px] text-foreground-subtle`,children:[r(Sm,{recordId:t.recordId}),r(`span`,{children:r(Kr,{i18nKey:`system.notificationSimulateResult.delivery`,values:{value:t.delivery},components:{b:r(`span`,{className:`text-foreground`})}})}),r(`span`,{children:r(Kr,{i18nKey:`system.notificationSimulateResult.candidates`,values:{value:t.candidates},components:{b:r(`span`,{className:`text-foreground`})}})}),r(`span`,{title:ym[t.still],children:r(Kr,{i18nKey:`system.notificationSimulateResult.still`,values:{value:t.still},components:{b:r(`span`,{className:`text-foreground`})}})}),t.droppedBy!==void 0&&r(K,{variant:`warning`,children:i(`system.notificationSimulateResult.droppedBy`,{by:t.droppedBy})})]}),t.notes.length>0&&r(`ul`,{className:`space-y-1 rounded-md border border-border bg-surface px-2.5 py-2`,children:t.notes.map(e=>r(`li`,{className:`text-[11px] leading-snug text-foreground-subtle`,children:e},e))}),t.outcomes.length===0?r(`p`,{className:`text-[11px] text-foreground-subtle`,children:r(Kr,{i18nKey:`system.notificationSimulateResult.noRuleEvaluated`,values:{delivery:t.delivery},components:{b:r(`span`,{className:`text-foreground`})}})}):r(`ul`,{className:`divide-y divide-border rounded-md border border-border`,children:t.outcomes.map(e=>r(Cm,{outcome:e,targetName:n},e.ruleId))})]})}function Sm({recordId:t}){let{t:n}=Y(),[i,o]=a(!1);return e(`span`,{className:`inline-flex items-center gap-1 rounded border border-border px-1.5 py-0.5`,children:[r(`code`,{className:`text-[10px] text-foreground`,children:t}),r(U,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>{let e=navigator.clipboard;e!==void 0&&e.writeText(t).then(()=>{o(!0),setTimeout(()=>o(!1),1500)},()=>o(!1))},title:n(`system.notificationSimulateResult.copyRecordId`,`Copy record id`),children:r(O,{className:`h-3 w-3`})}),i&&r(`span`,{className:`text-[10px] text-success`,children:n(`common.copiedLower`)})]})}function Cm({outcome:t,targetName:n}){let{t:i}=Y();return e(`li`,{className:`space-y-1 px-2.5 py-2`,children:[e(`div`,{className:`flex items-center gap-2`,children:[t.matched?r(S,{className:`h-3.5 w-3.5 shrink-0 text-success`}):r(j,{className:`h-3.5 w-3.5 shrink-0 text-foreground-subtle`}),r(`span`,{className:`min-w-0 flex-1 truncate text-xs text-foreground`,children:t.ruleName}),e(`span`,{className:`shrink-0 text-[10px] text-foreground-subtle`,title:bm[t.cooldown],children:[`cooldown: `,t.cooldown]})]}),!t.matched&&r(`p`,{className:`pl-5 text-[11px] text-foreground-subtle`,children:t.failedCondition===void 0?i(`system.notificationSimulateResult.didNotMatchTheEngine`,`Did not match. The engine reported no failing condition id.`):r(Kr,{i18nKey:`system.notificationSimulateResult.failingCondition`,values:{condition:t.failedCondition},components:{code:r(`code`,{className:`text-foreground`})}})}),t.matched&&e(`p`,{className:`pl-5 text-[11px] text-foreground-subtle`,children:[i(`system.notificationSimulateResult.enqueued`,{count:t.enqueued}),t.targetIds.length>0?` → ${t.targetIds.map(n).join(`, `)}`:` — ${i(`system.notificationSimulateResult.noTargetResolved`)}`,`.`]}),t.matchedOn!==void 0&&t.matchedOn.length>0&&r(`p`,{className:`pl-5 text-[10px] text-foreground-muted`,children:i(`system.notificationSimulateResult.matchedOn`,{on:t.matchedOn.join(`, `)})})]})}s();var wm=`pipeline-analytics`,Tm=`nc.injectTestEvent`;function Em(){let{t}=Y(),s=w(),[c,l]=a(()=>rm()?.form??Hp()),[d,f]=a(()=>rm()?.caveats??[]),[p,m]=a(()=>rm()?.ruleName??null);i(()=>im(),[]);let[h,g]=a(null),[_,v]=a(!1),[y,b]=a(null),x=e=>l(t=>({...t,...e})),S=Qe({projection:`slim`}),C=o({queryKey:pp,queryFn:()=>s.trpcClient.notificationRules.getConditionCatalog.query({})}),E=o({queryKey:dp,queryFn:async()=>(await s.trpcClient.notificationRules.listRules.query({})).rules}),D=o({queryKey:fp,queryFn:()=>s.trpcClient.notificationOutput.listTargets.query({})}),O=c.deviceId,k=o({queryKey:[[`pipelineAnalytics`,`listEventKindsBatch`],{deviceId:O}],enabled:O!==null,staleTime:6e4,queryFn:async()=>O===null?[]:(await s.trpcClient.pipelineAnalytics.listEventKindsBatch.query({deviceIds:[O]})).flatMap(e=>[...e.kinds])}),A=n(()=>(S.data??[]).filter(e=>e.type===Te.Camera).map(e=>({id:e.id,name:e.name})),[S.data]),j=C.data?.taxonomy,M=k.data??[],P=n(()=>{let e=new Map;for(let t of D.data??[])e.set(t.id,t.name);return e},[D.data]),ee=u({mutationFn:async()=>{let e=qp(c);if(e===null)throw Error(`Pick a camera first.`);return s.trpcClient.addons.custom.mutate({addonId:wm,action:Tm,input:e})},onMutate:()=>{g(null),v(!1),b(null)},onSuccess:e=>{let t=dm(e);g(t),v(t===null)},onError:e=>b(e instanceof Error?e.message:`The simulation failed.`)}),F=Rp(c.trigger),I=E.data?.find(e=>e.id===c.onlyRuleId);return e(ci,{embedded:!0,icon:We,title:t(`system.notificationSimulate.simulateAnEvent`,`Simulate an event`),subtitle:t(`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:[S.isError&&r(H,{title:t(`system.notificationSimulate.failedToLoadCameras`,`Failed to load cameras`),message:S.error instanceof Error?S.error.message:t(`system.notificationSimulate.unknownError`,`Unknown error`),onRetry:()=>void S.refetch()}),p!==null&&r(`div`,{className:`rounded-md border border-primary/40 bg-primary/5 px-3 py-2 text-[11px] text-foreground`,children:r(Kr,{i18nKey:`system.notificationSimulate.seededFrom`,values:{rule:p},components:{b:r(`span`,{className:`font-medium`})}})}),d.length>0&&r(`div`,{className:`space-y-1 rounded-md border border-warning/40 bg-warning/5 px-3 py-2`,children:d.map(t=>e(`p`,{className:`flex gap-1.5 text-[11px] text-foreground`,children:[r(N,{className:`mt-0.5 h-3 w-3 shrink-0 text-warning`}),r(`span`,{children:t.note})]},t.conditionId))}),e(bt,{className:`space-y-4`,children:[e(`div`,{children:[r(`label`,{className:X,children:t(`system.notificationSimulate.ruleToSimulate`,`Rule to simulate`)}),r(W,{"data-testid":`simulate-seed-rule`,value:c.onlyRuleId,options:[{value:``,label:t(`system.notificationSimulate.pickARuleToPrefill`,`— pick a rule to prefill trigger + conditions —`)},...(E.data??[]).map(e=>({value:e.id,label:`${e.name} · ${e.delivery}`}))],onChange:e=>{let t=e.target.value;if(t.length===0){l(Hp()),f([]),m(null);return}let n=E.data?.find(e=>e.id===t);if(n===void 0){x({onlyRuleId:t});return}l(Zp(n)),f($p(n)),m(n.name)}}),r(`p`,{className:$t,children:t(`system.notificationSimulate.picksTheTriggerThatRule`,`Picks the trigger that rule listens for and fills the fields from its conditions. Edit any value below, then inject.`)})]}),e(`div`,{children:[r(`label`,{className:X,children:t(`system.notificationSimulate.camera`,`Camera`)}),r(W,{"data-testid":`simulate-camera`,value:c.deviceId===null?``:String(c.deviceId),options:[{value:``,label:A.length===0?t(`system.notificationSimulate.loadingCameras`,`Loading cameras…`):t(`system.notificationSimulate.pickACamera`,`— pick a camera —`)},...A.map(e=>({value:String(e.id),label:e.name}))],onChange:e=>{x({deviceId:Wp(e.target.value)??null,zones:[],crossingZoneId:``,sensorKind:``,sourceDeviceId:null,occupancy:{...c.occupancy,zoneId:``}})}}),r(`p`,{className:$t,children:t(`system.notificationSimulate.theCameraTheEventIs`,`The camera the event is attributed to — what a notification shows.`)})]}),e(`div`,{children:[r(`label`,{className:X,children:t(`system.notificationSimulate.trigger`,`Trigger`)}),r(W,{"data-testid":`simulate-trigger`,value:c.trigger,options:Ip.map(e=>({value:e.value,label:e.label})),onChange:e=>{let t=Lp(e.target.value);if(!t)return;let n=zp(c.trigger);x({trigger:t,source:c.source===``||c.source===n?zp(t):c.source})}}),e(`p`,{className:$t,children:[Ip.find(e=>e.value===c.trigger)?.hint,` `,r(Kr,{i18nKey:`system.notificationSimulate.onlyRulesWhoseTrigger`,values:{delivery:F},components:{b:r(`span`,{className:`text-foreground`})}})]})]}),r(mm,{form:c,cameras:A,taxonomy:j,kinds:M,kindsLoading:k.isLoading,onPatch:x}),e(`details`,{className:`rounded-md border border-border px-3 py-2`,open:!0,children:[r(`summary`,{className:`cursor-pointer text-[11px] font-semibold text-foreground`,children:t(`system.notificationSimulate.quality`,`Quality`)}),e(`div`,{className:`mt-2 space-y-3`,children:[r(`p`,{className:$t,children:t(`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.`)}),e(`div`,{children:[r(`label`,{className:X,children:t(`system.notificationSimulate.labelIdentityNamePlateSubclass`,`Label (identity name / plate / subclass)`)}),r(G,{value:c.label,placeholder:t(`system.notificationSimulate.eGMarcoAb123cd`,`e.g. Marco, AB123CD`),onChange:e=>x({label:e.target.value})})]}),e(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[e(`div`,{children:[r(`label`,{className:X,children:t(`system.notificationSimulate.detectionConfidence`,`Detection confidence`)}),r(Ir,{value:c.confidence,min:0,max:1,step:.05,onChange:e=>x({confidence:e})})]}),e(`div`,{children:[r(`label`,{className:X,children:t(`system.notificationSimulate.labelMatchConfidence`,`Label-match confidence`)}),r(Ir,{value:c.labelConfidence,min:0,max:1,step:.05,onChange:e=>x({labelConfidence:e})})]}),e(`div`,{children:[r(`label`,{className:X,children:t(`system.notificationSimulate.importance`,`Importance`)}),r(Ir,{value:c.importance,min:0,max:1,step:.05,onChange:e=>x({importance:e})})]}),e(`div`,{children:[r(`label`,{className:X,children:t(`system.notificationSimulate.dwellSeconds`,`Dwell (seconds)`)}),r(Ir,{value:c.dwellSeconds,min:0,step:1,onChange:e=>x({dwellSeconds:e})})]})]})]})]}),r(_m,{form:c,cameras:A,onPatch:x}),e(`div`,{className:`space-y-2 rounded-md border border-border px-3 py-2`,children:[r(`div`,{className:`text-[11px] font-semibold text-foreground`,children:t(`system.notificationSimulate.howToRunIt`,`How to run it`)}),r(vm,{checked:c.bypassCooldown,label:t(`system.notificationSimulate.ignoreTheCooldown`,`Ignore the cooldown`),hint:t(`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=>x({bypassCooldown:e})}),r(vm,{checked:c.bypassMute,label:t(`system.notificationSimulate.ignoreMutesAndSnoozes`,`Ignore mutes and snoozes`),hint:t(`system.notificationSimulate.aMutedCameraOrA`,`A muted camera or a snoozed rule drops the event before any rule is consulted.`),onChange:e=>x({bypassMute:e})}),r(vm,{checked:c.runActions,danger:!0,label:t(`system.notificationSimulate.runTheRuleSActions`,`Run the rule's actions — this actuates real devices`),hint:t(`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=>x({runActions:e})}),e(`div`,{className:`max-w-[14rem]`,children:[r(`label`,{className:X,children:t(`system.notificationSimulate.stillImage`,`Still image`)}),r(W,{value:c.still,options:[{value:`live`,label:t(`system.notificationSimulate.liveSnapshotOfTheCamera`,`Live snapshot of the camera`)},{value:`none`,label:t(`system.notificationSimulate.noImage`,`No image`)}],onChange:e=>x({still:e.target.value===`none`?`none`:`live`})})]}),e(`div`,{children:[r(`label`,{className:X,children:t(`system.notificationSimulate.evaluateOnlyOneRule`,`Evaluate only one rule`)}),r(W,{value:c.onlyRuleId,options:[{value:``,label:t(`system.notificationSimulate.everyEnabledRule`,`— every enabled rule —`)},...(E.data??[]).map(e=>({value:e.id,label:e.name}))],onChange:e=>x({onlyRuleId:e.target.value})}),c.onlyRuleId.length>0&&I===void 0&&r(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:r(Kr,{i18nKey:`system.notificationSimulate.ruleNotInList`,values:{id:c.onlyRuleId},components:{code:r(`code`,{})}})})]})]}),y!==null&&r(`div`,{className:`rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger`,children:y}),e(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[r(`p`,{className:`min-w-0 flex-1 text-[10px] text-foreground-subtle`,children:t(`system.notificationSimulate.nothingIsPersistedNoTrack`,`Nothing is persisted: no track, no event row, no stored media. Delivery is real.`)}),e(U,{size:`sm`,type:`button`,disabled:ee.isPending||!Up(c),onClick:()=>ee.mutate(),children:[ee.isPending?r(T,{className:`h-3.5 w-3.5 animate-spin`}):r(We,{className:`h-3.5 w-3.5`}),t(`system.notificationSimulate.injectEvent`,`Inject event`)]})]})]}),_&&r(`div`,{className:`rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-[11px] text-foreground`,children:t(`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.`)}),h!==null&&r(xm,{result:h,targetName:e=>P.get(e)??e})]})}var Dm=e=>typeof e==`string`&&e.length>0;function Om(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 km(e,t){return e.format.includes(t)?t:e.format[0]??`text`}function Am(e,t){let n=[];for(let r of e.attachments.mediaTypes){if(n.length>=e.attachments.max)break;let i=t[r];Dm(i)&&n.push({mediaType:r,url:i})}return n}function jm(e,t){if(e.actions<=0)return[];let n=[];for(let r of t){if(n.length>=e.actions)break;let t=Dm(r.label),i=Dm(r.url);!t&&!i||n.push({id:`test-${n.length+1}`,label:t?r.label:J.t(`helpers.notificationTestComposer.actionN`,{n:n.length+1}),...i?{url:r.url}:{}})}return n}function Mm(e,t){let n=e.levels.some(e=>e.id===t.level)?t.level:void 0,r=Am(e,t.attachmentUrls),i=jm(e,t.actions),a=e.ttl&&Dm(t.ttl)?Number(t.ttl):void 0;return{body:t.body,format:km(e,t.format),priority:Nm(t.priority),...Dm(t.title)?{title:t.title}:{},...n?{level:n}:{},...r.length>0?{attachments:r}:{},...i.length>0?{actions:i}:{},...e.clickUrl&&Dm(t.clickUrl)?{clickUrl:t.clickUrl}:{},...e.sound&&Dm(t.sound)?{sound:t.sound}:{},...a!==void 0&&Number.isFinite(a)?{ttl:a}:{},...Dm(t.tag)?{tag:t.tag}:{}}}function Nm(e){return Number.isFinite(e)?Math.min(5,Math.max(1,Math.round(e))):3}function Pm(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 Fm(e){return{level:``,priority:3,format:e.format[0]??`text`,title:``,body:``,attachmentUrls:{},actions:[],clickUrl:``,sound:``,ttl:``,tag:``}}var Im={image:g(`/addon/notifiers/samples/image`),video:g(`/addon/notifiers/samples/video`),gif:g(`/addon/notifiers/samples/gif`),audio:g(`/addon/notifiers/samples/audio`),icon:g(`/addon/notifiers/samples/icon`)};function Lm(e,t){return e.attachments.max>0&&e.attachments.mediaTypes.includes(t)}function Rm(e){let t=[`text`];for(let n of[`image`,`gif`,`video`,`audio`])Lm(e,n)&&t.push(n);return e.actions>0&&t.push(`actions`),e.levels.length>0&&t.push(`critical`),t.push(`overflow`),t}function zm(e,t,n){let r=Fm(e);return Lm(e,t)?{...r,body:n,attachmentUrls:{[t]:Im[t]}}:{...r,body:n}}function Bm(e,t){let n=Fm(e);switch(t){case`text`:return{...n,title:`CamStack`,body:J.t(`helpers.notificationTestComposer.presetText`)};case`image`:return zm(e,`image`,J.t(`helpers.notificationTestComposer.presetImage`));case`gif`:return zm(e,`gif`,J.t(`helpers.notificationTestComposer.presetGif`));case`video`:return zm(e,`video`,J.t(`helpers.notificationTestComposer.presetVideo`));case`audio`:return zm(e,`audio`,J.t(`helpers.notificationTestComposer.presetAudio`));case`actions`:{let t=Array.from({length:e.actions},(e,t)=>({label:J.t(`helpers.notificationTestComposer.actionN`,{n:t+1}),url:`/`}));return{...n,title:`CamStack`,body:J.t(`helpers.notificationTestComposer.presetActions`),actions:t,...e.clickUrl?{clickUrl:`/`}:{}}}case`critical`:{let t=Pm(e);return{...n,title:`CamStack`,body:J.t(`helpers.notificationTestComposer.presetCritical`),priority:5,level:t?.id??``}}case`overflow`:return{...n,body:`X`.repeat(e.bodyMaxLen+50)}}}s();var Vm={get text(){return J.t(`system.notificationTestPanel.presetText`)},get image(){return J.t(`system.notificationTestPanel.presetImage`)},get gif(){return J.t(`system.notificationTestPanel.presetGif`)},get video(){return J.t(`system.notificationTestPanel.presetVideo`)},get audio(){return J.t(`system.notificationTestPanel.presetAudio`)},get actions(){return J.t(`system.notificationTestPanel.presetActions`)},get critical(){return J.t(`system.notificationTestPanel.presetCritical`)},get overflow(){return J.t(`system.notificationTestPanel.presetOverflow`)}},Hm=`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`,Um=`block text-[11px] font-medium text-foreground mb-1`;function Wm({target:t,kind:i,open:o,onClose:s}){let{t:c}=Y(),l=w(),d=n(()=>Om(i.caps),[i.caps]),f=n(()=>Rm(i.caps),[i.caps]),[p,m]=a(()=>Fm(i.caps)),[h,g]=a(null),_=n(()=>Mm(i.caps,p),[i.caps,p]),v=p.body.length,y=v>d.bodyMaxLen,b=e=>m(t=>({...t,...e})),x=u({mutationFn:()=>l.trpcClient.notificationOutput.testTarget.mutate({addonId:t.addonId,targetId:t.id,sample:Mm(i.caps,p)}),onMutate:()=>g(null),onSuccess:e=>g(e),onError:e=>g({success:!1,error:e instanceof Error?e.message:J.t(`system.notificationTestPanel.testFailed`)})}),S=e=>{m(Bm(i.caps,e)),g(null)},C=(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},b({actions:r})};return r(xt,{open:o,onOpenChange:e=>!e&&s(),children:e(kt,{width:`lg`,className:`!max-w-2xl`,scroll:`body`,children:[r(wt,{children:r(vt,{children:c(`system.notificationTestPanel.testTitle`,{name:t.name,kind:i.label})})}),e(St,{className:`space-y-4 pr-1`,children:[r(`div`,{className:`flex flex-wrap gap-1.5`,children:f.map(e=>r(U,{size:`sm`,variant:`outline`,type:`button`,onClick:()=>S(e),children:Vm[e]},e))}),e(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[d.levels.length>0&&e(`div`,{children:[r(`label`,{className:Um,children:c(`system.notificationTestPanel.level`,`Level`)}),e(`select`,{className:Hm,value:p.level,onChange:e=>b({level:e.target.value}),children:[r(`option`,{value:``,children:c(`system.notificationTestPanel.deriveFromPriority`,`— derive from priority —`)}),d.levels.map(t=>e(`option`,{value:t.id,children:[t.label,t.ordinal===null?` (${c(`system.notificationTestPanel.qualitative`)})`:` (p${t.ordinal})`]},t.id))]}),(()=>{let t=d.levels.find(e=>e.id===p.level);return t?e(`div`,{className:`mt-1 space-y-1`,children:[t.description&&r(`p`,{className:`text-[10px] text-foreground-subtle`,children:t.description}),e(`div`,{className:`flex flex-wrap gap-1`,children:[t.flags?.critical&&r(K,{variant:`danger`,"data-testid":`flag-critical`,children:c(`system.notificationTestPanel.critical`)}),t.flags?.silent&&r(K,{variant:`info`,children:c(`system.notificationTestPanel.silent`)}),t.flags?.noPush&&r(K,{variant:`warning`,children:`no-push`})]}),t.requires&&t.requires.length>0&&e(`p`,{className:`text-[10px] text-warning`,children:[c(`system.notificationTestPanel.requiresTargetConfig`,`Requires target config:`),` `,t.requires.join(`, `)]})]}):null})()]}),e(`div`,{children:[e(`label`,{className:Um,children:[c(`system.notificationTestPanel.priorityOrdinal`,`Priority (ordinal):`),` `,p.priority]}),r(`input`,{type:`range`,min:1,max:5,step:1,value:p.priority,onChange:e=>b({priority:Number(e.target.value)}),className:`w-full accent-primary`,"aria-label":c(`system.notificationTestPanel.priority`)})]})]}),d.formats.length>0&&e(`div`,{children:[r(`label`,{className:Um,children:c(`system.notificationTestPanel.format`,`Format`)}),r(`div`,{className:`flex flex-wrap gap-2`,children:d.formats.map(t=>e(`label`,{className:`flex items-center gap-1.5 text-xs text-foreground cursor-pointer`,children:[r(`input`,{type:`radio`,name:`format`,className:`accent-primary`,checked:p.format===t,onChange:()=>b({format:t})}),t]},t))})]}),e(`div`,{children:[r(`label`,{className:Um,children:c(`system.notificationTestPanel.testTitle`,`Title`)}),r(`input`,{className:Hm,value:p.title,onChange:e=>b({title:e.target.value})})]}),e(`div`,{children:[e(`label`,{className:Um,children:[c(`system.notificationTestPanel.body`),` `,e(`span`,{className:y?`text-danger`:`text-foreground-subtle`,children:[`(`,v,`/`,d.bodyMaxLen,y?` — ${c(`system.notificationTestPanel.overflow`)}`:``,`)`]})]}),r(`textarea`,{className:`${Hm} min-h-[80px] resize-y`,value:p.body,onChange:e=>b({body:e.target.value})})]}),d.attachmentSlots.length>0&&e(`div`,{children:[e(`label`,{className:Um,children:[c(`system.notificationTestPanel.attachments`),` `,r(`span`,{className:`text-foreground-subtle`,children:d.attachmentMaxBytes?c(`system.notificationTestPanel.attachmentsMetaMb`,{mode:d.attachmentMode,max:d.attachmentMax,mb:Math.round(d.attachmentMaxBytes/1024/1024)}):c(`system.notificationTestPanel.attachmentsMeta`,{mode:d.attachmentMode,max:d.attachmentMax})})]}),r(`div`,{className:`space-y-1.5`,children:d.attachmentSlots.map(t=>e(`div`,{className:`flex items-center gap-2`,children:[r(`span`,{className:`text-[10px] w-12 shrink-0 text-foreground-subtle`,children:t}),r(`input`,{className:Hm,placeholder:c(`system.notificationTestPanel.url`,`{{mt}} URL`,{mt:t}),value:p.attachmentUrls[t]??``,onChange:e=>b({attachmentUrls:{...p.attachmentUrls,[t]:e.target.value}})})]},t))})]}),d.showActions&&e(`div`,{children:[r(`label`,{className:Um,children:c(`system.notificationTestPanel.actionsUpTo`,{max:d.maxActions})}),r(`div`,{className:`space-y-1.5`,children:Array.from({length:Math.min(d.maxActions,3)},(t,n)=>e(`div`,{className:`flex items-center gap-2`,children:[r(`input`,{className:Hm,placeholder:c(`system.notificationTestPanel.actionLabelPlaceholder`),value:p.actions[n]?.label??``,onChange:e=>C(n,`label`,e.target.value)}),r(`input`,{className:Hm,placeholder:c(`system.notificationTestPanel.actionUrlPlaceholder`),value:p.actions[n]?.url??``,onChange:e=>C(n,`url`,e.target.value)})]},n))})]}),e(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[d.showClickUrl&&e(`div`,{children:[r(`label`,{className:Um,children:c(`system.notificationTestPanel.clickUrl`,`Click URL`)}),r(`input`,{className:Hm,value:p.clickUrl,onChange:e=>b({clickUrl:e.target.value})})]}),d.showSound&&e(`div`,{children:[r(`label`,{className:Um,children:c(`system.notificationTestPanel.sound`,`Sound`)}),r(`input`,{className:Hm,value:p.sound,onChange:e=>b({sound:e.target.value})})]}),d.showTtl&&e(`div`,{children:[r(`label`,{className:Um,children:c(`system.notificationTestPanel.ttlSeconds`,`TTL (seconds)`)}),r(`input`,{className:Hm,type:`number`,value:p.ttl,onChange:e=>b({ttl:e.target.value})})]}),d.showTag&&e(`div`,{children:[r(`label`,{className:Um,children:c(`system.notificationTestPanel.tag`,`Tag`)}),r(`input`,{className:Hm,value:p.tag,onChange:e=>b({tag:e.target.value})})]})]}),h&&r(Gm,{result:h}),e(`details`,{className:`text-[10px]`,children:[r(`summary`,{className:`cursor-pointer text-foreground-subtle`,children:c(`system.notificationTestPanel.payloadPreview`,`Payload preview`)}),r(`pre`,{className:`mt-1 overflow-x-auto rounded bg-surface p-2 text-foreground-subtle`,children:JSON.stringify(_,null,2)})]})]}),e(Tt,{children:[r(U,{variant:`secondary`,size:`sm`,type:`button`,onClick:s,children:c(`common.close`,`Close`)}),e(U,{size:`sm`,type:`button`,disabled:x.isPending||p.body.length===0,onClick:()=>x.mutate(),children:[x.isPending?r(T,{className:`h-3.5 w-3.5 animate-spin`}):r(Ge,{className:`h-3.5 w-3.5`}),c(`system.notificationTestPanel.sendTest`,`Send test`)]})]})]})})}function Gm({result:t}){let{t:n}=Y(),i=t.renderedAs;return e(`div`,{className:`rounded-md border px-3 py-2 text-xs ${t.success?`border-success/40 bg-success/10`:`border-danger/40 bg-danger/10`}`,"data-testid":`test-result`,children:[e(`div`,{className:`flex items-center gap-2 font-medium`,children:[t.success?r(S,{className:`h-3.5 w-3.5 text-success`}):r(j,{className:`h-3.5 w-3.5 text-danger`}),r(`span`,{children:t.success?n(`system.notificationTestPanel.delivered`,`Delivered`):n(`system.notificationTestPanel.failed`,`Failed`)})]}),t.error&&r(`p`,{className:`mt-1 text-danger`,children:t.error}),i&&e(`dl`,{className:`mt-2 grid grid-cols-2 gap-x-3 gap-y-0.5 text-[11px] text-foreground-subtle`,children:[r(`dt`,{children:n(`system.notificationTestPanel.resolvedLevel`,`Resolved level`)}),r(`dd`,{className:`text-foreground`,children:i.level}),r(`dt`,{children:n(`system.notificationTestPanel.formatSent`,`Format sent`)}),r(`dd`,{className:`text-foreground`,children:i.format}),r(`dt`,{children:n(`system.notificationTestPanel.attachmentsSent`,`Attachments sent`)}),r(`dd`,{className:`text-foreground`,children:i.attachmentsSent}),r(`dt`,{children:n(`system.notificationTestPanel.actionsSent`,`Actions sent`)}),r(`dd`,{className:`text-foreground`,children:i.actionsSent}),r(`dt`,{children:n(`system.notificationTestPanel.truncated`,`Truncated`)}),r(`dd`,{className:`text-foreground`,children:i.truncated?n(`common.yes`):n(`common.no`)}),r(`dt`,{children:n(`system.notificationTestPanel.dropped`,`Dropped`)}),r(`dd`,{className:`text-foreground`,children:i.dropped.length>0?i.dropped.join(`, `):`—`})]})]})}function Km(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 qm(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 Jm(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 Ym=`••••••••`;function Xm(e){return e===`••••••••`||e===`__redacted__`}function Zm(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===``||Xm(n)||(i[t]=n)}return i}function Qm(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!==``?Ym:``}return r}function $m(e){return{...e}}var eh=[`Refusing to reuse the stored secret`,`Re-enter the secret`];function th(e){return eh.some(t=>e.includes(t))}function nh(e){return e==null||e===``?``:typeof e==`string`?e:JSON.stringify(e)}function rh(e,t,n){let r=new Set(n);return[...new Set([...Object.keys(e),...Object.keys(t)])].filter(n=>!r.has(n)&&nh(e[n])!==nh(t[n]))}function ih(e,t,n,r){if(r===void 0)return rh(e,t,n);let i=new Set(n),a=Zm(e,t,n);return r.filter(n=>i.has(n)?n in a:nh(e[n])!==nh(t[n]))}function ah(e,t,n){let r=Zm(e,t,n);return n.filter(e=>!(e in r))}function oh(e,t){return e.map(e=>e.type===`password`&&t.has(e.key)?{...e,required:!0}:e.type===`group`?{...e,fields:oh(e.fields,t)}:e.type===`sub-tabs`?{...e,tabs:e.tabs.map(e=>({...e,fields:oh(e.fields,t)}))}:e)}function sh(e,t){if(t.length===0)return e;let n=new Set(t);return{...e,sections:e.sections.map(e=>({...e,fields:oh(e.fields,n)}))}}function ch(e){let t=e.trim();return t.length===0?J.t(`common.copy`):J.t(`helpers.notificationTargets.copyOf`,{name:t})}function lh(e,t){return e.map(e=>e.type===`password`&&t.has(e.key)?{...e,placeholder:e.placeholder??J.t(`helpers.notificationTargets.keepSecret`)}:e.type===`group`?{...e,fields:lh(e.fields,t)}:e.type===`sub-tabs`?{...e,tabs:e.tabs.map(e=>({...e,fields:lh(e.fields,t)}))}:e)}function uh(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:lh(e.fields,r)}))}}function dh(e){return e.filter(e=>e.supportsDiscovery)}function fh(e,t,n){let r=n.destinationKeys??[];return t.some(t=>{if(t.kind!==n.kind)return!1;let i=0;for(let n of r){let r=e.config[n],a=t.config[n];if(!(r===void 0||a===void 0)){if(r!==a)return!1;i+=1}}return i>0})}function ph(e,t,n){return e.filter(e=>!fh(e,t,n))}function mh(e,t,n){return{id:n,name:e.suggestedName,kind:t.kind,addonId:t.addonId,enabled:!0,config:e.config}}var hh=`target`,gh=`kind`,_h=[hh,gh];function vh({kind:e,imgClassName:t,fallbackClassName:n}){return e?.iconUrl?r(`img`,{src:e.iconUrl,alt:e.label,className:t,loading:`lazy`,draggable:!1}):r(`span`,{className:n,children:e?.icon??`🔔`})}s();function yh(e,t){return`${e.kind}:${t}`}function bh({kinds:t,targets:i,onClose:s,onAdded:c}){let{t:l}=Y(),d=w(),[f,p]=a(new Set),m=o({queryKey:[`notificationOutput`,`discoverTargets`,t.map(e=>e.kind)],queryFn:async()=>Promise.all(t.map(async e=>{try{return{kind:e,proposals:ph(await d.trpcClient.notificationOutput.discoverTargets.query({addonId:e.addonId,kind:e.kind}),i,e),error:null}}catch(t){return{kind:e,proposals:[],error:t instanceof Error?t.message:String(t)}}})),staleTime:0,gcTime:0}),h=m.data??[],g=n(()=>h.flatMap(e=>e.proposals.flatMap((t,n)=>f.has(yh(e.kind,n))?[]:[{finding:e,proposal:t,index:n}])),[h,f]),_=h.reduce((e,t)=>e+t.proposals.length,0),v=u({mutationFn:async()=>{let e=Date.now();for(let[t,n]of g.entries()){let r=mh(n.proposal,n.finding.kind,`${n.finding.kind.kind}-${e}-${t}`);await d.trpcClient.notificationOutput.upsertTarget.mutate({addonId:n.finding.kind.addonId,target:r})}},onSuccess:c}),y=e=>p(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n});return r(Dt,{open:!0,onClose:s,icon:A,title:l(`system.notificationTargets.discoverTitle`,`Devices found`),width:`lg`,testId:`target-discovery-dialog`,error:v.error instanceof Error?v.error.message:null,footer:e(U,{size:`sm`,type:`button`,disabled:v.isPending||g.length===0,onClick:()=>v.mutate(),children:[v.isPending?r(T,{className:`h-3.5 w-3.5 animate-spin`}):null,l(`system.notificationTargets.discoverAdd`,`Add selected ({{count}})`,{count:g.length})]}),children:e(`div`,{className:`space-y-4`,children:[r(`p`,{className:`text-xs text-foreground-subtle`,children:l(`system.notificationTargets.discoverHelp`,`These devices are available on your connected accounts and have no target yet. Tick the ones to add.`)}),m.isLoading?e(`p`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[r(T,{className:`h-3.5 w-3.5 animate-spin`}),l(`system.notificationTargets.discoverSearching`,`Looking for devices…`)]}):null,!m.isLoading&&_===0&&h.every(e=>e.error===null)?r(`p`,{className:`text-xs text-foreground-subtle`,children:l(`system.notificationTargets.discoverNone`,`Every device that was found already has a target.`)}):null,h.map(t=>e(`section`,{className:`space-y-2`,children:[e(`div`,{className:`flex items-center gap-2 text-xs font-medium text-foreground`,children:[r(vh,{kind:t.kind,imgClassName:`h-5 w-5 object-contain shrink-0`,fallbackClassName:`text-lg leading-5`}),r(`span`,{children:t.kind.label})]}),t.error===null?null:r(H,{message:l(`system.notificationTargets.discoverFailed`,`Could not look for {{kind}}: {{message}}`,{kind:t.kind.label,message:t.error})}),t.proposals.length>0?r(`ul`,{className:`divide-y divide-border rounded-md border border-border`,children:t.proposals.map((n,i)=>{let a=yh(t.kind,i);return e(`li`,{className:`flex items-center gap-3 px-3 py-2`,children:[r(pt,{checked:!f.has(a),"aria-label":l(`system.notificationTargets.discoverPick`,`Add {{name}}`,{name:n.suggestedName}),onChange:()=>y(a)}),r(`span`,{className:`min-w-0 flex-1 truncate text-sm text-foreground`,children:n.suggestedName})]},a)})}):null]},t.kind.kind))]})})}function xh({refusal:t,edited:n,reenter:i}){let{t:a}=Y(),o=i.length>0?`Re-type: ${i.join(`, `)}.`:null;return t===null?n.length===0||o===null?null:r(`p`,{className:`text-[11px] text-warning`,"data-testid":`target-secret-reenter`,children:a(`system.targetSecretNotice.changed`,{fields:n.join(`, `),toType:o})}):e(`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:[r(`p`,{className:`font-semibold`,children:a(`system.targetSecretNotice.theHubNeedsTheSecret`,`The hub needs the secret again — nothing was saved.`)}),r(`p`,{className:`mt-1`,children:t}),o===null?null:r(`p`,{className:`mt-1 font-medium`,children:o})]})}s();var Sh=[`notificationOutput`,`listTargets`],Ch=[`notificationOutput`,`listTargetKinds`],wh=[`userManagement`,`listUsers`],Th=`ownerUserId`;function Eh(e){let t=e.config[Th];return typeof t==`string`&&t.length>0?t:null}function Dh(t){return[{key:`name`,header:J.t(`system.notificationTargets.target`,`Target`),render:n=>{let i=t.kindByKey.get(n.kind);return e(`span`,{className:`flex items-center gap-2`,children:[r(`span`,{className:`flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-surface text-xs`,title:i?.label??n.kind,children:r(vh,{kind:i,imgClassName:`h-5 w-5 object-contain`,fallbackClassName:``})}),r(lf,{name:n.name,enabled:n.enabled,...i===void 0?{}:{onOpen:()=>t.onOpen(n,i)}})]})}},{key:`kind`,header:J.t(`system.notificationTargets.kind`,`Kind`),nowrap:!0,render:e=>r(`span`,{className:`text-[11px] text-foreground-subtle`,children:t.kindByKey.get(e.kind)?.label??e.kind})},{key:`owner`,header:J.t(`system.notificationTargets.owner`,`Owner`),nowrap:!0,render:e=>{let n=Eh(e);return n===null?r(K,{variant:`default`,children:J.t(`common.systemWord`)}):r(`span`,{className:`text-[11px] text-foreground`,children:t.userNameById.get(n)??n})}},{key:`enabled`,header:J.t(`system.notificationTargets.on`,`On`),align:`center`,nowrap:!0,render:e=>r(af,{children:r(nt,{checked:e.enabled,onCheckedChange:n=>t.onToggle(e,n),"aria-label":J.t(`system.notificationTargets.toggle`,`toggle {{name}}`,{name:e.name})})})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:n=>{let i=t.kindByKey.get(n.kind);return e(af,{className:`flex items-center justify-end gap-1`,children:[r(U,{size:`sm`,variant:`ghost`,type:`button`,disabled:!i,onClick:()=>t.onTest(n),title:J.t(`system.notificationTargets.test`,`Test`),children:r(Ge,{className:`h-3.5 w-3.5`})}),r(U,{size:`sm`,variant:`ghost`,type:`button`,disabled:!i,onClick:()=>i&&t.onDuplicate(n,i),title:J.t(`system.notificationTargets.duplicate`,`Duplicate`),children:r(O,{className:`h-3.5 w-3.5`})}),r(U,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>t.onDelete(n),title:J.t(`common.delete`,`Delete`),children:r(h,{className:`h-3.5 w-3.5 text-danger`})})]})}}]}function Oh({createRequested:s=!1,onCreateConsumed:c,headerOwnsCreate:l=!1}={}){let{t:d}=Y(),f=w(),{state:p,openEdit:h,close:g}=Ct({editKey:`target`}),[_,v]=At(gh),[b,x]=a({mode:`closed`}),[S,C]=a(null),[T,E]=a(!1),D=t(null),O=o({queryKey:Sh,queryFn:()=>f.trpcClient.notificationOutput.listTargets.query({})}),k=o({queryKey:Ch,queryFn:async()=>(await f.trpcClient.notificationOutput.listTargetKinds.query({})).map(e=>{let t=e.iconUrl;return{...e,configSchema:e.configSchema,iconUrl:t}})}),j=n(()=>k.data??[],[k.data]),M=n(()=>dh(j),[j]),N=n(()=>{let e=new Map;for(let t of j)e.set(t.kind,t);return e},[j]),P=o({queryKey:wh,queryFn:()=>f.trpcClient.userManagement.listUsers.query()}),ee=n(()=>{let e=new Map;for(let t of P.data??[])e.set(t.id,t.username);return e},[P.data]),F=u({mutationFn:e=>f.trpcClient.notificationOutput.setTargetEnabled.mutate({addonId:e.target.addonId,targetId:e.target.id,enabled:e.enabled}),onSuccess:()=>void O.refetch()}),I=u({mutationFn:e=>f.trpcClient.notificationOutput.deleteTarget.mutate({addonId:e.addonId,targetId:e.id}),onSuccess:()=>void O.refetch()}),te=S?N.get(S.kind):void 0,L=()=>{p.mode===`edit`&&(D.current=p.id),x({mode:`closed`}),g(),v(null)},ne=()=>{D.current=`new`,x({mode:`pick-kind`}),h(`new`),v(null)};i(()=>{s&&(ne(),c?.())},[s]);let R=e=>{D.current=`new:${e.kind}`,x({mode:`form`,kind:e,target:null,cloneFrom:null}),h(`new`),v(e.kind)},z=(e,t)=>{D.current=e.id,x({mode:`form`,kind:t,target:e,cloneFrom:null}),h(e.id),v(null)};return i(()=>{if(b.mode!==`closed`)return;if(p.mode!==`edit`){p.mode===`closed`&&(D.current=null);return}let e=p.id;if(D.current===e)return;if(e===`new`){if(_===null||_.length===0){D.current=`new`,x({mode:`pick-kind`});return}let e=N.get(_);if(e===void 0)return;D.current=`new:${_}`,x({mode:`form`,kind:e,target:null,cloneFrom:null});return}let t=O.data?.find(t=>t.id===e);if(t===void 0)return;let n=N.get(t.kind);n!==void 0&&(D.current=e,x({mode:`form`,kind:n,target:t,cloneFrom:null}))},[b.mode,p,_,O.data,N]),e(ci,{embedded:!0,icon:y,title:d(`system.notificationTargets.notificationTargets`,`Notification Targets`),subtitle:d(`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:[!l||M.length>0?e(`div`,{className:`mb-3 flex justify-end gap-2`,children:[M.length>0?e(U,{size:`sm`,variant:`outline`,type:`button`,onClick:()=>E(!0),children:[r(A,{className:`h-3.5 w-3.5`}),d(`system.notificationTargets.findDevices`,`Find devices`)]}):null,l?null:e(U,{size:`sm`,type:`button`,onClick:ne,children:[r(m,{className:`h-3.5 w-3.5`}),d(`system.notificationTargets.addTarget`,`Add target`)]})]}):null,O.isLoading&&r(of,{}),O.isError&&!O.isLoading&&r(H,{title:d(`system.notificationTargets.failedToLoadTargets`,`Failed to load targets`),message:O.error instanceof Error?O.error.message:d(`system.notificationTargets.unknownError`,`Unknown error`),onRetry:()=>void O.refetch()}),!O.isLoading&&!O.isError&&(O.data??[]).length===0&&r(sf,{children:d(`system.notificationTargets.noNotificationTargetsYetClick`,`No notification targets yet. Click "Add target" to configure one.`)}),(O.data??[]).length>0&&r(cf,{columns:Dh({kindByKey:N,userNameById:ee,onToggle:(e,t)=>F.mutate({target:e,enabled:t}),onTest:C,onOpen:z,onDuplicate:(e,t)=>{D.current=`new:${t.kind}`,x({mode:`form`,kind:t,target:null,cloneFrom:e}),h(`new`),v(t.kind)},onDelete:e=>I.mutate(e)}),rows:O.data??[],rowKey:e=>e.id,minWidthPx:720,onRowClick:e=>{let t=N.get(e.kind);t!==void 0&&z(e,t)}}),b.mode===`pick-kind`&&r(kh,{kinds:j,onCancel:L,onPick:R}),b.mode===`form`&&r(Ah,{kind:b.kind,target:b.target,cloneFrom:b.cloneFrom,users:P.data??[],onCancel:L,onSaved:()=>{L(),O.refetch()}},b.target?.id??(b.cloneFrom===null?`new:${b.kind.kind}`:`dup:${b.cloneFrom.id}`)),T&&r(bh,{kinds:M,targets:O.data??[],onClose:()=>E(!1),onAdded:()=>{E(!1),O.refetch()}}),S&&te&&r(Wm,{target:S,kind:te,open:!0,onClose:()=>C(null)})]})}function kh({kinds:t,onPick:i,onCancel:a}){let{t:o}=Y(),s=n(()=>Km(t),[t]);return r(Dt,{open:!0,onClose:a,title:o(`system.notificationTargets.chooseANotificationKind`,`Choose a notification kind`),width:`lg`,children:e(`div`,{className:`space-y-4`,children:[s.length===0&&r(`p`,{className:`text-xs text-foreground-subtle`,children:o(`system.notificationTargets.noNotificationProvidersAreInstalled`,`No notification providers are installed. Install the notifiers addon (or connect Home Assistant) to add targets.`)}),s.map(t=>e(`div`,{children:[r(`div`,{className:`text-[10px] font-semibold uppercase tracking-wider text-foreground-subtle mb-1.5`,children:t.addonId}),r(`div`,{className:`grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-2`,children:t.kinds.map(n=>e(`button`,{type:`button`,onClick:()=>i(n),className:`flex flex-col items-center gap-1.5 rounded-lg border border-border bg-surface px-3 py-3 text-xs hover:border-primary/50 hover:bg-surface-hover transition-colors`,children:[r(vh,{kind:n,imgClassName:`h-7 w-7 object-contain`,fallbackClassName:`text-lg leading-7`}),r(`span`,{className:`font-medium text-foreground`,children:n.label})]},`${t.addonId}:${n.kind}`))})]},t.addonId))]})})}function Ah({kind:t,target:o,cloneFrom:s,users:c,onSaved:l,onCancel:f}){let{t:p}=Y(),m=w(),h=n(()=>qm(t.configSchema),[t.configSchema]),g=o??s,_=o?.id??s?.id,[v,b]=a(()=>s===null?o?.name??t.label:ch(s.name)),[x,S]=a(()=>g?.config??{}),[C,E]=a(()=>g?Qm(g.config,h):{}),[D,O]=a(_===void 0),[k,A]=a(null),[j,M]=a(null),[N,P]=a(g?Eh(g)??``:``);i(()=>{if(_===void 0)return;let e=!1;return m.trpcClient.notificationOutput.getTarget.query({addonId:t.addonId,targetId:_}).then(t=>{if(e)return;let n=$m(t.config);S(n),E(n),P(Eh(t)??``),O(!0)}).catch(t=>{e||(A(t instanceof Error?t.message:`Failed to load target secrets`),O(!0))}),()=>{e=!0}},[_,t.addonId,m.trpcClient]);let ee=()=>Zm(C,x,h),[F,I]=a(null),te=t.kind===`whatsapp`,L=u({mutationFn:()=>m.trpcClient.notificationOutput.probeTargetConfig.mutate({addonId:t.addonId,kind:t.kind,config:ee(),..._===void 0?{}:{targetId:_}}),onSuccess:e=>I(e),onError:e=>{I(null),A(e instanceof Error?e.message:`Connection test failed`)}}),ne=u({mutationFn:()=>{let{[Th]:e,...n}=Zm(C,x,h),r=N===``?n:{...n,[Th]:N},i={id:o?.id??`${t.kind}-${Date.now()}`,name:v,kind:t.kind,addonId:t.addonId,enabled:o?.enabled??!0,config:r};return m.trpcClient.notificationOutput.upsertTarget.mutate({addonId:t.addonId,target:i,...s===null?{}:{cloneSecretsFrom:s.id}})},onSuccess:l,onError:e=>{let t=e instanceof Error?e.message:`Save failed`;th(t)?M(t):A(t)}}),R=n(()=>Jm(t.configSchema),[t.configSchema]),z=n(()=>_===void 0?[]:ih(C,x,h,t.destinationKeys),[_,C,x,h,t.destinationKeys]),B=n(()=>_!==void 0&&(j!==null||z.length>0)?ah(C,x,h):[],[_,j,z,C,x,h]),re=n(()=>uh(sh(t.configSchema,B),x,h),[t.configSchema,B,x,h]),ie=e=>R.get(e)??e;return r(Dt,{open:!0,onClose:f,title:o?`Edit ${o.name}`:s?`Duplicate ${s.name}`:`Add ${t.label} target`,icon:y,width:`lg`,testId:`target-form-dialog`,beforeBody:e(d,{children:[k!=null&&k!==``&&r(`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}),e(`div`,{className:`mb-3 flex items-center gap-2 text-xs text-foreground-subtle`,children:[r(vh,{kind:t,imgClassName:`h-5 w-5 object-contain shrink-0`,fallbackClassName:`text-lg leading-5`}),r(`span`,{children:t.label})]})]}),footer:e(U,{size:`sm`,type:`button`,disabled:ne.isPending||!D||v.trim().length===0,onClick:()=>{A(null),M(null),ne.mutate()},children:[ne.isPending||!D?r(T,{className:`h-3.5 w-3.5 animate-spin`}):null,o?p(`system.notificationTargets.saveChanges`,`Save changes`):p(`system.notificationTargets.createTarget`,`Create target`)]}),children:e(`div`,{className:`space-y-4`,children:[e(`div`,{children:[r(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:p(`system.notificationTargets.name`,`Name`)}),r(`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:v,onChange:e=>b(e.target.value)})]}),e(`div`,{children:[r(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:p(`system.notificationTargets.owner`,`Owner`)}),r(W,{value:N,options:[{value:``,label:p(`system.notificationTargets.systemSharedAdminManaged`,`System (shared, admin-managed)`)},...c.map(e=>({value:e.id,label:e.username}))],onChange:e=>P(e.target.value)}),r(`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&&_!==void 0&&r(`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.`)}),r(xh,{refusal:j,edited:z.map(ie),reenter:B.map(ie)}),r(Ot,{schema:re,values:C,onChange:E}),te&&e(`div`,{className:`space-y-2`,children:[e(U,{size:`sm`,variant:`outline`,type:`button`,disabled:L.isPending,onClick:()=>{A(null),I(null),L.mutate()},children:[L.isPending?r(T,{className:`h-3.5 w-3.5 animate-spin`}):r(Ge,{className:`h-3.5 w-3.5`}),p(`system.notificationTargets.testConnection`,`Test connection`)]}),F!==null&&e(`p`,{className:F.ok?`text-[11px] text-success`:`text-[11px] text-danger`,"data-testid":`target-probe-result`,children:[F.ok?p(`system.notificationTargets.connected`,`Connected — {{value1}}`,{value1:F.stateInstance??`authorized`}):F.error??p(`system.notificationTargets.connectionFailed`,`Connection failed`),F.resolvedUrl.length>0?` · ${F.resolvedUrl}`:``]})]})]})})}s();var jh=`notificationTexts`,Mh=`Every sentence the Notification Center can print — and your wording for it.`;function Nh({entry:t,value:n,busy:i,onChange:a,onReset:o}){let{t:s}=Y(),c=Gl(t),l=t.override!==null;return e(`div`,{className:`flex flex-col gap-1.5 rounded border border-border p-3`,"data-testid":`text-row-${t.key}`,"data-source":t.source,children:[e(`div`,{className:`flex items-center gap-2 flex-wrap`,children:[r(`code`,{className:`text-xs font-medium`,children:t.key}),l?r(K,{variant:`info`,children:s(`common.customised`)}):null,t.source===`fallback`?r(K,{variant:`warning`,children:s(`system.notificationTexts.englishFallback`,`English fallback`)}):null]}),e(`div`,{className:`flex items-start gap-2`,children:[r(`div`,{className:`flex-1`,children:r(Ao,{label:``,value:n,onChange:a,vars:Wl(t),disabled:i,testId:`text-input-${t.key}`})}),r(U,{variant:`ghost`,size:`sm`,disabled:i||!l&&n===t.shipped,onClick:o,title:s(`system.notificationTexts.resetToTheShippedWording`,`Reset to the shipped wording`),"data-testid":`text-reset-${t.key}`,children:r(_,{className:`h-3.5 w-3.5`})})]}),e(`p`,{className:`text-xs text-foreground-subtle`,children:[r(`span`,{className:`font-medium`,children:s(`system.notificationTexts.shipped`,`Shipped:`)}),` `,r(`span`,{className:`font-mono`,children:t.shipped})]}),c===null?null:r(`p`,{className:`text-xs text-warning`,children:c})]})}function Ph(){let{t}=Y(),i=w(),s=c(),[l,d]=a(null),[f,p]=a(``),[m,h]=a(new Map),[g,_]=a(!1),v=o({queryKey:[jh,l??`hub`],queryFn:async()=>{let e=zl(await i.trpcClient.addons.custom.mutate({addonId:kl,action:Al,input:l===null?{}:{language:l}}));return _(e===null),e}}),y=()=>{h(new Map),s.invalidateQueries({queryKey:[jh]})},b=u({mutationFn:e=>i.trpcClient.addons.custom.mutate({addonId:kl,action:jl,input:{language:e}}),onSuccess:y}),x=u({mutationFn:e=>i.trpcClient.addons.custom.mutate({addonId:kl,action:Ml,input:e}),onSuccess:y}),S=v.data??null,C=n(()=>S===null?[]:Ul(S.entries,f),[S,f]);if(v.isLoading)return r(ci,{embedded:!0,icon:Ke,title:t(`system.notificationTexts.texts`,`Texts`),subtitle:Mh,children:r(T,{className:`h-5 w-5 animate-spin`})});if(v.isError||S===null)return r(ci,{embedded:!0,icon:Ke,title:t(`system.notificationTexts.texts`,`Texts`),subtitle:Mh,children:r(H,{title:t(`system.notificationTexts.theNotificationTextCatalogIs`,`The notification text catalog is not available on this hub`),message:g?t(`system.notificationTexts.theHubAnsweredSomethingThis`,`The hub answered something this admin build does not understand. Update both and reload.`):t(`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 E=S.language,D=b.isPending||x.isPending,O=Vl(S.entries,m),k=Hl(S.entries,m),j=S.entries.filter(e=>e.override!==null).length,M=S.languages.map(e=>({value:e,label:Nl[e]})),N=(e,t)=>h(n=>new Map(n).set(e,t)),P=e=>N(e.key,e.shipped);return r(ci,{embedded:!0,icon:Ke,title:t(`system.notificationTexts.texts`,`Texts`),subtitle:Mh,children:e(`div`,{className:`flex flex-col gap-4`,children:[b.isError?r(H,{title:t(`system.notificationTexts.couldNotChangeTheLanguage`,`Could not change the language`),message:String(b.error)}):null,x.isError?r(H,{title:t(`system.notificationTexts.couldNotSave`,`Could not save`),message:String(x.error)}):null,e(bt,{className:`p-4`,children:[e(`div`,{className:`flex flex-wrap items-end gap-6`,children:[e(`div`,{className:`flex flex-col gap-1`,children:[r(`label`,{className:`text-sm font-medium`,children:t(`system.notificationTexts.hubLanguage`,`Hub language`)}),r(`div`,{className:`w-44`,children:r(W,{value:S.activeLanguage,disabled:D,options:M,onChange:e=>{let t=e.target.value;Pl(t)&&b.mutate(t)},"data-testid":`texts-hub-language`})}),r(`p`,{className:`text-xs text-foreground-subtle`,children:t(`system.notificationTexts.everyNotificationIsWrittenIn`,`Every notification is written in this language.`)})]}),e(`div`,{className:`flex flex-col gap-1`,children:[r(`label`,{className:`text-sm font-medium`,children:t(`system.notificationTexts.editing`,`Editing`)}),r(`div`,{className:`w-44`,children:r(W,{value:E,disabled:D,options:M,onChange:e=>{let t=e.target.value;Pl(t)&&(h(new Map),d(t))},"data-testid":`texts-editing-language`})}),r(`p`,{className:`text-xs text-foreground-subtle`,children:E===S.activeLanguage?t(`system.notificationTexts.ofTextsCustomised`,`{{overriddenCount}} of {{length}} texts customised.`,{overriddenCount:j,length:S.entries.length}):t(`system.notificationTexts.thisHubDoesNotSpeak`,`This hub does not speak this language — these words are not in use yet.`)})]})]}),r(`p`,{className:`mt-3 text-xs text-foreground-subtle`,children:t(`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.`)})]}),e(`div`,{className:`flex flex-wrap items-center gap-3`,children:[e(`div`,{className:`relative min-w-[12rem] flex-1`,children:[r(A,{className:`absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-foreground-muted`}),r(G,{value:f,placeholder:t(`system.notificationTexts.searchAKeyOrA`,`Search a key or a sentence…`),onChange:e=>p(e.target.value),className:`pl-7`,"data-testid":`texts-search`})]}),e(`span`,{className:`text-xs text-foreground-subtle whitespace-nowrap`,children:[C.length,` of `,S.entries.length]}),e(U,{className:`ml-auto`,disabled:D||k===0,onClick:()=>x.mutate({language:E,overrides:O}),"data-testid":`texts-save`,children:[D?r(T,{className:`h-3.5 w-3.5 animate-spin`}):null,k===0?t(`common.save`,`Save`):t(`system.notificationTexts.save`,`Save {{pending}}`,{pending:k})]})]}),r(`div`,{className:`flex max-h-[60vh] flex-col gap-2 overflow-y-auto pr-1`,"data-testid":`texts-rows`,children:C.length===0?r(`p`,{className:`text-sm text-foreground-subtle`,children:t(`system.notificationTexts.noTextMatchesThatSearch`,`No text matches that search.`)}):C.map(e=>r(Nh,{entry:e,value:Bl(e,m),busy:D,onChange:t=>N(e.key,t),onReset:()=>P(e)},e.key))})]})})}s();var Fh=`simulate`,Ih=`rules`,Lh=new Set([`targets`,Ih,`sequences`]);function Rh(e){return e===`summaries`?`summary`:e===`timelapses`?`timelapse`:e===`calendar-events`?`calendar-events`:null}function zh(t,n,i){if(t===`mixed`)return;if(t===`all`)return e(U,{size:`sm`,type:`button`,"data-testid":`rules-new-menu`,onClick:n,children:[r(m,{className:`h-3.5 w-3.5`}),J.t(`systemPage.notifications.newRule`,`New rule`)]});if(Cf(t)){let n=Tf(t),a=Rh(t);return a===null?void 0:e(U,{size:`sm`,type:`button`,onClick:()=>i(a),"data-testid":t===`summaries`?`summary-new`:t===`timelapses`?`timelapse-new`:`calendar-events-new`,children:[r(m,{className:`h-3.5 w-3.5`}),n.newLabel]})}let a=pr.find(e=>e.key===t);if(!(a===void 0||!a.creatable))return e(U,{size:`sm`,type:`button`,onClick:()=>i(t),"data-testid":`rules-new-${t}`,children:[r(m,{className:`h-3.5 w-3.5`}),a.newRuleLabel]})}function Bh(){let{t}=Y(),[n,o]=gr(),[s,c]=a(!1),[l,u]=a(null);i(()=>{let e=n.get(`tab`);if(e===null||!Cf(e))return;let t=new URLSearchParams(n);t.set(`tab`,Ih),t.set(`section`,e),o(t,{replace:!0})},[n,o]);let d=n.get(`tab`)??`targets`,[f]=At(`section`),p=wf(f)??`all`,h=e=>{nm(em(e));let t=new URLSearchParams(n);t.set(`tab`,Fh),o(t,{replace:!0})},g=e=>{o(Za(n,e.id),{replace:!0})},_=jn(`/system/notifications`,{t,isAdmin:!0})??{icon:y,title:t(`system.notifications`,`Notifications`)},v=()=>c(!1),b=(()=>{if(d===`targets`)return e(U,{size:`sm`,type:`button`,"data-testid":`notifications-add-target`,onClick:()=>c(!0),children:[r(m,{className:`h-3.5 w-3.5`}),t(`systemPage.notifications.addTarget`,`Add target`)]});if(d===`sequences`)return e(U,{size:`sm`,type:`button`,"data-testid":`notifications-add-sequence`,onClick:()=>c(!0),children:[r(m,{className:`h-3.5 w-3.5`}),t(`systemPage.notifications.newSequence`,`New sequence`)]});if(d===Ih)return zh(p,()=>c(!0),e=>u(e))})();return i(()=>{Lh.has(d)||(c(!1),u(null))},[d]),r(ai,{icon:_.icon,title:_.title,defaultSection:`targets`,sectionsLabel:`${_.title} sections`,actions:b,sections:[{id:`targets`,label:t(`systemPage.notifications.targets`,`Targets`),content:r(Oh,{headerOwnsCreate:!0,createRequested:d===`targets`&&s,onCreateConsumed:v}),ownedParams:_h},{id:Ih,label:t(`systemPage.notifications.rules`,`Rules`),content:r(gp,{onSimulateRule:h,onOpenHistory:g,headerOwnsCreate:!0,createRequested:d===Ih&&s,onCreateConsumed:v,createTypeRequested:d===Ih?l:null,onCreateTypeConsumed:()=>u(null)}),ownedParams:[`section`,`rule`,`editTab`]},{id:`sequences`,label:t(`systemPage.notifications.sequences`,`Sequences`),content:r(Mp,{headerOwnsCreate:!0,createRequested:d===`sequences`&&s,onCreateConsumed:v}),ownedParams:Tp},{id:Fh,label:t(`systemPage.notifications.simulate`,`Simulate`),content:r(Em,{})},{id:Ga,label:t(`systemPage.notifications.history`,`History`),content:r(co,{}),ownedParams:qa},{id:`alarm`,label:t(`systemPage.notifications.alarm`,`Alarm`),content:r(Wa,{})},{id:`texts`,label:t(`systemPage.notifications.texts`,`Texts`),content:r(Ph,{})},{id:`settings`,label:t(`systemPage.notifications.settings`,`Settings`),content:r(Fp,{})}]})}export{Bh as NotificationsPage,Bh as default};
|